sqlite3-binding.c 7.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918202919202920202921202922202923202924202925202926202927202928202929202930202931202932202933202934202935202936202937202938202939202940202941202942202943202944202945202946202947202948202949202950202951202952202953202954202955202956202957202958202959202960202961202962202963202964202965202966202967202968202969202970202971202972202973202974202975202976202977202978202979202980202981202982202983202984202985202986202987202988202989202990202991202992202993202994202995202996202997202998202999203000203001203002203003203004203005203006203007203008203009203010203011203012203013203014203015203016203017203018203019203020203021203022203023203024203025203026203027203028203029203030203031203032203033203034203035203036203037203038203039203040203041203042203043203044203045203046203047203048203049203050203051203052203053203054203055203056203057203058203059203060203061203062203063203064203065203066203067203068203069203070203071203072203073203074203075203076203077203078203079203080203081203082203083203084203085203086203087203088203089203090203091203092203093203094203095203096203097203098203099203100203101203102203103203104203105203106203107203108203109203110203111203112203113203114203115203116203117203118203119203120203121203122203123203124203125203126203127203128203129203130203131203132203133203134203135203136203137203138203139203140203141203142203143203144203145203146203147203148203149203150203151203152203153203154203155203156203157203158203159203160203161203162203163203164203165203166203167203168203169203170203171203172203173203174203175203176203177203178203179203180203181203182203183203184203185203186203187203188203189203190203191203192203193203194203195203196203197203198203199203200203201203202203203203204203205203206203207203208203209203210203211203212203213203214203215203216203217203218203219203220203221203222203223203224203225203226203227203228203229203230203231203232203233203234203235203236203237203238203239203240203241203242203243203244203245203246203247203248203249203250203251203252203253203254203255203256203257203258203259203260203261203262203263203264203265203266203267203268203269203270203271203272203273203274203275203276203277203278203279203280203281203282203283203284203285203286203287203288203289203290203291203292203293203294203295203296203297203298203299203300203301203302203303203304203305203306203307203308203309203310203311203312203313203314203315203316203317203318203319203320203321203322203323203324203325203326203327203328203329203330203331203332203333203334203335203336203337203338203339203340203341203342203343203344203345203346203347203348203349203350203351203352203353203354203355203356203357203358203359203360203361203362203363203364203365203366203367203368203369203370203371203372203373203374203375203376203377203378203379203380203381203382203383203384203385203386203387203388203389203390203391203392203393203394203395203396203397203398203399203400203401203402203403203404203405203406203407203408203409203410203411203412203413203414203415203416203417203418203419203420203421203422203423203424203425203426203427203428203429203430203431203432203433203434203435203436203437203438203439203440203441203442203443203444203445203446203447203448203449203450203451203452203453203454203455203456203457203458203459203460203461203462203463203464203465203466203467203468203469203470203471203472203473203474203475203476203477203478203479203480203481203482203483203484203485203486203487203488203489203490203491203492203493203494203495203496203497203498203499203500203501203502203503203504203505203506203507203508203509203510203511203512203513203514203515203516203517203518203519203520203521203522203523203524203525203526203527203528203529203530203531203532203533203534203535203536203537203538203539203540203541203542203543203544203545203546203547203548203549203550203551203552203553203554203555203556203557203558203559203560203561203562203563203564203565203566203567203568203569203570203571203572203573203574203575203576203577203578203579203580203581203582203583203584203585203586203587203588203589203590203591203592203593203594203595203596203597203598203599203600203601203602203603203604203605203606203607203608203609203610203611203612203613203614203615203616203617203618203619203620203621203622203623203624203625203626203627203628203629203630203631203632203633203634203635203636203637203638203639203640203641203642203643203644203645203646203647203648203649203650203651203652203653203654203655203656203657203658203659203660203661203662203663203664203665203666203667203668203669203670203671203672203673203674203675203676203677203678203679203680203681203682203683203684203685203686203687203688203689203690203691203692203693203694203695203696203697203698203699203700203701203702203703203704203705203706203707203708203709203710203711203712203713203714203715203716203717203718203719203720203721203722203723203724203725203726203727203728203729203730203731203732203733203734203735203736203737203738203739203740203741203742203743203744203745203746203747203748203749203750203751203752203753203754203755203756203757203758203759203760203761203762203763203764203765203766203767203768203769203770203771203772203773203774203775203776203777203778203779203780203781203782203783203784203785203786203787203788203789203790203791203792203793203794203795203796203797203798203799203800203801203802203803203804203805203806203807203808203809203810203811203812203813203814203815203816203817203818203819203820203821203822203823203824203825203826203827203828203829203830203831203832203833203834203835203836203837203838203839203840203841203842203843203844203845203846203847203848203849203850203851203852203853203854203855203856203857203858203859203860203861203862203863203864203865203866203867203868203869203870203871203872203873203874203875203876203877203878203879203880203881203882203883203884203885203886203887203888203889203890203891203892203893203894203895203896203897203898203899203900203901203902203903203904203905203906203907203908203909203910203911203912203913203914203915203916203917203918203919203920203921203922203923203924203925203926203927203928203929203930203931203932203933203934203935203936203937203938203939203940203941203942203943203944203945203946203947203948203949203950203951203952203953203954203955203956203957203958203959203960203961203962203963203964203965203966203967203968203969203970203971203972203973203974203975203976203977203978203979203980203981203982203983203984203985203986203987203988203989203990203991203992203993203994203995203996203997203998203999204000204001204002204003204004204005204006204007204008204009204010204011204012204013204014204015204016204017204018204019204020204021204022204023204024204025204026204027204028204029204030204031204032204033204034204035204036204037204038204039204040204041204042204043204044204045204046204047204048204049204050204051204052204053204054204055204056204057204058204059204060204061204062204063204064204065204066204067204068204069204070204071204072204073204074204075204076204077204078204079204080204081204082204083204084204085204086204087204088204089204090204091204092204093204094204095204096204097204098204099204100204101204102204103204104204105204106204107204108204109204110204111204112204113204114204115204116204117204118204119204120204121204122204123204124204125204126204127204128204129204130204131204132204133204134204135204136204137204138204139204140204141204142204143204144204145204146204147204148204149204150204151204152204153204154204155204156204157204158204159204160204161204162204163204164204165204166204167204168204169204170204171204172204173204174204175204176204177204178204179204180204181204182204183204184204185204186204187204188204189204190204191204192204193204194204195204196204197204198204199204200204201204202204203204204204205204206204207204208204209204210204211204212204213204214204215204216204217204218204219204220204221204222204223204224204225204226204227204228204229204230204231204232204233204234204235204236204237204238204239204240204241204242204243204244204245204246204247204248204249204250204251204252204253204254204255204256204257204258204259204260204261204262204263204264204265204266204267204268204269204270204271204272204273204274204275204276204277204278204279204280204281204282204283204284204285204286204287204288204289204290204291204292204293204294204295204296204297204298204299204300204301204302204303204304204305204306204307204308204309204310204311204312204313204314204315204316204317204318204319204320204321204322204323204324204325204326204327204328204329204330204331204332204333204334204335204336204337204338204339204340204341204342204343204344204345204346204347204348204349204350204351204352204353204354204355204356204357204358204359204360204361204362204363204364204365204366204367204368204369204370204371204372204373204374204375204376204377204378204379204380204381204382204383204384204385204386204387204388204389204390204391204392204393204394204395204396204397204398204399204400204401204402204403204404204405204406204407204408204409204410204411204412204413204414204415204416204417204418204419204420204421204422204423204424204425204426204427204428204429204430204431204432204433204434204435204436204437204438204439204440204441204442204443204444204445204446204447204448204449204450204451204452204453204454204455204456204457204458204459204460204461204462204463204464204465204466204467204468204469204470204471204472204473204474204475204476204477204478204479204480204481204482204483204484204485204486204487204488204489204490204491204492204493204494204495204496204497204498204499204500204501204502204503204504204505204506204507204508204509204510204511204512204513204514204515204516204517204518204519204520204521204522204523204524204525204526204527204528204529204530204531204532204533204534204535204536204537204538204539204540204541204542204543204544204545204546204547204548204549204550204551204552204553204554204555204556204557204558204559204560204561204562204563204564204565204566204567204568204569204570204571204572204573204574204575204576204577204578204579204580204581204582204583204584204585204586204587204588204589204590204591204592204593204594204595204596204597204598204599204600204601204602204603204604204605204606204607204608204609204610204611204612204613204614204615204616204617204618204619204620204621204622204623204624204625204626204627204628204629204630204631204632204633204634204635204636204637204638204639204640204641204642204643204644204645204646204647204648204649204650204651204652204653204654204655204656204657204658204659204660204661204662204663204664204665204666204667204668204669204670204671204672204673204674204675204676204677204678204679204680204681204682204683204684204685204686204687204688204689204690204691204692204693204694204695204696204697204698204699204700204701204702204703204704204705204706204707204708204709204710204711204712204713204714204715204716204717204718204719204720204721204722204723204724204725204726204727204728204729204730204731204732204733204734204735204736204737204738204739204740204741204742204743204744204745204746204747204748204749204750204751204752204753204754204755204756204757204758204759204760204761204762204763204764204765204766204767204768204769204770204771204772204773204774204775204776204777204778204779204780204781204782204783204784204785204786204787204788204789204790204791204792204793204794204795204796204797204798204799204800204801204802204803204804204805204806204807204808204809204810204811204812204813204814204815204816204817204818204819204820204821204822204823204824204825204826204827204828204829204830204831204832204833204834204835204836204837204838204839204840204841204842204843204844204845204846204847204848204849204850204851204852204853204854204855204856204857204858204859204860204861204862204863204864204865204866204867204868204869204870204871204872204873204874204875204876204877204878204879204880204881204882204883204884204885204886204887204888204889204890204891204892204893204894204895204896204897204898204899204900204901204902204903204904204905204906204907204908204909204910204911204912204913204914204915204916204917204918204919204920204921204922204923204924204925204926204927204928204929204930204931204932204933204934204935204936204937204938204939204940204941204942204943204944204945204946204947204948204949204950204951204952204953204954204955204956204957204958204959204960204961204962204963204964204965204966204967204968204969204970204971204972204973204974204975204976204977204978204979204980204981204982204983204984204985204986204987204988204989204990204991204992204993204994204995204996204997204998204999205000205001205002205003205004205005205006205007205008205009205010205011205012205013205014205015205016205017205018205019205020205021205022205023205024205025205026205027205028205029205030205031205032205033205034205035205036205037205038205039205040205041205042205043205044205045205046205047205048205049205050205051205052205053205054205055205056205057205058205059205060205061205062205063205064205065205066205067205068205069205070205071205072205073205074205075205076205077205078205079205080205081205082205083205084205085205086205087205088205089205090205091205092205093205094205095205096205097205098205099205100205101205102205103205104205105205106205107205108205109205110205111205112205113205114205115205116205117205118205119205120205121205122205123205124205125205126205127205128205129205130205131205132205133205134205135205136205137205138205139205140205141205142205143205144205145205146205147205148205149205150205151205152205153205154205155205156205157205158205159205160205161205162205163205164205165205166205167205168205169205170205171205172205173205174205175205176205177205178205179205180205181205182205183205184205185205186205187205188205189205190205191205192205193205194205195205196205197205198205199205200205201205202205203205204205205205206205207205208205209205210205211205212205213205214205215205216205217205218205219205220205221205222205223205224205225205226205227205228205229205230205231205232205233205234205235205236205237205238205239205240205241205242205243205244205245205246205247205248205249205250205251205252205253205254205255205256205257205258205259205260205261205262205263205264205265205266205267205268205269205270205271205272205273205274205275205276205277205278205279205280205281205282205283205284205285205286205287205288205289205290205291205292205293205294205295205296205297205298205299205300205301205302205303205304205305205306205307205308205309205310205311205312205313205314205315205316205317205318205319205320205321205322205323205324205325205326205327205328205329205330205331205332205333205334205335205336205337205338205339205340205341205342205343205344205345205346205347205348205349205350205351205352205353205354205355205356205357205358205359205360205361205362205363205364205365205366205367205368205369205370205371205372205373205374205375205376205377205378205379205380205381205382205383205384205385205386205387205388205389205390205391205392205393205394205395205396205397205398205399205400205401205402205403205404205405205406205407205408205409205410205411205412205413205414205415205416205417205418205419205420205421205422205423205424205425205426205427205428205429205430205431205432205433205434205435205436205437205438205439205440205441205442205443205444205445205446205447205448205449205450205451205452205453205454205455205456205457205458205459205460205461205462205463205464205465205466205467205468205469205470205471205472205473205474205475205476205477205478205479205480205481205482205483205484205485205486205487205488205489205490205491205492205493205494205495205496205497205498205499205500205501205502205503205504205505205506205507205508205509205510205511205512205513205514205515205516205517205518205519205520205521205522205523205524205525205526205527205528205529205530205531205532205533205534205535205536205537205538205539205540205541205542205543205544205545205546205547205548205549205550205551205552205553205554205555205556205557205558205559205560205561205562205563205564205565205566205567205568205569205570205571205572205573205574205575205576205577205578205579205580205581205582205583205584205585205586205587205588205589205590205591205592205593205594205595205596205597205598205599205600205601205602205603205604205605205606205607205608205609205610205611205612205613205614205615205616205617205618205619205620205621205622205623205624205625205626205627205628205629205630205631205632205633205634205635205636205637205638205639205640205641205642205643205644205645205646205647205648205649205650205651205652205653205654205655205656205657205658205659205660205661205662205663205664205665205666205667205668205669205670205671205672205673205674205675205676205677205678205679205680205681205682205683205684205685205686205687205688205689205690205691205692205693205694205695205696205697205698205699205700205701205702205703205704205705205706205707205708205709205710205711205712205713205714205715205716205717205718205719205720205721205722205723205724205725205726205727205728205729205730205731205732205733205734205735205736205737205738205739205740205741205742205743205744205745205746205747205748205749205750205751205752205753205754205755205756205757205758205759205760205761205762205763205764205765205766205767205768205769205770205771205772205773205774205775205776205777205778205779205780205781205782205783205784205785205786205787205788205789205790205791205792205793205794205795205796205797205798205799205800205801205802205803205804205805205806205807205808205809205810205811205812205813205814205815205816205817205818205819205820205821205822205823205824205825205826205827205828205829205830205831205832205833205834205835205836205837205838205839205840205841205842205843205844205845205846205847205848205849205850205851205852205853205854205855205856205857205858205859205860205861205862205863205864205865205866205867205868205869205870205871205872205873205874205875205876205877205878205879205880205881205882205883205884205885205886205887205888205889205890205891205892205893205894205895205896205897205898205899205900205901205902205903205904205905205906205907205908205909205910205911205912205913205914205915205916205917205918205919205920205921205922205923205924205925205926205927205928205929205930205931205932205933205934205935205936205937205938205939205940205941205942205943205944205945205946205947205948205949205950205951205952205953205954205955205956205957205958205959205960205961205962205963205964205965205966205967205968205969205970205971205972205973205974205975205976205977205978205979205980205981205982205983205984205985205986205987205988205989205990205991205992205993205994205995205996205997205998205999206000206001206002206003206004206005206006206007206008206009206010206011206012206013206014206015206016206017206018206019206020206021206022206023206024206025206026206027206028206029206030206031206032206033206034206035206036206037206038206039206040206041206042206043206044206045206046206047206048206049206050206051206052206053206054206055206056206057206058206059206060206061206062206063206064206065206066206067206068206069206070206071206072206073206074206075206076206077206078206079206080206081206082206083206084206085206086206087206088206089206090206091206092206093206094206095206096206097206098206099206100206101206102206103206104206105206106206107206108206109206110206111206112206113206114206115206116206117206118206119206120206121206122206123206124206125206126206127206128206129206130206131206132206133206134206135206136206137206138206139206140206141206142206143206144206145206146206147206148206149206150206151206152206153206154206155206156206157206158206159206160206161206162206163206164206165206166206167206168206169206170206171206172206173206174206175206176206177206178206179206180206181206182206183206184206185206186206187206188206189206190206191206192206193206194206195206196206197206198206199206200206201206202206203206204206205206206206207206208206209206210206211206212206213206214206215206216206217206218206219206220206221206222206223206224206225206226206227206228206229206230206231206232206233206234206235206236206237206238206239206240206241206242206243206244206245206246206247206248206249206250206251206252206253206254206255206256206257206258206259206260206261206262206263206264206265206266206267206268206269206270206271206272206273206274206275206276206277206278206279206280206281206282206283206284206285206286206287206288206289206290206291206292206293206294206295206296206297206298206299206300206301206302206303206304206305206306206307206308206309206310206311206312206313206314206315206316206317206318206319206320206321206322206323206324206325206326206327206328206329206330206331206332206333206334206335206336206337206338206339206340206341206342206343206344206345206346206347206348206349206350206351206352206353206354206355206356206357206358206359206360206361206362206363206364206365206366206367206368206369206370206371206372206373206374206375206376206377206378206379206380206381206382206383206384206385206386206387206388206389206390206391206392206393206394206395206396206397206398206399206400206401206402206403206404206405206406206407206408206409206410206411206412206413206414206415206416206417206418206419206420206421206422206423206424206425206426206427206428206429206430206431206432206433206434206435206436206437206438206439206440206441206442206443206444206445206446206447206448206449206450206451206452206453206454206455206456206457206458206459206460206461206462206463206464206465206466206467206468206469206470206471206472206473206474206475206476206477206478206479206480206481206482206483206484206485206486206487206488206489206490206491206492206493206494206495206496206497206498206499206500206501206502206503206504206505206506206507206508206509206510206511206512206513206514206515206516206517206518206519206520206521206522206523206524206525206526206527206528206529206530206531206532206533206534206535206536206537206538206539206540206541206542206543206544206545206546206547206548206549206550206551206552206553206554206555206556206557206558206559206560206561206562206563206564206565206566206567206568206569206570206571206572206573206574206575206576206577206578206579206580206581206582206583206584206585206586206587206588206589206590206591206592206593206594206595206596206597206598206599206600206601206602206603206604206605206606206607206608206609206610206611206612206613206614206615206616206617206618206619206620206621206622206623206624206625206626206627206628206629206630206631206632206633206634206635206636206637206638206639206640206641206642206643206644206645206646206647206648206649206650206651206652206653206654206655206656206657206658206659206660206661206662206663206664206665206666206667206668206669206670206671206672206673206674206675206676206677206678206679206680206681206682206683206684206685206686206687206688206689206690206691206692206693206694206695206696206697206698206699206700206701206702206703206704206705206706206707206708206709206710206711206712206713206714206715206716206717206718206719206720206721206722206723206724206725206726206727206728206729206730206731206732206733206734206735206736206737206738206739206740206741206742206743206744206745206746206747206748206749206750206751206752206753206754206755206756206757206758206759206760206761206762206763206764206765206766206767206768206769206770206771206772206773206774206775206776206777206778206779206780206781206782206783206784206785206786206787206788206789206790206791206792206793206794206795206796206797206798206799206800206801206802206803206804206805206806206807206808206809206810206811206812206813206814206815206816206817206818206819206820206821206822206823206824206825206826206827206828206829206830206831206832206833206834206835206836206837206838206839206840206841206842206843206844206845206846206847206848206849206850206851206852206853206854206855206856206857206858206859206860206861206862206863206864206865206866206867206868206869206870206871206872206873206874206875206876206877206878206879206880206881206882206883206884206885206886206887206888206889206890206891206892206893206894206895206896206897206898206899206900206901206902206903206904206905206906206907206908206909206910206911206912206913206914206915206916206917206918206919206920206921206922206923206924206925206926206927206928206929206930206931206932206933206934206935206936206937206938206939206940206941206942206943206944206945206946206947206948206949206950206951206952206953206954206955206956206957206958206959206960206961206962206963206964206965206966206967206968206969206970206971206972206973206974206975206976206977206978206979206980206981206982206983206984206985206986206987206988206989206990206991206992206993206994206995206996206997206998206999207000207001207002207003207004207005207006207007207008207009207010207011207012207013207014207015207016207017207018207019207020207021207022207023207024207025207026207027207028207029207030207031207032207033207034207035207036207037207038207039207040207041207042207043207044207045207046207047207048207049207050207051207052207053207054207055207056207057207058207059207060207061207062207063207064207065207066207067207068207069207070207071207072207073207074207075207076207077207078207079207080207081207082207083207084207085207086207087207088207089207090207091207092207093207094207095207096207097207098207099207100207101207102207103207104207105207106207107207108207109207110207111207112207113207114207115207116207117207118207119207120207121207122207123207124207125207126207127207128207129207130207131207132207133207134207135207136207137207138207139207140207141207142207143207144207145207146207147207148207149207150207151207152207153207154207155207156207157207158207159207160207161207162207163207164207165207166207167207168207169207170207171207172207173207174207175207176207177207178207179207180207181207182207183207184207185207186207187207188207189207190207191207192207193207194207195207196207197207198207199207200207201207202207203207204207205207206207207207208207209207210207211207212207213207214207215207216207217207218207219207220207221207222207223207224207225207226207227207228207229207230207231207232207233207234207235207236207237207238207239207240207241207242207243207244207245207246207247207248207249207250207251207252207253207254207255207256207257207258207259207260207261207262207263207264207265207266207267207268207269207270207271207272207273207274207275207276207277207278207279207280207281207282207283207284207285207286207287207288207289207290207291207292207293207294207295207296207297207298207299207300207301207302207303207304207305207306207307207308207309207310207311207312207313207314207315207316207317207318207319207320207321207322207323207324207325207326207327207328207329207330207331207332207333207334207335207336207337207338207339207340207341207342207343207344207345207346207347207348207349207350207351207352207353207354207355207356207357207358207359207360207361207362207363207364207365207366207367207368207369207370207371207372207373207374207375207376207377207378207379207380207381207382207383207384207385207386207387207388207389207390207391207392207393207394207395207396207397207398207399207400207401207402207403207404207405207406207407207408207409207410207411207412207413207414207415207416207417207418207419207420207421207422207423207424207425207426207427207428207429207430207431207432207433207434207435207436207437207438207439207440207441207442207443207444207445207446207447207448207449207450207451207452207453207454207455207456207457207458207459207460207461207462207463207464207465207466207467207468207469207470207471207472207473207474207475207476207477207478207479207480207481207482207483207484207485207486207487207488207489207490207491207492207493207494207495207496207497207498207499207500207501207502207503207504207505207506207507207508207509207510207511207512207513207514207515207516207517207518207519207520207521207522207523207524207525207526207527207528207529207530207531207532207533207534207535207536207537207538207539207540207541207542207543207544207545207546207547207548207549207550207551207552207553207554207555207556207557207558207559207560207561207562207563207564207565207566207567207568207569207570207571207572207573207574207575207576207577207578207579207580207581207582207583207584207585207586207587207588207589207590207591207592207593207594207595207596207597207598207599207600207601207602207603207604207605207606207607207608207609207610207611207612207613207614207615207616207617207618207619207620207621207622207623207624207625207626207627207628207629207630207631207632207633207634207635207636207637207638207639207640207641207642207643207644207645207646207647207648207649207650207651207652207653207654207655207656207657207658207659207660207661207662207663207664207665207666207667207668207669207670207671207672207673207674207675207676207677207678207679207680207681207682207683207684207685207686207687207688207689207690207691207692207693207694207695207696207697207698207699207700207701207702207703207704207705207706207707207708207709207710207711207712207713207714207715207716207717207718207719207720207721207722207723207724207725207726207727207728207729207730207731207732207733207734207735207736207737207738207739207740207741207742207743207744207745207746207747207748207749207750207751207752207753207754207755207756207757207758207759207760207761207762207763207764207765207766207767207768207769207770207771207772207773207774207775207776207777207778207779207780207781207782207783207784207785207786207787207788207789207790207791207792207793207794207795207796207797207798207799207800207801207802207803207804207805207806207807207808207809207810207811207812207813207814207815207816207817207818207819207820207821207822207823207824207825207826207827207828207829207830207831207832207833207834207835207836207837207838207839207840207841207842207843207844207845207846207847207848207849207850207851207852207853207854207855207856207857207858207859207860207861207862207863207864207865207866207867207868207869207870207871207872207873207874207875207876207877207878207879207880207881207882207883207884207885207886207887207888207889207890207891207892207893207894207895207896207897207898207899207900207901207902207903207904207905207906207907207908207909207910207911207912207913207914207915207916207917207918207919207920207921207922207923207924207925207926207927207928207929207930207931207932207933207934207935207936207937207938207939207940207941207942207943207944207945207946207947207948207949207950207951207952207953207954207955207956207957207958207959207960207961207962207963207964207965207966207967207968207969207970207971207972207973207974207975207976207977207978207979207980207981207982207983207984207985207986207987207988207989207990207991207992207993207994207995207996207997207998207999208000208001208002208003208004208005208006208007208008208009208010208011208012208013208014208015208016208017208018208019208020208021208022208023208024208025208026208027208028208029208030208031208032208033208034208035208036208037208038208039208040208041208042208043208044208045208046208047208048208049208050208051208052208053208054208055208056208057208058208059208060208061208062208063208064208065208066208067208068208069208070208071208072208073208074208075208076208077208078208079208080208081208082208083208084208085208086208087208088208089208090208091208092208093208094208095208096208097208098208099208100208101208102208103208104208105208106208107208108208109208110208111208112208113208114208115208116208117208118208119208120208121208122208123208124208125208126208127208128208129208130208131208132208133208134208135208136208137208138208139208140208141208142208143208144208145208146208147208148208149208150208151208152208153208154208155208156208157208158208159208160208161208162208163208164208165208166208167208168208169208170208171208172208173208174208175208176208177208178208179208180208181208182208183208184208185208186208187208188208189208190208191208192208193208194208195208196208197208198208199208200208201208202208203208204208205208206208207208208208209208210208211208212208213208214208215208216208217208218208219208220208221208222208223208224208225208226208227208228208229208230208231208232208233208234208235208236208237208238208239208240208241208242208243208244208245208246208247208248208249208250208251208252208253208254208255208256208257208258208259208260208261208262208263208264208265208266208267208268208269208270208271208272208273208274208275208276208277208278208279208280208281208282208283208284208285208286208287208288208289208290208291208292208293208294208295208296208297208298208299208300208301208302208303208304208305208306208307208308208309208310208311208312208313208314208315208316208317208318208319208320208321208322208323208324208325208326208327208328208329208330208331208332208333208334208335208336208337208338208339208340208341208342208343208344208345208346208347208348208349208350208351208352208353208354208355208356208357208358208359208360208361208362208363208364208365208366208367208368208369208370208371208372208373208374208375208376208377208378208379208380208381208382208383208384208385208386208387208388208389208390208391208392208393208394208395208396208397208398208399208400208401208402208403208404208405208406208407208408208409208410208411208412208413208414208415208416208417208418208419208420208421208422208423208424208425208426208427208428208429208430208431208432208433208434208435208436208437208438208439208440208441208442208443208444208445208446208447208448208449208450208451208452208453208454208455208456208457208458208459208460208461208462208463208464208465208466208467208468208469208470208471208472208473208474208475208476208477208478208479208480208481208482208483208484208485208486208487208488208489208490208491208492208493208494208495208496208497208498208499208500208501208502208503208504208505208506208507208508208509208510208511208512208513208514208515208516208517208518208519208520208521208522208523208524208525208526208527208528208529208530208531208532208533208534208535208536208537208538208539208540208541208542208543208544208545208546208547208548208549208550208551208552208553208554208555208556208557208558208559208560208561208562208563208564208565208566208567208568208569208570208571208572208573208574208575208576208577208578208579208580208581208582208583208584208585208586208587208588208589208590208591208592208593208594208595208596208597208598208599208600208601208602208603208604208605208606208607208608208609208610208611208612208613208614208615208616208617208618208619208620208621208622208623208624208625208626208627208628208629208630208631208632208633208634208635208636208637208638208639208640208641208642208643208644208645208646208647208648208649208650208651208652208653208654208655208656208657208658208659208660208661208662208663208664208665208666208667208668208669208670208671208672208673208674208675208676208677208678208679208680208681208682208683208684208685208686208687208688208689208690208691208692208693208694208695208696208697208698208699208700208701208702208703208704208705208706208707208708208709208710208711208712208713208714208715208716208717208718208719208720208721208722208723208724208725208726208727208728208729208730208731208732208733208734208735208736208737208738208739208740208741208742208743208744208745208746208747208748208749208750208751208752208753208754208755208756208757208758208759208760208761208762208763208764208765208766208767208768208769208770208771208772208773208774208775208776208777208778208779208780208781208782208783208784208785208786208787208788208789208790208791208792208793208794208795208796208797208798208799208800208801208802208803208804208805208806208807208808208809208810208811208812208813208814208815208816208817208818208819208820208821208822208823208824208825208826208827208828208829208830208831208832208833208834208835208836208837208838208839208840208841208842208843208844208845208846208847208848208849208850208851208852208853208854208855208856208857208858208859208860208861208862208863208864208865208866208867208868208869208870208871208872208873208874208875208876208877208878208879208880208881208882208883208884208885208886208887208888208889208890208891208892208893208894208895208896208897208898208899208900208901208902208903208904208905208906208907208908208909208910208911208912208913208914208915208916208917208918208919208920208921208922208923208924208925208926208927208928208929208930208931208932208933208934208935208936208937208938208939208940208941208942208943208944208945208946208947208948208949208950208951208952208953208954208955208956208957208958208959208960208961208962208963208964208965208966208967208968208969208970208971208972208973208974208975208976208977208978208979208980208981208982208983208984208985208986208987208988208989208990208991208992208993208994208995208996208997208998208999209000209001209002209003209004209005209006209007209008209009209010209011209012209013209014209015209016209017209018209019209020209021209022209023209024209025209026209027209028209029209030209031209032209033209034209035209036209037209038209039209040209041209042209043209044209045209046209047209048209049209050209051209052209053209054209055209056209057209058209059209060209061209062209063209064209065209066209067209068209069209070209071209072209073209074209075209076209077209078209079209080209081209082209083209084209085209086209087209088209089209090209091209092209093209094209095209096209097209098209099209100209101209102209103209104209105209106209107209108209109209110209111209112209113209114209115209116209117209118209119209120209121209122209123209124209125209126209127209128209129209130209131209132209133209134209135209136209137209138209139209140209141209142209143209144209145209146209147209148209149209150209151209152209153209154209155209156209157209158209159209160209161209162209163209164209165209166209167209168209169209170209171209172209173209174209175209176209177209178209179209180209181209182209183209184209185209186209187209188209189209190209191209192209193209194209195209196209197209198209199209200209201209202209203209204209205209206209207209208209209209210209211209212209213209214209215209216209217209218209219209220209221209222209223209224209225209226209227209228209229209230209231209232209233209234209235209236209237209238209239209240209241209242209243209244209245209246209247209248209249209250209251209252209253209254209255209256209257209258209259209260209261209262209263209264209265209266209267209268209269209270209271209272209273209274209275209276209277209278209279209280209281209282209283209284209285209286209287209288209289209290209291209292209293209294209295209296209297209298209299209300209301209302209303209304209305209306209307209308209309209310209311209312209313209314209315209316209317209318209319209320209321209322209323209324209325209326209327209328209329209330209331209332209333209334209335209336209337209338209339209340209341209342209343209344209345209346209347209348209349209350209351209352209353209354209355209356209357209358209359209360209361209362209363209364209365209366209367209368209369209370209371209372209373209374209375209376209377209378209379209380209381209382209383209384209385209386209387209388209389209390209391209392209393209394209395209396209397209398209399209400209401209402209403209404209405209406209407209408209409209410209411209412209413209414209415209416209417209418209419209420209421209422209423209424209425209426209427209428209429209430209431209432209433209434209435209436209437209438209439209440209441209442209443209444209445209446209447209448209449209450209451209452209453209454209455209456209457209458209459209460209461209462209463209464209465209466209467209468209469209470209471209472209473209474209475209476209477209478209479209480209481209482209483209484209485209486209487209488209489209490209491209492209493209494209495209496209497209498209499209500209501209502209503209504209505209506209507209508209509209510209511209512209513209514209515209516209517209518209519209520209521209522209523209524209525209526209527209528209529209530209531209532209533209534209535209536209537209538209539209540209541209542209543209544209545209546209547209548209549209550209551209552209553209554209555209556209557209558209559209560209561209562209563209564209565209566209567209568209569209570209571209572209573209574209575209576209577209578209579209580209581209582209583209584209585209586209587209588209589209590209591209592209593209594209595209596209597209598209599209600209601209602209603209604209605209606209607209608209609209610209611209612209613209614209615209616209617209618209619209620209621209622209623209624209625209626209627209628209629209630209631209632209633209634209635209636209637209638209639209640209641209642209643209644209645209646209647209648209649209650209651209652209653209654209655209656209657209658209659209660209661209662209663209664209665209666209667209668209669209670209671209672209673209674209675209676209677209678209679209680209681209682209683209684209685209686209687209688209689209690209691209692209693209694209695209696209697209698209699209700209701209702209703209704209705209706209707209708209709209710209711209712209713209714209715209716209717209718209719209720209721209722209723209724209725209726209727209728209729209730209731209732209733209734209735209736209737209738209739209740209741209742209743209744209745209746209747209748209749209750209751209752209753209754209755209756209757209758209759209760209761209762209763209764209765209766209767209768209769209770209771209772209773209774209775209776209777209778209779209780209781209782209783209784209785209786209787209788209789209790209791209792209793209794209795209796209797209798209799209800209801209802209803209804209805209806209807209808209809209810209811209812209813209814209815209816209817209818209819209820209821209822209823209824209825209826209827209828209829209830209831209832209833209834209835209836209837209838209839209840209841209842209843209844209845209846209847209848209849209850209851209852209853209854209855209856209857209858209859209860209861209862209863209864209865209866209867209868209869209870209871209872209873209874209875209876209877209878209879209880209881209882209883209884209885209886209887209888209889209890209891209892209893209894209895209896209897209898209899209900209901209902209903209904209905209906209907209908209909209910209911209912209913209914209915209916209917209918209919209920209921209922209923209924209925209926209927209928209929209930209931209932209933209934209935209936209937209938209939209940209941209942209943209944209945209946209947209948209949209950209951209952209953209954209955209956209957209958209959209960209961209962209963209964209965209966209967209968209969209970209971209972209973209974209975209976209977209978209979209980209981209982209983209984209985209986209987209988209989209990209991209992209993209994209995209996209997209998209999210000210001210002210003210004210005210006210007210008210009210010210011210012210013210014210015210016210017210018210019210020210021210022210023210024210025210026210027210028210029210030210031210032210033210034210035210036210037210038210039210040210041210042210043210044210045210046210047210048210049210050210051210052210053210054210055210056210057210058210059210060210061210062210063210064210065210066210067210068210069210070210071210072210073210074210075210076210077210078210079210080210081210082210083210084210085210086210087210088210089210090210091210092210093210094210095210096210097210098210099210100210101210102210103210104210105210106210107210108210109210110210111210112210113210114210115210116210117210118210119210120210121210122210123210124210125210126210127210128210129210130210131210132210133210134210135210136210137210138210139210140210141210142210143210144210145210146210147210148210149210150210151210152210153210154210155210156210157210158210159210160210161210162210163210164210165210166210167210168210169210170210171210172210173210174210175210176210177210178210179210180210181210182210183210184210185210186210187210188210189210190210191210192210193210194210195210196210197210198210199210200210201210202210203210204210205210206210207210208210209210210210211210212210213210214210215210216210217210218210219210220210221210222210223210224210225210226210227210228210229210230210231210232210233210234210235210236210237210238210239210240210241210242210243210244210245210246210247210248210249210250210251210252210253210254210255210256210257210258210259210260210261210262210263210264210265210266210267210268210269210270210271210272210273210274210275210276210277210278210279210280210281210282210283210284210285210286210287210288210289210290210291210292210293210294210295210296210297210298210299210300210301210302210303210304210305210306210307210308210309210310210311210312210313210314210315210316210317210318210319210320210321210322210323210324210325210326210327210328210329210330210331210332210333210334210335210336210337210338210339210340210341210342210343210344210345210346210347210348210349210350210351210352210353210354210355210356210357210358210359210360210361210362210363210364210365210366210367210368210369210370210371210372210373210374210375210376210377210378210379210380210381210382210383210384210385210386210387210388210389210390210391210392210393210394210395210396210397210398210399210400210401210402210403210404210405210406210407210408210409210410210411210412210413210414210415210416210417210418210419210420210421210422210423210424210425210426210427210428210429210430210431210432210433210434210435210436210437210438210439210440210441210442210443210444210445210446210447210448210449210450210451210452210453210454210455210456210457210458210459210460210461210462210463210464210465210466210467210468210469210470210471210472210473210474210475210476210477210478210479210480210481210482210483210484210485210486210487210488210489210490210491210492210493210494210495210496210497210498210499210500210501210502210503210504210505210506210507210508210509210510210511210512210513210514210515210516210517210518210519210520210521210522210523210524210525210526210527210528210529210530210531210532210533210534210535210536210537210538210539210540210541210542210543210544210545210546210547210548210549210550210551210552210553210554210555210556210557210558210559210560210561210562210563210564210565210566210567210568210569210570210571210572210573210574210575210576210577210578210579210580210581210582210583210584210585210586210587210588210589210590210591210592210593210594210595210596210597210598210599210600210601210602210603210604210605210606210607210608210609210610210611210612210613210614210615210616210617210618210619210620210621210622210623210624210625210626210627210628210629210630210631210632210633210634210635210636210637210638210639210640210641210642210643210644210645210646210647210648210649210650210651210652210653210654210655210656210657210658210659210660210661210662210663210664210665210666210667210668210669210670210671210672210673210674210675210676210677210678210679210680210681210682210683210684210685210686210687210688210689210690210691210692210693210694210695210696210697210698210699210700210701210702210703210704210705210706210707210708210709210710210711210712210713210714210715210716210717210718210719210720210721210722210723210724210725210726210727210728210729210730210731210732210733210734210735210736210737210738210739210740210741210742210743210744210745210746210747210748210749210750210751210752210753210754210755210756210757210758210759210760210761210762210763210764210765210766210767210768210769210770210771210772210773210774210775210776210777210778210779210780210781210782210783210784210785210786210787210788210789210790210791210792210793210794210795210796210797210798210799210800210801210802210803210804210805210806210807210808210809210810210811210812210813210814210815210816210817210818210819210820210821210822210823210824210825210826210827210828210829210830210831210832210833210834210835210836210837210838210839210840210841210842210843210844210845210846210847210848210849210850210851210852210853210854210855210856210857210858210859210860210861210862210863210864210865210866210867210868210869210870210871210872210873210874210875210876210877210878210879210880210881210882210883210884210885210886210887210888210889210890210891210892210893210894210895210896210897210898210899210900210901210902210903210904210905210906210907210908210909210910210911210912210913210914210915210916210917210918210919210920210921210922210923210924210925210926210927210928210929210930210931210932210933210934210935210936210937210938210939210940210941210942210943210944210945210946210947210948210949210950210951210952210953210954210955210956210957210958210959210960210961210962210963210964210965210966210967210968210969210970210971210972210973210974210975210976210977210978210979210980210981210982210983210984210985210986210987210988210989210990210991210992210993210994210995210996210997210998210999211000211001211002211003211004211005211006211007211008211009211010211011211012211013211014211015211016211017211018211019211020211021211022211023211024211025211026211027211028211029211030211031211032211033211034211035211036211037211038211039211040211041211042211043211044211045211046211047211048211049211050211051211052211053211054211055211056211057211058211059211060211061211062211063211064211065211066211067211068211069211070211071211072211073211074211075211076211077211078211079211080211081211082211083211084211085211086211087211088211089211090211091211092211093211094211095211096211097211098211099211100211101211102211103211104211105211106211107211108211109211110211111211112211113211114211115211116211117211118211119211120211121211122211123211124211125211126211127211128211129211130211131211132211133211134211135211136211137211138211139211140211141211142211143211144211145211146211147211148211149211150211151211152211153211154211155211156211157211158211159211160211161211162211163211164211165211166211167211168211169211170211171211172211173211174211175211176211177211178211179211180211181211182211183211184211185211186211187211188211189211190211191211192211193211194211195211196211197211198211199211200211201211202211203211204211205211206211207211208211209211210211211211212211213211214211215211216211217211218211219211220211221211222211223211224211225211226211227211228211229211230211231211232211233211234211235211236211237211238211239211240211241211242211243211244211245211246211247211248211249211250211251211252211253211254211255211256211257211258211259211260211261211262211263211264211265211266211267211268211269211270211271211272211273211274211275211276211277211278211279211280211281211282211283211284211285211286211287211288211289211290211291211292211293211294211295211296211297211298211299211300211301211302211303211304211305211306211307211308211309211310211311211312211313211314211315211316211317211318211319211320211321211322211323211324211325211326211327211328211329211330211331211332211333211334211335211336211337211338211339211340211341211342211343211344211345211346211347211348211349211350211351211352211353211354211355211356211357211358211359211360211361211362211363211364211365211366211367211368211369211370211371211372211373211374211375211376211377211378211379211380211381211382211383211384211385211386211387211388211389211390211391211392211393211394211395211396211397211398211399211400211401211402211403211404211405211406211407211408211409211410211411211412211413211414211415211416211417211418211419211420211421211422211423211424211425211426211427211428211429211430211431211432211433211434211435211436211437211438211439211440211441211442211443211444211445211446211447211448211449211450211451211452211453211454211455211456211457211458211459211460211461211462211463211464211465211466211467211468211469211470211471211472211473211474211475211476211477211478211479211480211481211482211483211484211485211486211487211488211489211490211491211492211493211494211495211496211497211498211499211500211501211502211503211504211505211506211507211508211509211510211511211512211513211514211515211516211517211518211519211520211521211522211523211524211525211526211527211528211529211530211531211532211533211534211535211536211537211538211539211540211541211542211543211544211545211546211547211548211549211550211551211552211553211554211555211556211557211558211559211560211561211562211563211564211565211566211567211568211569211570211571211572211573211574211575211576211577211578211579211580211581211582211583211584211585211586211587211588211589211590211591211592211593211594211595211596211597211598211599211600211601211602211603211604211605211606211607211608211609211610211611211612211613211614211615211616211617211618211619211620211621211622211623211624211625211626211627211628211629211630211631211632211633211634211635211636211637211638211639211640211641211642211643211644211645211646211647211648211649211650211651211652211653211654211655211656211657211658211659211660211661211662211663211664211665211666211667211668211669211670211671211672211673211674211675211676211677211678211679211680211681211682211683211684211685211686211687211688211689211690211691211692211693211694211695211696211697211698211699211700211701211702211703211704211705211706211707211708211709211710211711211712211713211714211715211716211717211718211719211720211721211722211723211724211725211726211727211728211729211730211731211732211733211734211735211736211737211738211739211740211741211742211743211744211745211746211747211748211749211750211751211752211753211754211755211756211757211758211759211760211761211762211763211764211765211766211767211768211769211770211771211772211773211774211775211776211777211778211779211780211781211782211783211784211785211786211787211788211789211790211791211792211793211794211795211796211797211798211799211800211801211802211803211804211805211806211807211808211809211810211811211812211813211814211815211816211817211818211819211820211821211822211823211824211825211826211827211828211829211830211831211832211833211834211835211836211837211838211839211840211841211842211843211844211845211846211847211848211849211850211851211852211853211854211855211856211857211858211859211860211861211862211863211864211865211866211867211868211869211870211871211872211873211874211875211876211877211878211879211880211881211882211883211884211885211886211887211888211889211890211891211892211893211894211895211896211897211898211899211900211901211902211903211904211905211906211907211908211909211910211911211912211913211914211915211916211917211918211919211920211921211922211923211924211925211926211927211928211929211930211931211932211933211934211935211936211937211938211939211940211941211942211943211944211945211946211947211948211949211950211951211952211953211954211955211956211957211958211959211960211961211962211963211964211965211966211967211968211969211970211971211972211973211974211975211976211977211978211979211980211981211982211983211984211985211986211987211988211989211990211991211992211993211994211995211996211997211998211999212000212001212002212003212004212005212006212007212008212009212010212011212012212013212014212015212016212017212018212019212020212021212022212023212024212025212026212027212028212029212030212031212032212033212034212035212036212037212038212039212040212041212042212043212044212045212046212047212048212049212050212051212052212053212054212055212056212057212058212059212060212061212062212063212064212065212066212067212068212069212070212071212072212073212074212075212076212077212078212079212080212081212082212083212084212085212086212087212088212089212090212091212092212093212094212095212096212097212098212099212100212101212102212103212104212105212106212107212108212109212110212111212112212113212114212115212116212117212118212119212120212121212122212123212124212125212126212127212128212129212130212131212132212133212134212135212136212137212138212139212140212141212142212143212144212145212146212147212148212149212150212151212152212153212154212155212156212157212158212159212160212161212162212163212164212165212166212167212168212169212170212171212172212173212174212175212176212177212178212179212180212181212182212183212184212185212186212187212188212189212190212191212192212193212194212195212196212197212198212199212200212201212202212203212204212205212206212207212208212209212210212211212212212213212214212215212216212217212218212219212220212221212222212223212224
  1. #ifndef USE_LIBSQLITE3
  2. /******************************************************************************
  3. ** This file is an amalgamation of many separate C source files from SQLite
  4. ** version 3.24.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=" CTIMEOPT_VAL(SQLITE_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_SORTER_REFERENCES
  311. "ENABLE_SORTER_REFERENCES",
  312. #endif
  313. #if SQLITE_ENABLE_SQLLOG
  314. "ENABLE_SQLLOG",
  315. #endif
  316. #if defined(SQLITE_ENABLE_STAT4)
  317. "ENABLE_STAT4",
  318. #elif defined(SQLITE_ENABLE_STAT3)
  319. "ENABLE_STAT3",
  320. #endif
  321. #if SQLITE_ENABLE_STMTVTAB
  322. "ENABLE_STMTVTAB",
  323. #endif
  324. #if SQLITE_ENABLE_STMT_SCANSTATUS
  325. "ENABLE_STMT_SCANSTATUS",
  326. #endif
  327. #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  328. "ENABLE_UNKNOWN_SQL_FUNCTION",
  329. #endif
  330. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  331. "ENABLE_UNLOCK_NOTIFY",
  332. #endif
  333. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  334. "ENABLE_UPDATE_DELETE_LIMIT",
  335. #endif
  336. #if SQLITE_ENABLE_URI_00_ERROR
  337. "ENABLE_URI_00_ERROR",
  338. #endif
  339. #if SQLITE_ENABLE_VFSTRACE
  340. "ENABLE_VFSTRACE",
  341. #endif
  342. #if SQLITE_ENABLE_WHERETRACE
  343. "ENABLE_WHERETRACE",
  344. #endif
  345. #if SQLITE_ENABLE_ZIPVFS
  346. "ENABLE_ZIPVFS",
  347. #endif
  348. #if SQLITE_EXPLAIN_ESTIMATED_ROWS
  349. "EXPLAIN_ESTIMATED_ROWS",
  350. #endif
  351. #if SQLITE_EXTRA_IFNULLROW
  352. "EXTRA_IFNULLROW",
  353. #endif
  354. #ifdef SQLITE_EXTRA_INIT
  355. "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
  356. #endif
  357. #ifdef SQLITE_EXTRA_SHUTDOWN
  358. "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
  359. #endif
  360. #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
  361. "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
  362. #endif
  363. #if SQLITE_FTS5_ENABLE_TEST_MI
  364. "FTS5_ENABLE_TEST_MI",
  365. #endif
  366. #if SQLITE_FTS5_NO_WITHOUT_ROWID
  367. "FTS5_NO_WITHOUT_ROWID",
  368. #endif
  369. #if SQLITE_HAS_CODEC
  370. "HAS_CODEC",
  371. #endif
  372. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  373. "HAVE_ISNAN",
  374. #endif
  375. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  376. "HOMEGROWN_RECURSIVE_MUTEX",
  377. #endif
  378. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  379. "IGNORE_AFP_LOCK_ERRORS",
  380. #endif
  381. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  382. "IGNORE_FLOCK_LOCK_ERRORS",
  383. #endif
  384. #if SQLITE_INLINE_MEMCPY
  385. "INLINE_MEMCPY",
  386. #endif
  387. #if SQLITE_INT64_TYPE
  388. "INT64_TYPE",
  389. #endif
  390. #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  391. "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
  392. #endif
  393. #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
  394. "LIKE_DOESNT_MATCH_BLOBS",
  395. #endif
  396. #if SQLITE_LOCK_TRACE
  397. "LOCK_TRACE",
  398. #endif
  399. #if SQLITE_LOG_CACHE_SPILL
  400. "LOG_CACHE_SPILL",
  401. #endif
  402. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  403. "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
  404. #endif
  405. #ifdef SQLITE_MAX_ATTACHED
  406. "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
  407. #endif
  408. #ifdef SQLITE_MAX_COLUMN
  409. "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
  410. #endif
  411. #ifdef SQLITE_MAX_COMPOUND_SELECT
  412. "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
  413. #endif
  414. #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
  415. "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
  416. #endif
  417. #ifdef SQLITE_MAX_EXPR_DEPTH
  418. "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
  419. #endif
  420. #ifdef SQLITE_MAX_FUNCTION_ARG
  421. "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
  422. #endif
  423. #ifdef SQLITE_MAX_LENGTH
  424. "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
  425. #endif
  426. #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
  427. "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
  428. #endif
  429. #ifdef SQLITE_MAX_MEMORY
  430. "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
  431. #endif
  432. #ifdef SQLITE_MAX_MMAP_SIZE
  433. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  434. #endif
  435. #ifdef SQLITE_MAX_MMAP_SIZE_
  436. "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
  437. #endif
  438. #ifdef SQLITE_MAX_PAGE_COUNT
  439. "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
  440. #endif
  441. #ifdef SQLITE_MAX_PAGE_SIZE
  442. "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
  443. #endif
  444. #ifdef SQLITE_MAX_SCHEMA_RETRY
  445. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  446. #endif
  447. #ifdef SQLITE_MAX_SQL_LENGTH
  448. "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
  449. #endif
  450. #ifdef SQLITE_MAX_TRIGGER_DEPTH
  451. "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
  452. #endif
  453. #ifdef SQLITE_MAX_VARIABLE_NUMBER
  454. "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
  455. #endif
  456. #ifdef SQLITE_MAX_VDBE_OP
  457. "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
  458. #endif
  459. #ifdef SQLITE_MAX_WORKER_THREADS
  460. "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
  461. #endif
  462. #if SQLITE_MEMDEBUG
  463. "MEMDEBUG",
  464. #endif
  465. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  466. "MIXED_ENDIAN_64BIT_FLOAT",
  467. #endif
  468. #if SQLITE_MMAP_READWRITE
  469. "MMAP_READWRITE",
  470. #endif
  471. #if SQLITE_MUTEX_NOOP
  472. "MUTEX_NOOP",
  473. #endif
  474. #if SQLITE_MUTEX_NREF
  475. "MUTEX_NREF",
  476. #endif
  477. #if SQLITE_MUTEX_OMIT
  478. "MUTEX_OMIT",
  479. #endif
  480. #if SQLITE_MUTEX_PTHREADS
  481. "MUTEX_PTHREADS",
  482. #endif
  483. #if SQLITE_MUTEX_W32
  484. "MUTEX_W32",
  485. #endif
  486. #if SQLITE_NEED_ERR_NAME
  487. "NEED_ERR_NAME",
  488. #endif
  489. #if SQLITE_NOINLINE
  490. "NOINLINE",
  491. #endif
  492. #if SQLITE_NO_SYNC
  493. "NO_SYNC",
  494. #endif
  495. #if SQLITE_OMIT_ALTERTABLE
  496. "OMIT_ALTERTABLE",
  497. #endif
  498. #if SQLITE_OMIT_ANALYZE
  499. "OMIT_ANALYZE",
  500. #endif
  501. #if SQLITE_OMIT_ATTACH
  502. "OMIT_ATTACH",
  503. #endif
  504. #if SQLITE_OMIT_AUTHORIZATION
  505. "OMIT_AUTHORIZATION",
  506. #endif
  507. #if SQLITE_OMIT_AUTOINCREMENT
  508. "OMIT_AUTOINCREMENT",
  509. #endif
  510. #if SQLITE_OMIT_AUTOINIT
  511. "OMIT_AUTOINIT",
  512. #endif
  513. #if SQLITE_OMIT_AUTOMATIC_INDEX
  514. "OMIT_AUTOMATIC_INDEX",
  515. #endif
  516. #if SQLITE_OMIT_AUTORESET
  517. "OMIT_AUTORESET",
  518. #endif
  519. #if SQLITE_OMIT_AUTOVACUUM
  520. "OMIT_AUTOVACUUM",
  521. #endif
  522. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  523. "OMIT_BETWEEN_OPTIMIZATION",
  524. #endif
  525. #if SQLITE_OMIT_BLOB_LITERAL
  526. "OMIT_BLOB_LITERAL",
  527. #endif
  528. #if SQLITE_OMIT_BTREECOUNT
  529. "OMIT_BTREECOUNT",
  530. #endif
  531. #if SQLITE_OMIT_CAST
  532. "OMIT_CAST",
  533. #endif
  534. #if SQLITE_OMIT_CHECK
  535. "OMIT_CHECK",
  536. #endif
  537. #if SQLITE_OMIT_COMPLETE
  538. "OMIT_COMPLETE",
  539. #endif
  540. #if SQLITE_OMIT_COMPOUND_SELECT
  541. "OMIT_COMPOUND_SELECT",
  542. #endif
  543. #if SQLITE_OMIT_CONFLICT_CLAUSE
  544. "OMIT_CONFLICT_CLAUSE",
  545. #endif
  546. #if SQLITE_OMIT_CTE
  547. "OMIT_CTE",
  548. #endif
  549. #if SQLITE_OMIT_DATETIME_FUNCS
  550. "OMIT_DATETIME_FUNCS",
  551. #endif
  552. #if SQLITE_OMIT_DECLTYPE
  553. "OMIT_DECLTYPE",
  554. #endif
  555. #if SQLITE_OMIT_DEPRECATED
  556. "OMIT_DEPRECATED",
  557. #endif
  558. #if SQLITE_OMIT_DISKIO
  559. "OMIT_DISKIO",
  560. #endif
  561. #if SQLITE_OMIT_EXPLAIN
  562. "OMIT_EXPLAIN",
  563. #endif
  564. #if SQLITE_OMIT_FLAG_PRAGMAS
  565. "OMIT_FLAG_PRAGMAS",
  566. #endif
  567. #if SQLITE_OMIT_FLOATING_POINT
  568. "OMIT_FLOATING_POINT",
  569. #endif
  570. #if SQLITE_OMIT_FOREIGN_KEY
  571. "OMIT_FOREIGN_KEY",
  572. #endif
  573. #if SQLITE_OMIT_GET_TABLE
  574. "OMIT_GET_TABLE",
  575. #endif
  576. #if SQLITE_OMIT_HEX_INTEGER
  577. "OMIT_HEX_INTEGER",
  578. #endif
  579. #if SQLITE_OMIT_INCRBLOB
  580. "OMIT_INCRBLOB",
  581. #endif
  582. #if SQLITE_OMIT_INTEGRITY_CHECK
  583. "OMIT_INTEGRITY_CHECK",
  584. #endif
  585. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  586. "OMIT_LIKE_OPTIMIZATION",
  587. #endif
  588. #if SQLITE_OMIT_LOAD_EXTENSION
  589. "OMIT_LOAD_EXTENSION",
  590. #endif
  591. #if SQLITE_OMIT_LOCALTIME
  592. "OMIT_LOCALTIME",
  593. #endif
  594. #if SQLITE_OMIT_LOOKASIDE
  595. "OMIT_LOOKASIDE",
  596. #endif
  597. #if SQLITE_OMIT_MEMORYDB
  598. "OMIT_MEMORYDB",
  599. #endif
  600. #if SQLITE_OMIT_OR_OPTIMIZATION
  601. "OMIT_OR_OPTIMIZATION",
  602. #endif
  603. #if SQLITE_OMIT_PAGER_PRAGMAS
  604. "OMIT_PAGER_PRAGMAS",
  605. #endif
  606. #if SQLITE_OMIT_PARSER_TRACE
  607. "OMIT_PARSER_TRACE",
  608. #endif
  609. #if SQLITE_OMIT_POPEN
  610. "OMIT_POPEN",
  611. #endif
  612. #if SQLITE_OMIT_PRAGMA
  613. "OMIT_PRAGMA",
  614. #endif
  615. #if SQLITE_OMIT_PROGRESS_CALLBACK
  616. "OMIT_PROGRESS_CALLBACK",
  617. #endif
  618. #if SQLITE_OMIT_QUICKBALANCE
  619. "OMIT_QUICKBALANCE",
  620. #endif
  621. #if SQLITE_OMIT_REINDEX
  622. "OMIT_REINDEX",
  623. #endif
  624. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  625. "OMIT_SCHEMA_PRAGMAS",
  626. #endif
  627. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  628. "OMIT_SCHEMA_VERSION_PRAGMAS",
  629. #endif
  630. #if SQLITE_OMIT_SHARED_CACHE
  631. "OMIT_SHARED_CACHE",
  632. #endif
  633. #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  634. "OMIT_SHUTDOWN_DIRECTORIES",
  635. #endif
  636. #if SQLITE_OMIT_SUBQUERY
  637. "OMIT_SUBQUERY",
  638. #endif
  639. #if SQLITE_OMIT_TCL_VARIABLE
  640. "OMIT_TCL_VARIABLE",
  641. #endif
  642. #if SQLITE_OMIT_TEMPDB
  643. "OMIT_TEMPDB",
  644. #endif
  645. #if SQLITE_OMIT_TEST_CONTROL
  646. "OMIT_TEST_CONTROL",
  647. #endif
  648. #if SQLITE_OMIT_TRACE
  649. "OMIT_TRACE",
  650. #endif
  651. #if SQLITE_OMIT_TRIGGER
  652. "OMIT_TRIGGER",
  653. #endif
  654. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  655. "OMIT_TRUNCATE_OPTIMIZATION",
  656. #endif
  657. #if SQLITE_OMIT_UTF16
  658. "OMIT_UTF16",
  659. #endif
  660. #if SQLITE_OMIT_VACUUM
  661. "OMIT_VACUUM",
  662. #endif
  663. #if SQLITE_OMIT_VIEW
  664. "OMIT_VIEW",
  665. #endif
  666. #if SQLITE_OMIT_VIRTUALTABLE
  667. "OMIT_VIRTUALTABLE",
  668. #endif
  669. #if SQLITE_OMIT_WAL
  670. "OMIT_WAL",
  671. #endif
  672. #if SQLITE_OMIT_WSD
  673. "OMIT_WSD",
  674. #endif
  675. #if SQLITE_OMIT_XFER_OPT
  676. "OMIT_XFER_OPT",
  677. #endif
  678. #if SQLITE_PCACHE_SEPARATE_HEADER
  679. "PCACHE_SEPARATE_HEADER",
  680. #endif
  681. #if SQLITE_PERFORMANCE_TRACE
  682. "PERFORMANCE_TRACE",
  683. #endif
  684. #if SQLITE_POWERSAFE_OVERWRITE
  685. "POWERSAFE_OVERWRITE",
  686. #endif
  687. #if SQLITE_PREFER_PROXY_LOCKING
  688. "PREFER_PROXY_LOCKING",
  689. #endif
  690. #if SQLITE_PROXY_DEBUG
  691. "PROXY_DEBUG",
  692. #endif
  693. #if SQLITE_REVERSE_UNORDERED_SELECTS
  694. "REVERSE_UNORDERED_SELECTS",
  695. #endif
  696. #if SQLITE_RTREE_INT_ONLY
  697. "RTREE_INT_ONLY",
  698. #endif
  699. #if SQLITE_SECURE_DELETE
  700. "SECURE_DELETE",
  701. #endif
  702. #if SQLITE_SMALL_STACK
  703. "SMALL_STACK",
  704. #endif
  705. #ifdef SQLITE_SORTER_PMASZ
  706. "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
  707. #endif
  708. #if SQLITE_SOUNDEX
  709. "SOUNDEX",
  710. #endif
  711. #ifdef SQLITE_STAT4_SAMPLES
  712. "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
  713. #endif
  714. #ifdef SQLITE_STMTJRNL_SPILL
  715. "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
  716. #endif
  717. #if SQLITE_SUBSTR_COMPATIBILITY
  718. "SUBSTR_COMPATIBILITY",
  719. #endif
  720. #if SQLITE_SYSTEM_MALLOC
  721. "SYSTEM_MALLOC",
  722. #endif
  723. #if SQLITE_TCL
  724. "TCL",
  725. #endif
  726. #ifdef SQLITE_TEMP_STORE
  727. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  728. #endif
  729. #if SQLITE_TEST
  730. "TEST",
  731. #endif
  732. #if defined(SQLITE_THREADSAFE)
  733. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  734. #elif defined(THREADSAFE)
  735. "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
  736. #else
  737. "THREADSAFE=1",
  738. #endif
  739. #if SQLITE_UNLINK_AFTER_CLOSE
  740. "UNLINK_AFTER_CLOSE",
  741. #endif
  742. #if SQLITE_UNTESTABLE
  743. "UNTESTABLE",
  744. #endif
  745. #if SQLITE_USER_AUTHENTICATION
  746. "USER_AUTHENTICATION",
  747. #endif
  748. #if SQLITE_USE_ALLOCA
  749. "USE_ALLOCA",
  750. #endif
  751. #if SQLITE_USE_FCNTL_TRACE
  752. "USE_FCNTL_TRACE",
  753. #endif
  754. #if SQLITE_USE_URI
  755. "USE_URI",
  756. #endif
  757. #if SQLITE_VDBE_COVERAGE
  758. "VDBE_COVERAGE",
  759. #endif
  760. #if SQLITE_WIN32_MALLOC
  761. "WIN32_MALLOC",
  762. #endif
  763. #if SQLITE_ZERO_MALLOC
  764. "ZERO_MALLOC",
  765. #endif
  766. /*
  767. ** END CODE GENERATED BY tool/mkctime.tcl
  768. */
  769. };
  770. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
  771. *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
  772. return (const char**)sqlite3azCompileOpt;
  773. }
  774. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  775. /************** End of ctime.c ***********************************************/
  776. /************** Begin file sqliteInt.h ***************************************/
  777. /*
  778. ** 2001 September 15
  779. **
  780. ** The author disclaims copyright to this source code. In place of
  781. ** a legal notice, here is a blessing:
  782. **
  783. ** May you do good and not evil.
  784. ** May you find forgiveness for yourself and forgive others.
  785. ** May you share freely, never taking more than you give.
  786. **
  787. *************************************************************************
  788. ** Internal interface definitions for SQLite.
  789. **
  790. */
  791. #ifndef SQLITEINT_H
  792. #define SQLITEINT_H
  793. /* Special Comments:
  794. **
  795. ** Some comments have special meaning to the tools that measure test
  796. ** coverage:
  797. **
  798. ** NO_TEST - The branches on this line are not
  799. ** measured by branch coverage. This is
  800. ** used on lines of code that actually
  801. ** implement parts of coverage testing.
  802. **
  803. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  804. ** and the correct answer is still obtained,
  805. ** though perhaps more slowly.
  806. **
  807. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  808. ** and the correct answer is still obtained,
  809. ** though perhaps more slowly.
  810. **
  811. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  812. ** that would be harmless and undetectable
  813. ** if it did occur.
  814. **
  815. ** In all cases, the special comment must be enclosed in the usual
  816. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  817. ** asterisks and the comment text.
  818. */
  819. /*
  820. ** Make sure the Tcl calling convention macro is defined. This macro is
  821. ** only used by test code and Tcl integration code.
  822. */
  823. #ifndef SQLITE_TCLAPI
  824. # define SQLITE_TCLAPI
  825. #endif
  826. /*
  827. ** Include the header file used to customize the compiler options for MSVC.
  828. ** This should be done first so that it can successfully prevent spurious
  829. ** compiler warnings due to subsequent content in this file and other files
  830. ** that are included by this file.
  831. */
  832. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  833. /************** Begin file msvc.h ********************************************/
  834. /*
  835. ** 2015 January 12
  836. **
  837. ** The author disclaims copyright to this source code. In place of
  838. ** a legal notice, here is a blessing:
  839. **
  840. ** May you do good and not evil.
  841. ** May you find forgiveness for yourself and forgive others.
  842. ** May you share freely, never taking more than you give.
  843. **
  844. ******************************************************************************
  845. **
  846. ** This file contains code that is specific to MSVC.
  847. */
  848. #ifndef SQLITE_MSVC_H
  849. #define SQLITE_MSVC_H
  850. #if defined(_MSC_VER)
  851. #pragma warning(disable : 4054)
  852. #pragma warning(disable : 4055)
  853. #pragma warning(disable : 4100)
  854. #pragma warning(disable : 4127)
  855. #pragma warning(disable : 4130)
  856. #pragma warning(disable : 4152)
  857. #pragma warning(disable : 4189)
  858. #pragma warning(disable : 4206)
  859. #pragma warning(disable : 4210)
  860. #pragma warning(disable : 4232)
  861. #pragma warning(disable : 4244)
  862. #pragma warning(disable : 4305)
  863. #pragma warning(disable : 4306)
  864. #pragma warning(disable : 4702)
  865. #pragma warning(disable : 4706)
  866. #endif /* defined(_MSC_VER) */
  867. #endif /* SQLITE_MSVC_H */
  868. /************** End of msvc.h ************************************************/
  869. /************** Continuing where we left off in sqliteInt.h ******************/
  870. /*
  871. ** Special setup for VxWorks
  872. */
  873. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  874. /************** Begin file vxworks.h *****************************************/
  875. /*
  876. ** 2015-03-02
  877. **
  878. ** The author disclaims copyright to this source code. In place of
  879. ** a legal notice, here is a blessing:
  880. **
  881. ** May you do good and not evil.
  882. ** May you find forgiveness for yourself and forgive others.
  883. ** May you share freely, never taking more than you give.
  884. **
  885. ******************************************************************************
  886. **
  887. ** This file contains code that is specific to Wind River's VxWorks
  888. */
  889. #if defined(__RTP__) || defined(_WRS_KERNEL)
  890. /* This is VxWorks. Set up things specially for that OS
  891. */
  892. #include <vxWorks.h>
  893. #include <pthread.h> /* amalgamator: dontcache */
  894. #define OS_VXWORKS 1
  895. #define SQLITE_OS_OTHER 0
  896. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  897. #define SQLITE_OMIT_LOAD_EXTENSION 1
  898. #define SQLITE_ENABLE_LOCKING_STYLE 0
  899. #define HAVE_UTIME 1
  900. #else
  901. /* This is not VxWorks. */
  902. #define OS_VXWORKS 0
  903. #define HAVE_FCHOWN 1
  904. #define HAVE_READLINK 1
  905. #define HAVE_LSTAT 1
  906. #endif /* defined(_WRS_KERNEL) */
  907. /************** End of vxworks.h *********************************************/
  908. /************** Continuing where we left off in sqliteInt.h ******************/
  909. /*
  910. ** These #defines should enable >2GB file support on POSIX if the
  911. ** underlying operating system supports it. If the OS lacks
  912. ** large file support, or if the OS is windows, these should be no-ops.
  913. **
  914. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  915. ** system #includes. Hence, this block of code must be the very first
  916. ** code in all source files.
  917. **
  918. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  919. ** on the compiler command line. This is necessary if you are compiling
  920. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  921. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  922. ** without this option, LFS is enable. But LFS does not exist in the kernel
  923. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  924. ** portability you should omit LFS.
  925. **
  926. ** The previous paragraph was written in 2005. (This paragraph is written
  927. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  928. ** you should probably leave LFS enabled. But some embedded platforms might
  929. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  930. **
  931. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  932. */
  933. #ifndef SQLITE_DISABLE_LFS
  934. # define _LARGE_FILE 1
  935. # ifndef _FILE_OFFSET_BITS
  936. # define _FILE_OFFSET_BITS 64
  937. # endif
  938. # define _LARGEFILE_SOURCE 1
  939. #endif
  940. /* The GCC_VERSION and MSVC_VERSION macros are used to
  941. ** conditionally include optimizations for each of these compilers. A
  942. ** value of 0 means that compiler is not being used. The
  943. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  944. ** optimizations, and hence set all compiler macros to 0
  945. **
  946. ** There was once also a CLANG_VERSION macro. However, we learn that the
  947. ** version numbers in clang are for "marketing" only and are inconsistent
  948. ** and unreliable. Fortunately, all versions of clang also recognize the
  949. ** gcc version numbers and have reasonable settings for gcc version numbers,
  950. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  951. ** when compiling with clang.
  952. */
  953. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  954. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  955. #else
  956. # define GCC_VERSION 0
  957. #endif
  958. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  959. # define MSVC_VERSION _MSC_VER
  960. #else
  961. # define MSVC_VERSION 0
  962. #endif
  963. /* Needed for various definitions... */
  964. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  965. # define _GNU_SOURCE
  966. #endif
  967. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  968. # define _BSD_SOURCE
  969. #endif
  970. /*
  971. ** For MinGW, check to see if we can include the header file containing its
  972. ** version information, among other things. Normally, this internal MinGW
  973. ** header file would [only] be included automatically by other MinGW header
  974. ** files; however, the contained version information is now required by this
  975. ** header file to work around binary compatibility issues (see below) and
  976. ** this is the only known way to reliably obtain it. This entire #if block
  977. ** would be completely unnecessary if there was any other way of detecting
  978. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  979. ** some MinGW-specific macros). When compiling for MinGW, either the
  980. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  981. ** defined; otherwise, detection of conditions specific to MinGW will be
  982. ** disabled.
  983. */
  984. #if defined(_HAVE_MINGW_H)
  985. # include "mingw.h"
  986. #elif defined(_HAVE__MINGW_H)
  987. # include "_mingw.h"
  988. #endif
  989. /*
  990. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  991. ** define is required to maintain binary compatibility with the MSVC runtime
  992. ** library in use (e.g. for Windows XP).
  993. */
  994. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  995. defined(_WIN32) && !defined(_WIN64) && \
  996. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  997. defined(__MSVCRT__)
  998. # define _USE_32BIT_TIME_T
  999. #endif
  1000. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  1001. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  1002. ** MinGW.
  1003. */
  1004. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1005. /************** Begin file sqlite3.h *****************************************/
  1006. /*
  1007. ** 2001-09-15
  1008. **
  1009. ** The author disclaims copyright to this source code. In place of
  1010. ** a legal notice, here is a blessing:
  1011. **
  1012. ** May you do good and not evil.
  1013. ** May you find forgiveness for yourself and forgive others.
  1014. ** May you share freely, never taking more than you give.
  1015. **
  1016. *************************************************************************
  1017. ** This header file defines the interface that the SQLite library
  1018. ** presents to client programs. If a C-function, structure, datatype,
  1019. ** or constant definition does not appear in this file, then it is
  1020. ** not a published API of SQLite, is subject to change without
  1021. ** notice, and should not be referenced by programs that use SQLite.
  1022. **
  1023. ** Some of the definitions that are in this file are marked as
  1024. ** "experimental". Experimental interfaces are normally new
  1025. ** features recently added to SQLite. We do not anticipate changes
  1026. ** to experimental interfaces but reserve the right to make minor changes
  1027. ** if experience from use "in the wild" suggest such changes are prudent.
  1028. **
  1029. ** The official C-language API documentation for SQLite is derived
  1030. ** from comments in this file. This file is the authoritative source
  1031. ** on how SQLite interfaces are supposed to operate.
  1032. **
  1033. ** The name of this file under configuration management is "sqlite.h.in".
  1034. ** The makefile makes some minor changes to this file (such as inserting
  1035. ** the version number) and changes its name to "sqlite3.h" as
  1036. ** part of the build process.
  1037. */
  1038. #ifndef SQLITE3_H
  1039. #define SQLITE3_H
  1040. #include <stdarg.h> /* Needed for the definition of va_list */
  1041. /*
  1042. ** Make sure we can call this stuff from C++.
  1043. */
  1044. #if 0
  1045. extern "C" {
  1046. #endif
  1047. /*
  1048. ** Provide the ability to override linkage features of the interface.
  1049. */
  1050. #ifndef SQLITE_EXTERN
  1051. # define SQLITE_EXTERN extern
  1052. #endif
  1053. #ifndef SQLITE_API
  1054. # define SQLITE_API
  1055. #endif
  1056. #ifndef SQLITE_CDECL
  1057. # define SQLITE_CDECL
  1058. #endif
  1059. #ifndef SQLITE_APICALL
  1060. # define SQLITE_APICALL
  1061. #endif
  1062. #ifndef SQLITE_STDCALL
  1063. # define SQLITE_STDCALL SQLITE_APICALL
  1064. #endif
  1065. #ifndef SQLITE_CALLBACK
  1066. # define SQLITE_CALLBACK
  1067. #endif
  1068. #ifndef SQLITE_SYSAPI
  1069. # define SQLITE_SYSAPI
  1070. #endif
  1071. /*
  1072. ** These no-op macros are used in front of interfaces to mark those
  1073. ** interfaces as either deprecated or experimental. New applications
  1074. ** should not use deprecated interfaces - they are supported for backwards
  1075. ** compatibility only. Application writers should be aware that
  1076. ** experimental interfaces are subject to change in point releases.
  1077. **
  1078. ** These macros used to resolve to various kinds of compiler magic that
  1079. ** would generate warning messages when they were used. But that
  1080. ** compiler magic ended up generating such a flurry of bug reports
  1081. ** that we have taken it all out and gone back to using simple
  1082. ** noop macros.
  1083. */
  1084. #define SQLITE_DEPRECATED
  1085. #define SQLITE_EXPERIMENTAL
  1086. /*
  1087. ** Ensure these symbols were not defined by some previous header file.
  1088. */
  1089. #ifdef SQLITE_VERSION
  1090. # undef SQLITE_VERSION
  1091. #endif
  1092. #ifdef SQLITE_VERSION_NUMBER
  1093. # undef SQLITE_VERSION_NUMBER
  1094. #endif
  1095. /*
  1096. ** CAPI3REF: Compile-Time Library Version Numbers
  1097. **
  1098. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1099. ** evaluates to a string literal that is the SQLite version in the
  1100. ** format "X.Y.Z" where X is the major version number (always 3 for
  1101. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1102. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1103. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1104. ** numbers used in [SQLITE_VERSION].)^
  1105. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1106. ** be larger than the release from which it is derived. Either Y will
  1107. ** be held constant and Z will be incremented or else Y will be incremented
  1108. ** and Z will be reset to zero.
  1109. **
  1110. ** Since [version 3.6.18] ([dateof:3.6.18]),
  1111. ** SQLite source code has been stored in the
  1112. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1113. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  1114. ** a string which identifies a particular check-in of SQLite
  1115. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  1116. ** string contains the date and time of the check-in (UTC) and a SHA1
  1117. ** or SHA3-256 hash of the entire source tree. If the source code has
  1118. ** been edited in any way since it was last checked in, then the last
  1119. ** four hexadecimal digits of the hash may be modified.
  1120. **
  1121. ** See also: [sqlite3_libversion()],
  1122. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1123. ** [sqlite_version()] and [sqlite_source_id()].
  1124. */
  1125. #define SQLITE_VERSION "3.24.0"
  1126. #define SQLITE_VERSION_NUMBER 3024000
  1127. #define SQLITE_SOURCE_ID "2018-06-04 19:24:41 c7ee0833225bfd8c5ec2f9bf62b97c4e04d03bd9566366d5221ac8fb199a87ca"
  1128. /*
  1129. ** CAPI3REF: Run-Time Library Version Numbers
  1130. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1131. **
  1132. ** These interfaces provide the same information as the [SQLITE_VERSION],
  1133. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1134. ** but are associated with the library instead of the header file. ^(Cautious
  1135. ** programmers might include assert() statements in their application to
  1136. ** verify that values returned by these interfaces match the macros in
  1137. ** the header, and thus ensure that the application is
  1138. ** compiled with matching library and header files.
  1139. **
  1140. ** <blockquote><pre>
  1141. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1142. ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1143. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1144. ** </pre></blockquote>)^
  1145. **
  1146. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1147. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  1148. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  1149. ** function is provided for use in DLLs since DLL users usually do not have
  1150. ** direct access to string constants within the DLL. ^The
  1151. ** sqlite3_libversion_number() function returns an integer equal to
  1152. ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
  1153. ** a pointer to a string constant whose value is the same as the
  1154. ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
  1155. ** using an edited copy of [the amalgamation], then the last four characters
  1156. ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1157. **
  1158. ** See also: [sqlite_version()] and [sqlite_source_id()].
  1159. */
  1160. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1161. SQLITE_API const char *sqlite3_libversion(void);
  1162. SQLITE_API const char *sqlite3_sourceid(void);
  1163. SQLITE_API int sqlite3_libversion_number(void);
  1164. /*
  1165. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1166. **
  1167. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  1168. ** indicating whether the specified option was defined at
  1169. ** compile time. ^The SQLITE_ prefix may be omitted from the
  1170. ** option name passed to sqlite3_compileoption_used().
  1171. **
  1172. ** ^The sqlite3_compileoption_get() function allows iterating
  1173. ** over the list of options that were defined at compile time by
  1174. ** returning the N-th compile time option string. ^If N is out of range,
  1175. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  1176. ** prefix is omitted from any strings returned by
  1177. ** sqlite3_compileoption_get().
  1178. **
  1179. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1180. ** and sqlite3_compileoption_get() may be omitted by specifying the
  1181. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1182. **
  1183. ** See also: SQL functions [sqlite_compileoption_used()] and
  1184. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1185. */
  1186. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1187. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1188. SQLITE_API const char *sqlite3_compileoption_get(int N);
  1189. #endif
  1190. /*
  1191. ** CAPI3REF: Test To See If The Library Is Threadsafe
  1192. **
  1193. ** ^The sqlite3_threadsafe() function returns zero if and only if
  1194. ** SQLite was compiled with mutexing code omitted due to the
  1195. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1196. **
  1197. ** SQLite can be compiled with or without mutexes. When
  1198. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1199. ** are enabled and SQLite is threadsafe. When the
  1200. ** [SQLITE_THREADSAFE] macro is 0,
  1201. ** the mutexes are omitted. Without the mutexes, it is not safe
  1202. ** to use SQLite concurrently from more than one thread.
  1203. **
  1204. ** Enabling mutexes incurs a measurable performance penalty.
  1205. ** So if speed is of utmost importance, it makes sense to disable
  1206. ** the mutexes. But for maximum safety, mutexes should be enabled.
  1207. ** ^The default behavior is for mutexes to be enabled.
  1208. **
  1209. ** This interface can be used by an application to make sure that the
  1210. ** version of SQLite that it is linking against was compiled with
  1211. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1212. **
  1213. ** This interface only reports on the compile-time mutex setting
  1214. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  1215. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1216. ** can be fully or partially disabled using a call to [sqlite3_config()]
  1217. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1218. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  1219. ** sqlite3_threadsafe() function shows only the compile-time setting of
  1220. ** thread safety, not any run-time changes to that setting made by
  1221. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1222. ** is unchanged by calls to sqlite3_config().)^
  1223. **
  1224. ** See the [threading mode] documentation for additional information.
  1225. */
  1226. SQLITE_API int sqlite3_threadsafe(void);
  1227. /*
  1228. ** CAPI3REF: Database Connection Handle
  1229. ** KEYWORDS: {database connection} {database connections}
  1230. **
  1231. ** Each open SQLite database is represented by a pointer to an instance of
  1232. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  1233. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  1234. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1235. ** and [sqlite3_close_v2()] are its destructors. There are many other
  1236. ** interfaces (such as
  1237. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1238. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1239. ** sqlite3 object.
  1240. */
  1241. typedef struct sqlite3 sqlite3;
  1242. /*
  1243. ** CAPI3REF: 64-Bit Integer Types
  1244. ** KEYWORDS: sqlite_int64 sqlite_uint64
  1245. **
  1246. ** Because there is no cross-platform way to specify 64-bit integer types
  1247. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1248. **
  1249. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1250. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1251. ** compatibility only.
  1252. **
  1253. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1254. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  1255. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  1256. ** between 0 and +18446744073709551615 inclusive.
  1257. */
  1258. #ifdef SQLITE_INT64_TYPE
  1259. typedef SQLITE_INT64_TYPE sqlite_int64;
  1260. # ifdef SQLITE_UINT64_TYPE
  1261. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1262. # else
  1263. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1264. # endif
  1265. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1266. typedef __int64 sqlite_int64;
  1267. typedef unsigned __int64 sqlite_uint64;
  1268. #else
  1269. typedef long long int sqlite_int64;
  1270. typedef unsigned long long int sqlite_uint64;
  1271. #endif
  1272. typedef sqlite_int64 sqlite3_int64;
  1273. typedef sqlite_uint64 sqlite3_uint64;
  1274. /*
  1275. ** If compiling for a processor that lacks floating point support,
  1276. ** substitute integer for floating-point.
  1277. */
  1278. #ifdef SQLITE_OMIT_FLOATING_POINT
  1279. # define double sqlite3_int64
  1280. #endif
  1281. /*
  1282. ** CAPI3REF: Closing A Database Connection
  1283. ** DESTRUCTOR: sqlite3
  1284. **
  1285. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1286. ** for the [sqlite3] object.
  1287. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1288. ** the [sqlite3] object is successfully destroyed and all associated
  1289. ** resources are deallocated.
  1290. **
  1291. ** ^If the database connection is associated with unfinalized prepared
  1292. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1293. ** will leave the database connection open and return [SQLITE_BUSY].
  1294. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1295. ** and/or unfinished sqlite3_backups, then the database connection becomes
  1296. ** an unusable "zombie" which will automatically be deallocated when the
  1297. ** last prepared statement is finalized or the last sqlite3_backup is
  1298. ** finished. The sqlite3_close_v2() interface is intended for use with
  1299. ** host languages that are garbage collected, and where the order in which
  1300. ** destructors are called is arbitrary.
  1301. **
  1302. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1303. ** [sqlite3_blob_close | close] all [BLOB handles], and
  1304. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1305. ** with the [sqlite3] object prior to attempting to close the object. ^If
  1306. ** sqlite3_close_v2() is called on a [database connection] that still has
  1307. ** outstanding [prepared statements], [BLOB handles], and/or
  1308. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1309. ** of resources is deferred until all [prepared statements], [BLOB handles],
  1310. ** and [sqlite3_backup] objects are also destroyed.
  1311. **
  1312. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1313. ** the transaction is automatically rolled back.
  1314. **
  1315. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1316. ** must be either a NULL
  1317. ** pointer or an [sqlite3] object pointer obtained
  1318. ** from [sqlite3_open()], [sqlite3_open16()], or
  1319. ** [sqlite3_open_v2()], and not previously closed.
  1320. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1321. ** argument is a harmless no-op.
  1322. */
  1323. SQLITE_API int sqlite3_close(sqlite3*);
  1324. SQLITE_API int sqlite3_close_v2(sqlite3*);
  1325. /*
  1326. ** The type for a callback function.
  1327. ** This is legacy and deprecated. It is included for historical
  1328. ** compatibility and is not documented.
  1329. */
  1330. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1331. /*
  1332. ** CAPI3REF: One-Step Query Execution Interface
  1333. ** METHOD: sqlite3
  1334. **
  1335. ** The sqlite3_exec() interface is a convenience wrapper around
  1336. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1337. ** that allows an application to run multiple statements of SQL
  1338. ** without having to use a lot of C code.
  1339. **
  1340. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1341. ** semicolon-separate SQL statements passed into its 2nd argument,
  1342. ** in the context of the [database connection] passed in as its 1st
  1343. ** argument. ^If the callback function of the 3rd argument to
  1344. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1345. ** coming out of the evaluated SQL statements. ^The 4th argument to
  1346. ** sqlite3_exec() is relayed through to the 1st argument of each
  1347. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  1348. ** is NULL, then no callback is ever invoked and result rows are
  1349. ** ignored.
  1350. **
  1351. ** ^If an error occurs while evaluating the SQL statements passed into
  1352. ** sqlite3_exec(), then execution of the current statement stops and
  1353. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  1354. ** is not NULL then any error message is written into memory obtained
  1355. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1356. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1357. ** on error message strings returned through the 5th parameter of
  1358. ** sqlite3_exec() after the error message string is no longer needed.
  1359. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1360. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1361. ** NULL before returning.
  1362. **
  1363. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1364. ** routine returns SQLITE_ABORT without invoking the callback again and
  1365. ** without running any subsequent SQL statements.
  1366. **
  1367. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1368. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  1369. ** callback is an array of pointers to strings obtained as if from
  1370. ** [sqlite3_column_text()], one for each column. ^If an element of a
  1371. ** result row is NULL then the corresponding string pointer for the
  1372. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  1373. ** sqlite3_exec() callback is an array of pointers to strings where each
  1374. ** entry represents the name of corresponding result column as obtained
  1375. ** from [sqlite3_column_name()].
  1376. **
  1377. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1378. ** to an empty string, or a pointer that contains only whitespace and/or
  1379. ** SQL comments, then no SQL statements are evaluated and the database
  1380. ** is not changed.
  1381. **
  1382. ** Restrictions:
  1383. **
  1384. ** <ul>
  1385. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1386. ** is a valid and open [database connection].
  1387. ** <li> The application must not close the [database connection] specified by
  1388. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1389. ** <li> The application must not modify the SQL statement text passed into
  1390. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1391. ** </ul>
  1392. */
  1393. SQLITE_API int sqlite3_exec(
  1394. sqlite3*, /* An open database */
  1395. const char *sql, /* SQL to be evaluated */
  1396. int (*callback)(void*,int,char**,char**), /* Callback function */
  1397. void *, /* 1st argument to callback */
  1398. char **errmsg /* Error msg written here */
  1399. );
  1400. /*
  1401. ** CAPI3REF: Result Codes
  1402. ** KEYWORDS: {result code definitions}
  1403. **
  1404. ** Many SQLite functions return an integer result code from the set shown
  1405. ** here in order to indicate success or failure.
  1406. **
  1407. ** New error codes may be added in future versions of SQLite.
  1408. **
  1409. ** See also: [extended result code definitions]
  1410. */
  1411. #define SQLITE_OK 0 /* Successful result */
  1412. /* beginning-of-error-codes */
  1413. #define SQLITE_ERROR 1 /* Generic error */
  1414. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  1415. #define SQLITE_PERM 3 /* Access permission denied */
  1416. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  1417. #define SQLITE_BUSY 5 /* The database file is locked */
  1418. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  1419. #define SQLITE_NOMEM 7 /* A malloc() failed */
  1420. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  1421. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  1422. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  1423. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  1424. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  1425. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  1426. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  1427. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  1428. #define SQLITE_EMPTY 16 /* Internal use only */
  1429. #define SQLITE_SCHEMA 17 /* The database schema changed */
  1430. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  1431. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  1432. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  1433. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  1434. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  1435. #define SQLITE_AUTH 23 /* Authorization denied */
  1436. #define SQLITE_FORMAT 24 /* Not used */
  1437. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  1438. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  1439. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  1440. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  1441. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  1442. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  1443. /* end-of-error-codes */
  1444. /*
  1445. ** CAPI3REF: Extended Result Codes
  1446. ** KEYWORDS: {extended result code definitions}
  1447. **
  1448. ** In its default configuration, SQLite API routines return one of 30 integer
  1449. ** [result codes]. However, experience has shown that many of
  1450. ** these result codes are too coarse-grained. They do not provide as
  1451. ** much information about problems as programmers might like. In an effort to
  1452. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1453. ** and later) include
  1454. ** support for additional result codes that provide more detailed information
  1455. ** about errors. These [extended result codes] are enabled or disabled
  1456. ** on a per database connection basis using the
  1457. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  1458. ** the most recent error can be obtained using
  1459. ** [sqlite3_extended_errcode()].
  1460. */
  1461. #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
  1462. #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
  1463. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  1464. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  1465. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  1466. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  1467. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  1468. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  1469. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  1470. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  1471. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  1472. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  1473. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  1474. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  1475. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  1476. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1477. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  1478. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  1479. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  1480. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  1481. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  1482. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  1483. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  1484. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  1485. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  1486. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  1487. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  1488. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  1489. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  1490. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  1491. #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
  1492. #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
  1493. #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
  1494. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  1495. #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
  1496. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  1497. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  1498. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  1499. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  1500. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  1501. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  1502. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  1503. #define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
  1504. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  1505. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  1506. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  1507. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  1508. #define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
  1509. #define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
  1510. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  1511. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1512. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1513. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1514. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1515. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1516. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1517. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1518. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1519. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1520. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  1521. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  1522. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1523. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  1524. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  1525. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  1526. /*
  1527. ** CAPI3REF: Flags For File Open Operations
  1528. **
  1529. ** These bit values are intended for use in the
  1530. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1531. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1532. */
  1533. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1534. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1535. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1536. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1537. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1538. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1539. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1540. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1541. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1542. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1543. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1544. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1545. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1546. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1547. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1548. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1549. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1550. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1551. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1552. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1553. /* Reserved: 0x00F00000 */
  1554. /*
  1555. ** CAPI3REF: Device Characteristics
  1556. **
  1557. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1558. ** object returns an integer which is a vector of these
  1559. ** bit values expressing I/O characteristics of the mass storage
  1560. ** device that holds the file that the [sqlite3_io_methods]
  1561. ** refers to.
  1562. **
  1563. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1564. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1565. ** mean that writes of blocks that are nnn bytes in size and
  1566. ** are aligned to an address which is an integer multiple of
  1567. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1568. ** that when data is appended to a file, the data is appended
  1569. ** first then the size of the file is extended, never the other
  1570. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1571. ** information is written to disk in the same order as calls
  1572. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1573. ** after reboot following a crash or power loss, the only bytes in a
  1574. ** file that were written at the application level might have changed
  1575. ** and that adjacent bytes, even bytes within the same sector are
  1576. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1577. ** flag indicates that a file cannot be deleted when open. The
  1578. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1579. ** read-only media and cannot be changed even by processes with
  1580. ** elevated privileges.
  1581. **
  1582. ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1583. ** filesystem supports doing multiple write operations atomically when those
  1584. ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1585. ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1586. */
  1587. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1588. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1589. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1590. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1591. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1592. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1593. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1594. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1595. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1596. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1597. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1598. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1599. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1600. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  1601. #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
  1602. /*
  1603. ** CAPI3REF: File Locking Levels
  1604. **
  1605. ** SQLite uses one of these integer values as the second
  1606. ** argument to calls it makes to the xLock() and xUnlock() methods
  1607. ** of an [sqlite3_io_methods] object.
  1608. */
  1609. #define SQLITE_LOCK_NONE 0
  1610. #define SQLITE_LOCK_SHARED 1
  1611. #define SQLITE_LOCK_RESERVED 2
  1612. #define SQLITE_LOCK_PENDING 3
  1613. #define SQLITE_LOCK_EXCLUSIVE 4
  1614. /*
  1615. ** CAPI3REF: Synchronization Type Flags
  1616. **
  1617. ** When SQLite invokes the xSync() method of an
  1618. ** [sqlite3_io_methods] object it uses a combination of
  1619. ** these integer values as the second argument.
  1620. **
  1621. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1622. ** sync operation only needs to flush data to mass storage. Inode
  1623. ** information need not be flushed. If the lower four bits of the flag
  1624. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1625. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1626. ** to use Mac OS X style fullsync instead of fsync().
  1627. **
  1628. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1629. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1630. ** settings. The [synchronous pragma] determines when calls to the
  1631. ** xSync VFS method occur and applies uniformly across all platforms.
  1632. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1633. ** energetic or rigorous or forceful the sync operations are and
  1634. ** only make a difference on Mac OSX for the default SQLite code.
  1635. ** (Third-party VFS implementations might also make the distinction
  1636. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1637. ** operating systems natively supported by SQLite, only Mac OSX
  1638. ** cares about the difference.)
  1639. */
  1640. #define SQLITE_SYNC_NORMAL 0x00002
  1641. #define SQLITE_SYNC_FULL 0x00003
  1642. #define SQLITE_SYNC_DATAONLY 0x00010
  1643. /*
  1644. ** CAPI3REF: OS Interface Open File Handle
  1645. **
  1646. ** An [sqlite3_file] object represents an open file in the
  1647. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1648. ** implementations will
  1649. ** want to subclass this object by appending additional fields
  1650. ** for their own use. The pMethods entry is a pointer to an
  1651. ** [sqlite3_io_methods] object that defines methods for performing
  1652. ** I/O operations on the open file.
  1653. */
  1654. typedef struct sqlite3_file sqlite3_file;
  1655. struct sqlite3_file {
  1656. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1657. };
  1658. /*
  1659. ** CAPI3REF: OS Interface File Virtual Methods Object
  1660. **
  1661. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1662. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1663. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1664. ** This object defines the methods used to perform various operations
  1665. ** against the open file represented by the [sqlite3_file] object.
  1666. **
  1667. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1668. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1669. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1670. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1671. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1672. ** to NULL.
  1673. **
  1674. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1675. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1676. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1677. ** flag may be ORed in to indicate that only the data of the file
  1678. ** and not its inode needs to be synced.
  1679. **
  1680. ** The integer values to xLock() and xUnlock() are one of
  1681. ** <ul>
  1682. ** <li> [SQLITE_LOCK_NONE],
  1683. ** <li> [SQLITE_LOCK_SHARED],
  1684. ** <li> [SQLITE_LOCK_RESERVED],
  1685. ** <li> [SQLITE_LOCK_PENDING], or
  1686. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1687. ** </ul>
  1688. ** xLock() increases the lock. xUnlock() decreases the lock.
  1689. ** The xCheckReservedLock() method checks whether any database connection,
  1690. ** either in this process or in some other process, is holding a RESERVED,
  1691. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1692. ** if such a lock exists and false otherwise.
  1693. **
  1694. ** The xFileControl() method is a generic interface that allows custom
  1695. ** VFS implementations to directly control an open file using the
  1696. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1697. ** integer opcode. The third argument is a generic pointer intended to
  1698. ** point to a structure that may contain arguments or space in which to
  1699. ** write return values. Potential uses for xFileControl() might be
  1700. ** functions to enable blocking locks with timeouts, to change the
  1701. ** locking strategy (for example to use dot-file locks), to inquire
  1702. ** about the status of a lock, or to break stale locks. The SQLite
  1703. ** core reserves all opcodes less than 100 for its own use.
  1704. ** A [file control opcodes | list of opcodes] less than 100 is available.
  1705. ** Applications that define a custom xFileControl method should use opcodes
  1706. ** greater than 100 to avoid conflicts. VFS implementations should
  1707. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1708. ** recognize.
  1709. **
  1710. ** The xSectorSize() method returns the sector size of the
  1711. ** device that underlies the file. The sector size is the
  1712. ** minimum write that can be performed without disturbing
  1713. ** other bytes in the file. The xDeviceCharacteristics()
  1714. ** method returns a bit vector describing behaviors of the
  1715. ** underlying device:
  1716. **
  1717. ** <ul>
  1718. ** <li> [SQLITE_IOCAP_ATOMIC]
  1719. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1720. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1721. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1722. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1723. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1724. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1725. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1726. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1727. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1728. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1729. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1730. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1731. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1732. ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1733. ** </ul>
  1734. **
  1735. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1736. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1737. ** mean that writes of blocks that are nnn bytes in size and
  1738. ** are aligned to an address which is an integer multiple of
  1739. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1740. ** that when data is appended to a file, the data is appended
  1741. ** first then the size of the file is extended, never the other
  1742. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1743. ** information is written to disk in the same order as calls
  1744. ** to xWrite().
  1745. **
  1746. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1747. ** in the unread portions of the buffer with zeros. A VFS that
  1748. ** fails to zero-fill short reads might seem to work. However,
  1749. ** failure to zero-fill short reads will eventually lead to
  1750. ** database corruption.
  1751. */
  1752. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1753. struct sqlite3_io_methods {
  1754. int iVersion;
  1755. int (*xClose)(sqlite3_file*);
  1756. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1757. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1758. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1759. int (*xSync)(sqlite3_file*, int flags);
  1760. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1761. int (*xLock)(sqlite3_file*, int);
  1762. int (*xUnlock)(sqlite3_file*, int);
  1763. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1764. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1765. int (*xSectorSize)(sqlite3_file*);
  1766. int (*xDeviceCharacteristics)(sqlite3_file*);
  1767. /* Methods above are valid for version 1 */
  1768. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1769. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1770. void (*xShmBarrier)(sqlite3_file*);
  1771. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1772. /* Methods above are valid for version 2 */
  1773. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1774. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1775. /* Methods above are valid for version 3 */
  1776. /* Additional methods may be added in future releases */
  1777. };
  1778. /*
  1779. ** CAPI3REF: Standard File Control Opcodes
  1780. ** KEYWORDS: {file control opcodes} {file control opcode}
  1781. **
  1782. ** These integer constants are opcodes for the xFileControl method
  1783. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1784. ** interface.
  1785. **
  1786. ** <ul>
  1787. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1788. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1789. ** opcode causes the xFileControl method to write the current state of
  1790. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1791. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1792. ** into an integer that the pArg argument points to. This capability
  1793. ** is used during testing and is only available when the SQLITE_TEST
  1794. ** compile-time option is used.
  1795. **
  1796. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1797. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1798. ** layer a hint of how large the database file will grow to be during the
  1799. ** current transaction. This hint is not guaranteed to be accurate but it
  1800. ** is often close. The underlying VFS might choose to preallocate database
  1801. ** file space based on this hint in order to help writes to the database
  1802. ** file run faster.
  1803. **
  1804. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1805. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1806. ** extends and truncates the database file in chunks of a size specified
  1807. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1808. ** point to an integer (type int) containing the new chunk-size to use
  1809. ** for the nominated database. Allocating database file space in large
  1810. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1811. ** improve performance on some systems.
  1812. **
  1813. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1814. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1815. ** to the [sqlite3_file] object associated with a particular database
  1816. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1817. **
  1818. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1819. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1820. ** to the [sqlite3_file] object associated with the journal file (either
  1821. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1822. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1823. **
  1824. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1825. ** No longer in use.
  1826. **
  1827. ** <li>[[SQLITE_FCNTL_SYNC]]
  1828. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1829. ** sent to the VFS immediately before the xSync method is invoked on a
  1830. ** database file descriptor. Or, if the xSync method is not invoked
  1831. ** because the user has configured SQLite with
  1832. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1833. ** of the xSync method. In most cases, the pointer argument passed with
  1834. ** this file-control is NULL. However, if the database file is being synced
  1835. ** as part of a multi-database commit, the argument points to a nul-terminated
  1836. ** string containing the transactions master-journal file name. VFSes that
  1837. ** do not need this signal should silently ignore this opcode. Applications
  1838. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1839. ** disrupt the operation of the specialized VFSes that do require it.
  1840. **
  1841. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1842. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1843. ** and sent to the VFS after a transaction has been committed immediately
  1844. ** but before the database is unlocked. VFSes that do not need this signal
  1845. ** should silently ignore this opcode. Applications should not call
  1846. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1847. ** operation of the specialized VFSes that do require it.
  1848. **
  1849. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1850. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1851. ** retry counts and intervals for certain disk I/O operations for the
  1852. ** windows [VFS] in order to provide robustness in the presence of
  1853. ** anti-virus programs. By default, the windows VFS will retry file read,
  1854. ** file write, and file delete operations up to 10 times, with a delay
  1855. ** of 25 milliseconds before the first retry and with the delay increasing
  1856. ** by an additional 25 milliseconds with each subsequent retry. This
  1857. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1858. ** to be adjusted. The values are changed for all database connections
  1859. ** within the same process. The argument is a pointer to an array of two
  1860. ** integers where the first integer is the new retry count and the second
  1861. ** integer is the delay. If either integer is negative, then the setting
  1862. ** is not changed but instead the prior value of that setting is written
  1863. ** into the array entry, allowing the current retry settings to be
  1864. ** interrogated. The zDbName parameter is ignored.
  1865. **
  1866. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1867. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1868. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1869. ** write ahead log and shared memory files used for transaction control
  1870. ** are automatically deleted when the latest connection to the database
  1871. ** closes. Setting persistent WAL mode causes those files to persist after
  1872. ** close. Persisting the files is useful when other processes that do not
  1873. ** have write permission on the directory containing the database file want
  1874. ** to read the database file, as the WAL and shared memory files must exist
  1875. ** in order for the database to be readable. The fourth parameter to
  1876. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1877. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1878. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1879. ** WAL persistence setting.
  1880. **
  1881. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1882. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1883. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1884. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1885. ** xDeviceCharacteristics methods. The fourth parameter to
  1886. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1887. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1888. ** mode. If the integer is -1, then it is overwritten with the current
  1889. ** zero-damage mode setting.
  1890. **
  1891. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1892. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1893. ** a write transaction to indicate that, unless it is rolled back for some
  1894. ** reason, the entire database file will be overwritten by the current
  1895. ** transaction. This is used by VACUUM operations.
  1896. **
  1897. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1898. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1899. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1900. ** final bottom-level VFS are written into memory obtained from
  1901. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1902. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1903. ** The caller is responsible for freeing the memory when done. As with
  1904. ** all file-control actions, there is no guarantee that this will actually
  1905. ** do anything. Callers should initialize the char* variable to a NULL
  1906. ** pointer in case this file-control is not implemented. This file-control
  1907. ** is intended for diagnostic use only.
  1908. **
  1909. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1910. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1911. ** [VFSes] currently in use. ^(The argument X in
  1912. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1913. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1914. ** to a pointer to the top-level VFS.)^
  1915. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1916. ** upper-most shim only.
  1917. **
  1918. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1919. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1920. ** file control is sent to the open [sqlite3_file] object corresponding
  1921. ** to the database file to which the pragma statement refers. ^The argument
  1922. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1923. ** pointers to strings (char**) in which the second element of the array
  1924. ** is the name of the pragma and the third element is the argument to the
  1925. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1926. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1927. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1928. ** or the equivalent and that string will become the result of the pragma or
  1929. ** the error message if the pragma fails. ^If the
  1930. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1931. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1932. ** file control returns [SQLITE_OK], then the parser assumes that the
  1933. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1934. ** prepared statement if result string is NULL, or that returns a copy
  1935. ** of the result string if the string is non-NULL.
  1936. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1937. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1938. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1939. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1940. ** file control occurs at the beginning of pragma statement analysis and so
  1941. ** it is able to override built-in [PRAGMA] statements.
  1942. **
  1943. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1944. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1945. ** file-control may be invoked by SQLite on the database file handle
  1946. ** shortly after it is opened in order to provide a custom VFS with access
  1947. ** to the connections busy-handler callback. The argument is of type (void **)
  1948. ** - an array of two (void *) values. The first (void *) actually points
  1949. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1950. ** busy-handler, this function should be invoked with the second (void *) in
  1951. ** the array as the only argument. If it returns non-zero, then the operation
  1952. ** should be retried. If it returns zero, the custom VFS should abandon the
  1953. ** current operation.
  1954. **
  1955. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1956. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1957. ** to have SQLite generate a
  1958. ** temporary filename using the same algorithm that is followed to generate
  1959. ** temporary filenames for TEMP tables and other internal uses. The
  1960. ** argument should be a char** which will be filled with the filename
  1961. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1962. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1963. **
  1964. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1965. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1966. ** maximum number of bytes that will be used for memory-mapped I/O.
  1967. ** The argument is a pointer to a value of type sqlite3_int64 that
  1968. ** is an advisory maximum number of bytes in the file to memory map. The
  1969. ** pointer is overwritten with the old value. The limit is not changed if
  1970. ** the value originally pointed to is negative, and so the current limit
  1971. ** can be queried by passing in a pointer to a negative number. This
  1972. ** file-control is used internally to implement [PRAGMA mmap_size].
  1973. **
  1974. ** <li>[[SQLITE_FCNTL_TRACE]]
  1975. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1976. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1977. ** This file control is used by some VFS activity tracing [shims].
  1978. ** The argument is a zero-terminated string. Higher layers in the
  1979. ** SQLite stack may generate instances of this file control if
  1980. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1981. **
  1982. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1983. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1984. ** pointer to an integer and it writes a boolean into that integer depending
  1985. ** on whether or not the file has been renamed, moved, or deleted since it
  1986. ** was first opened.
  1987. **
  1988. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  1989. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  1990. ** underlying native file handle associated with a file handle. This file
  1991. ** control interprets its argument as a pointer to a native file handle and
  1992. ** writes the resulting value there.
  1993. **
  1994. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1995. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1996. ** opcode causes the xFileControl method to swap the file handle with the one
  1997. ** pointed to by the pArg argument. This capability is used during testing
  1998. ** and only needs to be supported when SQLITE_TEST is defined.
  1999. **
  2000. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  2001. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  2002. ** be advantageous to block on the next WAL lock if the lock is not immediately
  2003. ** available. The WAL subsystem issues this signal during rare
  2004. ** circumstances in order to fix a problem with priority inversion.
  2005. ** Applications should <em>not</em> use this file-control.
  2006. **
  2007. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2008. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2009. ** VFS should return SQLITE_NOTFOUND for this opcode.
  2010. **
  2011. ** <li>[[SQLITE_FCNTL_RBU]]
  2012. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2013. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  2014. ** this opcode.
  2015. **
  2016. ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2017. ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2018. ** the file descriptor is placed in "batch write mode", which
  2019. ** means all subsequent write operations will be deferred and done
  2020. ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
  2021. ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2022. ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2023. ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2024. ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2025. ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2026. ** except for calls to the xWrite method and the xFileControl method
  2027. ** with [SQLITE_FCNTL_SIZE_HINT].
  2028. **
  2029. ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2030. ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2031. ** operations since the previous successful call to
  2032. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2033. ** This file control returns [SQLITE_OK] if and only if the writes were
  2034. ** all performed successfully and have been committed to persistent storage.
  2035. ** ^Regardless of whether or not it is successful, this file control takes
  2036. ** the file descriptor out of batch write mode so that all subsequent
  2037. ** write operations are independent.
  2038. ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2039. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2040. **
  2041. ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2042. ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2043. ** operations since the previous successful call to
  2044. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2045. ** ^This file control takes the file descriptor out of batch write mode
  2046. ** so that all subsequent write operations are independent.
  2047. ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2048. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2049. **
  2050. ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
  2051. ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
  2052. ** a file lock using the xLock or xShmLock methods of the VFS to wait
  2053. ** for up to M milliseconds before failing, where M is the single
  2054. ** unsigned integer parameter.
  2055. ** </ul>
  2056. */
  2057. #define SQLITE_FCNTL_LOCKSTATE 1
  2058. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  2059. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  2060. #define SQLITE_FCNTL_LAST_ERRNO 4
  2061. #define SQLITE_FCNTL_SIZE_HINT 5
  2062. #define SQLITE_FCNTL_CHUNK_SIZE 6
  2063. #define SQLITE_FCNTL_FILE_POINTER 7
  2064. #define SQLITE_FCNTL_SYNC_OMITTED 8
  2065. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  2066. #define SQLITE_FCNTL_PERSIST_WAL 10
  2067. #define SQLITE_FCNTL_OVERWRITE 11
  2068. #define SQLITE_FCNTL_VFSNAME 12
  2069. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  2070. #define SQLITE_FCNTL_PRAGMA 14
  2071. #define SQLITE_FCNTL_BUSYHANDLER 15
  2072. #define SQLITE_FCNTL_TEMPFILENAME 16
  2073. #define SQLITE_FCNTL_MMAP_SIZE 18
  2074. #define SQLITE_FCNTL_TRACE 19
  2075. #define SQLITE_FCNTL_HAS_MOVED 20
  2076. #define SQLITE_FCNTL_SYNC 21
  2077. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  2078. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  2079. #define SQLITE_FCNTL_WAL_BLOCK 24
  2080. #define SQLITE_FCNTL_ZIPVFS 25
  2081. #define SQLITE_FCNTL_RBU 26
  2082. #define SQLITE_FCNTL_VFS_POINTER 27
  2083. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  2084. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  2085. #define SQLITE_FCNTL_PDB 30
  2086. #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
  2087. #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
  2088. #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
  2089. #define SQLITE_FCNTL_LOCK_TIMEOUT 34
  2090. /* deprecated names */
  2091. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  2092. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  2093. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  2094. /*
  2095. ** CAPI3REF: Mutex Handle
  2096. **
  2097. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2098. ** abstract type for a mutex object. The SQLite core never looks
  2099. ** at the internal representation of an [sqlite3_mutex]. It only
  2100. ** deals with pointers to the [sqlite3_mutex] object.
  2101. **
  2102. ** Mutexes are created using [sqlite3_mutex_alloc()].
  2103. */
  2104. typedef struct sqlite3_mutex sqlite3_mutex;
  2105. /*
  2106. ** CAPI3REF: Loadable Extension Thunk
  2107. **
  2108. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2109. ** the third parameter to entry points of [loadable extensions]. This
  2110. ** structure must be typedefed in order to work around compiler warnings
  2111. ** on some platforms.
  2112. */
  2113. typedef struct sqlite3_api_routines sqlite3_api_routines;
  2114. /*
  2115. ** CAPI3REF: OS Interface Object
  2116. **
  2117. ** An instance of the sqlite3_vfs object defines the interface between
  2118. ** the SQLite core and the underlying operating system. The "vfs"
  2119. ** in the name of the object stands for "virtual file system". See
  2120. ** the [VFS | VFS documentation] for further information.
  2121. **
  2122. ** The VFS interface is sometimes extended by adding new methods onto
  2123. ** the end. Each time such an extension occurs, the iVersion field
  2124. ** is incremented. The iVersion value started out as 1 in
  2125. ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
  2126. ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
  2127. ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
  2128. ** may be appended to the sqlite3_vfs object and the iVersion value
  2129. ** may increase again in future versions of SQLite.
  2130. ** Note that the structure
  2131. ** of the sqlite3_vfs object changes in the transition from
  2132. ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
  2133. ** and yet the iVersion field was not modified.
  2134. **
  2135. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2136. ** structure used by this VFS. mxPathname is the maximum length of
  2137. ** a pathname in this VFS.
  2138. **
  2139. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2140. ** the pNext pointer. The [sqlite3_vfs_register()]
  2141. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2142. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  2143. ** searches the list. Neither the application code nor the VFS
  2144. ** implementation should use the pNext pointer.
  2145. **
  2146. ** The pNext field is the only field in the sqlite3_vfs
  2147. ** structure that SQLite will ever modify. SQLite will only access
  2148. ** or modify this field while holding a particular static mutex.
  2149. ** The application should never modify anything within the sqlite3_vfs
  2150. ** object once the object has been registered.
  2151. **
  2152. ** The zName field holds the name of the VFS module. The name must
  2153. ** be unique across all VFS modules.
  2154. **
  2155. ** [[sqlite3_vfs.xOpen]]
  2156. ** ^SQLite guarantees that the zFilename parameter to xOpen
  2157. ** is either a NULL pointer or string obtained
  2158. ** from xFullPathname() with an optional suffix added.
  2159. ** ^If a suffix is added to the zFilename parameter, it will
  2160. ** consist of a single "-" character followed by no more than
  2161. ** 11 alphanumeric and/or "-" characters.
  2162. ** ^SQLite further guarantees that
  2163. ** the string will be valid and unchanged until xClose() is
  2164. ** called. Because of the previous sentence,
  2165. ** the [sqlite3_file] can safely store a pointer to the
  2166. ** filename if it needs to remember the filename for some reason.
  2167. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2168. ** must invent its own temporary name for the file. ^Whenever the
  2169. ** xFilename parameter is NULL it will also be the case that the
  2170. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2171. **
  2172. ** The flags argument to xOpen() includes all bits set in
  2173. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  2174. ** or [sqlite3_open16()] is used, then flags includes at least
  2175. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  2176. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2177. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  2178. **
  2179. ** ^(SQLite will also add one of the following flags to the xOpen()
  2180. ** call, depending on the object being opened:
  2181. **
  2182. ** <ul>
  2183. ** <li> [SQLITE_OPEN_MAIN_DB]
  2184. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  2185. ** <li> [SQLITE_OPEN_TEMP_DB]
  2186. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  2187. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  2188. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  2189. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  2190. ** <li> [SQLITE_OPEN_WAL]
  2191. ** </ul>)^
  2192. **
  2193. ** The file I/O implementation can use the object type flags to
  2194. ** change the way it deals with files. For example, an application
  2195. ** that does not care about crash recovery or rollback might make
  2196. ** the open of a journal file a no-op. Writes to this journal would
  2197. ** also be no-ops, and any attempt to read the journal would return
  2198. ** SQLITE_IOERR. Or the implementation might recognize that a database
  2199. ** file will be doing page-aligned sector reads and writes in a random
  2200. ** order and set up its I/O subsystem accordingly.
  2201. **
  2202. ** SQLite might also add one of the following flags to the xOpen method:
  2203. **
  2204. ** <ul>
  2205. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2206. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2207. ** </ul>
  2208. **
  2209. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2210. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  2211. ** will be set for TEMP databases and their journals, transient
  2212. ** databases, and subjournals.
  2213. **
  2214. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2215. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2216. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2217. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  2218. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2219. ** be created, and that it is an error if it already exists.
  2220. ** It is <i>not</i> used to indicate the file should be opened
  2221. ** for exclusive access.
  2222. **
  2223. ** ^At least szOsFile bytes of memory are allocated by SQLite
  2224. ** to hold the [sqlite3_file] structure passed as the third
  2225. ** argument to xOpen. The xOpen method does not have to
  2226. ** allocate the structure; it should just fill it in. Note that
  2227. ** the xOpen method must set the sqlite3_file.pMethods to either
  2228. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  2229. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  2230. ** element will be valid after xOpen returns regardless of the success
  2231. ** or failure of the xOpen call.
  2232. **
  2233. ** [[sqlite3_vfs.xAccess]]
  2234. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2235. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2236. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2237. ** to test whether a file is at least readable. The file can be a
  2238. ** directory.
  2239. **
  2240. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2241. ** output buffer xFullPathname. The exact size of the output buffer
  2242. ** is also passed as a parameter to both methods. If the output buffer
  2243. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2244. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2245. ** to prevent this by setting mxPathname to a sufficiently large value.
  2246. **
  2247. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2248. ** interfaces are not strictly a part of the filesystem, but they are
  2249. ** included in the VFS structure for completeness.
  2250. ** The xRandomness() function attempts to return nBytes bytes
  2251. ** of good-quality randomness into zOut. The return value is
  2252. ** the actual number of bytes of randomness obtained.
  2253. ** The xSleep() method causes the calling thread to sleep for at
  2254. ** least the number of microseconds given. ^The xCurrentTime()
  2255. ** method returns a Julian Day Number for the current date and time as
  2256. ** a floating point value.
  2257. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2258. ** Day Number multiplied by 86400000 (the number of milliseconds in
  2259. ** a 24-hour day).
  2260. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2261. ** date and time if that method is available (if iVersion is 2 or
  2262. ** greater and the function pointer is not NULL) and will fall back
  2263. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2264. **
  2265. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2266. ** are not used by the SQLite core. These optional interfaces are provided
  2267. ** by some VFSes to facilitate testing of the VFS code. By overriding
  2268. ** system calls with functions under its control, a test program can
  2269. ** simulate faults and error conditions that would otherwise be difficult
  2270. ** or impossible to induce. The set of system calls that can be overridden
  2271. ** varies from one VFS to another, and from one version of the same VFS to the
  2272. ** next. Applications that use these interfaces must be prepared for any
  2273. ** or all of these interfaces to be NULL or for their behavior to change
  2274. ** from one release to the next. Applications must not attempt to access
  2275. ** any of these methods if the iVersion of the VFS is less than 3.
  2276. */
  2277. typedef struct sqlite3_vfs sqlite3_vfs;
  2278. typedef void (*sqlite3_syscall_ptr)(void);
  2279. struct sqlite3_vfs {
  2280. int iVersion; /* Structure version number (currently 3) */
  2281. int szOsFile; /* Size of subclassed sqlite3_file */
  2282. int mxPathname; /* Maximum file pathname length */
  2283. sqlite3_vfs *pNext; /* Next registered VFS */
  2284. const char *zName; /* Name of this virtual file system */
  2285. void *pAppData; /* Pointer to application-specific data */
  2286. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2287. int flags, int *pOutFlags);
  2288. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2289. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2290. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2291. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2292. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2293. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2294. void (*xDlClose)(sqlite3_vfs*, void*);
  2295. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2296. int (*xSleep)(sqlite3_vfs*, int microseconds);
  2297. int (*xCurrentTime)(sqlite3_vfs*, double*);
  2298. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2299. /*
  2300. ** The methods above are in version 1 of the sqlite_vfs object
  2301. ** definition. Those that follow are added in version 2 or later
  2302. */
  2303. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2304. /*
  2305. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2306. ** Those below are for version 3 and greater.
  2307. */
  2308. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2309. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2310. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2311. /*
  2312. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2313. ** New fields may be appended in future versions. The iVersion
  2314. ** value will increment whenever this happens.
  2315. */
  2316. };
  2317. /*
  2318. ** CAPI3REF: Flags for the xAccess VFS method
  2319. **
  2320. ** These integer constants can be used as the third parameter to
  2321. ** the xAccess method of an [sqlite3_vfs] object. They determine
  2322. ** what kind of permissions the xAccess method is looking for.
  2323. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2324. ** simply checks whether the file exists.
  2325. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2326. ** checks whether the named directory is both readable and writable
  2327. ** (in other words, if files can be added, removed, and renamed within
  2328. ** the directory).
  2329. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2330. ** [temp_store_directory pragma], though this could change in a future
  2331. ** release of SQLite.
  2332. ** With SQLITE_ACCESS_READ, the xAccess method
  2333. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  2334. ** currently unused, though it might be used in a future release of
  2335. ** SQLite.
  2336. */
  2337. #define SQLITE_ACCESS_EXISTS 0
  2338. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  2339. #define SQLITE_ACCESS_READ 2 /* Unused */
  2340. /*
  2341. ** CAPI3REF: Flags for the xShmLock VFS method
  2342. **
  2343. ** These integer constants define the various locking operations
  2344. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  2345. ** following are the only legal combinations of flags to the
  2346. ** xShmLock method:
  2347. **
  2348. ** <ul>
  2349. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2350. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2351. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2352. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2353. ** </ul>
  2354. **
  2355. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2356. ** was given on the corresponding lock.
  2357. **
  2358. ** The xShmLock method can transition between unlocked and SHARED or
  2359. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  2360. ** and EXCLUSIVE.
  2361. */
  2362. #define SQLITE_SHM_UNLOCK 1
  2363. #define SQLITE_SHM_LOCK 2
  2364. #define SQLITE_SHM_SHARED 4
  2365. #define SQLITE_SHM_EXCLUSIVE 8
  2366. /*
  2367. ** CAPI3REF: Maximum xShmLock index
  2368. **
  2369. ** The xShmLock method on [sqlite3_io_methods] may use values
  2370. ** between 0 and this upper bound as its "offset" argument.
  2371. ** The SQLite core will never attempt to acquire or release a
  2372. ** lock outside of this range
  2373. */
  2374. #define SQLITE_SHM_NLOCK 8
  2375. /*
  2376. ** CAPI3REF: Initialize The SQLite Library
  2377. **
  2378. ** ^The sqlite3_initialize() routine initializes the
  2379. ** SQLite library. ^The sqlite3_shutdown() routine
  2380. ** deallocates any resources that were allocated by sqlite3_initialize().
  2381. ** These routines are designed to aid in process initialization and
  2382. ** shutdown on embedded systems. Workstation applications using
  2383. ** SQLite normally do not need to invoke either of these routines.
  2384. **
  2385. ** A call to sqlite3_initialize() is an "effective" call if it is
  2386. ** the first time sqlite3_initialize() is invoked during the lifetime of
  2387. ** the process, or if it is the first time sqlite3_initialize() is invoked
  2388. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  2389. ** of sqlite3_initialize() does any initialization. All other calls
  2390. ** are harmless no-ops.)^
  2391. **
  2392. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2393. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  2394. ** an effective call to sqlite3_shutdown() does any deinitialization.
  2395. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2396. **
  2397. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2398. ** is not. The sqlite3_shutdown() interface must only be called from a
  2399. ** single thread. All open [database connections] must be closed and all
  2400. ** other SQLite resources must be deallocated prior to invoking
  2401. ** sqlite3_shutdown().
  2402. **
  2403. ** Among other things, ^sqlite3_initialize() will invoke
  2404. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  2405. ** will invoke sqlite3_os_end().
  2406. **
  2407. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2408. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2409. ** the library (perhaps it is unable to allocate a needed resource such
  2410. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2411. **
  2412. ** ^The sqlite3_initialize() routine is called internally by many other
  2413. ** SQLite interfaces so that an application usually does not need to
  2414. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  2415. ** calls sqlite3_initialize() so the SQLite library will be automatically
  2416. ** initialized when [sqlite3_open()] is called if it has not be initialized
  2417. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2418. ** compile-time option, then the automatic calls to sqlite3_initialize()
  2419. ** are omitted and the application must call sqlite3_initialize() directly
  2420. ** prior to using any other SQLite interface. For maximum portability,
  2421. ** it is recommended that applications always invoke sqlite3_initialize()
  2422. ** directly prior to using any other SQLite interface. Future releases
  2423. ** of SQLite may require this. In other words, the behavior exhibited
  2424. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2425. ** default behavior in some future release of SQLite.
  2426. **
  2427. ** The sqlite3_os_init() routine does operating-system specific
  2428. ** initialization of the SQLite library. The sqlite3_os_end()
  2429. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  2430. ** performed by these routines include allocation or deallocation
  2431. ** of static resources, initialization of global variables,
  2432. ** setting up a default [sqlite3_vfs] module, or setting up
  2433. ** a default configuration using [sqlite3_config()].
  2434. **
  2435. ** The application should never invoke either sqlite3_os_init()
  2436. ** or sqlite3_os_end() directly. The application should only invoke
  2437. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  2438. ** interface is called automatically by sqlite3_initialize() and
  2439. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  2440. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2441. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2442. ** When [custom builds | built for other platforms]
  2443. ** (using the [SQLITE_OS_OTHER=1] compile-time
  2444. ** option) the application must supply a suitable implementation for
  2445. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  2446. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2447. ** must return [SQLITE_OK] on success and some other [error code] upon
  2448. ** failure.
  2449. */
  2450. SQLITE_API int sqlite3_initialize(void);
  2451. SQLITE_API int sqlite3_shutdown(void);
  2452. SQLITE_API int sqlite3_os_init(void);
  2453. SQLITE_API int sqlite3_os_end(void);
  2454. /*
  2455. ** CAPI3REF: Configuring The SQLite Library
  2456. **
  2457. ** The sqlite3_config() interface is used to make global configuration
  2458. ** changes to SQLite in order to tune SQLite to the specific needs of
  2459. ** the application. The default configuration is recommended for most
  2460. ** applications and so this routine is usually not necessary. It is
  2461. ** provided to support rare applications with unusual needs.
  2462. **
  2463. ** <b>The sqlite3_config() interface is not threadsafe. The application
  2464. ** must ensure that no other SQLite interfaces are invoked by other
  2465. ** threads while sqlite3_config() is running.</b>
  2466. **
  2467. ** The sqlite3_config() interface
  2468. ** may only be invoked prior to library initialization using
  2469. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2470. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2471. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2472. ** Note, however, that ^sqlite3_config() can be called as part of the
  2473. ** implementation of an application-defined [sqlite3_os_init()].
  2474. **
  2475. ** The first argument to sqlite3_config() is an integer
  2476. ** [configuration option] that determines
  2477. ** what property of SQLite is to be configured. Subsequent arguments
  2478. ** vary depending on the [configuration option]
  2479. ** in the first argument.
  2480. **
  2481. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2482. ** ^If the option is unknown or SQLite is unable to set the option
  2483. ** then this routine returns a non-zero [error code].
  2484. */
  2485. SQLITE_API int sqlite3_config(int, ...);
  2486. /*
  2487. ** CAPI3REF: Configure database connections
  2488. ** METHOD: sqlite3
  2489. **
  2490. ** The sqlite3_db_config() interface is used to make configuration
  2491. ** changes to a [database connection]. The interface is similar to
  2492. ** [sqlite3_config()] except that the changes apply to a single
  2493. ** [database connection] (specified in the first argument).
  2494. **
  2495. ** The second argument to sqlite3_db_config(D,V,...) is the
  2496. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  2497. ** that indicates what aspect of the [database connection] is being configured.
  2498. ** Subsequent arguments vary depending on the configuration verb.
  2499. **
  2500. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2501. ** the call is considered successful.
  2502. */
  2503. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2504. /*
  2505. ** CAPI3REF: Memory Allocation Routines
  2506. **
  2507. ** An instance of this object defines the interface between SQLite
  2508. ** and low-level memory allocation routines.
  2509. **
  2510. ** This object is used in only one place in the SQLite interface.
  2511. ** A pointer to an instance of this object is the argument to
  2512. ** [sqlite3_config()] when the configuration option is
  2513. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  2514. ** By creating an instance of this object
  2515. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2516. ** during configuration, an application can specify an alternative
  2517. ** memory allocation subsystem for SQLite to use for all of its
  2518. ** dynamic memory needs.
  2519. **
  2520. ** Note that SQLite comes with several [built-in memory allocators]
  2521. ** that are perfectly adequate for the overwhelming majority of applications
  2522. ** and that this object is only useful to a tiny minority of applications
  2523. ** with specialized memory allocation requirements. This object is
  2524. ** also used during testing of SQLite in order to specify an alternative
  2525. ** memory allocator that simulates memory out-of-memory conditions in
  2526. ** order to verify that SQLite recovers gracefully from such
  2527. ** conditions.
  2528. **
  2529. ** The xMalloc, xRealloc, and xFree methods must work like the
  2530. ** malloc(), realloc() and free() functions from the standard C library.
  2531. ** ^SQLite guarantees that the second argument to
  2532. ** xRealloc is always a value returned by a prior call to xRoundup.
  2533. **
  2534. ** xSize should return the allocated size of a memory allocation
  2535. ** previously obtained from xMalloc or xRealloc. The allocated size
  2536. ** is always at least as big as the requested size but may be larger.
  2537. **
  2538. ** The xRoundup method returns what would be the allocated size of
  2539. ** a memory allocation given a particular requested size. Most memory
  2540. ** allocators round up memory allocations at least to the next multiple
  2541. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  2542. ** Every memory allocation request coming in through [sqlite3_malloc()]
  2543. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  2544. ** that causes the corresponding memory allocation to fail.
  2545. **
  2546. ** The xInit method initializes the memory allocator. For example,
  2547. ** it might allocate any require mutexes or initialize internal data
  2548. ** structures. The xShutdown method is invoked (indirectly) by
  2549. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2550. ** by xInit. The pAppData pointer is used as the only parameter to
  2551. ** xInit and xShutdown.
  2552. **
  2553. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2554. ** the xInit method, so the xInit method need not be threadsafe. The
  2555. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2556. ** not need to be threadsafe either. For all other methods, SQLite
  2557. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2558. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2559. ** it is by default) and so the methods are automatically serialized.
  2560. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2561. ** methods must be threadsafe or else make their own arrangements for
  2562. ** serialization.
  2563. **
  2564. ** SQLite will never invoke xInit() more than once without an intervening
  2565. ** call to xShutdown().
  2566. */
  2567. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2568. struct sqlite3_mem_methods {
  2569. void *(*xMalloc)(int); /* Memory allocation function */
  2570. void (*xFree)(void*); /* Free a prior allocation */
  2571. void *(*xRealloc)(void*,int); /* Resize an allocation */
  2572. int (*xSize)(void*); /* Return the size of an allocation */
  2573. int (*xRoundup)(int); /* Round up request size to allocation size */
  2574. int (*xInit)(void*); /* Initialize the memory allocator */
  2575. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  2576. void *pAppData; /* Argument to xInit() and xShutdown() */
  2577. };
  2578. /*
  2579. ** CAPI3REF: Configuration Options
  2580. ** KEYWORDS: {configuration option}
  2581. **
  2582. ** These constants are the available integer configuration options that
  2583. ** can be passed as the first argument to the [sqlite3_config()] interface.
  2584. **
  2585. ** New configuration options may be added in future releases of SQLite.
  2586. ** Existing configuration options might be discontinued. Applications
  2587. ** should check the return code from [sqlite3_config()] to make sure that
  2588. ** the call worked. The [sqlite3_config()] interface will return a
  2589. ** non-zero [error code] if a discontinued or unsupported configuration option
  2590. ** is invoked.
  2591. **
  2592. ** <dl>
  2593. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2594. ** <dd>There are no arguments to this option. ^This option sets the
  2595. ** [threading mode] to Single-thread. In other words, it disables
  2596. ** all mutexing and puts SQLite into a mode where it can only be used
  2597. ** by a single thread. ^If SQLite is compiled with
  2598. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2599. ** it is not possible to change the [threading mode] from its default
  2600. ** value of Single-thread and so [sqlite3_config()] will return
  2601. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2602. ** configuration option.</dd>
  2603. **
  2604. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2605. ** <dd>There are no arguments to this option. ^This option sets the
  2606. ** [threading mode] to Multi-thread. In other words, it disables
  2607. ** mutexing on [database connection] and [prepared statement] objects.
  2608. ** The application is responsible for serializing access to
  2609. ** [database connections] and [prepared statements]. But other mutexes
  2610. ** are enabled so that SQLite will be safe to use in a multi-threaded
  2611. ** environment as long as no two threads attempt to use the same
  2612. ** [database connection] at the same time. ^If SQLite is compiled with
  2613. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2614. ** it is not possible to set the Multi-thread [threading mode] and
  2615. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2616. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2617. **
  2618. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2619. ** <dd>There are no arguments to this option. ^This option sets the
  2620. ** [threading mode] to Serialized. In other words, this option enables
  2621. ** all mutexes including the recursive
  2622. ** mutexes on [database connection] and [prepared statement] objects.
  2623. ** In this mode (which is the default when SQLite is compiled with
  2624. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2625. ** to [database connections] and [prepared statements] so that the
  2626. ** application is free to use the same [database connection] or the
  2627. ** same [prepared statement] in different threads at the same time.
  2628. ** ^If SQLite is compiled with
  2629. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2630. ** it is not possible to set the Serialized [threading mode] and
  2631. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2632. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2633. **
  2634. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2635. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  2636. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2637. ** The argument specifies
  2638. ** alternative low-level memory allocation routines to be used in place of
  2639. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2640. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2641. ** before the [sqlite3_config()] call returns.</dd>
  2642. **
  2643. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2644. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2645. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2646. ** The [sqlite3_mem_methods]
  2647. ** structure is filled with the currently defined memory allocation routines.)^
  2648. ** This option can be used to overload the default memory allocation
  2649. ** routines with a wrapper that simulations memory allocation failure or
  2650. ** tracks memory usage, for example. </dd>
  2651. **
  2652. ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2653. ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2654. ** type int, interpreted as a boolean, which if true provides a hint to
  2655. ** SQLite that it should avoid large memory allocations if possible.
  2656. ** SQLite will run faster if it is free to make large memory allocations,
  2657. ** but some application might prefer to run slower in exchange for
  2658. ** guarantees about memory fragmentation that are possible if large
  2659. ** allocations are avoided. This hint is normally off.
  2660. ** </dd>
  2661. **
  2662. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2663. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2664. ** interpreted as a boolean, which enables or disables the collection of
  2665. ** memory allocation statistics. ^(When memory allocation statistics are
  2666. ** disabled, the following SQLite interfaces become non-operational:
  2667. ** <ul>
  2668. ** <li> [sqlite3_memory_used()]
  2669. ** <li> [sqlite3_memory_highwater()]
  2670. ** <li> [sqlite3_soft_heap_limit64()]
  2671. ** <li> [sqlite3_status64()]
  2672. ** </ul>)^
  2673. ** ^Memory allocation statistics are enabled by default unless SQLite is
  2674. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2675. ** allocation statistics are disabled by default.
  2676. ** </dd>
  2677. **
  2678. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2679. ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2680. ** </dd>
  2681. **
  2682. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2683. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2684. ** that SQLite can use for the database page cache with the default page
  2685. ** cache implementation.
  2686. ** This configuration option is a no-op if an application-define page
  2687. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2688. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2689. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2690. ** and the number of cache lines (N).
  2691. ** The sz argument should be the size of the largest database page
  2692. ** (a power of two between 512 and 65536) plus some extra bytes for each
  2693. ** page header. ^The number of extra bytes needed by the page header
  2694. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2695. ** ^It is harmless, apart from the wasted memory,
  2696. ** for the sz parameter to be larger than necessary. The pMem
  2697. ** argument must be either a NULL pointer or a pointer to an 8-byte
  2698. ** aligned block of memory of at least sz*N bytes, otherwise
  2699. ** subsequent behavior is undefined.
  2700. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2701. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2702. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2703. ** is exhausted.
  2704. ** ^If pMem is NULL and N is non-zero, then each database connection
  2705. ** does an initial bulk allocation for page cache memory
  2706. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2707. ** of -1024*N bytes if N is negative, . ^If additional
  2708. ** page cache memory is needed beyond what is provided by the initial
  2709. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2710. ** additional cache line. </dd>
  2711. **
  2712. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2713. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  2714. ** that SQLite will use for all of its dynamic memory allocation needs
  2715. ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2716. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2717. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2718. ** [SQLITE_ERROR] if invoked otherwise.
  2719. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2720. ** An 8-byte aligned pointer to the memory,
  2721. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2722. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2723. ** to using its default memory allocator (the system malloc() implementation),
  2724. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2725. ** memory pointer is not NULL then the alternative memory
  2726. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2727. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2728. ** boundary or subsequent behavior of SQLite will be undefined.
  2729. ** The minimum allocation size is capped at 2**12. Reasonable values
  2730. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2731. **
  2732. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2733. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2734. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2735. ** The argument specifies alternative low-level mutex routines to be used
  2736. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  2737. ** the content of the [sqlite3_mutex_methods] structure before the call to
  2738. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2739. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2740. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2741. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2742. ** return [SQLITE_ERROR].</dd>
  2743. **
  2744. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2745. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2746. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  2747. ** [sqlite3_mutex_methods]
  2748. ** structure is filled with the currently defined mutex routines.)^
  2749. ** This option can be used to overload the default mutex allocation
  2750. ** routines with a wrapper used to track mutex usage for performance
  2751. ** profiling or testing, for example. ^If SQLite is compiled with
  2752. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2753. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2754. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2755. ** return [SQLITE_ERROR].</dd>
  2756. **
  2757. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2758. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2759. ** the default size of lookaside memory on each [database connection].
  2760. ** The first argument is the
  2761. ** size of each lookaside buffer slot and the second is the number of
  2762. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  2763. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2764. ** option to [sqlite3_db_config()] can be used to change the lookaside
  2765. ** configuration on individual connections.)^ </dd>
  2766. **
  2767. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2768. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  2769. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  2770. ** the interface to a custom page cache implementation.)^
  2771. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2772. **
  2773. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2774. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2775. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  2776. ** the current page cache implementation into that object.)^ </dd>
  2777. **
  2778. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2779. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2780. ** global [error log].
  2781. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2782. ** function with a call signature of void(*)(void*,int,const char*),
  2783. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2784. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2785. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2786. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2787. ** passed through as the first parameter to the application-defined logger
  2788. ** function whenever that function is invoked. ^The second parameter to
  2789. ** the logger function is a copy of the first parameter to the corresponding
  2790. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2791. ** [extended result code]. ^The third parameter passed to the logger is
  2792. ** log message after formatting via [sqlite3_snprintf()].
  2793. ** The SQLite logging interface is not reentrant; the logger function
  2794. ** supplied by the application must not invoke any SQLite interface.
  2795. ** In a multi-threaded application, the application-defined logger
  2796. ** function must be threadsafe. </dd>
  2797. **
  2798. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2799. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2800. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2801. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2802. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2803. ** [sqlite3_open16()] or
  2804. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2805. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2806. ** connection is opened. ^If it is globally disabled, filenames are
  2807. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2808. ** database connection is opened. ^(By default, URI handling is globally
  2809. ** disabled. The default value may be changed by compiling with the
  2810. ** [SQLITE_USE_URI] symbol defined.)^
  2811. **
  2812. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2813. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2814. ** argument which is interpreted as a boolean in order to enable or disable
  2815. ** the use of covering indices for full table scans in the query optimizer.
  2816. ** ^The default setting is determined
  2817. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2818. ** if that compile-time option is omitted.
  2819. ** The ability to disable the use of covering indices for full table scans
  2820. ** is because some incorrectly coded legacy applications might malfunction
  2821. ** when the optimization is enabled. Providing the ability to
  2822. ** disable the optimization allows the older, buggy application code to work
  2823. ** without change even with newer versions of SQLite.
  2824. **
  2825. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2826. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2827. ** <dd> These options are obsolete and should not be used by new code.
  2828. ** They are retained for backwards compatibility but are now no-ops.
  2829. ** </dd>
  2830. **
  2831. ** [[SQLITE_CONFIG_SQLLOG]]
  2832. ** <dt>SQLITE_CONFIG_SQLLOG
  2833. ** <dd>This option is only available if sqlite is compiled with the
  2834. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2835. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2836. ** The second should be of type (void*). The callback is invoked by the library
  2837. ** in three separate circumstances, identified by the value passed as the
  2838. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2839. ** passed as the second argument has just been opened. The third argument
  2840. ** points to a buffer containing the name of the main database file. If the
  2841. ** fourth parameter is 1, then the SQL statement that the third parameter
  2842. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2843. ** the connection being passed as the second parameter is being closed. The
  2844. ** third parameter is passed NULL In this case. An example of using this
  2845. ** configuration option can be seen in the "test_sqllog.c" source file in
  2846. ** the canonical SQLite source tree.</dd>
  2847. **
  2848. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2849. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2850. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2851. ** that are the default mmap size limit (the default setting for
  2852. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2853. ** ^The default setting can be overridden by each database connection using
  2854. ** either the [PRAGMA mmap_size] command, or by using the
  2855. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2856. ** will be silently truncated if necessary so that it does not exceed the
  2857. ** compile-time maximum mmap size set by the
  2858. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2859. ** ^If either argument to this option is negative, then that argument is
  2860. ** changed to its compile-time default.
  2861. **
  2862. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2863. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2864. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2865. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2866. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2867. ** that specifies the maximum size of the created heap.
  2868. **
  2869. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2870. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2871. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2872. ** is a pointer to an integer and writes into that integer the number of extra
  2873. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2874. ** The amount of extra space required can change depending on the compiler,
  2875. ** target platform, and SQLite version.
  2876. **
  2877. ** [[SQLITE_CONFIG_PMASZ]]
  2878. ** <dt>SQLITE_CONFIG_PMASZ
  2879. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2880. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2881. ** sorter to that integer. The default minimum PMA Size is set by the
  2882. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2883. ** to help with sort operations when multithreaded sorting
  2884. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2885. ** to be sorted exceeds the page size times the minimum of the
  2886. ** [PRAGMA cache_size] setting and this value.
  2887. **
  2888. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2889. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2890. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2891. ** becomes the [statement journal] spill-to-disk threshold.
  2892. ** [Statement journals] are held in memory until their size (in bytes)
  2893. ** exceeds this threshold, at which point they are written to disk.
  2894. ** Or if the threshold is -1, statement journals are always held
  2895. ** exclusively in memory.
  2896. ** Since many statement journals never become large, setting the spill
  2897. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2898. ** I/O required to support statement rollback.
  2899. ** The default value for this setting is controlled by the
  2900. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2901. **
  2902. ** [[SQLITE_CONFIG_SORTERREF_SIZE]]
  2903. ** <dt>SQLITE_CONFIG_SORTERREF_SIZE
  2904. ** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
  2905. ** of type (int) - the new value of the sorter-reference size threshold.
  2906. ** Usually, when SQLite uses an external sort to order records according
  2907. ** to an ORDER BY clause, all fields required by the caller are present in the
  2908. ** sorted records. However, if SQLite determines based on the declared type
  2909. ** of a table column that its values are likely to be very large - larger
  2910. ** than the configured sorter-reference size threshold - then a reference
  2911. ** is stored in each sorted record and the required column values loaded
  2912. ** from the database as records are returned in sorted order. The default
  2913. ** value for this option is to never use this optimization. Specifying a
  2914. ** negative value for this option restores the default behaviour.
  2915. ** This option is only available if SQLite is compiled with the
  2916. ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
  2917. ** </dl>
  2918. */
  2919. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2920. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2921. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2922. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2923. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2924. #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
  2925. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2926. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2927. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2928. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2929. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2930. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2931. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2932. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2933. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2934. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2935. #define SQLITE_CONFIG_URI 17 /* int */
  2936. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2937. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2938. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2939. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2940. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2941. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2942. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2943. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2944. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  2945. #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
  2946. #define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
  2947. /*
  2948. ** CAPI3REF: Database Connection Configuration Options
  2949. **
  2950. ** These constants are the available integer configuration options that
  2951. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2952. **
  2953. ** New configuration options may be added in future releases of SQLite.
  2954. ** Existing configuration options might be discontinued. Applications
  2955. ** should check the return code from [sqlite3_db_config()] to make sure that
  2956. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2957. ** non-zero [error code] if a discontinued or unsupported configuration option
  2958. ** is invoked.
  2959. **
  2960. ** <dl>
  2961. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2962. ** <dd> ^This option takes three additional arguments that determine the
  2963. ** [lookaside memory allocator] configuration for the [database connection].
  2964. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2965. ** pointer to a memory buffer to use for lookaside memory.
  2966. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2967. ** may be NULL in which case SQLite will allocate the
  2968. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2969. ** size of each lookaside buffer slot. ^The third argument is the number of
  2970. ** slots. The size of the buffer in the first argument must be greater than
  2971. ** or equal to the product of the second and third arguments. The buffer
  2972. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2973. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2974. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2975. ** configuration for a database connection can only be changed when that
  2976. ** connection is not currently using lookaside memory, or in other words
  2977. ** when the "current value" returned by
  2978. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2979. ** Any attempt to change the lookaside memory configuration when lookaside
  2980. ** memory is in use leaves the configuration unchanged and returns
  2981. ** [SQLITE_BUSY].)^</dd>
  2982. **
  2983. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2984. ** <dd> ^This option is used to enable or disable the enforcement of
  2985. ** [foreign key constraints]. There should be two additional arguments.
  2986. ** The first argument is an integer which is 0 to disable FK enforcement,
  2987. ** positive to enable FK enforcement or negative to leave FK enforcement
  2988. ** unchanged. The second parameter is a pointer to an integer into which
  2989. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2990. ** following this call. The second parameter may be a NULL pointer, in
  2991. ** which case the FK enforcement setting is not reported back. </dd>
  2992. **
  2993. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2994. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2995. ** There should be two additional arguments.
  2996. ** The first argument is an integer which is 0 to disable triggers,
  2997. ** positive to enable triggers or negative to leave the setting unchanged.
  2998. ** The second parameter is a pointer to an integer into which
  2999. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3000. ** following this call. The second parameter may be a NULL pointer, in
  3001. ** which case the trigger setting is not reported back. </dd>
  3002. **
  3003. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3004. ** <dd> ^This option is used to enable or disable the two-argument
  3005. ** version of the [fts3_tokenizer()] function which is part of the
  3006. ** [FTS3] full-text search engine extension.
  3007. ** There should be two additional arguments.
  3008. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3009. ** positive to enable fts3_tokenizer() or negative to leave the setting
  3010. ** unchanged.
  3011. ** The second parameter is a pointer to an integer into which
  3012. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3013. ** following this call. The second parameter may be a NULL pointer, in
  3014. ** which case the new setting is not reported back. </dd>
  3015. **
  3016. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3017. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3018. ** interface independently of the [load_extension()] SQL function.
  3019. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3020. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3021. ** There should be two additional arguments.
  3022. ** When the first argument to this interface is 1, then only the C-API is
  3023. ** enabled and the SQL function remains disabled. If the first argument to
  3024. ** this interface is 0, then both the C-API and the SQL function are disabled.
  3025. ** If the first argument is -1, then no changes are made to state of either the
  3026. ** C-API or the SQL function.
  3027. ** The second parameter is a pointer to an integer into which
  3028. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3029. ** is disabled or enabled following this call. The second parameter may
  3030. ** be a NULL pointer, in which case the new setting is not reported back.
  3031. ** </dd>
  3032. **
  3033. ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3034. ** <dd> ^This option is used to change the name of the "main" database
  3035. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  3036. ** which will become the new schema name in place of "main". ^SQLite
  3037. ** does not make a copy of the new main schema name string, so the application
  3038. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3039. ** until after the database connection closes.
  3040. ** </dd>
  3041. **
  3042. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3043. ** <dd> Usually, when a database in wal mode is closed or detached from a
  3044. ** database handle, SQLite checks if this will mean that there are now no
  3045. ** connections at all to the database. If so, it performs a checkpoint
  3046. ** operation before closing the connection. This option may be used to
  3047. ** override this behaviour. The first parameter passed to this operation
  3048. ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3049. ** default) to enable them, and negative to leave the setting unchanged.
  3050. ** The second parameter is a pointer to an integer
  3051. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3052. ** have been disabled - 0 if they are not disabled, 1 if they are.
  3053. ** </dd>
  3054. **
  3055. ** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3056. ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3057. ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
  3058. ** a single SQL query statement will always use the same algorithm regardless
  3059. ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3060. ** that look at the values of bound parameters, which can make some queries
  3061. ** slower. But the QPSG has the advantage of more predictable behavior. With
  3062. ** the QPSG active, SQLite will always use the same query plan in the field as
  3063. ** was used during testing in the lab.
  3064. ** The first argument to this setting is an integer which is 0 to disable
  3065. ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3066. ** unchanged. The second parameter is a pointer to an integer into which
  3067. ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3068. ** following this call.
  3069. ** </dd>
  3070. **
  3071. ** <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3072. ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
  3073. ** include output for any operations performed by trigger programs. This
  3074. ** option is used to set or clear (the default) a flag that governs this
  3075. ** behavior. The first parameter passed to this operation is an integer -
  3076. ** positive to enable output for trigger programs, or zero to disable it,
  3077. ** or negative to leave the setting unchanged.
  3078. ** The second parameter is a pointer to an integer into which is written
  3079. ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
  3080. ** it is not disabled, 1 if it is.
  3081. ** </dd>
  3082. **
  3083. ** <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3084. ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3085. ** [VACUUM] in order to reset a database back to an empty database
  3086. ** with no schema and no content. The following process works even for
  3087. ** a badly corrupted database file:
  3088. ** <ol>
  3089. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3090. ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3091. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3092. ** </ol>
  3093. ** Because resetting a database is destructive and irreversible, the
  3094. ** process requires the use of this obscure API and multiple steps to help
  3095. ** ensure that it does not happen by accident.
  3096. ** </dd>
  3097. ** </dl>
  3098. */
  3099. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  3100. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  3101. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  3102. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  3103. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3104. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3105. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  3106. #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
  3107. #define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
  3108. #define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
  3109. #define SQLITE_DBCONFIG_MAX 1009 /* Largest DBCONFIG */
  3110. /*
  3111. ** CAPI3REF: Enable Or Disable Extended Result Codes
  3112. ** METHOD: sqlite3
  3113. **
  3114. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3115. ** [extended result codes] feature of SQLite. ^The extended result
  3116. ** codes are disabled by default for historical compatibility.
  3117. */
  3118. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3119. /*
  3120. ** CAPI3REF: Last Insert Rowid
  3121. ** METHOD: sqlite3
  3122. **
  3123. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3124. ** has a unique 64-bit signed
  3125. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3126. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3127. ** names are not also used by explicitly declared columns. ^If
  3128. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3129. ** is another alias for the rowid.
  3130. **
  3131. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3132. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3133. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3134. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  3135. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  3136. ** zero.
  3137. **
  3138. ** As well as being set automatically as rows are inserted into database
  3139. ** tables, the value returned by this function may be set explicitly by
  3140. ** [sqlite3_set_last_insert_rowid()]
  3141. **
  3142. ** Some virtual table implementations may INSERT rows into rowid tables as
  3143. ** part of committing a transaction (e.g. to flush data accumulated in memory
  3144. ** to disk). In this case subsequent calls to this function return the rowid
  3145. ** associated with these internal INSERT operations, which leads to
  3146. ** unintuitive results. Virtual table implementations that do write to rowid
  3147. ** tables in this way can avoid this problem by restoring the original
  3148. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  3149. ** control to the user.
  3150. **
  3151. ** ^(If an [INSERT] occurs within a trigger then this routine will
  3152. ** return the [rowid] of the inserted row as long as the trigger is
  3153. ** running. Once the trigger program ends, the value returned
  3154. ** by this routine reverts to what it was before the trigger was fired.)^
  3155. **
  3156. ** ^An [INSERT] that fails due to a constraint violation is not a
  3157. ** successful [INSERT] and does not change the value returned by this
  3158. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3159. ** and INSERT OR ABORT make no changes to the return value of this
  3160. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  3161. ** encounters a constraint violation, it does not fail. The
  3162. ** INSERT continues to completion after deleting rows that caused
  3163. ** the constraint problem so INSERT OR REPLACE will always change
  3164. ** the return value of this interface.)^
  3165. **
  3166. ** ^For the purposes of this routine, an [INSERT] is considered to
  3167. ** be successful even if it is subsequently rolled back.
  3168. **
  3169. ** This function is accessible to SQL statements via the
  3170. ** [last_insert_rowid() SQL function].
  3171. **
  3172. ** If a separate thread performs a new [INSERT] on the same
  3173. ** database connection while the [sqlite3_last_insert_rowid()]
  3174. ** function is running and thus changes the last insert [rowid],
  3175. ** then the value returned by [sqlite3_last_insert_rowid()] is
  3176. ** unpredictable and might not equal either the old or the new
  3177. ** last insert [rowid].
  3178. */
  3179. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3180. /*
  3181. ** CAPI3REF: Set the Last Insert Rowid value.
  3182. ** METHOD: sqlite3
  3183. **
  3184. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3185. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  3186. ** without inserting a row into the database.
  3187. */
  3188. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3189. /*
  3190. ** CAPI3REF: Count The Number Of Rows Modified
  3191. ** METHOD: sqlite3
  3192. **
  3193. ** ^This function returns the number of rows modified, inserted or
  3194. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3195. ** statement on the database connection specified by the only parameter.
  3196. ** ^Executing any other type of SQL statement does not modify the value
  3197. ** returned by this function.
  3198. **
  3199. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3200. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  3201. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3202. **
  3203. ** Changes to a view that are intercepted by
  3204. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  3205. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  3206. ** DELETE statement run on a view is always zero. Only changes made to real
  3207. ** tables are counted.
  3208. **
  3209. ** Things are more complicated if the sqlite3_changes() function is
  3210. ** executed while a trigger program is running. This may happen if the
  3211. ** program uses the [changes() SQL function], or if some other callback
  3212. ** function invokes sqlite3_changes() directly. Essentially:
  3213. **
  3214. ** <ul>
  3215. ** <li> ^(Before entering a trigger program the value returned by
  3216. ** sqlite3_changes() function is saved. After the trigger program
  3217. ** has finished, the original value is restored.)^
  3218. **
  3219. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  3220. ** statement sets the value returned by sqlite3_changes()
  3221. ** upon completion as normal. Of course, this value will not include
  3222. ** any changes performed by sub-triggers, as the sqlite3_changes()
  3223. ** value will be saved and restored after each sub-trigger has run.)^
  3224. ** </ul>
  3225. **
  3226. ** ^This means that if the changes() SQL function (or similar) is used
  3227. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  3228. ** returns the value as set when the calling statement began executing.
  3229. ** ^If it is used by the second or subsequent such statement within a trigger
  3230. ** program, the value returned reflects the number of rows modified by the
  3231. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3232. **
  3233. ** See also the [sqlite3_total_changes()] interface, the
  3234. ** [count_changes pragma], and the [changes() SQL function].
  3235. **
  3236. ** If a separate thread makes changes on the same database connection
  3237. ** while [sqlite3_changes()] is running then the value returned
  3238. ** is unpredictable and not meaningful.
  3239. */
  3240. SQLITE_API int sqlite3_changes(sqlite3*);
  3241. /*
  3242. ** CAPI3REF: Total Number Of Rows Modified
  3243. ** METHOD: sqlite3
  3244. **
  3245. ** ^This function returns the total number of rows inserted, modified or
  3246. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3247. ** since the database connection was opened, including those executed as
  3248. ** part of trigger programs. ^Executing any other type of SQL statement
  3249. ** does not affect the value returned by sqlite3_total_changes().
  3250. **
  3251. ** ^Changes made as part of [foreign key actions] are included in the
  3252. ** count, but those made as part of REPLACE constraint resolution are
  3253. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  3254. ** are not counted.
  3255. **
  3256. ** See also the [sqlite3_changes()] interface, the
  3257. ** [count_changes pragma], and the [total_changes() SQL function].
  3258. **
  3259. ** If a separate thread makes changes on the same database connection
  3260. ** while [sqlite3_total_changes()] is running then the value
  3261. ** returned is unpredictable and not meaningful.
  3262. */
  3263. SQLITE_API int sqlite3_total_changes(sqlite3*);
  3264. /*
  3265. ** CAPI3REF: Interrupt A Long-Running Query
  3266. ** METHOD: sqlite3
  3267. **
  3268. ** ^This function causes any pending database operation to abort and
  3269. ** return at its earliest opportunity. This routine is typically
  3270. ** called in response to a user action such as pressing "Cancel"
  3271. ** or Ctrl-C where the user wants a long query operation to halt
  3272. ** immediately.
  3273. **
  3274. ** ^It is safe to call this routine from a thread different from the
  3275. ** thread that is currently running the database operation. But it
  3276. ** is not safe to call this routine with a [database connection] that
  3277. ** is closed or might close before sqlite3_interrupt() returns.
  3278. **
  3279. ** ^If an SQL operation is very nearly finished at the time when
  3280. ** sqlite3_interrupt() is called, then it might not have an opportunity
  3281. ** to be interrupted and might continue to completion.
  3282. **
  3283. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3284. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3285. ** that is inside an explicit transaction, then the entire transaction
  3286. ** will be rolled back automatically.
  3287. **
  3288. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3289. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  3290. ** that are started after the sqlite3_interrupt() call and before the
  3291. ** running statements reaches zero are interrupted as if they had been
  3292. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  3293. ** that are started after the running statement count reaches zero are
  3294. ** not effected by the sqlite3_interrupt().
  3295. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3296. ** SQL statements is a no-op and has no effect on SQL statements
  3297. ** that are started after the sqlite3_interrupt() call returns.
  3298. */
  3299. SQLITE_API void sqlite3_interrupt(sqlite3*);
  3300. /*
  3301. ** CAPI3REF: Determine If An SQL Statement Is Complete
  3302. **
  3303. ** These routines are useful during command-line input to determine if the
  3304. ** currently entered text seems to form a complete SQL statement or
  3305. ** if additional input is needed before sending the text into
  3306. ** SQLite for parsing. ^These routines return 1 if the input string
  3307. ** appears to be a complete SQL statement. ^A statement is judged to be
  3308. ** complete if it ends with a semicolon token and is not a prefix of a
  3309. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  3310. ** string literals or quoted identifier names or comments are not
  3311. ** independent tokens (they are part of the token in which they are
  3312. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  3313. ** and comments that follow the final semicolon are ignored.
  3314. **
  3315. ** ^These routines return 0 if the statement is incomplete. ^If a
  3316. ** memory allocation fails, then SQLITE_NOMEM is returned.
  3317. **
  3318. ** ^These routines do not parse the SQL statements thus
  3319. ** will not detect syntactically incorrect SQL.
  3320. **
  3321. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  3322. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3323. ** automatically by sqlite3_complete16(). If that initialization fails,
  3324. ** then the return value from sqlite3_complete16() will be non-zero
  3325. ** regardless of whether or not the input SQL is complete.)^
  3326. **
  3327. ** The input to [sqlite3_complete()] must be a zero-terminated
  3328. ** UTF-8 string.
  3329. **
  3330. ** The input to [sqlite3_complete16()] must be a zero-terminated
  3331. ** UTF-16 string in native byte order.
  3332. */
  3333. SQLITE_API int sqlite3_complete(const char *sql);
  3334. SQLITE_API int sqlite3_complete16(const void *sql);
  3335. /*
  3336. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3337. ** KEYWORDS: {busy-handler callback} {busy handler}
  3338. ** METHOD: sqlite3
  3339. **
  3340. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3341. ** that might be invoked with argument P whenever
  3342. ** an attempt is made to access a database table associated with
  3343. ** [database connection] D when another thread
  3344. ** or process has the table locked.
  3345. ** The sqlite3_busy_handler() interface is used to implement
  3346. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3347. **
  3348. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3349. ** is returned immediately upon encountering the lock. ^If the busy callback
  3350. ** is not NULL, then the callback might be invoked with two arguments.
  3351. **
  3352. ** ^The first argument to the busy handler is a copy of the void* pointer which
  3353. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  3354. ** the busy handler callback is the number of times that the busy handler has
  3355. ** been invoked previously for the same locking event. ^If the
  3356. ** busy callback returns 0, then no additional attempts are made to
  3357. ** access the database and [SQLITE_BUSY] is returned
  3358. ** to the application.
  3359. ** ^If the callback returns non-zero, then another attempt
  3360. ** is made to access the database and the cycle repeats.
  3361. **
  3362. ** The presence of a busy handler does not guarantee that it will be invoked
  3363. ** when there is lock contention. ^If SQLite determines that invoking the busy
  3364. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3365. ** to the application instead of invoking the
  3366. ** busy handler.
  3367. ** Consider a scenario where one process is holding a read lock that
  3368. ** it is trying to promote to a reserved lock and
  3369. ** a second process is holding a reserved lock that it is trying
  3370. ** to promote to an exclusive lock. The first process cannot proceed
  3371. ** because it is blocked by the second and the second process cannot
  3372. ** proceed because it is blocked by the first. If both processes
  3373. ** invoke the busy handlers, neither will make any progress. Therefore,
  3374. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3375. ** will induce the first process to release its read lock and allow
  3376. ** the second process to proceed.
  3377. **
  3378. ** ^The default busy callback is NULL.
  3379. **
  3380. ** ^(There can only be a single busy handler defined for each
  3381. ** [database connection]. Setting a new busy handler clears any
  3382. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  3383. ** or evaluating [PRAGMA busy_timeout=N] will change the
  3384. ** busy handler and thus clear any previously set busy handler.
  3385. **
  3386. ** The busy callback should not take any actions which modify the
  3387. ** database connection that invoked the busy handler. In other words,
  3388. ** the busy handler is not reentrant. Any such actions
  3389. ** result in undefined behavior.
  3390. **
  3391. ** A busy handler must not close the database connection
  3392. ** or [prepared statement] that invoked the busy handler.
  3393. */
  3394. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3395. /*
  3396. ** CAPI3REF: Set A Busy Timeout
  3397. ** METHOD: sqlite3
  3398. **
  3399. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3400. ** for a specified amount of time when a table is locked. ^The handler
  3401. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3402. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  3403. ** the handler returns 0 which causes [sqlite3_step()] to return
  3404. ** [SQLITE_BUSY].
  3405. **
  3406. ** ^Calling this routine with an argument less than or equal to zero
  3407. ** turns off all busy handlers.
  3408. **
  3409. ** ^(There can only be a single busy handler for a particular
  3410. ** [database connection] at any given moment. If another busy handler
  3411. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  3412. ** this routine, that other busy handler is cleared.)^
  3413. **
  3414. ** See also: [PRAGMA busy_timeout]
  3415. */
  3416. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3417. /*
  3418. ** CAPI3REF: Convenience Routines For Running Queries
  3419. ** METHOD: sqlite3
  3420. **
  3421. ** This is a legacy interface that is preserved for backwards compatibility.
  3422. ** Use of this interface is not recommended.
  3423. **
  3424. ** Definition: A <b>result table</b> is memory data structure created by the
  3425. ** [sqlite3_get_table()] interface. A result table records the
  3426. ** complete query results from one or more queries.
  3427. **
  3428. ** The table conceptually has a number of rows and columns. But
  3429. ** these numbers are not part of the result table itself. These
  3430. ** numbers are obtained separately. Let N be the number of rows
  3431. ** and M be the number of columns.
  3432. **
  3433. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3434. ** There are (N+1)*M elements in the array. The first M pointers point
  3435. ** to zero-terminated strings that contain the names of the columns.
  3436. ** The remaining entries all point to query results. NULL values result
  3437. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  3438. ** string representation as returned by [sqlite3_column_text()].
  3439. **
  3440. ** A result table might consist of one or more memory allocations.
  3441. ** It is not safe to pass a result table directly to [sqlite3_free()].
  3442. ** A result table should be deallocated using [sqlite3_free_table()].
  3443. **
  3444. ** ^(As an example of the result table format, suppose a query result
  3445. ** is as follows:
  3446. **
  3447. ** <blockquote><pre>
  3448. ** Name | Age
  3449. ** -----------------------
  3450. ** Alice | 43
  3451. ** Bob | 28
  3452. ** Cindy | 21
  3453. ** </pre></blockquote>
  3454. **
  3455. ** There are two column (M==2) and three rows (N==3). Thus the
  3456. ** result table has 8 entries. Suppose the result table is stored
  3457. ** in an array names azResult. Then azResult holds this content:
  3458. **
  3459. ** <blockquote><pre>
  3460. ** azResult&#91;0] = "Name";
  3461. ** azResult&#91;1] = "Age";
  3462. ** azResult&#91;2] = "Alice";
  3463. ** azResult&#91;3] = "43";
  3464. ** azResult&#91;4] = "Bob";
  3465. ** azResult&#91;5] = "28";
  3466. ** azResult&#91;6] = "Cindy";
  3467. ** azResult&#91;7] = "21";
  3468. ** </pre></blockquote>)^
  3469. **
  3470. ** ^The sqlite3_get_table() function evaluates one or more
  3471. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3472. ** string of its 2nd parameter and returns a result table to the
  3473. ** pointer given in its 3rd parameter.
  3474. **
  3475. ** After the application has finished with the result from sqlite3_get_table(),
  3476. ** it must pass the result table pointer to sqlite3_free_table() in order to
  3477. ** release the memory that was malloced. Because of the way the
  3478. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3479. ** function must not try to call [sqlite3_free()] directly. Only
  3480. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3481. **
  3482. ** The sqlite3_get_table() interface is implemented as a wrapper around
  3483. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  3484. ** to any internal data structures of SQLite. It uses only the public
  3485. ** interface defined here. As a consequence, errors that occur in the
  3486. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3487. ** reflected in subsequent calls to [sqlite3_errcode()] or
  3488. ** [sqlite3_errmsg()].
  3489. */
  3490. SQLITE_API int sqlite3_get_table(
  3491. sqlite3 *db, /* An open database */
  3492. const char *zSql, /* SQL to be evaluated */
  3493. char ***pazResult, /* Results of the query */
  3494. int *pnRow, /* Number of result rows written here */
  3495. int *pnColumn, /* Number of result columns written here */
  3496. char **pzErrmsg /* Error msg written here */
  3497. );
  3498. SQLITE_API void sqlite3_free_table(char **result);
  3499. /*
  3500. ** CAPI3REF: Formatted String Printing Functions
  3501. **
  3502. ** These routines are work-alikes of the "printf()" family of functions
  3503. ** from the standard C library.
  3504. ** These routines understand most of the common formatting options from
  3505. ** the standard library printf()
  3506. ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
  3507. ** See the [built-in printf()] documentation for details.
  3508. **
  3509. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3510. ** results into memory obtained from [sqlite3_malloc64()].
  3511. ** The strings returned by these two routines should be
  3512. ** released by [sqlite3_free()]. ^Both routines return a
  3513. ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
  3514. ** memory to hold the resulting string.
  3515. **
  3516. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3517. ** the standard C library. The result is written into the
  3518. ** buffer supplied as the second parameter whose size is given by
  3519. ** the first parameter. Note that the order of the
  3520. ** first two parameters is reversed from snprintf().)^ This is an
  3521. ** historical accident that cannot be fixed without breaking
  3522. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  3523. ** returns a pointer to its buffer instead of the number of
  3524. ** characters actually written into the buffer.)^ We admit that
  3525. ** the number of characters written would be a more useful return
  3526. ** value but we cannot change the implementation of sqlite3_snprintf()
  3527. ** now without breaking compatibility.
  3528. **
  3529. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3530. ** guarantees that the buffer is always zero-terminated. ^The first
  3531. ** parameter "n" is the total size of the buffer, including space for
  3532. ** the zero terminator. So the longest string that can be completely
  3533. ** written will be n-1 characters.
  3534. **
  3535. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3536. **
  3537. ** See also: [built-in printf()], [printf() SQL function]
  3538. */
  3539. SQLITE_API char *sqlite3_mprintf(const char*,...);
  3540. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3541. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3542. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3543. /*
  3544. ** CAPI3REF: Memory Allocation Subsystem
  3545. **
  3546. ** The SQLite core uses these three routines for all of its own
  3547. ** internal memory allocation needs. "Core" in the previous sentence
  3548. ** does not include operating-system specific VFS implementation. The
  3549. ** Windows VFS uses native malloc() and free() for some operations.
  3550. **
  3551. ** ^The sqlite3_malloc() routine returns a pointer to a block
  3552. ** of memory at least N bytes in length, where N is the parameter.
  3553. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3554. ** memory, it returns a NULL pointer. ^If the parameter N to
  3555. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3556. ** a NULL pointer.
  3557. **
  3558. ** ^The sqlite3_malloc64(N) routine works just like
  3559. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3560. ** of a signed 32-bit integer.
  3561. **
  3562. ** ^Calling sqlite3_free() with a pointer previously returned
  3563. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3564. ** that it might be reused. ^The sqlite3_free() routine is
  3565. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  3566. ** to sqlite3_free() is harmless. After being freed, memory
  3567. ** should neither be read nor written. Even reading previously freed
  3568. ** memory might result in a segmentation fault or other severe error.
  3569. ** Memory corruption, a segmentation fault, or other severe error
  3570. ** might result if sqlite3_free() is called with a non-NULL pointer that
  3571. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3572. **
  3573. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3574. ** prior memory allocation X to be at least N bytes.
  3575. ** ^If the X parameter to sqlite3_realloc(X,N)
  3576. ** is a NULL pointer then its behavior is identical to calling
  3577. ** sqlite3_malloc(N).
  3578. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3579. ** negative then the behavior is exactly the same as calling
  3580. ** sqlite3_free(X).
  3581. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3582. ** of at least N bytes in size or NULL if insufficient memory is available.
  3583. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3584. ** of the prior allocation are copied into the beginning of buffer returned
  3585. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3586. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3587. ** prior allocation is not freed.
  3588. **
  3589. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3590. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3591. ** of a 32-bit signed integer.
  3592. **
  3593. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3594. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3595. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3596. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3597. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  3598. ** sqlite3_msize(X) returns zero. If X points to something that is not
  3599. ** the beginning of memory allocation, or if it points to a formerly
  3600. ** valid memory allocation that has now been freed, then the behavior
  3601. ** of sqlite3_msize(X) is undefined and possibly harmful.
  3602. **
  3603. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3604. ** sqlite3_malloc64(), and sqlite3_realloc64()
  3605. ** is always aligned to at least an 8 byte boundary, or to a
  3606. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3607. ** option is used.
  3608. **
  3609. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3610. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3611. ** implementation of these routines to be omitted. That capability
  3612. ** is no longer provided. Only built-in memory allocators can be used.
  3613. **
  3614. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3615. ** the system malloc() and free() directly when converting
  3616. ** filenames between the UTF-8 encoding used by SQLite
  3617. ** and whatever filename encoding is used by the particular Windows
  3618. ** installation. Memory allocation errors were detected, but
  3619. ** they were reported back as [SQLITE_CANTOPEN] or
  3620. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3621. **
  3622. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3623. ** must be either NULL or else pointers obtained from a prior
  3624. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3625. ** not yet been released.
  3626. **
  3627. ** The application must not read or write any part of
  3628. ** a block of memory after it has been released using
  3629. ** [sqlite3_free()] or [sqlite3_realloc()].
  3630. */
  3631. SQLITE_API void *sqlite3_malloc(int);
  3632. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3633. SQLITE_API void *sqlite3_realloc(void*, int);
  3634. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3635. SQLITE_API void sqlite3_free(void*);
  3636. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3637. /*
  3638. ** CAPI3REF: Memory Allocator Statistics
  3639. **
  3640. ** SQLite provides these two interfaces for reporting on the status
  3641. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3642. ** routines, which form the built-in memory allocation subsystem.
  3643. **
  3644. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3645. ** of memory currently outstanding (malloced but not freed).
  3646. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3647. ** value of [sqlite3_memory_used()] since the high-water mark
  3648. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  3649. ** [sqlite3_memory_highwater()] include any overhead
  3650. ** added by SQLite in its implementation of [sqlite3_malloc()],
  3651. ** but not overhead added by the any underlying system library
  3652. ** routines that [sqlite3_malloc()] may call.
  3653. **
  3654. ** ^The memory high-water mark is reset to the current value of
  3655. ** [sqlite3_memory_used()] if and only if the parameter to
  3656. ** [sqlite3_memory_highwater()] is true. ^The value returned
  3657. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3658. ** prior to the reset.
  3659. */
  3660. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3661. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3662. /*
  3663. ** CAPI3REF: Pseudo-Random Number Generator
  3664. **
  3665. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3666. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3667. ** already uses the largest possible [ROWID]. The PRNG is also used for
  3668. ** the build-in random() and randomblob() SQL functions. This interface allows
  3669. ** applications to access the same PRNG for other purposes.
  3670. **
  3671. ** ^A call to this routine stores N bytes of randomness into buffer P.
  3672. ** ^The P parameter can be a NULL pointer.
  3673. **
  3674. ** ^If this routine has not been previously called or if the previous
  3675. ** call had N less than one or a NULL pointer for P, then the PRNG is
  3676. ** seeded using randomness obtained from the xRandomness method of
  3677. ** the default [sqlite3_vfs] object.
  3678. ** ^If the previous call to this routine had an N of 1 or more and a
  3679. ** non-NULL P then the pseudo-randomness is generated
  3680. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3681. ** method.
  3682. */
  3683. SQLITE_API void sqlite3_randomness(int N, void *P);
  3684. /*
  3685. ** CAPI3REF: Compile-Time Authorization Callbacks
  3686. ** METHOD: sqlite3
  3687. ** KEYWORDS: {authorizer callback}
  3688. **
  3689. ** ^This routine registers an authorizer callback with a particular
  3690. ** [database connection], supplied in the first argument.
  3691. ** ^The authorizer callback is invoked as SQL statements are being compiled
  3692. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3693. ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3694. ** and [sqlite3_prepare16_v3()]. ^At various
  3695. ** points during the compilation process, as logic is being created
  3696. ** to perform various actions, the authorizer callback is invoked to
  3697. ** see if those actions are allowed. ^The authorizer callback should
  3698. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3699. ** specific action but allow the SQL statement to continue to be
  3700. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3701. ** rejected with an error. ^If the authorizer callback returns
  3702. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3703. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3704. ** the authorizer will fail with an error message.
  3705. **
  3706. ** When the callback returns [SQLITE_OK], that means the operation
  3707. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  3708. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3709. ** authorizer will fail with an error message explaining that
  3710. ** access is denied.
  3711. **
  3712. ** ^The first parameter to the authorizer callback is a copy of the third
  3713. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3714. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3715. ** the particular action to be authorized. ^The third through sixth parameters
  3716. ** to the callback are either NULL pointers or zero-terminated strings
  3717. ** that contain additional details about the action to be authorized.
  3718. ** Applications must always be prepared to encounter a NULL pointer in any
  3719. ** of the third through the sixth parameters of the authorization callback.
  3720. **
  3721. ** ^If the action code is [SQLITE_READ]
  3722. ** and the callback returns [SQLITE_IGNORE] then the
  3723. ** [prepared statement] statement is constructed to substitute
  3724. ** a NULL value in place of the table column that would have
  3725. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  3726. ** return can be used to deny an untrusted user access to individual
  3727. ** columns of a table.
  3728. ** ^When a table is referenced by a [SELECT] but no column values are
  3729. ** extracted from that table (for example in a query like
  3730. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3731. ** is invoked once for that table with a column name that is an empty string.
  3732. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3733. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3734. ** [truncate optimization] is disabled and all rows are deleted individually.
  3735. **
  3736. ** An authorizer is used when [sqlite3_prepare | preparing]
  3737. ** SQL statements from an untrusted source, to ensure that the SQL statements
  3738. ** do not try to access data they are not allowed to see, or that they do not
  3739. ** try to execute malicious statements that damage the database. For
  3740. ** example, an application may allow a user to enter arbitrary
  3741. ** SQL queries for evaluation by a database. But the application does
  3742. ** not want the user to be able to make arbitrary changes to the
  3743. ** database. An authorizer could then be put in place while the
  3744. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3745. ** disallows everything except [SELECT] statements.
  3746. **
  3747. ** Applications that need to process SQL from untrusted sources
  3748. ** might also consider lowering resource limits using [sqlite3_limit()]
  3749. ** and limiting database size using the [max_page_count] [PRAGMA]
  3750. ** in addition to using an authorizer.
  3751. **
  3752. ** ^(Only a single authorizer can be in place on a database connection
  3753. ** at a time. Each call to sqlite3_set_authorizer overrides the
  3754. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  3755. ** The authorizer is disabled by default.
  3756. **
  3757. ** The authorizer callback must not do anything that will modify
  3758. ** the database connection that invoked the authorizer callback.
  3759. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3760. ** database connections for the meaning of "modify" in this paragraph.
  3761. **
  3762. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3763. ** statement might be re-prepared during [sqlite3_step()] due to a
  3764. ** schema change. Hence, the application should ensure that the
  3765. ** correct authorizer callback remains in place during the [sqlite3_step()].
  3766. **
  3767. ** ^Note that the authorizer callback is invoked only during
  3768. ** [sqlite3_prepare()] or its variants. Authorization is not
  3769. ** performed during statement evaluation in [sqlite3_step()], unless
  3770. ** as stated in the previous paragraph, sqlite3_step() invokes
  3771. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3772. */
  3773. SQLITE_API int sqlite3_set_authorizer(
  3774. sqlite3*,
  3775. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3776. void *pUserData
  3777. );
  3778. /*
  3779. ** CAPI3REF: Authorizer Return Codes
  3780. **
  3781. ** The [sqlite3_set_authorizer | authorizer callback function] must
  3782. ** return either [SQLITE_OK] or one of these two constants in order
  3783. ** to signal SQLite whether or not the action is permitted. See the
  3784. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3785. ** information.
  3786. **
  3787. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3788. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  3789. */
  3790. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  3791. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  3792. /*
  3793. ** CAPI3REF: Authorizer Action Codes
  3794. **
  3795. ** The [sqlite3_set_authorizer()] interface registers a callback function
  3796. ** that is invoked to authorize certain SQL statement actions. The
  3797. ** second parameter to the callback is an integer code that specifies
  3798. ** what action is being authorized. These are the integer action codes that
  3799. ** the authorizer callback may be passed.
  3800. **
  3801. ** These action code values signify what kind of operation is to be
  3802. ** authorized. The 3rd and 4th parameters to the authorization
  3803. ** callback function will be parameters or NULL depending on which of these
  3804. ** codes is used as the second parameter. ^(The 5th parameter to the
  3805. ** authorizer callback is the name of the database ("main", "temp",
  3806. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3807. ** is the name of the inner-most trigger or view that is responsible for
  3808. ** the access attempt or NULL if this access attempt is directly from
  3809. ** top-level SQL code.
  3810. */
  3811. /******************************************* 3rd ************ 4th ***********/
  3812. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3813. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3814. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3815. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3816. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3817. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3818. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3819. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3820. #define SQLITE_DELETE 9 /* Table Name NULL */
  3821. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3822. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3823. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3824. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3825. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3826. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3827. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3828. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3829. #define SQLITE_INSERT 18 /* Table Name NULL */
  3830. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3831. #define SQLITE_READ 20 /* Table Name Column Name */
  3832. #define SQLITE_SELECT 21 /* NULL NULL */
  3833. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3834. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3835. #define SQLITE_ATTACH 24 /* Filename NULL */
  3836. #define SQLITE_DETACH 25 /* Database Name NULL */
  3837. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3838. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3839. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3840. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3841. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3842. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  3843. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  3844. #define SQLITE_COPY 0 /* No longer used */
  3845. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  3846. /*
  3847. ** CAPI3REF: Tracing And Profiling Functions
  3848. ** METHOD: sqlite3
  3849. **
  3850. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3851. ** instead of the routines described here.
  3852. **
  3853. ** These routines register callback functions that can be used for
  3854. ** tracing and profiling the execution of SQL statements.
  3855. **
  3856. ** ^The callback function registered by sqlite3_trace() is invoked at
  3857. ** various times when an SQL statement is being run by [sqlite3_step()].
  3858. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3859. ** SQL statement text as the statement first begins executing.
  3860. ** ^(Additional sqlite3_trace() callbacks might occur
  3861. ** as each triggered subprogram is entered. The callbacks for triggers
  3862. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3863. **
  3864. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3865. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3866. **
  3867. ** ^The callback function registered by sqlite3_profile() is invoked
  3868. ** as each SQL statement finishes. ^The profile callback contains
  3869. ** the original statement text and an estimate of wall-clock time
  3870. ** of how long that statement took to run. ^The profile callback
  3871. ** time is in units of nanoseconds, however the current implementation
  3872. ** is only capable of millisecond resolution so the six least significant
  3873. ** digits in the time are meaningless. Future versions of SQLite
  3874. ** might provide greater resolution on the profiler callback. The
  3875. ** sqlite3_profile() function is considered experimental and is
  3876. ** subject to change in future versions of SQLite.
  3877. */
  3878. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3879. void(*xTrace)(void*,const char*), void*);
  3880. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3881. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3882. /*
  3883. ** CAPI3REF: SQL Trace Event Codes
  3884. ** KEYWORDS: SQLITE_TRACE
  3885. **
  3886. ** These constants identify classes of events that can be monitored
  3887. ** using the [sqlite3_trace_v2()] tracing logic. The M argument
  3888. ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
  3889. ** the following constants. ^The first argument to the trace callback
  3890. ** is one of the following constants.
  3891. **
  3892. ** New tracing constants may be added in future releases.
  3893. **
  3894. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  3895. ** ^The T argument is one of the integer type codes above.
  3896. ** ^The C argument is a copy of the context pointer passed in as the
  3897. ** fourth argument to [sqlite3_trace_v2()].
  3898. ** The P and X arguments are pointers whose meanings depend on T.
  3899. **
  3900. ** <dl>
  3901. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  3902. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  3903. ** first begins running and possibly at other times during the
  3904. ** execution of the prepared statement, such as at the start of each
  3905. ** trigger subprogram. ^The P argument is a pointer to the
  3906. ** [prepared statement]. ^The X argument is a pointer to a string which
  3907. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  3908. ** that indicates the invocation of a trigger. ^The callback can compute
  3909. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  3910. ** interface by using the X argument when X begins with "--" and invoking
  3911. ** [sqlite3_expanded_sql(P)] otherwise.
  3912. **
  3913. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  3914. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  3915. ** information as is provided by the [sqlite3_profile()] callback.
  3916. ** ^The P argument is a pointer to the [prepared statement] and the
  3917. ** X argument points to a 64-bit integer which is the estimated of
  3918. ** the number of nanosecond that the prepared statement took to run.
  3919. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  3920. **
  3921. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  3922. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  3923. ** statement generates a single row of result.
  3924. ** ^The P argument is a pointer to the [prepared statement] and the
  3925. ** X argument is unused.
  3926. **
  3927. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  3928. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  3929. ** connection closes.
  3930. ** ^The P argument is a pointer to the [database connection] object
  3931. ** and the X argument is unused.
  3932. ** </dl>
  3933. */
  3934. #define SQLITE_TRACE_STMT 0x01
  3935. #define SQLITE_TRACE_PROFILE 0x02
  3936. #define SQLITE_TRACE_ROW 0x04
  3937. #define SQLITE_TRACE_CLOSE 0x08
  3938. /*
  3939. ** CAPI3REF: SQL Trace Hook
  3940. ** METHOD: sqlite3
  3941. **
  3942. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  3943. ** function X against [database connection] D, using property mask M
  3944. ** and context pointer P. ^If the X callback is
  3945. ** NULL or if the M mask is zero, then tracing is disabled. The
  3946. ** M argument should be the bitwise OR-ed combination of
  3947. ** zero or more [SQLITE_TRACE] constants.
  3948. **
  3949. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  3950. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  3951. **
  3952. ** ^The X callback is invoked whenever any of the events identified by
  3953. ** mask M occur. ^The integer return value from the callback is currently
  3954. ** ignored, though this may change in future releases. Callback
  3955. ** implementations should return zero to ensure future compatibility.
  3956. **
  3957. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  3958. ** ^The T argument is one of the [SQLITE_TRACE]
  3959. ** constants to indicate why the callback was invoked.
  3960. ** ^The C argument is a copy of the context pointer.
  3961. ** The P and X arguments are pointers whose meanings depend on T.
  3962. **
  3963. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  3964. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  3965. ** are deprecated.
  3966. */
  3967. SQLITE_API int sqlite3_trace_v2(
  3968. sqlite3*,
  3969. unsigned uMask,
  3970. int(*xCallback)(unsigned,void*,void*,void*),
  3971. void *pCtx
  3972. );
  3973. /*
  3974. ** CAPI3REF: Query Progress Callbacks
  3975. ** METHOD: sqlite3
  3976. **
  3977. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  3978. ** function X to be invoked periodically during long running calls to
  3979. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  3980. ** database connection D. An example use for this
  3981. ** interface is to keep a GUI updated during a large query.
  3982. **
  3983. ** ^The parameter P is passed through as the only parameter to the
  3984. ** callback function X. ^The parameter N is the approximate number of
  3985. ** [virtual machine instructions] that are evaluated between successive
  3986. ** invocations of the callback X. ^If N is less than one then the progress
  3987. ** handler is disabled.
  3988. **
  3989. ** ^Only a single progress handler may be defined at one time per
  3990. ** [database connection]; setting a new progress handler cancels the
  3991. ** old one. ^Setting parameter X to NULL disables the progress handler.
  3992. ** ^The progress handler is also disabled by setting N to a value less
  3993. ** than 1.
  3994. **
  3995. ** ^If the progress callback returns non-zero, the operation is
  3996. ** interrupted. This feature can be used to implement a
  3997. ** "Cancel" button on a GUI progress dialog box.
  3998. **
  3999. ** The progress handler callback must not do anything that will modify
  4000. ** the database connection that invoked the progress handler.
  4001. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4002. ** database connections for the meaning of "modify" in this paragraph.
  4003. **
  4004. */
  4005. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  4006. /*
  4007. ** CAPI3REF: Opening A New Database Connection
  4008. ** CONSTRUCTOR: sqlite3
  4009. **
  4010. ** ^These routines open an SQLite database file as specified by the
  4011. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4012. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4013. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4014. ** returned in *ppDb, even if an error occurs. The only exception is that
  4015. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4016. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4017. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4018. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  4019. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4020. ** an English language description of the error following a failure of any
  4021. ** of the sqlite3_open() routines.
  4022. **
  4023. ** ^The default encoding will be UTF-8 for databases created using
  4024. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  4025. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4026. **
  4027. ** Whether or not an error occurs when it is opened, resources
  4028. ** associated with the [database connection] handle should be released by
  4029. ** passing it to [sqlite3_close()] when it is no longer required.
  4030. **
  4031. ** The sqlite3_open_v2() interface works like sqlite3_open()
  4032. ** except that it accepts two additional parameters for additional control
  4033. ** over the new database connection. ^(The flags parameter to
  4034. ** sqlite3_open_v2() can take one of
  4035. ** the following three values, optionally combined with the
  4036. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  4037. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  4038. **
  4039. ** <dl>
  4040. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4041. ** <dd>The database is opened in read-only mode. If the database does not
  4042. ** already exist, an error is returned.</dd>)^
  4043. **
  4044. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4045. ** <dd>The database is opened for reading and writing if possible, or reading
  4046. ** only if the file is write protected by the operating system. In either
  4047. ** case the database must already exist, otherwise an error is returned.</dd>)^
  4048. **
  4049. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4050. ** <dd>The database is opened for reading and writing, and is created if
  4051. ** it does not already exist. This is the behavior that is always used for
  4052. ** sqlite3_open() and sqlite3_open16().</dd>)^
  4053. ** </dl>
  4054. **
  4055. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4056. ** combinations shown above optionally combined with other
  4057. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4058. ** then the behavior is undefined.
  4059. **
  4060. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4061. ** opens in the multi-thread [threading mode] as long as the single-thread
  4062. ** mode has not been set at compile-time or start-time. ^If the
  4063. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4064. ** in the serialized [threading mode] unless single-thread was
  4065. ** previously selected at compile-time or start-time.
  4066. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4067. ** eligible to use [shared cache mode], regardless of whether or not shared
  4068. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  4069. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4070. ** participate in [shared cache mode] even if it is enabled.
  4071. **
  4072. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4073. ** [sqlite3_vfs] object that defines the operating system interface that
  4074. ** the new database connection should use. ^If the fourth parameter is
  4075. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4076. **
  4077. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4078. ** is created for the connection. ^This in-memory database will vanish when
  4079. ** the database connection is closed. Future versions of SQLite might
  4080. ** make use of additional special filenames that begin with the ":" character.
  4081. ** It is recommended that when a database filename actually does begin with
  4082. ** a ":" character you should prefix the filename with a pathname such as
  4083. ** "./" to avoid ambiguity.
  4084. **
  4085. ** ^If the filename is an empty string, then a private, temporary
  4086. ** on-disk database will be created. ^This private database will be
  4087. ** automatically deleted as soon as the database connection is closed.
  4088. **
  4089. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4090. **
  4091. ** ^If [URI filename] interpretation is enabled, and the filename argument
  4092. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4093. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4094. ** set in the third argument to sqlite3_open_v2(), or if it has
  4095. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4096. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4097. ** URI filename interpretation is turned off
  4098. ** by default, but future releases of SQLite might enable URI filename
  4099. ** interpretation by default. See "[URI filenames]" for additional
  4100. ** information.
  4101. **
  4102. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4103. ** authority, then it must be either an empty string or the string
  4104. ** "localhost". ^If the authority is not an empty string or "localhost", an
  4105. ** error is returned to the caller. ^The fragment component of a URI, if
  4106. ** present, is ignored.
  4107. **
  4108. ** ^SQLite uses the path component of the URI as the name of the disk file
  4109. ** which contains the database. ^If the path begins with a '/' character,
  4110. ** then it is interpreted as an absolute path. ^If the path does not begin
  4111. ** with a '/' (meaning that the authority section is omitted from the URI)
  4112. ** then the path is interpreted as a relative path.
  4113. ** ^(On windows, the first component of an absolute path
  4114. ** is a drive specification (e.g. "C:").)^
  4115. **
  4116. ** [[core URI query parameters]]
  4117. ** The query component of a URI may contain parameters that are interpreted
  4118. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4119. ** SQLite and its built-in [VFSes] interpret the
  4120. ** following query parameters:
  4121. **
  4122. ** <ul>
  4123. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4124. ** a VFS object that provides the operating system interface that should
  4125. ** be used to access the database file on disk. ^If this option is set to
  4126. ** an empty string the default VFS object is used. ^Specifying an unknown
  4127. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4128. ** present, then the VFS specified by the option takes precedence over
  4129. ** the value passed as the fourth parameter to sqlite3_open_v2().
  4130. **
  4131. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4132. ** "rwc", or "memory". Attempting to set it to any other value is
  4133. ** an error)^.
  4134. ** ^If "ro" is specified, then the database is opened for read-only
  4135. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  4136. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  4137. ** "rw", then the database is opened for read-write (but not create)
  4138. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  4139. ** been set. ^Value "rwc" is equivalent to setting both
  4140. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  4141. ** set to "memory" then a pure [in-memory database] that never reads
  4142. ** or writes from disk is used. ^It is an error to specify a value for
  4143. ** the mode parameter that is less restrictive than that specified by
  4144. ** the flags passed in the third parameter to sqlite3_open_v2().
  4145. **
  4146. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4147. ** "private". ^Setting it to "shared" is equivalent to setting the
  4148. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4149. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  4150. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4151. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4152. ** a URI filename, its value overrides any behavior requested by setting
  4153. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4154. **
  4155. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4156. ** [powersafe overwrite] property does or does not apply to the
  4157. ** storage media on which the database file resides.
  4158. **
  4159. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4160. ** which if set disables file locking in rollback journal modes. This
  4161. ** is useful for accessing a database on a filesystem that does not
  4162. ** support locking. Caution: Database corruption might result if two
  4163. ** or more processes write to the same database and any one of those
  4164. ** processes uses nolock=1.
  4165. **
  4166. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4167. ** parameter that indicates that the database file is stored on
  4168. ** read-only media. ^When immutable is set, SQLite assumes that the
  4169. ** database file cannot be changed, even by a process with higher
  4170. ** privilege, and so the database is opened read-only and all locking
  4171. ** and change detection is disabled. Caution: Setting the immutable
  4172. ** property on a database file that does in fact change can result
  4173. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4174. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  4175. **
  4176. ** </ul>
  4177. **
  4178. ** ^Specifying an unknown parameter in the query component of a URI is not an
  4179. ** error. Future versions of SQLite might understand additional query
  4180. ** parameters. See "[query parameters with special meaning to SQLite]" for
  4181. ** additional information.
  4182. **
  4183. ** [[URI filename examples]] <h3>URI filename examples</h3>
  4184. **
  4185. ** <table border="1" align=center cellpadding=5>
  4186. ** <tr><th> URI filenames <th> Results
  4187. ** <tr><td> file:data.db <td>
  4188. ** Open the file "data.db" in the current directory.
  4189. ** <tr><td> file:/home/fred/data.db<br>
  4190. ** file:///home/fred/data.db <br>
  4191. ** file://localhost/home/fred/data.db <br> <td>
  4192. ** Open the database file "/home/fred/data.db".
  4193. ** <tr><td> file://darkstar/home/fred/data.db <td>
  4194. ** An error. "darkstar" is not a recognized authority.
  4195. ** <tr><td style="white-space:nowrap">
  4196. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4197. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4198. ** C:. Note that the %20 escaping in this example is not strictly
  4199. ** necessary - space characters can be used literally
  4200. ** in URI filenames.
  4201. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  4202. ** Open file "data.db" in the current directory for read-only access.
  4203. ** Regardless of whether or not shared-cache mode is enabled by
  4204. ** default, use a private cache.
  4205. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4206. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4207. ** that uses dot-files in place of posix advisory locking.
  4208. ** <tr><td> file:data.db?mode=readonly <td>
  4209. ** An error. "readonly" is not a valid option for the "mode" parameter.
  4210. ** </table>
  4211. **
  4212. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4213. ** query components of a URI. A hexadecimal escape sequence consists of a
  4214. ** percent sign - "%" - followed by exactly two hexadecimal digits
  4215. ** specifying an octet value. ^Before the path or query components of a
  4216. ** URI filename are interpreted, they are encoded using UTF-8 and all
  4217. ** hexadecimal escape sequences replaced by a single byte containing the
  4218. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4219. ** the results are undefined.
  4220. **
  4221. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  4222. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4223. ** codepage is currently defined. Filenames containing international
  4224. ** characters must be converted to UTF-8 prior to passing them into
  4225. ** sqlite3_open() or sqlite3_open_v2().
  4226. **
  4227. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4228. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  4229. ** features that require the use of temporary files may fail.
  4230. **
  4231. ** See also: [sqlite3_temp_directory]
  4232. */
  4233. SQLITE_API int sqlite3_open(
  4234. const char *filename, /* Database filename (UTF-8) */
  4235. sqlite3 **ppDb /* OUT: SQLite db handle */
  4236. );
  4237. SQLITE_API int sqlite3_open16(
  4238. const void *filename, /* Database filename (UTF-16) */
  4239. sqlite3 **ppDb /* OUT: SQLite db handle */
  4240. );
  4241. SQLITE_API int sqlite3_open_v2(
  4242. const char *filename, /* Database filename (UTF-8) */
  4243. sqlite3 **ppDb, /* OUT: SQLite db handle */
  4244. int flags, /* Flags */
  4245. const char *zVfs /* Name of VFS module to use */
  4246. );
  4247. /*
  4248. ** CAPI3REF: Obtain Values For URI Parameters
  4249. **
  4250. ** These are utility routines, useful to VFS implementations, that check
  4251. ** to see if a database file was a URI that contained a specific query
  4252. ** parameter, and if so obtains the value of that query parameter.
  4253. **
  4254. ** If F is the database filename pointer passed into the xOpen() method of
  4255. ** a VFS implementation when the flags parameter to xOpen() has one or
  4256. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4257. ** P is the name of the query parameter, then
  4258. ** sqlite3_uri_parameter(F,P) returns the value of the P
  4259. ** parameter if it exists or a NULL pointer if P does not appear as a
  4260. ** query parameter on F. If P is a query parameter of F
  4261. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4262. ** a pointer to an empty string.
  4263. **
  4264. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4265. ** parameter and returns true (1) or false (0) according to the value
  4266. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4267. ** value of query parameter P is one of "yes", "true", or "on" in any
  4268. ** case or if the value begins with a non-zero number. The
  4269. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4270. ** query parameter P is one of "no", "false", or "off" in any case or
  4271. ** if the value begins with a numeric zero. If P is not a query
  4272. ** parameter on F or if the value of P is does not match any of the
  4273. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4274. **
  4275. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4276. ** 64-bit signed integer and returns that integer, or D if P does not
  4277. ** exist. If the value of P is something other than an integer, then
  4278. ** zero is returned.
  4279. **
  4280. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4281. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  4282. ** is not a database file pathname pointer that SQLite passed into the xOpen
  4283. ** VFS method, then the behavior of this routine is undefined and probably
  4284. ** undesirable.
  4285. */
  4286. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4287. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4288. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4289. /*
  4290. ** CAPI3REF: Error Codes And Messages
  4291. ** METHOD: sqlite3
  4292. **
  4293. ** ^If the most recent sqlite3_* API call associated with
  4294. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4295. ** returns the numeric [result code] or [extended result code] for that
  4296. ** API call.
  4297. ** If the most recent API call was successful,
  4298. ** then the return value from sqlite3_errcode() is undefined.
  4299. ** ^The sqlite3_extended_errcode()
  4300. ** interface is the same except that it always returns the
  4301. ** [extended result code] even when extended result codes are
  4302. ** disabled.
  4303. **
  4304. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4305. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4306. ** ^(Memory to hold the error message string is managed internally.
  4307. ** The application does not need to worry about freeing the result.
  4308. ** However, the error string might be overwritten or deallocated by
  4309. ** subsequent calls to other SQLite interface functions.)^
  4310. **
  4311. ** ^The sqlite3_errstr() interface returns the English-language text
  4312. ** that describes the [result code], as UTF-8.
  4313. ** ^(Memory to hold the error message string is managed internally
  4314. ** and must not be freed by the application)^.
  4315. **
  4316. ** When the serialized [threading mode] is in use, it might be the
  4317. ** case that a second error occurs on a separate thread in between
  4318. ** the time of the first error and the call to these interfaces.
  4319. ** When that happens, the second error will be reported since these
  4320. ** interfaces always report the most recent result. To avoid
  4321. ** this, each thread can obtain exclusive use of the [database connection] D
  4322. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4323. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4324. ** all calls to the interfaces listed here are completed.
  4325. **
  4326. ** If an interface fails with SQLITE_MISUSE, that means the interface
  4327. ** was invoked incorrectly by the application. In that case, the
  4328. ** error code and message may or may not be set.
  4329. */
  4330. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4331. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4332. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4333. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4334. SQLITE_API const char *sqlite3_errstr(int);
  4335. /*
  4336. ** CAPI3REF: Prepared Statement Object
  4337. ** KEYWORDS: {prepared statement} {prepared statements}
  4338. **
  4339. ** An instance of this object represents a single SQL statement that
  4340. ** has been compiled into binary form and is ready to be evaluated.
  4341. **
  4342. ** Think of each SQL statement as a separate computer program. The
  4343. ** original SQL text is source code. A prepared statement object
  4344. ** is the compiled object code. All SQL must be converted into a
  4345. ** prepared statement before it can be run.
  4346. **
  4347. ** The life-cycle of a prepared statement object usually goes like this:
  4348. **
  4349. ** <ol>
  4350. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4351. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4352. ** interfaces.
  4353. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4354. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4355. ** to step 2. Do this zero or more times.
  4356. ** <li> Destroy the object using [sqlite3_finalize()].
  4357. ** </ol>
  4358. */
  4359. typedef struct sqlite3_stmt sqlite3_stmt;
  4360. /*
  4361. ** CAPI3REF: Run-time Limits
  4362. ** METHOD: sqlite3
  4363. **
  4364. ** ^(This interface allows the size of various constructs to be limited
  4365. ** on a connection by connection basis. The first parameter is the
  4366. ** [database connection] whose limit is to be set or queried. The
  4367. ** second parameter is one of the [limit categories] that define a
  4368. ** class of constructs to be size limited. The third parameter is the
  4369. ** new limit for that construct.)^
  4370. **
  4371. ** ^If the new limit is a negative number, the limit is unchanged.
  4372. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  4373. ** [limits | hard upper bound]
  4374. ** set at compile-time by a C preprocessor macro called
  4375. ** [limits | SQLITE_MAX_<i>NAME</i>].
  4376. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4377. ** ^Attempts to increase a limit above its hard upper bound are
  4378. ** silently truncated to the hard upper bound.
  4379. **
  4380. ** ^Regardless of whether or not the limit was changed, the
  4381. ** [sqlite3_limit()] interface returns the prior value of the limit.
  4382. ** ^Hence, to find the current value of a limit without changing it,
  4383. ** simply invoke this interface with the third parameter set to -1.
  4384. **
  4385. ** Run-time limits are intended for use in applications that manage
  4386. ** both their own internal database and also databases that are controlled
  4387. ** by untrusted external sources. An example application might be a
  4388. ** web browser that has its own databases for storing history and
  4389. ** separate databases controlled by JavaScript applications downloaded
  4390. ** off the Internet. The internal databases can be given the
  4391. ** large, default limits. Databases managed by external sources can
  4392. ** be given much smaller limits designed to prevent a denial of service
  4393. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  4394. ** interface to further control untrusted SQL. The size of the database
  4395. ** created by an untrusted script can be contained using the
  4396. ** [max_page_count] [PRAGMA].
  4397. **
  4398. ** New run-time limit categories may be added in future releases.
  4399. */
  4400. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4401. /*
  4402. ** CAPI3REF: Run-Time Limit Categories
  4403. ** KEYWORDS: {limit category} {*limit categories}
  4404. **
  4405. ** These constants define various performance limits
  4406. ** that can be lowered at run-time using [sqlite3_limit()].
  4407. ** The synopsis of the meanings of the various limits is shown below.
  4408. ** Additional information is available at [limits | Limits in SQLite].
  4409. **
  4410. ** <dl>
  4411. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4412. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4413. **
  4414. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4415. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4416. **
  4417. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4418. ** <dd>The maximum number of columns in a table definition or in the
  4419. ** result set of a [SELECT] or the maximum number of columns in an index
  4420. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4421. **
  4422. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4423. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4424. **
  4425. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4426. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4427. **
  4428. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4429. ** <dd>The maximum number of instructions in a virtual machine program
  4430. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  4431. ** the equivalent tries to allocate space for more than this many opcodes
  4432. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4433. **
  4434. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4435. ** <dd>The maximum number of arguments on a function.</dd>)^
  4436. **
  4437. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4438. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4439. **
  4440. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4441. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4442. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4443. ** [GLOB] operators.</dd>)^
  4444. **
  4445. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4446. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4447. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4448. **
  4449. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4450. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4451. **
  4452. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4453. ** <dd>The maximum number of auxiliary worker threads that a single
  4454. ** [prepared statement] may start.</dd>)^
  4455. ** </dl>
  4456. */
  4457. #define SQLITE_LIMIT_LENGTH 0
  4458. #define SQLITE_LIMIT_SQL_LENGTH 1
  4459. #define SQLITE_LIMIT_COLUMN 2
  4460. #define SQLITE_LIMIT_EXPR_DEPTH 3
  4461. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  4462. #define SQLITE_LIMIT_VDBE_OP 5
  4463. #define SQLITE_LIMIT_FUNCTION_ARG 6
  4464. #define SQLITE_LIMIT_ATTACHED 7
  4465. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  4466. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  4467. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  4468. #define SQLITE_LIMIT_WORKER_THREADS 11
  4469. /*
  4470. ** CAPI3REF: Prepare Flags
  4471. **
  4472. ** These constants define various flags that can be passed into
  4473. ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4474. ** [sqlite3_prepare16_v3()] interfaces.
  4475. **
  4476. ** New flags may be added in future releases of SQLite.
  4477. **
  4478. ** <dl>
  4479. ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4480. ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4481. ** that the prepared statement will be retained for a long time and
  4482. ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4483. ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
  4484. ** be used just once or at most a few times and then destroyed using
  4485. ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4486. ** on this hint by avoiding the use of [lookaside memory] so as not to
  4487. ** deplete the limited store of lookaside memory. Future versions of
  4488. ** SQLite may act on this hint differently.
  4489. ** </dl>
  4490. */
  4491. #define SQLITE_PREPARE_PERSISTENT 0x01
  4492. /*
  4493. ** CAPI3REF: Compiling An SQL Statement
  4494. ** KEYWORDS: {SQL statement compiler}
  4495. ** METHOD: sqlite3
  4496. ** CONSTRUCTOR: sqlite3_stmt
  4497. **
  4498. ** To execute an SQL statement, it must first be compiled into a byte-code
  4499. ** program using one of these routines. Or, in other words, these routines
  4500. ** are constructors for the [prepared statement] object.
  4501. **
  4502. ** The preferred routine to use is [sqlite3_prepare_v2()]. The
  4503. ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4504. ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4505. ** for special purposes.
  4506. **
  4507. ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4508. ** does all parsing using UTF-8. The UTF-16 interfaces are provided
  4509. ** as a convenience. The UTF-16 interfaces work by converting the
  4510. ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4511. **
  4512. ** The first argument, "db", is a [database connection] obtained from a
  4513. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4514. ** [sqlite3_open16()]. The database connection must not have been closed.
  4515. **
  4516. ** The second argument, "zSql", is the statement to be compiled, encoded
  4517. ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
  4518. ** and sqlite3_prepare_v3()
  4519. ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4520. ** and sqlite3_prepare16_v3() use UTF-16.
  4521. **
  4522. ** ^If the nByte argument is negative, then zSql is read up to the
  4523. ** first zero terminator. ^If nByte is positive, then it is the
  4524. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  4525. ** statement is generated.
  4526. ** If the caller knows that the supplied string is nul-terminated, then
  4527. ** there is a small performance advantage to passing an nByte parameter that
  4528. ** is the number of bytes in the input string <i>including</i>
  4529. ** the nul-terminator.
  4530. **
  4531. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4532. ** past the end of the first SQL statement in zSql. These routines only
  4533. ** compile the first statement in zSql, so *pzTail is left pointing to
  4534. ** what remains uncompiled.
  4535. **
  4536. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4537. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  4538. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  4539. ** string or a comment) then *ppStmt is set to NULL.
  4540. ** The calling procedure is responsible for deleting the compiled
  4541. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4542. ** ppStmt may not be NULL.
  4543. **
  4544. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4545. ** otherwise an [error code] is returned.
  4546. **
  4547. ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4548. ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4549. ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4550. ** are retained for backwards compatibility, but their use is discouraged.
  4551. ** ^In the "vX" interfaces, the prepared statement
  4552. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4553. ** original SQL text. This causes the [sqlite3_step()] interface to
  4554. ** behave differently in three ways:
  4555. **
  4556. ** <ol>
  4557. ** <li>
  4558. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4559. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4560. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4561. ** retries will occur before sqlite3_step() gives up and returns an error.
  4562. ** </li>
  4563. **
  4564. ** <li>
  4565. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4566. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  4567. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4568. ** and the application would have to make a second call to [sqlite3_reset()]
  4569. ** in order to find the underlying cause of the problem. With the "v2" prepare
  4570. ** interfaces, the underlying reason for the error is returned immediately.
  4571. ** </li>
  4572. **
  4573. ** <li>
  4574. ** ^If the specific value bound to [parameter | host parameter] in the
  4575. ** WHERE clause might influence the choice of query plan for a statement,
  4576. ** then the statement will be automatically recompiled, as if there had been
  4577. ** a schema change, on the first [sqlite3_step()] call following any change
  4578. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  4579. ** ^The specific value of WHERE-clause [parameter] might influence the
  4580. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4581. ** or [GLOB] operator or if the parameter is compared to an indexed column
  4582. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4583. ** </li>
  4584. ** </ol>
  4585. **
  4586. ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4587. ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4588. ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
  4589. ** sqlite3_prepare_v2() interface works exactly the same as
  4590. ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4591. */
  4592. SQLITE_API int sqlite3_prepare(
  4593. sqlite3 *db, /* Database handle */
  4594. const char *zSql, /* SQL statement, UTF-8 encoded */
  4595. int nByte, /* Maximum length of zSql in bytes. */
  4596. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4597. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4598. );
  4599. SQLITE_API int sqlite3_prepare_v2(
  4600. sqlite3 *db, /* Database handle */
  4601. const char *zSql, /* SQL statement, UTF-8 encoded */
  4602. int nByte, /* Maximum length of zSql in bytes. */
  4603. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4604. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4605. );
  4606. SQLITE_API int sqlite3_prepare_v3(
  4607. sqlite3 *db, /* Database handle */
  4608. const char *zSql, /* SQL statement, UTF-8 encoded */
  4609. int nByte, /* Maximum length of zSql in bytes. */
  4610. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4611. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4612. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4613. );
  4614. SQLITE_API int sqlite3_prepare16(
  4615. sqlite3 *db, /* Database handle */
  4616. const void *zSql, /* SQL statement, UTF-16 encoded */
  4617. int nByte, /* Maximum length of zSql in bytes. */
  4618. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4619. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4620. );
  4621. SQLITE_API int sqlite3_prepare16_v2(
  4622. sqlite3 *db, /* Database handle */
  4623. const void *zSql, /* SQL statement, UTF-16 encoded */
  4624. int nByte, /* Maximum length of zSql in bytes. */
  4625. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4626. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4627. );
  4628. SQLITE_API int sqlite3_prepare16_v3(
  4629. sqlite3 *db, /* Database handle */
  4630. const void *zSql, /* SQL statement, UTF-16 encoded */
  4631. int nByte, /* Maximum length of zSql in bytes. */
  4632. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4633. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4634. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4635. );
  4636. /*
  4637. ** CAPI3REF: Retrieving Statement SQL
  4638. ** METHOD: sqlite3_stmt
  4639. **
  4640. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4641. ** SQL text used to create [prepared statement] P if P was
  4642. ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4643. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4644. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4645. ** string containing the SQL text of prepared statement P with
  4646. ** [bound parameters] expanded.
  4647. **
  4648. ** ^(For example, if a prepared statement is created using the SQL
  4649. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4650. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4651. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4652. ** will return "SELECT 2345,NULL".)^
  4653. **
  4654. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4655. ** is available to hold the result, or if the result would exceed the
  4656. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4657. **
  4658. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4659. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  4660. ** option causes sqlite3_expanded_sql() to always return NULL.
  4661. **
  4662. ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
  4663. ** automatically freed when the prepared statement is finalized.
  4664. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4665. ** is obtained from [sqlite3_malloc()] and must be free by the application
  4666. ** by passing it to [sqlite3_free()].
  4667. */
  4668. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4669. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4670. /*
  4671. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4672. ** METHOD: sqlite3_stmt
  4673. **
  4674. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4675. ** and only if the [prepared statement] X makes no direct changes to
  4676. ** the content of the database file.
  4677. **
  4678. ** Note that [application-defined SQL functions] or
  4679. ** [virtual tables] might change the database indirectly as a side effect.
  4680. ** ^(For example, if an application defines a function "eval()" that
  4681. ** calls [sqlite3_exec()], then the following SQL statement would
  4682. ** change the database file through side-effects:
  4683. **
  4684. ** <blockquote><pre>
  4685. ** SELECT eval('DELETE FROM t1') FROM t2;
  4686. ** </pre></blockquote>
  4687. **
  4688. ** But because the [SELECT] statement does not change the database file
  4689. ** directly, sqlite3_stmt_readonly() would still return true.)^
  4690. **
  4691. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4692. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4693. ** since the statements themselves do not actually modify the database but
  4694. ** rather they control the timing of when other statements modify the
  4695. ** database. ^The [ATTACH] and [DETACH] statements also cause
  4696. ** sqlite3_stmt_readonly() to return true since, while those statements
  4697. ** change the configuration of a database connection, they do not make
  4698. ** changes to the content of the database files on disk.
  4699. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4700. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4701. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4702. ** sqlite3_stmt_readonly() returns false for those commands.
  4703. */
  4704. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4705. /*
  4706. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4707. ** METHOD: sqlite3_stmt
  4708. **
  4709. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4710. ** [prepared statement] S has been stepped at least once using
  4711. ** [sqlite3_step(S)] but has neither run to completion (returned
  4712. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4713. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  4714. ** interface returns false if S is a NULL pointer. If S is not a
  4715. ** NULL pointer and is not a pointer to a valid [prepared statement]
  4716. ** object, then the behavior is undefined and probably undesirable.
  4717. **
  4718. ** This interface can be used in combination [sqlite3_next_stmt()]
  4719. ** to locate all prepared statements associated with a database
  4720. ** connection that are in need of being reset. This can be used,
  4721. ** for example, in diagnostic routines to search for prepared
  4722. ** statements that are holding a transaction open.
  4723. */
  4724. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4725. /*
  4726. ** CAPI3REF: Dynamically Typed Value Object
  4727. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4728. **
  4729. ** SQLite uses the sqlite3_value object to represent all values
  4730. ** that can be stored in a database table. SQLite uses dynamic typing
  4731. ** for the values it stores. ^Values stored in sqlite3_value objects
  4732. ** can be integers, floating point values, strings, BLOBs, or NULL.
  4733. **
  4734. ** An sqlite3_value object may be either "protected" or "unprotected".
  4735. ** Some interfaces require a protected sqlite3_value. Other interfaces
  4736. ** will accept either a protected or an unprotected sqlite3_value.
  4737. ** Every interface that accepts sqlite3_value arguments specifies
  4738. ** whether or not it requires a protected sqlite3_value. The
  4739. ** [sqlite3_value_dup()] interface can be used to construct a new
  4740. ** protected sqlite3_value from an unprotected sqlite3_value.
  4741. **
  4742. ** The terms "protected" and "unprotected" refer to whether or not
  4743. ** a mutex is held. An internal mutex is held for a protected
  4744. ** sqlite3_value object but no mutex is held for an unprotected
  4745. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  4746. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  4747. ** or if SQLite is run in one of reduced mutex modes
  4748. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  4749. ** then there is no distinction between protected and unprotected
  4750. ** sqlite3_value objects and they can be used interchangeably. However,
  4751. ** for maximum code portability it is recommended that applications
  4752. ** still make the distinction between protected and unprotected
  4753. ** sqlite3_value objects even when not strictly required.
  4754. **
  4755. ** ^The sqlite3_value objects that are passed as parameters into the
  4756. ** implementation of [application-defined SQL functions] are protected.
  4757. ** ^The sqlite3_value object returned by
  4758. ** [sqlite3_column_value()] is unprotected.
  4759. ** Unprotected sqlite3_value objects may only be used as arguments
  4760. ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  4761. ** [sqlite3_value_dup()].
  4762. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  4763. ** interfaces require protected sqlite3_value objects.
  4764. */
  4765. typedef struct sqlite3_value sqlite3_value;
  4766. /*
  4767. ** CAPI3REF: SQL Function Context Object
  4768. **
  4769. ** The context in which an SQL function executes is stored in an
  4770. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  4771. ** is always first parameter to [application-defined SQL functions].
  4772. ** The application-defined SQL function implementation will pass this
  4773. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  4774. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  4775. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  4776. ** and/or [sqlite3_set_auxdata()].
  4777. */
  4778. typedef struct sqlite3_context sqlite3_context;
  4779. /*
  4780. ** CAPI3REF: Binding Values To Prepared Statements
  4781. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  4782. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  4783. ** METHOD: sqlite3_stmt
  4784. **
  4785. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  4786. ** literals may be replaced by a [parameter] that matches one of following
  4787. ** templates:
  4788. **
  4789. ** <ul>
  4790. ** <li> ?
  4791. ** <li> ?NNN
  4792. ** <li> :VVV
  4793. ** <li> @VVV
  4794. ** <li> $VVV
  4795. ** </ul>
  4796. **
  4797. ** In the templates above, NNN represents an integer literal,
  4798. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  4799. ** parameters (also called "host parameter names" or "SQL parameters")
  4800. ** can be set using the sqlite3_bind_*() routines defined here.
  4801. **
  4802. ** ^The first argument to the sqlite3_bind_*() routines is always
  4803. ** a pointer to the [sqlite3_stmt] object returned from
  4804. ** [sqlite3_prepare_v2()] or its variants.
  4805. **
  4806. ** ^The second argument is the index of the SQL parameter to be set.
  4807. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  4808. ** SQL parameter is used more than once, second and subsequent
  4809. ** occurrences have the same index as the first occurrence.
  4810. ** ^The index for named parameters can be looked up using the
  4811. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  4812. ** for "?NNN" parameters is the value of NNN.
  4813. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  4814. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  4815. **
  4816. ** ^The third argument is the value to bind to the parameter.
  4817. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4818. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  4819. ** is ignored and the end result is the same as sqlite3_bind_null().
  4820. **
  4821. ** ^(In those routines that have a fourth argument, its value is the
  4822. ** number of bytes in the parameter. To be clear: the value is the
  4823. ** number of <u>bytes</u> in the value, not the number of characters.)^
  4824. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4825. ** is negative, then the length of the string is
  4826. ** the number of bytes up to the first zero terminator.
  4827. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  4828. ** the behavior is undefined.
  4829. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  4830. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  4831. ** that parameter must be the byte offset
  4832. ** where the NUL terminator would occur assuming the string were NUL
  4833. ** terminated. If any NUL characters occur at byte offsets less than
  4834. ** the value of the fourth parameter then the resulting string value will
  4835. ** contain embedded NULs. The result of expressions involving strings
  4836. ** with embedded NULs is undefined.
  4837. **
  4838. ** ^The fifth argument to the BLOB and string binding interfaces
  4839. ** is a destructor used to dispose of the BLOB or
  4840. ** string after SQLite has finished with it. ^The destructor is called
  4841. ** to dispose of the BLOB or string even if the call to bind API fails.
  4842. ** ^If the fifth argument is
  4843. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  4844. ** information is in static, unmanaged space and does not need to be freed.
  4845. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  4846. ** SQLite makes its own private copy of the data immediately, before
  4847. ** the sqlite3_bind_*() routine returns.
  4848. **
  4849. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  4850. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  4851. ** to specify the encoding of the text in the third parameter. If
  4852. ** the sixth argument to sqlite3_bind_text64() is not one of the
  4853. ** allowed values shown above, or if the text encoding is different
  4854. ** from the encoding specified by the sixth parameter, then the behavior
  4855. ** is undefined.
  4856. **
  4857. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  4858. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  4859. ** (just an integer to hold its size) while it is being processed.
  4860. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  4861. ** content is later written using
  4862. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  4863. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  4864. **
  4865. ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  4866. ** [prepared statement] S to have an SQL value of NULL, but to also be
  4867. ** associated with the pointer P of type T. ^D is either a NULL pointer or
  4868. ** a pointer to a destructor function for P. ^SQLite will invoke the
  4869. ** destructor D with a single argument of P when it is finished using
  4870. ** P. The T parameter should be a static string, preferably a string
  4871. ** literal. The sqlite3_bind_pointer() routine is part of the
  4872. ** [pointer passing interface] added for SQLite 3.20.0.
  4873. **
  4874. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  4875. ** for the [prepared statement] or with a prepared statement for which
  4876. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  4877. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  4878. ** routine is passed a [prepared statement] that has been finalized, the
  4879. ** result is undefined and probably harmful.
  4880. **
  4881. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  4882. ** ^Unbound parameters are interpreted as NULL.
  4883. **
  4884. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  4885. ** [error code] if anything goes wrong.
  4886. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  4887. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  4888. ** [SQLITE_MAX_LENGTH].
  4889. ** ^[SQLITE_RANGE] is returned if the parameter
  4890. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  4891. **
  4892. ** See also: [sqlite3_bind_parameter_count()],
  4893. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  4894. */
  4895. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  4896. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  4897. void(*)(void*));
  4898. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  4899. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  4900. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  4901. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  4902. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  4903. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  4904. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  4905. void(*)(void*), unsigned char encoding);
  4906. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  4907. SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  4908. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  4909. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  4910. /*
  4911. ** CAPI3REF: Number Of SQL Parameters
  4912. ** METHOD: sqlite3_stmt
  4913. **
  4914. ** ^This routine can be used to find the number of [SQL parameters]
  4915. ** in a [prepared statement]. SQL parameters are tokens of the
  4916. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  4917. ** placeholders for values that are [sqlite3_bind_blob | bound]
  4918. ** to the parameters at a later time.
  4919. **
  4920. ** ^(This routine actually returns the index of the largest (rightmost)
  4921. ** parameter. For all forms except ?NNN, this will correspond to the
  4922. ** number of unique parameters. If parameters of the ?NNN form are used,
  4923. ** there may be gaps in the list.)^
  4924. **
  4925. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4926. ** [sqlite3_bind_parameter_name()], and
  4927. ** [sqlite3_bind_parameter_index()].
  4928. */
  4929. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  4930. /*
  4931. ** CAPI3REF: Name Of A Host Parameter
  4932. ** METHOD: sqlite3_stmt
  4933. **
  4934. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  4935. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  4936. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4937. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4938. ** respectively.
  4939. ** In other words, the initial ":" or "$" or "@" or "?"
  4940. ** is included as part of the name.)^
  4941. ** ^Parameters of the form "?" without a following integer have no name
  4942. ** and are referred to as "nameless" or "anonymous parameters".
  4943. **
  4944. ** ^The first host parameter has an index of 1, not 0.
  4945. **
  4946. ** ^If the value N is out of range or if the N-th parameter is
  4947. ** nameless, then NULL is returned. ^The returned string is
  4948. ** always in UTF-8 encoding even if the named parameter was
  4949. ** originally specified as UTF-16 in [sqlite3_prepare16()],
  4950. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4951. **
  4952. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4953. ** [sqlite3_bind_parameter_count()], and
  4954. ** [sqlite3_bind_parameter_index()].
  4955. */
  4956. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  4957. /*
  4958. ** CAPI3REF: Index Of A Parameter With A Given Name
  4959. ** METHOD: sqlite3_stmt
  4960. **
  4961. ** ^Return the index of an SQL parameter given its name. ^The
  4962. ** index value returned is suitable for use as the second
  4963. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  4964. ** is returned if no matching parameter is found. ^The parameter
  4965. ** name must be given in UTF-8 even if the original statement
  4966. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  4967. ** [sqlite3_prepare16_v3()].
  4968. **
  4969. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4970. ** [sqlite3_bind_parameter_count()], and
  4971. ** [sqlite3_bind_parameter_name()].
  4972. */
  4973. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  4974. /*
  4975. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  4976. ** METHOD: sqlite3_stmt
  4977. **
  4978. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  4979. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  4980. ** ^Use this routine to reset all host parameters to NULL.
  4981. */
  4982. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  4983. /*
  4984. ** CAPI3REF: Number Of Columns In A Result Set
  4985. ** METHOD: sqlite3_stmt
  4986. **
  4987. ** ^Return the number of columns in the result set returned by the
  4988. ** [prepared statement]. ^If this routine returns 0, that means the
  4989. ** [prepared statement] returns no data (for example an [UPDATE]).
  4990. ** ^However, just because this routine returns a positive number does not
  4991. ** mean that one or more rows of data will be returned. ^A SELECT statement
  4992. ** will always have a positive sqlite3_column_count() but depending on the
  4993. ** WHERE clause constraints and the table content, it might return no rows.
  4994. **
  4995. ** See also: [sqlite3_data_count()]
  4996. */
  4997. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  4998. /*
  4999. ** CAPI3REF: Column Names In A Result Set
  5000. ** METHOD: sqlite3_stmt
  5001. **
  5002. ** ^These routines return the name assigned to a particular column
  5003. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  5004. ** interface returns a pointer to a zero-terminated UTF-8 string
  5005. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  5006. ** UTF-16 string. ^The first parameter is the [prepared statement]
  5007. ** that implements the [SELECT] statement. ^The second parameter is the
  5008. ** column number. ^The leftmost column is number 0.
  5009. **
  5010. ** ^The returned string pointer is valid until either the [prepared statement]
  5011. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5012. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5013. ** or until the next call to
  5014. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5015. **
  5016. ** ^If sqlite3_malloc() fails during the processing of either routine
  5017. ** (for example during a conversion from UTF-8 to UTF-16) then a
  5018. ** NULL pointer is returned.
  5019. **
  5020. ** ^The name of a result column is the value of the "AS" clause for
  5021. ** that column, if there is an AS clause. If there is no AS clause
  5022. ** then the name of the column is unspecified and may change from
  5023. ** one release of SQLite to the next.
  5024. */
  5025. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5026. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5027. /*
  5028. ** CAPI3REF: Source Of Data In A Query Result
  5029. ** METHOD: sqlite3_stmt
  5030. **
  5031. ** ^These routines provide a means to determine the database, table, and
  5032. ** table column that is the origin of a particular result column in
  5033. ** [SELECT] statement.
  5034. ** ^The name of the database or table or column can be returned as
  5035. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  5036. ** the database name, the _table_ routines return the table name, and
  5037. ** the origin_ routines return the column name.
  5038. ** ^The returned string is valid until the [prepared statement] is destroyed
  5039. ** using [sqlite3_finalize()] or until the statement is automatically
  5040. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5041. ** or until the same information is requested
  5042. ** again in a different encoding.
  5043. **
  5044. ** ^The names returned are the original un-aliased names of the
  5045. ** database, table, and column.
  5046. **
  5047. ** ^The first argument to these interfaces is a [prepared statement].
  5048. ** ^These functions return information about the Nth result column returned by
  5049. ** the statement, where N is the second function argument.
  5050. ** ^The left-most column is column 0 for these routines.
  5051. **
  5052. ** ^If the Nth column returned by the statement is an expression or
  5053. ** subquery and is not a column value, then all of these functions return
  5054. ** NULL. ^These routine might also return NULL if a memory allocation error
  5055. ** occurs. ^Otherwise, they return the name of the attached database, table,
  5056. ** or column that query result column was extracted from.
  5057. **
  5058. ** ^As with all other SQLite APIs, those whose names end with "16" return
  5059. ** UTF-16 encoded strings and the other functions return UTF-8.
  5060. **
  5061. ** ^These APIs are only available if the library was compiled with the
  5062. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5063. **
  5064. ** If two or more threads call one or more of these routines against the same
  5065. ** prepared statement and column at the same time then the results are
  5066. ** undefined.
  5067. **
  5068. ** If two or more threads call one or more
  5069. ** [sqlite3_column_database_name | column metadata interfaces]
  5070. ** for the same [prepared statement] and result column
  5071. ** at the same time then the results are undefined.
  5072. */
  5073. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5074. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5075. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5076. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5077. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5078. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5079. /*
  5080. ** CAPI3REF: Declared Datatype Of A Query Result
  5081. ** METHOD: sqlite3_stmt
  5082. **
  5083. ** ^(The first parameter is a [prepared statement].
  5084. ** If this statement is a [SELECT] statement and the Nth column of the
  5085. ** returned result set of that [SELECT] is a table column (not an
  5086. ** expression or subquery) then the declared type of the table
  5087. ** column is returned.)^ ^If the Nth column of the result set is an
  5088. ** expression or subquery, then a NULL pointer is returned.
  5089. ** ^The returned string is always UTF-8 encoded.
  5090. **
  5091. ** ^(For example, given the database schema:
  5092. **
  5093. ** CREATE TABLE t1(c1 VARIANT);
  5094. **
  5095. ** and the following statement to be compiled:
  5096. **
  5097. ** SELECT c1 + 1, c1 FROM t1;
  5098. **
  5099. ** this routine would return the string "VARIANT" for the second result
  5100. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5101. **
  5102. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  5103. ** is declared to contain a particular type does not mean that the
  5104. ** data stored in that column is of the declared type. SQLite is
  5105. ** strongly typed, but the typing is dynamic not static. ^Type
  5106. ** is associated with individual values, not with the containers
  5107. ** used to hold those values.
  5108. */
  5109. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5110. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5111. /*
  5112. ** CAPI3REF: Evaluate An SQL Statement
  5113. ** METHOD: sqlite3_stmt
  5114. **
  5115. ** After a [prepared statement] has been prepared using any of
  5116. ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5117. ** or [sqlite3_prepare16_v3()] or one of the legacy
  5118. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5119. ** must be called one or more times to evaluate the statement.
  5120. **
  5121. ** The details of the behavior of the sqlite3_step() interface depend
  5122. ** on whether the statement was prepared using the newer "vX" interfaces
  5123. ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5124. ** [sqlite3_prepare16_v2()] or the older legacy
  5125. ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  5126. ** new "vX" interface is recommended for new applications but the legacy
  5127. ** interface will continue to be supported.
  5128. **
  5129. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5130. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5131. ** ^With the "v2" interface, any of the other [result codes] or
  5132. ** [extended result codes] might be returned as well.
  5133. **
  5134. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5135. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  5136. ** or occurs outside of an explicit transaction, then you can retry the
  5137. ** statement. If the statement is not a [COMMIT] and occurs within an
  5138. ** explicit transaction then you should rollback the transaction before
  5139. ** continuing.
  5140. **
  5141. ** ^[SQLITE_DONE] means that the statement has finished executing
  5142. ** successfully. sqlite3_step() should not be called again on this virtual
  5143. ** machine without first calling [sqlite3_reset()] to reset the virtual
  5144. ** machine back to its initial state.
  5145. **
  5146. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5147. ** is returned each time a new row of data is ready for processing by the
  5148. ** caller. The values may be accessed using the [column access functions].
  5149. ** sqlite3_step() is called again to retrieve the next row of data.
  5150. **
  5151. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5152. ** violation) has occurred. sqlite3_step() should not be called again on
  5153. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5154. ** ^With the legacy interface, a more specific error code (for example,
  5155. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5156. ** can be obtained by calling [sqlite3_reset()] on the
  5157. ** [prepared statement]. ^In the "v2" interface,
  5158. ** the more specific error code is returned directly by sqlite3_step().
  5159. **
  5160. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5161. ** Perhaps it was called on a [prepared statement] that has
  5162. ** already been [sqlite3_finalize | finalized] or on one that had
  5163. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  5164. ** be the case that the same database connection is being used by two or
  5165. ** more threads at the same moment in time.
  5166. **
  5167. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5168. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5169. ** other than [SQLITE_ROW] before any subsequent invocation of
  5170. ** sqlite3_step(). Failure to reset the prepared statement using
  5171. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5172. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5173. ** sqlite3_step() began
  5174. ** calling [sqlite3_reset()] automatically in this circumstance rather
  5175. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  5176. ** break because any application that ever receives an SQLITE_MISUSE error
  5177. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  5178. ** can be used to restore the legacy behavior.
  5179. **
  5180. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5181. ** API always returns a generic error code, [SQLITE_ERROR], following any
  5182. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  5183. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5184. ** specific [error codes] that better describes the error.
  5185. ** We admit that this is a goofy design. The problem has been fixed
  5186. ** with the "v2" interface. If you prepare all of your SQL statements
  5187. ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5188. ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5189. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5190. ** then the more specific [error codes] are returned directly
  5191. ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
  5192. */
  5193. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5194. /*
  5195. ** CAPI3REF: Number of columns in a result set
  5196. ** METHOD: sqlite3_stmt
  5197. **
  5198. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5199. ** current row of the result set of [prepared statement] P.
  5200. ** ^If prepared statement P does not have results ready to return
  5201. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5202. ** interfaces) then sqlite3_data_count(P) returns 0.
  5203. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5204. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5205. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  5206. ** will return non-zero if previous call to [sqlite3_step](P) returned
  5207. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5208. ** where it always returns zero since each step of that multi-step
  5209. ** pragma returns 0 columns of data.
  5210. **
  5211. ** See also: [sqlite3_column_count()]
  5212. */
  5213. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5214. /*
  5215. ** CAPI3REF: Fundamental Datatypes
  5216. ** KEYWORDS: SQLITE_TEXT
  5217. **
  5218. ** ^(Every value in SQLite has one of five fundamental datatypes:
  5219. **
  5220. ** <ul>
  5221. ** <li> 64-bit signed integer
  5222. ** <li> 64-bit IEEE floating point number
  5223. ** <li> string
  5224. ** <li> BLOB
  5225. ** <li> NULL
  5226. ** </ul>)^
  5227. **
  5228. ** These constants are codes for each of those types.
  5229. **
  5230. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5231. ** for a completely different meaning. Software that links against both
  5232. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5233. ** SQLITE_TEXT.
  5234. */
  5235. #define SQLITE_INTEGER 1
  5236. #define SQLITE_FLOAT 2
  5237. #define SQLITE_BLOB 4
  5238. #define SQLITE_NULL 5
  5239. #ifdef SQLITE_TEXT
  5240. # undef SQLITE_TEXT
  5241. #else
  5242. # define SQLITE_TEXT 3
  5243. #endif
  5244. #define SQLITE3_TEXT 3
  5245. /*
  5246. ** CAPI3REF: Result Values From A Query
  5247. ** KEYWORDS: {column access functions}
  5248. ** METHOD: sqlite3_stmt
  5249. **
  5250. ** <b>Summary:</b>
  5251. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5252. ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5253. ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5254. ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5255. ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5256. ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5257. ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5258. ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
  5259. ** [sqlite3_value|unprotected sqlite3_value] object.
  5260. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5261. ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5262. ** or a UTF-8 TEXT result in bytes
  5263. ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5264. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5265. ** TEXT in bytes
  5266. ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5267. ** datatype of the result
  5268. ** </table></blockquote>
  5269. **
  5270. ** <b>Details:</b>
  5271. **
  5272. ** ^These routines return information about a single column of the current
  5273. ** result row of a query. ^In every case the first argument is a pointer
  5274. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5275. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5276. ** and the second argument is the index of the column for which information
  5277. ** should be returned. ^The leftmost column of the result set has the index 0.
  5278. ** ^The number of columns in the result can be determined using
  5279. ** [sqlite3_column_count()].
  5280. **
  5281. ** If the SQL statement does not currently point to a valid row, or if the
  5282. ** column index is out of range, the result is undefined.
  5283. ** These routines may only be called when the most recent call to
  5284. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5285. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5286. ** If any of these routines are called after [sqlite3_reset()] or
  5287. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5288. ** something other than [SQLITE_ROW], the results are undefined.
  5289. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5290. ** are called from a different thread while any of these routines
  5291. ** are pending, then the results are undefined.
  5292. **
  5293. ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5294. ** each return the value of a result column in a specific data format. If
  5295. ** the result column is not initially in the requested format (for example,
  5296. ** if the query returns an integer but the sqlite3_column_text() interface
  5297. ** is used to extract the value) then an automatic type conversion is performed.
  5298. **
  5299. ** ^The sqlite3_column_type() routine returns the
  5300. ** [SQLITE_INTEGER | datatype code] for the initial data type
  5301. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  5302. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5303. ** The return value of sqlite3_column_type() can be used to decide which
  5304. ** of the first six interface should be used to extract the column value.
  5305. ** The value returned by sqlite3_column_type() is only meaningful if no
  5306. ** automatic type conversions have occurred for the value in question.
  5307. ** After a type conversion, the result of calling sqlite3_column_type()
  5308. ** is undefined, though harmless. Future
  5309. ** versions of SQLite may change the behavior of sqlite3_column_type()
  5310. ** following a type conversion.
  5311. **
  5312. ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5313. ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5314. ** of that BLOB or string.
  5315. **
  5316. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5317. ** routine returns the number of bytes in that BLOB or string.
  5318. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5319. ** the string to UTF-8 and then returns the number of bytes.
  5320. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5321. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5322. ** the number of bytes in that string.
  5323. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5324. **
  5325. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5326. ** routine returns the number of bytes in that BLOB or string.
  5327. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5328. ** the string to UTF-16 and then returns the number of bytes.
  5329. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5330. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5331. ** the number of bytes in that string.
  5332. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5333. **
  5334. ** ^The values returned by [sqlite3_column_bytes()] and
  5335. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5336. ** of the string. ^For clarity: the values returned by
  5337. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5338. ** bytes in the string, not the number of characters.
  5339. **
  5340. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5341. ** even empty strings, are always zero-terminated. ^The return
  5342. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5343. **
  5344. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5345. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  5346. ** an unprotected sqlite3_value object may only be used safely with
  5347. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5348. ** If the [unprotected sqlite3_value] object returned by
  5349. ** [sqlite3_column_value()] is used in any other way, including calls
  5350. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5351. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5352. ** Hence, the sqlite3_column_value() interface
  5353. ** is normally only useful within the implementation of
  5354. ** [application-defined SQL functions] or [virtual tables], not within
  5355. ** top-level application code.
  5356. **
  5357. ** The these routines may attempt to convert the datatype of the result.
  5358. ** ^For example, if the internal representation is FLOAT and a text result
  5359. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5360. ** conversion automatically. ^(The following table details the conversions
  5361. ** that are applied:
  5362. **
  5363. ** <blockquote>
  5364. ** <table border="1">
  5365. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  5366. **
  5367. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  5368. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  5369. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  5370. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  5371. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  5372. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  5373. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  5374. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  5375. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  5376. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  5377. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  5378. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  5379. ** <tr><td> TEXT <td> BLOB <td> No change
  5380. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  5381. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  5382. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  5383. ** </table>
  5384. ** </blockquote>)^
  5385. **
  5386. ** Note that when type conversions occur, pointers returned by prior
  5387. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5388. ** sqlite3_column_text16() may be invalidated.
  5389. ** Type conversions and pointer invalidations might occur
  5390. ** in the following cases:
  5391. **
  5392. ** <ul>
  5393. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5394. ** sqlite3_column_text16() is called. A zero-terminator might
  5395. ** need to be added to the string.</li>
  5396. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5397. ** sqlite3_column_text16() is called. The content must be converted
  5398. ** to UTF-16.</li>
  5399. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5400. ** sqlite3_column_text() is called. The content must be converted
  5401. ** to UTF-8.</li>
  5402. ** </ul>
  5403. **
  5404. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5405. ** not invalidate a prior pointer, though of course the content of the buffer
  5406. ** that the prior pointer references will have been modified. Other kinds
  5407. ** of conversion are done in place when it is possible, but sometimes they
  5408. ** are not possible and in those cases prior pointers are invalidated.
  5409. **
  5410. ** The safest policy is to invoke these routines
  5411. ** in one of the following ways:
  5412. **
  5413. ** <ul>
  5414. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5415. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5416. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5417. ** </ul>
  5418. **
  5419. ** In other words, you should call sqlite3_column_text(),
  5420. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5421. ** into the desired format, then invoke sqlite3_column_bytes() or
  5422. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  5423. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5424. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5425. ** with calls to sqlite3_column_bytes().
  5426. **
  5427. ** ^The pointers returned are valid until a type conversion occurs as
  5428. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5429. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  5430. ** and BLOBs is freed automatically. Do not pass the pointers returned
  5431. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5432. ** [sqlite3_free()].
  5433. **
  5434. ** ^(If a memory allocation error occurs during the evaluation of any
  5435. ** of these routines, a default value is returned. The default value
  5436. ** is either the integer 0, the floating point number 0.0, or a NULL
  5437. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  5438. ** [SQLITE_NOMEM].)^
  5439. */
  5440. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5441. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5442. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5443. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5444. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5445. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5446. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5447. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5448. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5449. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5450. /*
  5451. ** CAPI3REF: Destroy A Prepared Statement Object
  5452. ** DESTRUCTOR: sqlite3_stmt
  5453. **
  5454. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5455. ** ^If the most recent evaluation of the statement encountered no errors
  5456. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5457. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  5458. ** sqlite3_finalize(S) returns the appropriate [error code] or
  5459. ** [extended error code].
  5460. **
  5461. ** ^The sqlite3_finalize(S) routine can be called at any point during
  5462. ** the life cycle of [prepared statement] S:
  5463. ** before statement S is ever evaluated, after
  5464. ** one or more calls to [sqlite3_reset()], or after any call
  5465. ** to [sqlite3_step()] regardless of whether or not the statement has
  5466. ** completed execution.
  5467. **
  5468. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5469. **
  5470. ** The application must finalize every [prepared statement] in order to avoid
  5471. ** resource leaks. It is a grievous error for the application to try to use
  5472. ** a prepared statement after it has been finalized. Any use of a prepared
  5473. ** statement after it has been finalized can result in undefined and
  5474. ** undesirable behavior such as segfaults and heap corruption.
  5475. */
  5476. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5477. /*
  5478. ** CAPI3REF: Reset A Prepared Statement Object
  5479. ** METHOD: sqlite3_stmt
  5480. **
  5481. ** The sqlite3_reset() function is called to reset a [prepared statement]
  5482. ** object back to its initial state, ready to be re-executed.
  5483. ** ^Any SQL statement variables that had values bound to them using
  5484. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5485. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5486. **
  5487. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5488. ** back to the beginning of its program.
  5489. **
  5490. ** ^If the most recent call to [sqlite3_step(S)] for the
  5491. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5492. ** or if [sqlite3_step(S)] has never before been called on S,
  5493. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5494. **
  5495. ** ^If the most recent call to [sqlite3_step(S)] for the
  5496. ** [prepared statement] S indicated an error, then
  5497. ** [sqlite3_reset(S)] returns an appropriate [error code].
  5498. **
  5499. ** ^The [sqlite3_reset(S)] interface does not change the values
  5500. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5501. */
  5502. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5503. /*
  5504. ** CAPI3REF: Create Or Redefine SQL Functions
  5505. ** KEYWORDS: {function creation routines}
  5506. ** KEYWORDS: {application-defined SQL function}
  5507. ** KEYWORDS: {application-defined SQL functions}
  5508. ** METHOD: sqlite3
  5509. **
  5510. ** ^These functions (collectively known as "function creation routines")
  5511. ** are used to add SQL functions or aggregates or to redefine the behavior
  5512. ** of existing SQL functions or aggregates. The only differences between
  5513. ** these routines are the text encoding expected for
  5514. ** the second parameter (the name of the function being created)
  5515. ** and the presence or absence of a destructor callback for
  5516. ** the application data pointer.
  5517. **
  5518. ** ^The first parameter is the [database connection] to which the SQL
  5519. ** function is to be added. ^If an application uses more than one database
  5520. ** connection then application-defined SQL functions must be added
  5521. ** to each database connection separately.
  5522. **
  5523. ** ^The second parameter is the name of the SQL function to be created or
  5524. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  5525. ** representation, exclusive of the zero-terminator. ^Note that the name
  5526. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  5527. ** ^Any attempt to create a function with a longer name
  5528. ** will result in [SQLITE_MISUSE] being returned.
  5529. **
  5530. ** ^The third parameter (nArg)
  5531. ** is the number of arguments that the SQL function or
  5532. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5533. ** aggregate may take any number of arguments between 0 and the limit
  5534. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  5535. ** parameter is less than -1 or greater than 127 then the behavior is
  5536. ** undefined.
  5537. **
  5538. ** ^The fourth parameter, eTextRep, specifies what
  5539. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5540. ** its parameters. The application should set this parameter to
  5541. ** [SQLITE_UTF16LE] if the function implementation invokes
  5542. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5543. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5544. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5545. ** otherwise. ^The same SQL function may be registered multiple times using
  5546. ** different preferred text encodings, with different implementations for
  5547. ** each encoding.
  5548. ** ^When multiple implementations of the same function are available, SQLite
  5549. ** will pick the one that involves the least amount of data conversion.
  5550. **
  5551. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5552. ** to signal that the function will always return the same result given
  5553. ** the same inputs within a single SQL statement. Most SQL functions are
  5554. ** deterministic. The built-in [random()] SQL function is an example of a
  5555. ** function that is not deterministic. The SQLite query planner is able to
  5556. ** perform additional optimizations on deterministic functions, so use
  5557. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5558. **
  5559. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  5560. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5561. **
  5562. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  5563. ** pointers to C-language functions that implement the SQL function or
  5564. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5565. ** callback only; NULL pointers must be passed as the xStep and xFinal
  5566. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5567. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5568. ** SQL function or aggregate, pass NULL pointers for all three function
  5569. ** callbacks.
  5570. **
  5571. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  5572. ** then it is destructor for the application data pointer.
  5573. ** The destructor is invoked when the function is deleted, either by being
  5574. ** overloaded or when the database connection closes.)^
  5575. ** ^The destructor is also invoked if the call to
  5576. ** sqlite3_create_function_v2() fails.
  5577. ** ^When the destructor callback of the tenth parameter is invoked, it
  5578. ** is passed a single argument which is a copy of the application data
  5579. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  5580. **
  5581. ** ^It is permitted to register multiple implementations of the same
  5582. ** functions with the same name but with either differing numbers of
  5583. ** arguments or differing preferred text encodings. ^SQLite will use
  5584. ** the implementation that most closely matches the way in which the
  5585. ** SQL function is used. ^A function implementation with a non-negative
  5586. ** nArg parameter is a better match than a function implementation with
  5587. ** a negative nArg. ^A function where the preferred text encoding
  5588. ** matches the database encoding is a better
  5589. ** match than a function where the encoding is different.
  5590. ** ^A function where the encoding difference is between UTF16le and UTF16be
  5591. ** is a closer match than a function where the encoding difference is
  5592. ** between UTF8 and UTF16.
  5593. **
  5594. ** ^Built-in functions may be overloaded by new application-defined functions.
  5595. **
  5596. ** ^An application-defined function is permitted to call other
  5597. ** SQLite interfaces. However, such calls must not
  5598. ** close the database connection nor finalize or reset the prepared
  5599. ** statement in which the function is running.
  5600. */
  5601. SQLITE_API int sqlite3_create_function(
  5602. sqlite3 *db,
  5603. const char *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_function16(
  5612. sqlite3 *db,
  5613. const void *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. );
  5621. SQLITE_API int sqlite3_create_function_v2(
  5622. sqlite3 *db,
  5623. const char *zFunctionName,
  5624. int nArg,
  5625. int eTextRep,
  5626. void *pApp,
  5627. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5628. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5629. void (*xFinal)(sqlite3_context*),
  5630. void(*xDestroy)(void*)
  5631. );
  5632. /*
  5633. ** CAPI3REF: Text Encodings
  5634. **
  5635. ** These constant define integer codes that represent the various
  5636. ** text encodings supported by SQLite.
  5637. */
  5638. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  5639. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  5640. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  5641. #define SQLITE_UTF16 4 /* Use native byte order */
  5642. #define SQLITE_ANY 5 /* Deprecated */
  5643. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  5644. /*
  5645. ** CAPI3REF: Function Flags
  5646. **
  5647. ** These constants may be ORed together with the
  5648. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5649. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5650. ** [sqlite3_create_function_v2()].
  5651. */
  5652. #define SQLITE_DETERMINISTIC 0x800
  5653. /*
  5654. ** CAPI3REF: Deprecated Functions
  5655. ** DEPRECATED
  5656. **
  5657. ** These functions are [deprecated]. In order to maintain
  5658. ** backwards compatibility with older code, these functions continue
  5659. ** to be supported. However, new applications should avoid
  5660. ** the use of these functions. To encourage programmers to avoid
  5661. ** these functions, we will not explain what they do.
  5662. */
  5663. #ifndef SQLITE_OMIT_DEPRECATED
  5664. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5665. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5666. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5667. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5668. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5669. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5670. void*,sqlite3_int64);
  5671. #endif
  5672. /*
  5673. ** CAPI3REF: Obtaining SQL Values
  5674. ** METHOD: sqlite3_value
  5675. **
  5676. ** <b>Summary:</b>
  5677. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5678. ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  5679. ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  5680. ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  5681. ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  5682. ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  5683. ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  5684. ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  5685. ** the native byteorder
  5686. ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  5687. ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  5688. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5689. ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  5690. ** or a UTF-8 TEXT in bytes
  5691. ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  5692. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5693. ** TEXT in bytes
  5694. ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  5695. ** datatype of the value
  5696. ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  5697. ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  5698. ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
  5699. ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
  5700. ** against a virtual table.
  5701. ** </table></blockquote>
  5702. **
  5703. ** <b>Details:</b>
  5704. **
  5705. ** These routines extract type, size, and content information from
  5706. ** [protected sqlite3_value] objects. Protected sqlite3_value objects
  5707. ** are used to pass parameter information into implementation of
  5708. ** [application-defined SQL functions] and [virtual tables].
  5709. **
  5710. ** These routines work only with [protected sqlite3_value] objects.
  5711. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  5712. ** is not threadsafe.
  5713. **
  5714. ** ^These routines work just like the corresponding [column access functions]
  5715. ** except that these routines take a single [protected sqlite3_value] object
  5716. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  5717. **
  5718. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  5719. ** in the native byte-order of the host machine. ^The
  5720. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  5721. ** extract UTF-16 strings as big-endian and little-endian respectively.
  5722. **
  5723. ** ^If [sqlite3_value] object V was initialized
  5724. ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  5725. ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  5726. ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
  5727. ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
  5728. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  5729. **
  5730. ** ^(The sqlite3_value_type(V) interface returns the
  5731. ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  5732. ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  5733. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  5734. ** Other interfaces might change the datatype for an sqlite3_value object.
  5735. ** For example, if the datatype is initially SQLITE_INTEGER and
  5736. ** sqlite3_value_text(V) is called to extract a text value for that
  5737. ** integer, then subsequent calls to sqlite3_value_type(V) might return
  5738. ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
  5739. ** occurs is undefined and may change from one release of SQLite to the next.
  5740. **
  5741. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  5742. ** numeric affinity to the value. This means that an attempt is
  5743. ** made to convert the value to an integer or floating point. If
  5744. ** such a conversion is possible without loss of information (in other
  5745. ** words, if the value is a string that looks like a number)
  5746. ** then the conversion is performed. Otherwise no conversion occurs.
  5747. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  5748. **
  5749. ** ^Within the [xUpdate] method of a [virtual table], the
  5750. ** sqlite3_value_nochange(X) interface returns true if and only if
  5751. ** the column corresponding to X is unchanged by the UPDATE operation
  5752. ** that the xUpdate method call was invoked to implement and if
  5753. ** and the prior [xColumn] method call that was invoked to extracted
  5754. ** the value for that column returned without setting a result (probably
  5755. ** because it queried [sqlite3_vtab_nochange()] and found that the column
  5756. ** was unchanging). ^Within an [xUpdate] method, any value for which
  5757. ** sqlite3_value_nochange(X) is true will in all other respects appear
  5758. ** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
  5759. ** than within an [xUpdate] method call for an UPDATE statement, then
  5760. ** the return value is arbitrary and meaningless.
  5761. **
  5762. ** Please pay particular attention to the fact that the pointer returned
  5763. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  5764. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  5765. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  5766. ** or [sqlite3_value_text16()].
  5767. **
  5768. ** These routines must be called from the same thread as
  5769. ** the SQL function that supplied the [sqlite3_value*] parameters.
  5770. */
  5771. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  5772. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  5773. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  5774. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  5775. SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  5776. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  5777. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  5778. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  5779. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  5780. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  5781. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  5782. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  5783. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  5784. SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
  5785. /*
  5786. ** CAPI3REF: Finding The Subtype Of SQL Values
  5787. ** METHOD: sqlite3_value
  5788. **
  5789. ** The sqlite3_value_subtype(V) function returns the subtype for
  5790. ** an [application-defined SQL function] argument V. The subtype
  5791. ** information can be used to pass a limited amount of context from
  5792. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  5793. ** routine to set the subtype for the return value of an SQL function.
  5794. */
  5795. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  5796. /*
  5797. ** CAPI3REF: Copy And Free SQL Values
  5798. ** METHOD: sqlite3_value
  5799. **
  5800. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  5801. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  5802. ** is a [protected sqlite3_value] object even if the input is not.
  5803. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  5804. ** memory allocation fails.
  5805. **
  5806. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  5807. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  5808. ** then sqlite3_value_free(V) is a harmless no-op.
  5809. */
  5810. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  5811. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  5812. /*
  5813. ** CAPI3REF: Obtain Aggregate Function Context
  5814. ** METHOD: sqlite3_context
  5815. **
  5816. ** Implementations of aggregate SQL functions use this
  5817. ** routine to allocate memory for storing their state.
  5818. **
  5819. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  5820. ** for a particular aggregate function, SQLite
  5821. ** allocates N of memory, zeroes out that memory, and returns a pointer
  5822. ** to the new memory. ^On second and subsequent calls to
  5823. ** sqlite3_aggregate_context() for the same aggregate function instance,
  5824. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  5825. ** called once for each invocation of the xStep callback and then one
  5826. ** last time when the xFinal callback is invoked. ^(When no rows match
  5827. ** an aggregate query, the xStep() callback of the aggregate function
  5828. ** implementation is never called and xFinal() is called exactly once.
  5829. ** In those cases, sqlite3_aggregate_context() might be called for the
  5830. ** first time from within xFinal().)^
  5831. **
  5832. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  5833. ** when first called if N is less than or equal to zero or if a memory
  5834. ** allocate error occurs.
  5835. **
  5836. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  5837. ** determined by the N parameter on first successful call. Changing the
  5838. ** value of N in subsequent call to sqlite3_aggregate_context() within
  5839. ** the same aggregate function instance will not resize the memory
  5840. ** allocation.)^ Within the xFinal callback, it is customary to set
  5841. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  5842. ** pointless memory allocations occur.
  5843. **
  5844. ** ^SQLite automatically frees the memory allocated by
  5845. ** sqlite3_aggregate_context() when the aggregate query concludes.
  5846. **
  5847. ** The first parameter must be a copy of the
  5848. ** [sqlite3_context | SQL function context] that is the first parameter
  5849. ** to the xStep or xFinal callback routine that implements the aggregate
  5850. ** function.
  5851. **
  5852. ** This routine must be called from the same thread in which
  5853. ** the aggregate SQL function is running.
  5854. */
  5855. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  5856. /*
  5857. ** CAPI3REF: User Data For Functions
  5858. ** METHOD: sqlite3_context
  5859. **
  5860. ** ^The sqlite3_user_data() interface returns a copy of
  5861. ** the pointer that was the pUserData parameter (the 5th parameter)
  5862. ** of the [sqlite3_create_function()]
  5863. ** and [sqlite3_create_function16()] routines that originally
  5864. ** registered the application defined function.
  5865. **
  5866. ** This routine must be called from the same thread in which
  5867. ** the application-defined function is running.
  5868. */
  5869. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  5870. /*
  5871. ** CAPI3REF: Database Connection For Functions
  5872. ** METHOD: sqlite3_context
  5873. **
  5874. ** ^The sqlite3_context_db_handle() interface returns a copy of
  5875. ** the pointer to the [database connection] (the 1st parameter)
  5876. ** of the [sqlite3_create_function()]
  5877. ** and [sqlite3_create_function16()] routines that originally
  5878. ** registered the application defined function.
  5879. */
  5880. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  5881. /*
  5882. ** CAPI3REF: Function Auxiliary Data
  5883. ** METHOD: sqlite3_context
  5884. **
  5885. ** These functions may be used by (non-aggregate) SQL functions to
  5886. ** associate metadata with argument values. If the same value is passed to
  5887. ** multiple invocations of the same SQL function during query execution, under
  5888. ** some circumstances the associated metadata may be preserved. An example
  5889. ** of where this might be useful is in a regular-expression matching
  5890. ** function. The compiled version of the regular expression can be stored as
  5891. ** metadata associated with the pattern string.
  5892. ** Then as long as the pattern string remains the same,
  5893. ** the compiled regular expression can be reused on multiple
  5894. ** invocations of the same function.
  5895. **
  5896. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  5897. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  5898. ** value to the application-defined function. ^N is zero for the left-most
  5899. ** function argument. ^If there is no metadata
  5900. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  5901. ** returns a NULL pointer.
  5902. **
  5903. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  5904. ** argument of the application-defined function. ^Subsequent
  5905. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  5906. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  5907. ** NULL if the metadata has been discarded.
  5908. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  5909. ** SQLite will invoke the destructor function X with parameter P exactly
  5910. ** once, when the metadata is discarded.
  5911. ** SQLite is free to discard the metadata at any time, including: <ul>
  5912. ** <li> ^(when the corresponding function parameter changes)^, or
  5913. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  5914. ** SQL statement)^, or
  5915. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  5916. ** parameter)^, or
  5917. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  5918. ** allocation error occurs.)^ </ul>
  5919. **
  5920. ** Note the last bullet in particular. The destructor X in
  5921. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  5922. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  5923. ** should be called near the end of the function implementation and the
  5924. ** function implementation should not make any use of P after
  5925. ** sqlite3_set_auxdata() has been called.
  5926. **
  5927. ** ^(In practice, metadata is preserved between function calls for
  5928. ** function parameters that are compile-time constants, including literal
  5929. ** values and [parameters] and expressions composed from the same.)^
  5930. **
  5931. ** The value of the N parameter to these interfaces should be non-negative.
  5932. ** Future enhancements may make use of negative N values to define new
  5933. ** kinds of function caching behavior.
  5934. **
  5935. ** These routines must be called from the same thread in which
  5936. ** the SQL function is running.
  5937. */
  5938. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  5939. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  5940. /*
  5941. ** CAPI3REF: Constants Defining Special Destructor Behavior
  5942. **
  5943. ** These are special values for the destructor that is passed in as the
  5944. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  5945. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  5946. ** and will never change. It does not need to be destroyed. ^The
  5947. ** SQLITE_TRANSIENT value means that the content will likely change in
  5948. ** the near future and that SQLite should make its own private copy of
  5949. ** the content before returning.
  5950. **
  5951. ** The typedef is necessary to work around problems in certain
  5952. ** C++ compilers.
  5953. */
  5954. typedef void (*sqlite3_destructor_type)(void*);
  5955. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  5956. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  5957. /*
  5958. ** CAPI3REF: Setting The Result Of An SQL Function
  5959. ** METHOD: sqlite3_context
  5960. **
  5961. ** These routines are used by the xFunc or xFinal callbacks that
  5962. ** implement SQL functions and aggregates. See
  5963. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  5964. ** for additional information.
  5965. **
  5966. ** These functions work very much like the [parameter binding] family of
  5967. ** functions used to bind values to host parameters in prepared statements.
  5968. ** Refer to the [SQL parameter] documentation for additional information.
  5969. **
  5970. ** ^The sqlite3_result_blob() interface sets the result from
  5971. ** an application-defined function to be the BLOB whose content is pointed
  5972. ** to by the second parameter and which is N bytes long where N is the
  5973. ** third parameter.
  5974. **
  5975. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  5976. ** interfaces set the result of the application-defined function to be
  5977. ** a BLOB containing all zero bytes and N bytes in size.
  5978. **
  5979. ** ^The sqlite3_result_double() interface sets the result from
  5980. ** an application-defined function to be a floating point value specified
  5981. ** by its 2nd argument.
  5982. **
  5983. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  5984. ** cause the implemented SQL function to throw an exception.
  5985. ** ^SQLite uses the string pointed to by the
  5986. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  5987. ** as the text of an error message. ^SQLite interprets the error
  5988. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  5989. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  5990. ** byte order. ^If the third parameter to sqlite3_result_error()
  5991. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  5992. ** message all text up through the first zero character.
  5993. ** ^If the third parameter to sqlite3_result_error() or
  5994. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  5995. ** bytes (not characters) from the 2nd parameter as the error message.
  5996. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  5997. ** routines make a private copy of the error message text before
  5998. ** they return. Hence, the calling function can deallocate or
  5999. ** modify the text after they return without harm.
  6000. ** ^The sqlite3_result_error_code() function changes the error code
  6001. ** returned by SQLite as a result of an error in a function. ^By default,
  6002. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  6003. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  6004. **
  6005. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  6006. ** error indicating that a string or BLOB is too long to represent.
  6007. **
  6008. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  6009. ** error indicating that a memory allocation failed.
  6010. **
  6011. ** ^The sqlite3_result_int() interface sets the return value
  6012. ** of the application-defined function to be the 32-bit signed integer
  6013. ** value given in the 2nd argument.
  6014. ** ^The sqlite3_result_int64() interface sets the return value
  6015. ** of the application-defined function to be the 64-bit signed integer
  6016. ** value given in the 2nd argument.
  6017. **
  6018. ** ^The sqlite3_result_null() interface sets the return value
  6019. ** of the application-defined function to be NULL.
  6020. **
  6021. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  6022. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  6023. ** set the return value of the application-defined function to be
  6024. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  6025. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  6026. ** ^The sqlite3_result_text64() interface sets the return value of an
  6027. ** application-defined function to be a text string in an encoding
  6028. ** specified by the fifth (and last) parameter, which must be one
  6029. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6030. ** ^SQLite takes the text result from the application from
  6031. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6032. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6033. ** is negative, then SQLite takes result text from the 2nd parameter
  6034. ** through the first zero character.
  6035. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6036. ** is non-negative, then as many bytes (not characters) of the text
  6037. ** pointed to by the 2nd parameter are taken as the application-defined
  6038. ** function result. If the 3rd parameter is non-negative, then it
  6039. ** must be the byte offset into the string where the NUL terminator would
  6040. ** appear if the string where NUL terminated. If any NUL characters occur
  6041. ** in the string at a byte offset that is less than the value of the 3rd
  6042. ** parameter, then the resulting string will contain embedded NULs and the
  6043. ** result of expressions operating on strings with embedded NULs is undefined.
  6044. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6045. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6046. ** function as the destructor on the text or BLOB result when it has
  6047. ** finished using that result.
  6048. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6049. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6050. ** assumes that the text or BLOB result is in constant space and does not
  6051. ** copy the content of the parameter nor call a destructor on the content
  6052. ** when it has finished using that result.
  6053. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6054. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6055. ** then SQLite makes a copy of the result into space obtained
  6056. ** from [sqlite3_malloc()] before it returns.
  6057. **
  6058. ** ^The sqlite3_result_value() interface sets the result of
  6059. ** the application-defined function to be a copy of the
  6060. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  6061. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6062. ** so that the [sqlite3_value] specified in the parameter may change or
  6063. ** be deallocated after sqlite3_result_value() returns without harm.
  6064. ** ^A [protected sqlite3_value] object may always be used where an
  6065. ** [unprotected sqlite3_value] object is required, so either
  6066. ** kind of [sqlite3_value] object can be used with this interface.
  6067. **
  6068. ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6069. ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6070. ** also associates the host-language pointer P or type T with that
  6071. ** NULL value such that the pointer can be retrieved within an
  6072. ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6073. ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6074. ** for the P parameter. ^SQLite invokes D with P as its only argument
  6075. ** when SQLite is finished with P. The T parameter should be a static
  6076. ** string and preferably a string literal. The sqlite3_result_pointer()
  6077. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6078. **
  6079. ** If these routines are called from within the different thread
  6080. ** than the one containing the application-defined function that received
  6081. ** the [sqlite3_context] pointer, the results are undefined.
  6082. */
  6083. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6084. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6085. sqlite3_uint64,void(*)(void*));
  6086. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6087. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6088. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6089. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6090. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6091. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6092. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6093. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6094. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6095. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6096. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6097. void(*)(void*), unsigned char encoding);
  6098. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6099. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6100. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6101. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6102. SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6103. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6104. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6105. /*
  6106. ** CAPI3REF: Setting The Subtype Of An SQL Function
  6107. ** METHOD: sqlite3_context
  6108. **
  6109. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6110. ** the result from the [application-defined SQL function] with
  6111. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  6112. ** of the subtype T are preserved in current versions of SQLite;
  6113. ** higher order bits are discarded.
  6114. ** The number of subtype bytes preserved by SQLite might increase
  6115. ** in future releases of SQLite.
  6116. */
  6117. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6118. /*
  6119. ** CAPI3REF: Define New Collating Sequences
  6120. ** METHOD: sqlite3
  6121. **
  6122. ** ^These functions add, remove, or modify a [collation] associated
  6123. ** with the [database connection] specified as the first argument.
  6124. **
  6125. ** ^The name of the collation is a UTF-8 string
  6126. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6127. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6128. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6129. ** considered to be the same name.
  6130. **
  6131. ** ^(The third argument (eTextRep) must be one of the constants:
  6132. ** <ul>
  6133. ** <li> [SQLITE_UTF8],
  6134. ** <li> [SQLITE_UTF16LE],
  6135. ** <li> [SQLITE_UTF16BE],
  6136. ** <li> [SQLITE_UTF16], or
  6137. ** <li> [SQLITE_UTF16_ALIGNED].
  6138. ** </ul>)^
  6139. ** ^The eTextRep argument determines the encoding of strings passed
  6140. ** to the collating function callback, xCallback.
  6141. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6142. ** force strings to be UTF16 with native byte order.
  6143. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6144. ** on an even byte address.
  6145. **
  6146. ** ^The fourth argument, pArg, is an application data pointer that is passed
  6147. ** through as the first argument to the collating function callback.
  6148. **
  6149. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6150. ** ^Multiple collating functions can be registered using the same name but
  6151. ** with different eTextRep parameters and SQLite will use whichever
  6152. ** function requires the least amount of data transformation.
  6153. ** ^If the xCallback argument is NULL then the collating function is
  6154. ** deleted. ^When all collating functions having the same name are deleted,
  6155. ** that collation is no longer usable.
  6156. **
  6157. ** ^The collating function callback is invoked with a copy of the pArg
  6158. ** application data pointer and with two strings in the encoding specified
  6159. ** by the eTextRep argument. The collating function must return an
  6160. ** integer that is negative, zero, or positive
  6161. ** if the first string is less than, equal to, or greater than the second,
  6162. ** respectively. A collating function must always return the same answer
  6163. ** given the same inputs. If two or more collating functions are registered
  6164. ** to the same collation name (using different eTextRep values) then all
  6165. ** must give an equivalent answer when invoked with equivalent strings.
  6166. ** The collating function must obey the following properties for all
  6167. ** strings A, B, and C:
  6168. **
  6169. ** <ol>
  6170. ** <li> If A==B then B==A.
  6171. ** <li> If A==B and B==C then A==C.
  6172. ** <li> If A&lt;B THEN B&gt;A.
  6173. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6174. ** </ol>
  6175. **
  6176. ** If a collating function fails any of the above constraints and that
  6177. ** collating function is registered and used, then the behavior of SQLite
  6178. ** is undefined.
  6179. **
  6180. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6181. ** with the addition that the xDestroy callback is invoked on pArg when
  6182. ** the collating function is deleted.
  6183. ** ^Collating functions are deleted when they are overridden by later
  6184. ** calls to the collation creation functions or when the
  6185. ** [database connection] is closed using [sqlite3_close()].
  6186. **
  6187. ** ^The xDestroy callback is <u>not</u> called if the
  6188. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  6189. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  6190. ** check the return code and dispose of the application data pointer
  6191. ** themselves rather than expecting SQLite to deal with it for them.
  6192. ** This is different from every other SQLite interface. The inconsistency
  6193. ** is unfortunate but cannot be changed without breaking backwards
  6194. ** compatibility.
  6195. **
  6196. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6197. */
  6198. SQLITE_API int sqlite3_create_collation(
  6199. sqlite3*,
  6200. const char *zName,
  6201. int eTextRep,
  6202. void *pArg,
  6203. int(*xCompare)(void*,int,const void*,int,const void*)
  6204. );
  6205. SQLITE_API int sqlite3_create_collation_v2(
  6206. sqlite3*,
  6207. const char *zName,
  6208. int eTextRep,
  6209. void *pArg,
  6210. int(*xCompare)(void*,int,const void*,int,const void*),
  6211. void(*xDestroy)(void*)
  6212. );
  6213. SQLITE_API int sqlite3_create_collation16(
  6214. sqlite3*,
  6215. const void *zName,
  6216. int eTextRep,
  6217. void *pArg,
  6218. int(*xCompare)(void*,int,const void*,int,const void*)
  6219. );
  6220. /*
  6221. ** CAPI3REF: Collation Needed Callbacks
  6222. ** METHOD: sqlite3
  6223. **
  6224. ** ^To avoid having to register all collation sequences before a database
  6225. ** can be used, a single callback function may be registered with the
  6226. ** [database connection] to be invoked whenever an undefined collation
  6227. ** sequence is required.
  6228. **
  6229. ** ^If the function is registered using the sqlite3_collation_needed() API,
  6230. ** then it is passed the names of undefined collation sequences as strings
  6231. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6232. ** the names are passed as UTF-16 in machine native byte order.
  6233. ** ^A call to either function replaces the existing collation-needed callback.
  6234. **
  6235. ** ^(When the callback is invoked, the first argument passed is a copy
  6236. ** of the second argument to sqlite3_collation_needed() or
  6237. ** sqlite3_collation_needed16(). The second argument is the database
  6238. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6239. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6240. ** sequence function required. The fourth parameter is the name of the
  6241. ** required collation sequence.)^
  6242. **
  6243. ** The callback function should register the desired collation using
  6244. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6245. ** [sqlite3_create_collation_v2()].
  6246. */
  6247. SQLITE_API int sqlite3_collation_needed(
  6248. sqlite3*,
  6249. void*,
  6250. void(*)(void*,sqlite3*,int eTextRep,const char*)
  6251. );
  6252. SQLITE_API int sqlite3_collation_needed16(
  6253. sqlite3*,
  6254. void*,
  6255. void(*)(void*,sqlite3*,int eTextRep,const void*)
  6256. );
  6257. #ifdef SQLITE_HAS_CODEC
  6258. /*
  6259. ** Specify the key for an encrypted database. This routine should be
  6260. ** called right after sqlite3_open().
  6261. **
  6262. ** The code to implement this API is not available in the public release
  6263. ** of SQLite.
  6264. */
  6265. SQLITE_API int sqlite3_key(
  6266. sqlite3 *db, /* Database to be rekeyed */
  6267. const void *pKey, int nKey /* The key */
  6268. );
  6269. SQLITE_API int sqlite3_key_v2(
  6270. sqlite3 *db, /* Database to be rekeyed */
  6271. const char *zDbName, /* Name of the database */
  6272. const void *pKey, int nKey /* The key */
  6273. );
  6274. /*
  6275. ** Change the key on an open database. If the current database is not
  6276. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  6277. ** database is decrypted.
  6278. **
  6279. ** The code to implement this API is not available in the public release
  6280. ** of SQLite.
  6281. */
  6282. SQLITE_API int sqlite3_rekey(
  6283. sqlite3 *db, /* Database to be rekeyed */
  6284. const void *pKey, int nKey /* The new key */
  6285. );
  6286. SQLITE_API int sqlite3_rekey_v2(
  6287. sqlite3 *db, /* Database to be rekeyed */
  6288. const char *zDbName, /* Name of the database */
  6289. const void *pKey, int nKey /* The new key */
  6290. );
  6291. /*
  6292. ** Specify the activation key for a SEE database. Unless
  6293. ** activated, none of the SEE routines will work.
  6294. */
  6295. SQLITE_API void sqlite3_activate_see(
  6296. const char *zPassPhrase /* Activation phrase */
  6297. );
  6298. #endif
  6299. #ifdef SQLITE_ENABLE_CEROD
  6300. /*
  6301. ** Specify the activation key for a CEROD database. Unless
  6302. ** activated, none of the CEROD routines will work.
  6303. */
  6304. SQLITE_API void sqlite3_activate_cerod(
  6305. const char *zPassPhrase /* Activation phrase */
  6306. );
  6307. #endif
  6308. /*
  6309. ** CAPI3REF: Suspend Execution For A Short Time
  6310. **
  6311. ** The sqlite3_sleep() function causes the current thread to suspend execution
  6312. ** for at least a number of milliseconds specified in its parameter.
  6313. **
  6314. ** If the operating system does not support sleep requests with
  6315. ** millisecond time resolution, then the time will be rounded up to
  6316. ** the nearest second. The number of milliseconds of sleep actually
  6317. ** requested from the operating system is returned.
  6318. **
  6319. ** ^SQLite implements this interface by calling the xSleep()
  6320. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  6321. ** of the default VFS is not implemented correctly, or not implemented at
  6322. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6323. ** in the previous paragraphs.
  6324. */
  6325. SQLITE_API int sqlite3_sleep(int);
  6326. /*
  6327. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6328. **
  6329. ** ^(If this global variable is made to point to a string which is
  6330. ** the name of a folder (a.k.a. directory), then all temporary files
  6331. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6332. ** will be placed in that directory.)^ ^If this variable
  6333. ** is a NULL pointer, then SQLite performs a search for an appropriate
  6334. ** temporary file directory.
  6335. **
  6336. ** Applications are strongly discouraged from using this global variable.
  6337. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6338. ** But for all other platforms, it is highly recommended that applications
  6339. ** neither read nor write this variable. This global variable is a relic
  6340. ** that exists for backwards compatibility of legacy applications and should
  6341. ** be avoided in new projects.
  6342. **
  6343. ** It is not safe to read or modify this variable in more than one
  6344. ** thread at a time. It is not safe to read or modify this variable
  6345. ** if a [database connection] is being used at the same time in a separate
  6346. ** thread.
  6347. ** It is intended that this variable be set once
  6348. ** as part of process initialization and before any SQLite interface
  6349. ** routines have been called and that this variable remain unchanged
  6350. ** thereafter.
  6351. **
  6352. ** ^The [temp_store_directory pragma] may modify this variable and cause
  6353. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6354. ** the [temp_store_directory pragma] always assumes that any string
  6355. ** that this variable points to is held in memory obtained from
  6356. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6357. ** using [sqlite3_free].
  6358. ** Hence, if this variable is modified directly, either it should be
  6359. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6360. ** or else the use of the [temp_store_directory pragma] should be avoided.
  6361. ** Except when requested by the [temp_store_directory pragma], SQLite
  6362. ** does not free the memory that sqlite3_temp_directory points to. If
  6363. ** the application wants that memory to be freed, it must do
  6364. ** so itself, taking care to only do so after all [database connection]
  6365. ** objects have been destroyed.
  6366. **
  6367. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  6368. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  6369. ** features that require the use of temporary files may fail. Here is an
  6370. ** example of how to do this using C++ with the Windows Runtime:
  6371. **
  6372. ** <blockquote><pre>
  6373. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6374. ** &nbsp; TemporaryFolder->Path->Data();
  6375. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6376. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6377. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6378. ** &nbsp; NULL, NULL);
  6379. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6380. ** </pre></blockquote>
  6381. */
  6382. SQLITE_API char *sqlite3_temp_directory;
  6383. /*
  6384. ** CAPI3REF: Name Of The Folder Holding Database Files
  6385. **
  6386. ** ^(If this global variable is made to point to a string which is
  6387. ** the name of a folder (a.k.a. directory), then all database files
  6388. ** specified with a relative pathname and created or accessed by
  6389. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6390. ** to be relative to that directory.)^ ^If this variable is a NULL
  6391. ** pointer, then SQLite assumes that all database files specified
  6392. ** with a relative pathname are relative to the current directory
  6393. ** for the process. Only the windows VFS makes use of this global
  6394. ** variable; it is ignored by the unix VFS.
  6395. **
  6396. ** Changing the value of this variable while a database connection is
  6397. ** open can result in a corrupt database.
  6398. **
  6399. ** It is not safe to read or modify this variable in more than one
  6400. ** thread at a time. It is not safe to read or modify this variable
  6401. ** if a [database connection] is being used at the same time in a separate
  6402. ** thread.
  6403. ** It is intended that this variable be set once
  6404. ** as part of process initialization and before any SQLite interface
  6405. ** routines have been called and that this variable remain unchanged
  6406. ** thereafter.
  6407. **
  6408. ** ^The [data_store_directory pragma] may modify this variable and cause
  6409. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6410. ** the [data_store_directory pragma] always assumes that any string
  6411. ** that this variable points to is held in memory obtained from
  6412. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6413. ** using [sqlite3_free].
  6414. ** Hence, if this variable is modified directly, either it should be
  6415. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6416. ** or else the use of the [data_store_directory pragma] should be avoided.
  6417. */
  6418. SQLITE_API char *sqlite3_data_directory;
  6419. /*
  6420. ** CAPI3REF: Win32 Specific Interface
  6421. **
  6422. ** These interfaces are available only on Windows. The
  6423. ** [sqlite3_win32_set_directory] interface is used to set the value associated
  6424. ** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  6425. ** zValue, depending on the value of the type parameter. The zValue parameter
  6426. ** should be NULL to cause the previous value to be freed via [sqlite3_free];
  6427. ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  6428. ** prior to being used. The [sqlite3_win32_set_directory] interface returns
  6429. ** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  6430. ** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
  6431. ** [sqlite3_data_directory] variable is intended to act as a replacement for
  6432. ** the current directory on the sub-platforms of Win32 where that concept is
  6433. ** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
  6434. ** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  6435. ** sqlite3_win32_set_directory interface except the string parameter must be
  6436. ** UTF-8 or UTF-16, respectively.
  6437. */
  6438. SQLITE_API int sqlite3_win32_set_directory(
  6439. unsigned long type, /* Identifier for directory being set or reset */
  6440. void *zValue /* New value for directory being set or reset */
  6441. );
  6442. SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  6443. SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  6444. /*
  6445. ** CAPI3REF: Win32 Directory Types
  6446. **
  6447. ** These macros are only available on Windows. They define the allowed values
  6448. ** for the type argument to the [sqlite3_win32_set_directory] interface.
  6449. */
  6450. #define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
  6451. #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
  6452. /*
  6453. ** CAPI3REF: Test For Auto-Commit Mode
  6454. ** KEYWORDS: {autocommit mode}
  6455. ** METHOD: sqlite3
  6456. **
  6457. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6458. ** zero if the given database connection is or is not in autocommit mode,
  6459. ** respectively. ^Autocommit mode is on by default.
  6460. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6461. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6462. **
  6463. ** If certain kinds of errors occur on a statement within a multi-statement
  6464. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6465. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6466. ** transaction might be rolled back automatically. The only way to
  6467. ** find out whether SQLite automatically rolled back the transaction after
  6468. ** an error is to use this function.
  6469. **
  6470. ** If another thread changes the autocommit status of the database
  6471. ** connection while this routine is running, then the return value
  6472. ** is undefined.
  6473. */
  6474. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6475. /*
  6476. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6477. ** METHOD: sqlite3_stmt
  6478. **
  6479. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6480. ** to which a [prepared statement] belongs. ^The [database connection]
  6481. ** returned by sqlite3_db_handle is the same [database connection]
  6482. ** that was the first argument
  6483. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6484. ** create the statement in the first place.
  6485. */
  6486. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6487. /*
  6488. ** CAPI3REF: Return The Filename For A Database Connection
  6489. ** METHOD: sqlite3
  6490. **
  6491. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6492. ** associated with database N of connection D. ^The main database file
  6493. ** has the name "main". If there is no attached database N on the database
  6494. ** connection D, or if database N is a temporary or in-memory database, then
  6495. ** a NULL pointer is returned.
  6496. **
  6497. ** ^The filename returned by this function is the output of the
  6498. ** xFullPathname method of the [VFS]. ^In other words, the filename
  6499. ** will be an absolute pathname, even if the filename used
  6500. ** to open the database originally was a URI or relative pathname.
  6501. */
  6502. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6503. /*
  6504. ** CAPI3REF: Determine if a database is read-only
  6505. ** METHOD: sqlite3
  6506. **
  6507. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6508. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6509. ** the name of a database on connection D.
  6510. */
  6511. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6512. /*
  6513. ** CAPI3REF: Find the next prepared statement
  6514. ** METHOD: sqlite3
  6515. **
  6516. ** ^This interface returns a pointer to the next [prepared statement] after
  6517. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  6518. ** then this interface returns a pointer to the first prepared statement
  6519. ** associated with the database connection pDb. ^If no prepared statement
  6520. ** satisfies the conditions of this routine, it returns NULL.
  6521. **
  6522. ** The [database connection] pointer D in a call to
  6523. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6524. ** connection and in particular must not be a NULL pointer.
  6525. */
  6526. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6527. /*
  6528. ** CAPI3REF: Commit And Rollback Notification Callbacks
  6529. ** METHOD: sqlite3
  6530. **
  6531. ** ^The sqlite3_commit_hook() interface registers a callback
  6532. ** function to be invoked whenever a transaction is [COMMIT | committed].
  6533. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6534. ** for the same database connection is overridden.
  6535. ** ^The sqlite3_rollback_hook() interface registers a callback
  6536. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6537. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6538. ** for the same database connection is overridden.
  6539. ** ^The pArg argument is passed through to the callback.
  6540. ** ^If the callback on a commit hook function returns non-zero,
  6541. ** then the commit is converted into a rollback.
  6542. **
  6543. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6544. ** return the P argument from the previous call of the same function
  6545. ** on the same [database connection] D, or NULL for
  6546. ** the first call for each function on D.
  6547. **
  6548. ** The commit and rollback hook callbacks are not reentrant.
  6549. ** The callback implementation must not do anything that will modify
  6550. ** the database connection that invoked the callback. Any actions
  6551. ** to modify the database connection must be deferred until after the
  6552. ** completion of the [sqlite3_step()] call that triggered the commit
  6553. ** or rollback hook in the first place.
  6554. ** Note that running any other SQL statements, including SELECT statements,
  6555. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6556. ** the database connections for the meaning of "modify" in this paragraph.
  6557. **
  6558. ** ^Registering a NULL function disables the callback.
  6559. **
  6560. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6561. ** operation is allowed to continue normally. ^If the commit hook
  6562. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6563. ** ^The rollback hook is invoked on a rollback that results from a commit
  6564. ** hook returning non-zero, just as it would be with any other rollback.
  6565. **
  6566. ** ^For the purposes of this API, a transaction is said to have been
  6567. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6568. ** an error or constraint causes an implicit rollback to occur.
  6569. ** ^The rollback callback is not invoked if a transaction is
  6570. ** automatically rolled back because the database connection is closed.
  6571. **
  6572. ** See also the [sqlite3_update_hook()] interface.
  6573. */
  6574. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6575. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6576. /*
  6577. ** CAPI3REF: Data Change Notification Callbacks
  6578. ** METHOD: sqlite3
  6579. **
  6580. ** ^The sqlite3_update_hook() interface registers a callback function
  6581. ** with the [database connection] identified by the first argument
  6582. ** to be invoked whenever a row is updated, inserted or deleted in
  6583. ** a [rowid table].
  6584. ** ^Any callback set by a previous call to this function
  6585. ** for the same database connection is overridden.
  6586. **
  6587. ** ^The second argument is a pointer to the function to invoke when a
  6588. ** row is updated, inserted or deleted in a rowid table.
  6589. ** ^The first argument to the callback is a copy of the third argument
  6590. ** to sqlite3_update_hook().
  6591. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6592. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6593. ** to be invoked.
  6594. ** ^The third and fourth arguments to the callback contain pointers to the
  6595. ** database and table name containing the affected row.
  6596. ** ^The final callback parameter is the [rowid] of the row.
  6597. ** ^In the case of an update, this is the [rowid] after the update takes place.
  6598. **
  6599. ** ^(The update hook is not invoked when internal system tables are
  6600. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6601. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6602. **
  6603. ** ^In the current implementation, the update hook
  6604. ** is not invoked when conflicting rows are deleted because of an
  6605. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  6606. ** invoked when rows are deleted using the [truncate optimization].
  6607. ** The exceptions defined in this paragraph might change in a future
  6608. ** release of SQLite.
  6609. **
  6610. ** The update hook implementation must not do anything that will modify
  6611. ** the database connection that invoked the update hook. Any actions
  6612. ** to modify the database connection must be deferred until after the
  6613. ** completion of the [sqlite3_step()] call that triggered the update hook.
  6614. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6615. ** database connections for the meaning of "modify" in this paragraph.
  6616. **
  6617. ** ^The sqlite3_update_hook(D,C,P) function
  6618. ** returns the P argument from the previous call
  6619. ** on the same [database connection] D, or NULL for
  6620. ** the first call on D.
  6621. **
  6622. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6623. ** and [sqlite3_preupdate_hook()] interfaces.
  6624. */
  6625. SQLITE_API void *sqlite3_update_hook(
  6626. sqlite3*,
  6627. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  6628. void*
  6629. );
  6630. /*
  6631. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  6632. **
  6633. ** ^(This routine enables or disables the sharing of the database cache
  6634. ** and schema data structures between [database connection | connections]
  6635. ** to the same database. Sharing is enabled if the argument is true
  6636. ** and disabled if the argument is false.)^
  6637. **
  6638. ** ^Cache sharing is enabled and disabled for an entire process.
  6639. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  6640. ** In prior versions of SQLite,
  6641. ** sharing was enabled or disabled for each thread separately.
  6642. **
  6643. ** ^(The cache sharing mode set by this interface effects all subsequent
  6644. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  6645. ** Existing database connections continue use the sharing mode
  6646. ** that was in effect at the time they were opened.)^
  6647. **
  6648. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  6649. ** successfully. An [error code] is returned otherwise.)^
  6650. **
  6651. ** ^Shared cache is disabled by default. But this might change in
  6652. ** future releases of SQLite. Applications that care about shared
  6653. ** cache setting should set it explicitly.
  6654. **
  6655. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  6656. ** and will always return SQLITE_MISUSE. On those systems,
  6657. ** shared cache mode should be enabled per-database connection via
  6658. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  6659. **
  6660. ** This interface is threadsafe on processors where writing a
  6661. ** 32-bit integer is atomic.
  6662. **
  6663. ** See Also: [SQLite Shared-Cache Mode]
  6664. */
  6665. SQLITE_API int sqlite3_enable_shared_cache(int);
  6666. /*
  6667. ** CAPI3REF: Attempt To Free Heap Memory
  6668. **
  6669. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  6670. ** of heap memory by deallocating non-essential memory allocations
  6671. ** held by the database library. Memory used to cache database
  6672. ** pages to improve performance is an example of non-essential memory.
  6673. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  6674. ** which might be more or less than the amount requested.
  6675. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  6676. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6677. **
  6678. ** See also: [sqlite3_db_release_memory()]
  6679. */
  6680. SQLITE_API int sqlite3_release_memory(int);
  6681. /*
  6682. ** CAPI3REF: Free Memory Used By A Database Connection
  6683. ** METHOD: sqlite3
  6684. **
  6685. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  6686. ** memory as possible from database connection D. Unlike the
  6687. ** [sqlite3_release_memory()] interface, this interface is in effect even
  6688. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  6689. ** omitted.
  6690. **
  6691. ** See also: [sqlite3_release_memory()]
  6692. */
  6693. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  6694. /*
  6695. ** CAPI3REF: Impose A Limit On Heap Size
  6696. **
  6697. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  6698. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  6699. ** ^SQLite strives to keep heap memory utilization below the soft heap
  6700. ** limit by reducing the number of pages held in the page cache
  6701. ** as heap memory usages approaches the limit.
  6702. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  6703. ** below the limit, it will exceed the limit rather than generate
  6704. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  6705. ** is advisory only.
  6706. **
  6707. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  6708. ** the soft heap limit prior to the call, or negative in the case of an
  6709. ** error. ^If the argument N is negative
  6710. ** then no change is made to the soft heap limit. Hence, the current
  6711. ** size of the soft heap limit can be determined by invoking
  6712. ** sqlite3_soft_heap_limit64() with a negative argument.
  6713. **
  6714. ** ^If the argument N is zero then the soft heap limit is disabled.
  6715. **
  6716. ** ^(The soft heap limit is not enforced in the current implementation
  6717. ** if one or more of following conditions are true:
  6718. **
  6719. ** <ul>
  6720. ** <li> The soft heap limit is set to zero.
  6721. ** <li> Memory accounting is disabled using a combination of the
  6722. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  6723. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  6724. ** <li> An alternative page cache implementation is specified using
  6725. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  6726. ** <li> The page cache allocates from its own memory pool supplied
  6727. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  6728. ** from the heap.
  6729. ** </ul>)^
  6730. **
  6731. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  6732. ** the soft heap limit is enforced
  6733. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  6734. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  6735. ** the soft heap limit is enforced on every memory allocation. Without
  6736. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  6737. ** when memory is allocated by the page cache. Testing suggests that because
  6738. ** the page cache is the predominate memory user in SQLite, most
  6739. ** applications will achieve adequate soft heap limit enforcement without
  6740. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6741. **
  6742. ** The circumstances under which SQLite will enforce the soft heap limit may
  6743. ** changes in future releases of SQLite.
  6744. */
  6745. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  6746. /*
  6747. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  6748. ** DEPRECATED
  6749. **
  6750. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  6751. ** interface. This routine is provided for historical compatibility
  6752. ** only. All new applications should use the
  6753. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  6754. */
  6755. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  6756. /*
  6757. ** CAPI3REF: Extract Metadata About A Column Of A Table
  6758. ** METHOD: sqlite3
  6759. **
  6760. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  6761. ** information about column C of table T in database D
  6762. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  6763. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  6764. ** the final five arguments with appropriate values if the specified
  6765. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  6766. ** SQLITE_ERROR and if the specified column does not exist.
  6767. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  6768. ** NULL pointer, then this routine simply checks for the existence of the
  6769. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  6770. ** does not. If the table name parameter T in a call to
  6771. ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  6772. ** undefined behavior.
  6773. **
  6774. ** ^The column is identified by the second, third and fourth parameters to
  6775. ** this function. ^(The second parameter is either the name of the database
  6776. ** (i.e. "main", "temp", or an attached database) containing the specified
  6777. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  6778. ** for the table using the same algorithm used by the database engine to
  6779. ** resolve unqualified table references.
  6780. **
  6781. ** ^The third and fourth parameters to this function are the table and column
  6782. ** name of the desired column, respectively.
  6783. **
  6784. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  6785. ** and subsequent parameters to this function. ^Any of these arguments may be
  6786. ** NULL, in which case the corresponding element of metadata is omitted.
  6787. **
  6788. ** ^(<blockquote>
  6789. ** <table border="1">
  6790. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  6791. **
  6792. ** <tr><td> 5th <td> const char* <td> Data type
  6793. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  6794. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  6795. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  6796. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  6797. ** </table>
  6798. ** </blockquote>)^
  6799. **
  6800. ** ^The memory pointed to by the character pointers returned for the
  6801. ** declaration type and collation sequence is valid until the next
  6802. ** call to any SQLite API function.
  6803. **
  6804. ** ^If the specified table is actually a view, an [error code] is returned.
  6805. **
  6806. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  6807. ** is not a [WITHOUT ROWID] table and an
  6808. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  6809. ** parameters are set for the explicitly declared column. ^(If there is no
  6810. ** [INTEGER PRIMARY KEY] column, then the outputs
  6811. ** for the [rowid] are set as follows:
  6812. **
  6813. ** <pre>
  6814. ** data type: "INTEGER"
  6815. ** collation sequence: "BINARY"
  6816. ** not null: 0
  6817. ** primary key: 1
  6818. ** auto increment: 0
  6819. ** </pre>)^
  6820. **
  6821. ** ^This function causes all database schemas to be read from disk and
  6822. ** parsed, if that has not already been done, and returns an error if
  6823. ** any errors are encountered while loading the schema.
  6824. */
  6825. SQLITE_API int sqlite3_table_column_metadata(
  6826. sqlite3 *db, /* Connection handle */
  6827. const char *zDbName, /* Database name or NULL */
  6828. const char *zTableName, /* Table name */
  6829. const char *zColumnName, /* Column name */
  6830. char const **pzDataType, /* OUTPUT: Declared data type */
  6831. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  6832. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  6833. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  6834. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  6835. );
  6836. /*
  6837. ** CAPI3REF: Load An Extension
  6838. ** METHOD: sqlite3
  6839. **
  6840. ** ^This interface loads an SQLite extension library from the named file.
  6841. **
  6842. ** ^The sqlite3_load_extension() interface attempts to load an
  6843. ** [SQLite extension] library contained in the file zFile. If
  6844. ** the file cannot be loaded directly, attempts are made to load
  6845. ** with various operating-system specific extensions added.
  6846. ** So for example, if "samplelib" cannot be loaded, then names like
  6847. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  6848. ** be tried also.
  6849. **
  6850. ** ^The entry point is zProc.
  6851. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  6852. ** entry point name on its own. It first tries "sqlite3_extension_init".
  6853. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  6854. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  6855. ** characters in the filename from the last "/" to the first following
  6856. ** "." and omitting any initial "lib".)^
  6857. ** ^The sqlite3_load_extension() interface returns
  6858. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  6859. ** ^If an error occurs and pzErrMsg is not 0, then the
  6860. ** [sqlite3_load_extension()] interface shall attempt to
  6861. ** fill *pzErrMsg with error message text stored in memory
  6862. ** obtained from [sqlite3_malloc()]. The calling function
  6863. ** should free this memory by calling [sqlite3_free()].
  6864. **
  6865. ** ^Extension loading must be enabled using
  6866. ** [sqlite3_enable_load_extension()] or
  6867. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  6868. ** prior to calling this API,
  6869. ** otherwise an error will be returned.
  6870. **
  6871. ** <b>Security warning:</b> It is recommended that the
  6872. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  6873. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  6874. ** should be avoided. This will keep the SQL function [load_extension()]
  6875. ** disabled and prevent SQL injections from giving attackers
  6876. ** access to extension loading capabilities.
  6877. **
  6878. ** See also the [load_extension() SQL function].
  6879. */
  6880. SQLITE_API int sqlite3_load_extension(
  6881. sqlite3 *db, /* Load the extension into this database connection */
  6882. const char *zFile, /* Name of the shared library containing extension */
  6883. const char *zProc, /* Entry point. Derived from zFile if 0 */
  6884. char **pzErrMsg /* Put error message here if not 0 */
  6885. );
  6886. /*
  6887. ** CAPI3REF: Enable Or Disable Extension Loading
  6888. ** METHOD: sqlite3
  6889. **
  6890. ** ^So as not to open security holes in older applications that are
  6891. ** unprepared to deal with [extension loading], and as a means of disabling
  6892. ** [extension loading] while evaluating user-entered SQL, the following API
  6893. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  6894. **
  6895. ** ^Extension loading is off by default.
  6896. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  6897. ** to turn extension loading on and call it with onoff==0 to turn
  6898. ** it back off again.
  6899. **
  6900. ** ^This interface enables or disables both the C-API
  6901. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  6902. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  6903. ** to enable or disable only the C-API.)^
  6904. **
  6905. ** <b>Security warning:</b> It is recommended that extension loading
  6906. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  6907. ** rather than this interface, so the [load_extension()] SQL function
  6908. ** remains disabled. This will prevent SQL injections from giving attackers
  6909. ** access to extension loading capabilities.
  6910. */
  6911. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  6912. /*
  6913. ** CAPI3REF: Automatically Load Statically Linked Extensions
  6914. **
  6915. ** ^This interface causes the xEntryPoint() function to be invoked for
  6916. ** each new [database connection] that is created. The idea here is that
  6917. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  6918. ** that is to be automatically loaded into all new database connections.
  6919. **
  6920. ** ^(Even though the function prototype shows that xEntryPoint() takes
  6921. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  6922. ** arguments and expects an integer result as if the signature of the
  6923. ** entry point where as follows:
  6924. **
  6925. ** <blockquote><pre>
  6926. ** &nbsp; int xEntryPoint(
  6927. ** &nbsp; sqlite3 *db,
  6928. ** &nbsp; const char **pzErrMsg,
  6929. ** &nbsp; const struct sqlite3_api_routines *pThunk
  6930. ** &nbsp; );
  6931. ** </pre></blockquote>)^
  6932. **
  6933. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  6934. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  6935. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  6936. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  6937. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  6938. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  6939. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  6940. **
  6941. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  6942. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  6943. ** will be called more than once for each database connection that is opened.
  6944. **
  6945. ** See also: [sqlite3_reset_auto_extension()]
  6946. ** and [sqlite3_cancel_auto_extension()]
  6947. */
  6948. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  6949. /*
  6950. ** CAPI3REF: Cancel Automatic Extension Loading
  6951. **
  6952. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  6953. ** initialization routine X that was registered using a prior call to
  6954. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  6955. ** routine returns 1 if initialization routine X was successfully
  6956. ** unregistered and it returns 0 if X was not on the list of initialization
  6957. ** routines.
  6958. */
  6959. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  6960. /*
  6961. ** CAPI3REF: Reset Automatic Extension Loading
  6962. **
  6963. ** ^This interface disables all automatic extensions previously
  6964. ** registered using [sqlite3_auto_extension()].
  6965. */
  6966. SQLITE_API void sqlite3_reset_auto_extension(void);
  6967. /*
  6968. ** The interface to the virtual-table mechanism is currently considered
  6969. ** to be experimental. The interface might change in incompatible ways.
  6970. ** If this is a problem for you, do not use the interface at this time.
  6971. **
  6972. ** When the virtual-table mechanism stabilizes, we will declare the
  6973. ** interface fixed, support it indefinitely, and remove this comment.
  6974. */
  6975. /*
  6976. ** Structures used by the virtual table interface
  6977. */
  6978. typedef struct sqlite3_vtab sqlite3_vtab;
  6979. typedef struct sqlite3_index_info sqlite3_index_info;
  6980. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  6981. typedef struct sqlite3_module sqlite3_module;
  6982. /*
  6983. ** CAPI3REF: Virtual Table Object
  6984. ** KEYWORDS: sqlite3_module {virtual table module}
  6985. **
  6986. ** This structure, sometimes called a "virtual table module",
  6987. ** defines the implementation of a [virtual tables].
  6988. ** This structure consists mostly of methods for the module.
  6989. **
  6990. ** ^A virtual table module is created by filling in a persistent
  6991. ** instance of this structure and passing a pointer to that instance
  6992. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  6993. ** ^The registration remains valid until it is replaced by a different
  6994. ** module or until the [database connection] closes. The content
  6995. ** of this structure must not change while it is registered with
  6996. ** any database connection.
  6997. */
  6998. struct sqlite3_module {
  6999. int iVersion;
  7000. int (*xCreate)(sqlite3*, void *pAux,
  7001. int argc, const char *const*argv,
  7002. sqlite3_vtab **ppVTab, char**);
  7003. int (*xConnect)(sqlite3*, void *pAux,
  7004. int argc, const char *const*argv,
  7005. sqlite3_vtab **ppVTab, char**);
  7006. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  7007. int (*xDisconnect)(sqlite3_vtab *pVTab);
  7008. int (*xDestroy)(sqlite3_vtab *pVTab);
  7009. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  7010. int (*xClose)(sqlite3_vtab_cursor*);
  7011. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  7012. int argc, sqlite3_value **argv);
  7013. int (*xNext)(sqlite3_vtab_cursor*);
  7014. int (*xEof)(sqlite3_vtab_cursor*);
  7015. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  7016. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  7017. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  7018. int (*xBegin)(sqlite3_vtab *pVTab);
  7019. int (*xSync)(sqlite3_vtab *pVTab);
  7020. int (*xCommit)(sqlite3_vtab *pVTab);
  7021. int (*xRollback)(sqlite3_vtab *pVTab);
  7022. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  7023. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  7024. void **ppArg);
  7025. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7026. /* The methods above are in version 1 of the sqlite_module object. Those
  7027. ** below are for version 2 and greater. */
  7028. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7029. int (*xRelease)(sqlite3_vtab *pVTab, int);
  7030. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7031. };
  7032. /*
  7033. ** CAPI3REF: Virtual Table Indexing Information
  7034. ** KEYWORDS: sqlite3_index_info
  7035. **
  7036. ** The sqlite3_index_info structure and its substructures is used as part
  7037. ** of the [virtual table] interface to
  7038. ** pass information into and receive the reply from the [xBestIndex]
  7039. ** method of a [virtual table module]. The fields under **Inputs** are the
  7040. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  7041. ** results into the **Outputs** fields.
  7042. **
  7043. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  7044. **
  7045. ** <blockquote>column OP expr</blockquote>
  7046. **
  7047. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  7048. ** stored in aConstraint[].op using one of the
  7049. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  7050. ** ^(The index of the column is stored in
  7051. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  7052. ** expr on the right-hand side can be evaluated (and thus the constraint
  7053. ** is usable) and false if it cannot.)^
  7054. **
  7055. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  7056. ** and makes other simplifications to the WHERE clause in an attempt to
  7057. ** get as many WHERE clause terms into the form shown above as possible.
  7058. ** ^The aConstraint[] array only reports WHERE clause terms that are
  7059. ** relevant to the particular virtual table being queried.
  7060. **
  7061. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7062. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7063. **
  7064. ** The colUsed field indicates which columns of the virtual table may be
  7065. ** required by the current scan. Virtual table columns are numbered from
  7066. ** zero in the order in which they appear within the CREATE TABLE statement
  7067. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7068. ** the corresponding bit is set within the colUsed mask if the column may be
  7069. ** required by SQLite. If the table has at least 64 columns and any column
  7070. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7071. ** set. In other words, column iCol may be required if the expression
  7072. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  7073. ** non-zero.
  7074. **
  7075. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7076. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  7077. ** the right-hand side of the corresponding aConstraint[] is evaluated
  7078. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  7079. ** is true, then the constraint is assumed to be fully handled by the
  7080. ** virtual table and is not checked again by SQLite.)^
  7081. **
  7082. ** ^The idxNum and idxPtr values are recorded and passed into the
  7083. ** [xFilter] method.
  7084. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7085. ** needToFreeIdxPtr is true.
  7086. **
  7087. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7088. ** the correct order to satisfy the ORDER BY clause so that no separate
  7089. ** sorting step is required.
  7090. **
  7091. ** ^The estimatedCost value is an estimate of the cost of a particular
  7092. ** strategy. A cost of N indicates that the cost of the strategy is similar
  7093. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  7094. ** indicates that the expense of the operation is similar to that of a
  7095. ** binary search on a unique indexed field of an SQLite table with N rows.
  7096. **
  7097. ** ^The estimatedRows value is an estimate of the number of rows that
  7098. ** will be returned by the strategy.
  7099. **
  7100. ** The xBestIndex method may optionally populate the idxFlags field with a
  7101. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7102. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7103. ** assumes that the strategy may visit at most one row.
  7104. **
  7105. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7106. ** SQLite also assumes that if a call to the xUpdate() method is made as
  7107. ** part of the same statement to delete or update a virtual table row and the
  7108. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7109. ** any database changes. In other words, if the xUpdate() returns
  7110. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7111. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7112. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7113. ** the xUpdate method are automatically rolled back by SQLite.
  7114. **
  7115. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7116. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  7117. ** If a virtual table extension is
  7118. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  7119. ** to read or write the estimatedRows field are undefined (but are likely
  7120. ** to included crashing the application). The estimatedRows field should
  7121. ** therefore only be used if [sqlite3_libversion_number()] returns a
  7122. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7123. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  7124. ** It may therefore only be used if
  7125. ** sqlite3_libversion_number() returns a value greater than or equal to
  7126. ** 3009000.
  7127. */
  7128. struct sqlite3_index_info {
  7129. /* Inputs */
  7130. int nConstraint; /* Number of entries in aConstraint */
  7131. struct sqlite3_index_constraint {
  7132. int iColumn; /* Column constrained. -1 for ROWID */
  7133. unsigned char op; /* Constraint operator */
  7134. unsigned char usable; /* True if this constraint is usable */
  7135. int iTermOffset; /* Used internally - xBestIndex should ignore */
  7136. } *aConstraint; /* Table of WHERE clause constraints */
  7137. int nOrderBy; /* Number of terms in the ORDER BY clause */
  7138. struct sqlite3_index_orderby {
  7139. int iColumn; /* Column number */
  7140. unsigned char desc; /* True for DESC. False for ASC. */
  7141. } *aOrderBy; /* The ORDER BY clause */
  7142. /* Outputs */
  7143. struct sqlite3_index_constraint_usage {
  7144. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  7145. unsigned char omit; /* Do not code a test for this constraint */
  7146. } *aConstraintUsage;
  7147. int idxNum; /* Number used to identify the index */
  7148. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  7149. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  7150. int orderByConsumed; /* True if output is already ordered */
  7151. double estimatedCost; /* Estimated cost of using this index */
  7152. /* Fields below are only available in SQLite 3.8.2 and later */
  7153. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  7154. /* Fields below are only available in SQLite 3.9.0 and later */
  7155. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  7156. /* Fields below are only available in SQLite 3.10.0 and later */
  7157. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  7158. };
  7159. /*
  7160. ** CAPI3REF: Virtual Table Scan Flags
  7161. **
  7162. ** Virtual table implementations are allowed to set the
  7163. ** [sqlite3_index_info].idxFlags field to some combination of
  7164. ** these bits.
  7165. */
  7166. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  7167. /*
  7168. ** CAPI3REF: Virtual Table Constraint Operator Codes
  7169. **
  7170. ** These macros defined the allowed values for the
  7171. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  7172. ** an operator that is part of a constraint term in the wHERE clause of
  7173. ** a query that uses a [virtual table].
  7174. */
  7175. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  7176. #define SQLITE_INDEX_CONSTRAINT_GT 4
  7177. #define SQLITE_INDEX_CONSTRAINT_LE 8
  7178. #define SQLITE_INDEX_CONSTRAINT_LT 16
  7179. #define SQLITE_INDEX_CONSTRAINT_GE 32
  7180. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  7181. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  7182. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  7183. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  7184. #define SQLITE_INDEX_CONSTRAINT_NE 68
  7185. #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
  7186. #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7187. #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
  7188. #define SQLITE_INDEX_CONSTRAINT_IS 72
  7189. /*
  7190. ** CAPI3REF: Register A Virtual Table Implementation
  7191. ** METHOD: sqlite3
  7192. **
  7193. ** ^These routines are used to register a new [virtual table module] name.
  7194. ** ^Module names must be registered before
  7195. ** creating a new [virtual table] using the module and before using a
  7196. ** preexisting [virtual table] for the module.
  7197. **
  7198. ** ^The module name is registered on the [database connection] specified
  7199. ** by the first parameter. ^The name of the module is given by the
  7200. ** second parameter. ^The third parameter is a pointer to
  7201. ** the implementation of the [virtual table module]. ^The fourth
  7202. ** parameter is an arbitrary client data pointer that is passed through
  7203. ** into the [xCreate] and [xConnect] methods of the virtual table module
  7204. ** when a new virtual table is be being created or reinitialized.
  7205. **
  7206. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7207. ** is a pointer to a destructor for the pClientData. ^SQLite will
  7208. ** invoke the destructor function (if it is not NULL) when SQLite
  7209. ** no longer needs the pClientData pointer. ^The destructor will also
  7210. ** be invoked if the call to sqlite3_create_module_v2() fails.
  7211. ** ^The sqlite3_create_module()
  7212. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7213. ** destructor.
  7214. */
  7215. SQLITE_API int sqlite3_create_module(
  7216. sqlite3 *db, /* SQLite connection to register module with */
  7217. const char *zName, /* Name of the module */
  7218. const sqlite3_module *p, /* Methods for the module */
  7219. void *pClientData /* Client data for xCreate/xConnect */
  7220. );
  7221. SQLITE_API int sqlite3_create_module_v2(
  7222. sqlite3 *db, /* SQLite connection to register module with */
  7223. const char *zName, /* Name of the module */
  7224. const sqlite3_module *p, /* Methods for the module */
  7225. void *pClientData, /* Client data for xCreate/xConnect */
  7226. void(*xDestroy)(void*) /* Module destructor function */
  7227. );
  7228. /*
  7229. ** CAPI3REF: Virtual Table Instance Object
  7230. ** KEYWORDS: sqlite3_vtab
  7231. **
  7232. ** Every [virtual table module] implementation uses a subclass
  7233. ** of this object to describe a particular instance
  7234. ** of the [virtual table]. Each subclass will
  7235. ** be tailored to the specific needs of the module implementation.
  7236. ** The purpose of this superclass is to define certain fields that are
  7237. ** common to all module implementations.
  7238. **
  7239. ** ^Virtual tables methods can set an error message by assigning a
  7240. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  7241. ** take care that any prior string is freed by a call to [sqlite3_free()]
  7242. ** prior to assigning a new string to zErrMsg. ^After the error message
  7243. ** is delivered up to the client application, the string will be automatically
  7244. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7245. */
  7246. struct sqlite3_vtab {
  7247. const sqlite3_module *pModule; /* The module for this virtual table */
  7248. int nRef; /* Number of open cursors */
  7249. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  7250. /* Virtual table implementations will typically add additional fields */
  7251. };
  7252. /*
  7253. ** CAPI3REF: Virtual Table Cursor Object
  7254. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7255. **
  7256. ** Every [virtual table module] implementation uses a subclass of the
  7257. ** following structure to describe cursors that point into the
  7258. ** [virtual table] and are used
  7259. ** to loop through the virtual table. Cursors are created using the
  7260. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7261. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  7262. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7263. ** of the module. Each module implementation will define
  7264. ** the content of a cursor structure to suit its own needs.
  7265. **
  7266. ** This superclass exists in order to define fields of the cursor that
  7267. ** are common to all implementations.
  7268. */
  7269. struct sqlite3_vtab_cursor {
  7270. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  7271. /* Virtual table implementations will typically add additional fields */
  7272. };
  7273. /*
  7274. ** CAPI3REF: Declare The Schema Of A Virtual Table
  7275. **
  7276. ** ^The [xCreate] and [xConnect] methods of a
  7277. ** [virtual table module] call this interface
  7278. ** to declare the format (the names and datatypes of the columns) of
  7279. ** the virtual tables they implement.
  7280. */
  7281. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7282. /*
  7283. ** CAPI3REF: Overload A Function For A Virtual Table
  7284. ** METHOD: sqlite3
  7285. **
  7286. ** ^(Virtual tables can provide alternative implementations of functions
  7287. ** using the [xFindFunction] method of the [virtual table module].
  7288. ** But global versions of those functions
  7289. ** must exist in order to be overloaded.)^
  7290. **
  7291. ** ^(This API makes sure a global version of a function with a particular
  7292. ** name and number of parameters exists. If no such function exists
  7293. ** before this API is called, a new function is created.)^ ^The implementation
  7294. ** of the new function always causes an exception to be thrown. So
  7295. ** the new function is not good for anything by itself. Its only
  7296. ** purpose is to be a placeholder function that can be overloaded
  7297. ** by a [virtual table].
  7298. */
  7299. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7300. /*
  7301. ** The interface to the virtual-table mechanism defined above (back up
  7302. ** to a comment remarkably similar to this one) is currently considered
  7303. ** to be experimental. The interface might change in incompatible ways.
  7304. ** If this is a problem for you, do not use the interface at this time.
  7305. **
  7306. ** When the virtual-table mechanism stabilizes, we will declare the
  7307. ** interface fixed, support it indefinitely, and remove this comment.
  7308. */
  7309. /*
  7310. ** CAPI3REF: A Handle To An Open BLOB
  7311. ** KEYWORDS: {BLOB handle} {BLOB handles}
  7312. **
  7313. ** An instance of this object represents an open BLOB on which
  7314. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7315. ** ^Objects of this type are created by [sqlite3_blob_open()]
  7316. ** and destroyed by [sqlite3_blob_close()].
  7317. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7318. ** can be used to read or write small subsections of the BLOB.
  7319. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7320. */
  7321. typedef struct sqlite3_blob sqlite3_blob;
  7322. /*
  7323. ** CAPI3REF: Open A BLOB For Incremental I/O
  7324. ** METHOD: sqlite3
  7325. ** CONSTRUCTOR: sqlite3_blob
  7326. **
  7327. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7328. ** in row iRow, column zColumn, table zTable in database zDb;
  7329. ** in other words, the same BLOB that would be selected by:
  7330. **
  7331. ** <pre>
  7332. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7333. ** </pre>)^
  7334. **
  7335. ** ^(Parameter zDb is not the filename that contains the database, but
  7336. ** rather the symbolic name of the database. For attached databases, this is
  7337. ** the name that appears after the AS keyword in the [ATTACH] statement.
  7338. ** For the main database file, the database name is "main". For TEMP
  7339. ** tables, the database name is "temp".)^
  7340. **
  7341. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7342. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7343. ** read-only access.
  7344. **
  7345. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7346. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7347. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7348. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  7349. ** on *ppBlob after this function it returns.
  7350. **
  7351. ** This function fails with SQLITE_ERROR if any of the following are true:
  7352. ** <ul>
  7353. ** <li> ^(Database zDb does not exist)^,
  7354. ** <li> ^(Table zTable does not exist within database zDb)^,
  7355. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  7356. ** <li> ^(Column zColumn does not exist)^,
  7357. ** <li> ^(Row iRow is not present in the table)^,
  7358. ** <li> ^(The specified column of row iRow contains a value that is not
  7359. ** a TEXT or BLOB value)^,
  7360. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  7361. ** constraint and the blob is being opened for read/write access)^,
  7362. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  7363. ** column zColumn is part of a [child key] definition and the blob is
  7364. ** being opened for read/write access)^.
  7365. ** </ul>
  7366. **
  7367. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  7368. ** [database connection] error code and message accessible via
  7369. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7370. **
  7371. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7372. ** [sqlite3_blob_read()] interface and modified by using
  7373. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  7374. ** different row of the same table using the [sqlite3_blob_reopen()]
  7375. ** interface. However, the column, table, or database of a [BLOB handle]
  7376. ** cannot be changed after the [BLOB handle] is opened.
  7377. **
  7378. ** ^(If the row that a BLOB handle points to is modified by an
  7379. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7380. ** then the BLOB handle is marked as "expired".
  7381. ** This is true if any column of the row is changed, even a column
  7382. ** other than the one the BLOB handle is open on.)^
  7383. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7384. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7385. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7386. ** rolled back by the expiration of the BLOB. Such changes will eventually
  7387. ** commit if the transaction continues to completion.)^
  7388. **
  7389. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7390. ** the opened blob. ^The size of a blob may not be changed by this
  7391. ** interface. Use the [UPDATE] SQL command to change the size of a
  7392. ** blob.
  7393. **
  7394. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7395. ** and the built-in [zeroblob] SQL function may be used to create a
  7396. ** zero-filled blob to read or write using the incremental-blob interface.
  7397. **
  7398. ** To avoid a resource leak, every open [BLOB handle] should eventually
  7399. ** be released by a call to [sqlite3_blob_close()].
  7400. **
  7401. ** See also: [sqlite3_blob_close()],
  7402. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7403. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7404. */
  7405. SQLITE_API int sqlite3_blob_open(
  7406. sqlite3*,
  7407. const char *zDb,
  7408. const char *zTable,
  7409. const char *zColumn,
  7410. sqlite3_int64 iRow,
  7411. int flags,
  7412. sqlite3_blob **ppBlob
  7413. );
  7414. /*
  7415. ** CAPI3REF: Move a BLOB Handle to a New Row
  7416. ** METHOD: sqlite3_blob
  7417. **
  7418. ** ^This function is used to move an existing [BLOB handle] so that it points
  7419. ** to a different row of the same database table. ^The new row is identified
  7420. ** by the rowid value passed as the second argument. Only the row can be
  7421. ** changed. ^The database, table and column on which the blob handle is open
  7422. ** remain the same. Moving an existing [BLOB handle] to a new row is
  7423. ** faster than closing the existing handle and opening a new one.
  7424. **
  7425. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7426. ** it must exist and there must be either a blob or text value stored in
  7427. ** the nominated column.)^ ^If the new row is not present in the table, or if
  7428. ** it does not contain a blob or text value, or if another error occurs, an
  7429. ** SQLite error code is returned and the blob handle is considered aborted.
  7430. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7431. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7432. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7433. ** always returns zero.
  7434. **
  7435. ** ^This function sets the database handle error code and message.
  7436. */
  7437. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7438. /*
  7439. ** CAPI3REF: Close A BLOB Handle
  7440. ** DESTRUCTOR: sqlite3_blob
  7441. **
  7442. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7443. ** unconditionally. Even if this routine returns an error code, the
  7444. ** handle is still closed.)^
  7445. **
  7446. ** ^If the blob handle being closed was opened for read-write access, and if
  7447. ** the database is in auto-commit mode and there are no other open read-write
  7448. ** blob handles or active write statements, the current transaction is
  7449. ** committed. ^If an error occurs while committing the transaction, an error
  7450. ** code is returned and the transaction rolled back.
  7451. **
  7452. ** Calling this function with an argument that is not a NULL pointer or an
  7453. ** open blob handle results in undefined behaviour. ^Calling this routine
  7454. ** with a null pointer (such as would be returned by a failed call to
  7455. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7456. ** is passed a valid open blob handle, the values returned by the
  7457. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7458. */
  7459. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7460. /*
  7461. ** CAPI3REF: Return The Size Of An Open BLOB
  7462. ** METHOD: sqlite3_blob
  7463. **
  7464. ** ^Returns the size in bytes of the BLOB accessible via the
  7465. ** successfully opened [BLOB handle] in its only argument. ^The
  7466. ** incremental blob I/O routines can only read or overwriting existing
  7467. ** blob content; they cannot change the size of a blob.
  7468. **
  7469. ** This routine only works on a [BLOB handle] which has been created
  7470. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7471. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7472. ** to this routine results in undefined and probably undesirable behavior.
  7473. */
  7474. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7475. /*
  7476. ** CAPI3REF: Read Data From A BLOB Incrementally
  7477. ** METHOD: sqlite3_blob
  7478. **
  7479. ** ^(This function is used to read data from an open [BLOB handle] into a
  7480. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7481. ** from the open BLOB, starting at offset iOffset.)^
  7482. **
  7483. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7484. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  7485. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7486. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7487. ** can be determined using the [sqlite3_blob_bytes()] interface.
  7488. **
  7489. ** ^An attempt to read from an expired [BLOB handle] fails with an
  7490. ** error code of [SQLITE_ABORT].
  7491. **
  7492. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7493. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7494. **
  7495. ** This routine only works on a [BLOB handle] which has been created
  7496. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7497. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7498. ** to this routine results in undefined and probably undesirable behavior.
  7499. **
  7500. ** See also: [sqlite3_blob_write()].
  7501. */
  7502. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7503. /*
  7504. ** CAPI3REF: Write Data Into A BLOB Incrementally
  7505. ** METHOD: sqlite3_blob
  7506. **
  7507. ** ^(This function is used to write data into an open [BLOB handle] from a
  7508. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7509. ** into the open BLOB, starting at offset iOffset.)^
  7510. **
  7511. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7512. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7513. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  7514. ** [database connection] error code and message accessible via
  7515. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7516. **
  7517. ** ^If the [BLOB handle] passed as the first argument was not opened for
  7518. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7519. ** this function returns [SQLITE_READONLY].
  7520. **
  7521. ** This function may only modify the contents of the BLOB; it is
  7522. ** not possible to increase the size of a BLOB using this API.
  7523. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7524. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  7525. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  7526. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  7527. ** than zero [SQLITE_ERROR] is returned and no data is written.
  7528. **
  7529. ** ^An attempt to write to an expired [BLOB handle] fails with an
  7530. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  7531. ** before the [BLOB handle] expired are not rolled back by the
  7532. ** expiration of the handle, though of course those changes might
  7533. ** have been overwritten by the statement that expired the BLOB handle
  7534. ** or by other independent statements.
  7535. **
  7536. ** This routine only works on a [BLOB handle] which has been created
  7537. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7538. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7539. ** to this routine results in undefined and probably undesirable behavior.
  7540. **
  7541. ** See also: [sqlite3_blob_read()].
  7542. */
  7543. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7544. /*
  7545. ** CAPI3REF: Virtual File System Objects
  7546. **
  7547. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7548. ** that SQLite uses to interact
  7549. ** with the underlying operating system. Most SQLite builds come with a
  7550. ** single default VFS that is appropriate for the host computer.
  7551. ** New VFSes can be registered and existing VFSes can be unregistered.
  7552. ** The following interfaces are provided.
  7553. **
  7554. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7555. ** ^Names are case sensitive.
  7556. ** ^Names are zero-terminated UTF-8 strings.
  7557. ** ^If there is no match, a NULL pointer is returned.
  7558. ** ^If zVfsName is NULL then the default VFS is returned.
  7559. **
  7560. ** ^New VFSes are registered with sqlite3_vfs_register().
  7561. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7562. ** ^The same VFS can be registered multiple times without injury.
  7563. ** ^To make an existing VFS into the default VFS, register it again
  7564. ** with the makeDflt flag set. If two different VFSes with the
  7565. ** same name are registered, the behavior is undefined. If a
  7566. ** VFS is registered with a name that is NULL or an empty string,
  7567. ** then the behavior is undefined.
  7568. **
  7569. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7570. ** ^(If the default VFS is unregistered, another VFS is chosen as
  7571. ** the default. The choice for the new VFS is arbitrary.)^
  7572. */
  7573. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7574. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7575. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7576. /*
  7577. ** CAPI3REF: Mutexes
  7578. **
  7579. ** The SQLite core uses these routines for thread
  7580. ** synchronization. Though they are intended for internal
  7581. ** use by SQLite, code that links against SQLite is
  7582. ** permitted to use any of these routines.
  7583. **
  7584. ** The SQLite source code contains multiple implementations
  7585. ** of these mutex routines. An appropriate implementation
  7586. ** is selected automatically at compile-time. The following
  7587. ** implementations are available in the SQLite core:
  7588. **
  7589. ** <ul>
  7590. ** <li> SQLITE_MUTEX_PTHREADS
  7591. ** <li> SQLITE_MUTEX_W32
  7592. ** <li> SQLITE_MUTEX_NOOP
  7593. ** </ul>
  7594. **
  7595. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  7596. ** that does no real locking and is appropriate for use in
  7597. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  7598. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  7599. ** and Windows.
  7600. **
  7601. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  7602. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  7603. ** implementation is included with the library. In this case the
  7604. ** application must supply a custom mutex implementation using the
  7605. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  7606. ** before calling sqlite3_initialize() or any other public sqlite3_
  7607. ** function that calls sqlite3_initialize().
  7608. **
  7609. ** ^The sqlite3_mutex_alloc() routine allocates a new
  7610. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  7611. ** routine returns NULL if it is unable to allocate the requested
  7612. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  7613. ** integer constants:
  7614. **
  7615. ** <ul>
  7616. ** <li> SQLITE_MUTEX_FAST
  7617. ** <li> SQLITE_MUTEX_RECURSIVE
  7618. ** <li> SQLITE_MUTEX_STATIC_MASTER
  7619. ** <li> SQLITE_MUTEX_STATIC_MEM
  7620. ** <li> SQLITE_MUTEX_STATIC_OPEN
  7621. ** <li> SQLITE_MUTEX_STATIC_PRNG
  7622. ** <li> SQLITE_MUTEX_STATIC_LRU
  7623. ** <li> SQLITE_MUTEX_STATIC_PMEM
  7624. ** <li> SQLITE_MUTEX_STATIC_APP1
  7625. ** <li> SQLITE_MUTEX_STATIC_APP2
  7626. ** <li> SQLITE_MUTEX_STATIC_APP3
  7627. ** <li> SQLITE_MUTEX_STATIC_VFS1
  7628. ** <li> SQLITE_MUTEX_STATIC_VFS2
  7629. ** <li> SQLITE_MUTEX_STATIC_VFS3
  7630. ** </ul>
  7631. **
  7632. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  7633. ** cause sqlite3_mutex_alloc() to create
  7634. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  7635. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  7636. ** The mutex implementation does not need to make a distinction
  7637. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  7638. ** not want to. SQLite will only request a recursive mutex in
  7639. ** cases where it really needs one. If a faster non-recursive mutex
  7640. ** implementation is available on the host platform, the mutex subsystem
  7641. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  7642. **
  7643. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  7644. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  7645. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  7646. ** used by the current version of SQLite. Future versions of SQLite
  7647. ** may add additional static mutexes. Static mutexes are for internal
  7648. ** use by SQLite only. Applications that use SQLite mutexes should
  7649. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  7650. ** SQLITE_MUTEX_RECURSIVE.
  7651. **
  7652. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  7653. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  7654. ** returns a different mutex on every call. ^For the static
  7655. ** mutex types, the same mutex is returned on every call that has
  7656. ** the same type number.
  7657. **
  7658. ** ^The sqlite3_mutex_free() routine deallocates a previously
  7659. ** allocated dynamic mutex. Attempting to deallocate a static
  7660. ** mutex results in undefined behavior.
  7661. **
  7662. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  7663. ** to enter a mutex. ^If another thread is already within the mutex,
  7664. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  7665. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  7666. ** upon successful entry. ^(Mutexes created using
  7667. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  7668. ** In such cases, the
  7669. ** mutex must be exited an equal number of times before another thread
  7670. ** can enter.)^ If the same thread tries to enter any mutex other
  7671. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  7672. **
  7673. ** ^(Some systems (for example, Windows 95) do not support the operation
  7674. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  7675. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  7676. ** sqlite3_mutex_try() as an optimization so this is acceptable
  7677. ** behavior.)^
  7678. **
  7679. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  7680. ** previously entered by the same thread. The behavior
  7681. ** is undefined if the mutex is not currently entered by the
  7682. ** calling thread or is not currently allocated.
  7683. **
  7684. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  7685. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  7686. ** behave as no-ops.
  7687. **
  7688. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  7689. */
  7690. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  7691. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  7692. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  7693. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  7694. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  7695. /*
  7696. ** CAPI3REF: Mutex Methods Object
  7697. **
  7698. ** An instance of this structure defines the low-level routines
  7699. ** used to allocate and use mutexes.
  7700. **
  7701. ** Usually, the default mutex implementations provided by SQLite are
  7702. ** sufficient, however the application has the option of substituting a custom
  7703. ** implementation for specialized deployments or systems for which SQLite
  7704. ** does not provide a suitable implementation. In this case, the application
  7705. ** creates and populates an instance of this structure to pass
  7706. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  7707. ** Additionally, an instance of this structure can be used as an
  7708. ** output variable when querying the system for the current mutex
  7709. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  7710. **
  7711. ** ^The xMutexInit method defined by this structure is invoked as
  7712. ** part of system initialization by the sqlite3_initialize() function.
  7713. ** ^The xMutexInit routine is called by SQLite exactly once for each
  7714. ** effective call to [sqlite3_initialize()].
  7715. **
  7716. ** ^The xMutexEnd method defined by this structure is invoked as
  7717. ** part of system shutdown by the sqlite3_shutdown() function. The
  7718. ** implementation of this method is expected to release all outstanding
  7719. ** resources obtained by the mutex methods implementation, especially
  7720. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  7721. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  7722. **
  7723. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  7724. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  7725. ** xMutexNotheld) implement the following interfaces (respectively):
  7726. **
  7727. ** <ul>
  7728. ** <li> [sqlite3_mutex_alloc()] </li>
  7729. ** <li> [sqlite3_mutex_free()] </li>
  7730. ** <li> [sqlite3_mutex_enter()] </li>
  7731. ** <li> [sqlite3_mutex_try()] </li>
  7732. ** <li> [sqlite3_mutex_leave()] </li>
  7733. ** <li> [sqlite3_mutex_held()] </li>
  7734. ** <li> [sqlite3_mutex_notheld()] </li>
  7735. ** </ul>)^
  7736. **
  7737. ** The only difference is that the public sqlite3_XXX functions enumerated
  7738. ** above silently ignore any invocations that pass a NULL pointer instead
  7739. ** of a valid mutex handle. The implementations of the methods defined
  7740. ** by this structure are not required to handle this case, the results
  7741. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  7742. ** (i.e. it is acceptable to provide an implementation that segfaults if
  7743. ** it is passed a NULL pointer).
  7744. **
  7745. ** The xMutexInit() method must be threadsafe. It must be harmless to
  7746. ** invoke xMutexInit() multiple times within the same process and without
  7747. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  7748. ** xMutexInit() must be no-ops.
  7749. **
  7750. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  7751. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  7752. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  7753. ** memory allocation for a fast or recursive mutex.
  7754. **
  7755. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  7756. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  7757. ** If xMutexInit fails in any way, it is expected to clean up after itself
  7758. ** prior to returning.
  7759. */
  7760. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  7761. struct sqlite3_mutex_methods {
  7762. int (*xMutexInit)(void);
  7763. int (*xMutexEnd)(void);
  7764. sqlite3_mutex *(*xMutexAlloc)(int);
  7765. void (*xMutexFree)(sqlite3_mutex *);
  7766. void (*xMutexEnter)(sqlite3_mutex *);
  7767. int (*xMutexTry)(sqlite3_mutex *);
  7768. void (*xMutexLeave)(sqlite3_mutex *);
  7769. int (*xMutexHeld)(sqlite3_mutex *);
  7770. int (*xMutexNotheld)(sqlite3_mutex *);
  7771. };
  7772. /*
  7773. ** CAPI3REF: Mutex Verification Routines
  7774. **
  7775. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  7776. ** are intended for use inside assert() statements. The SQLite core
  7777. ** never uses these routines except inside an assert() and applications
  7778. ** are advised to follow the lead of the core. The SQLite core only
  7779. ** provides implementations for these routines when it is compiled
  7780. ** with the SQLITE_DEBUG flag. External mutex implementations
  7781. ** are only required to provide these routines if SQLITE_DEBUG is
  7782. ** defined and if NDEBUG is not defined.
  7783. **
  7784. ** These routines should return true if the mutex in their argument
  7785. ** is held or not held, respectively, by the calling thread.
  7786. **
  7787. ** The implementation is not required to provide versions of these
  7788. ** routines that actually work. If the implementation does not provide working
  7789. ** versions of these routines, it should at least provide stubs that always
  7790. ** return true so that one does not get spurious assertion failures.
  7791. **
  7792. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  7793. ** the routine should return 1. This seems counter-intuitive since
  7794. ** clearly the mutex cannot be held if it does not exist. But
  7795. ** the reason the mutex does not exist is because the build is not
  7796. ** using mutexes. And we do not want the assert() containing the
  7797. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  7798. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  7799. ** interface should also return 1 when given a NULL pointer.
  7800. */
  7801. #ifndef NDEBUG
  7802. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  7803. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  7804. #endif
  7805. /*
  7806. ** CAPI3REF: Mutex Types
  7807. **
  7808. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  7809. ** which is one of these integer constants.
  7810. **
  7811. ** The set of static mutexes may change from one SQLite release to the
  7812. ** next. Applications that override the built-in mutex logic must be
  7813. ** prepared to accommodate additional static mutexes.
  7814. */
  7815. #define SQLITE_MUTEX_FAST 0
  7816. #define SQLITE_MUTEX_RECURSIVE 1
  7817. #define SQLITE_MUTEX_STATIC_MASTER 2
  7818. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  7819. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  7820. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  7821. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  7822. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  7823. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  7824. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  7825. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  7826. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  7827. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  7828. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  7829. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  7830. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  7831. /*
  7832. ** CAPI3REF: Retrieve the mutex for a database connection
  7833. ** METHOD: sqlite3
  7834. **
  7835. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  7836. ** serializes access to the [database connection] given in the argument
  7837. ** when the [threading mode] is Serialized.
  7838. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  7839. ** routine returns a NULL pointer.
  7840. */
  7841. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  7842. /*
  7843. ** CAPI3REF: Low-Level Control Of Database Files
  7844. ** METHOD: sqlite3
  7845. **
  7846. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  7847. ** xFileControl method for the [sqlite3_io_methods] object associated
  7848. ** with a particular database identified by the second argument. ^The
  7849. ** name of the database is "main" for the main database or "temp" for the
  7850. ** TEMP database, or the name that appears after the AS keyword for
  7851. ** databases that are added using the [ATTACH] SQL command.
  7852. ** ^A NULL pointer can be used in place of "main" to refer to the
  7853. ** main database file.
  7854. ** ^The third and fourth parameters to this routine
  7855. ** are passed directly through to the second and third parameters of
  7856. ** the xFileControl method. ^The return value of the xFileControl
  7857. ** method becomes the return value of this routine.
  7858. **
  7859. ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
  7860. ** a pointer to the underlying [sqlite3_file] object to be written into
  7861. ** the space pointed to by the 4th parameter. ^The [SQLITE_FCNTL_FILE_POINTER]
  7862. ** case is a short-circuit path which does not actually invoke the
  7863. ** underlying sqlite3_io_methods.xFileControl method.
  7864. **
  7865. ** ^If the second parameter (zDbName) does not match the name of any
  7866. ** open database file, then SQLITE_ERROR is returned. ^This error
  7867. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  7868. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  7869. ** also return SQLITE_ERROR. There is no way to distinguish between
  7870. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  7871. ** xFileControl method.
  7872. **
  7873. ** See also: [file control opcodes]
  7874. */
  7875. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  7876. /*
  7877. ** CAPI3REF: Testing Interface
  7878. **
  7879. ** ^The sqlite3_test_control() interface is used to read out internal
  7880. ** state of SQLite and to inject faults into SQLite for testing
  7881. ** purposes. ^The first parameter is an operation code that determines
  7882. ** the number, meaning, and operation of all subsequent parameters.
  7883. **
  7884. ** This interface is not for use by applications. It exists solely
  7885. ** for verifying the correct operation of the SQLite library. Depending
  7886. ** on how the SQLite library is compiled, this interface might not exist.
  7887. **
  7888. ** The details of the operation codes, their meanings, the parameters
  7889. ** they take, and what they do are all subject to change without notice.
  7890. ** Unlike most of the SQLite API, this function is not guaranteed to
  7891. ** operate consistently from one release to the next.
  7892. */
  7893. SQLITE_API int sqlite3_test_control(int op, ...);
  7894. /*
  7895. ** CAPI3REF: Testing Interface Operation Codes
  7896. **
  7897. ** These constants are the valid operation code parameters used
  7898. ** as the first argument to [sqlite3_test_control()].
  7899. **
  7900. ** These parameters and their meanings are subject to change
  7901. ** without notice. These values are for testing purposes only.
  7902. ** Applications should not use any of these parameters or the
  7903. ** [sqlite3_test_control()] interface.
  7904. */
  7905. #define SQLITE_TESTCTRL_FIRST 5
  7906. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  7907. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  7908. #define SQLITE_TESTCTRL_PRNG_RESET 7
  7909. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  7910. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  7911. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  7912. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  7913. #define SQLITE_TESTCTRL_ASSERT 12
  7914. #define SQLITE_TESTCTRL_ALWAYS 13
  7915. #define SQLITE_TESTCTRL_RESERVE 14
  7916. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  7917. #define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
  7918. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
  7919. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  7920. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  7921. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  7922. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  7923. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  7924. #define SQLITE_TESTCTRL_BYTEORDER 22
  7925. #define SQLITE_TESTCTRL_ISINIT 23
  7926. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  7927. #define SQLITE_TESTCTRL_IMPOSTER 25
  7928. #define SQLITE_TESTCTRL_PARSER_COVERAGE 26
  7929. #define SQLITE_TESTCTRL_LAST 26 /* Largest TESTCTRL */
  7930. /*
  7931. ** CAPI3REF: SQL Keyword Checking
  7932. **
  7933. ** These routines provide access to the set of SQL language keywords
  7934. ** recognized by SQLite. Applications can uses these routines to determine
  7935. ** whether or not a specific identifier needs to be escaped (for example,
  7936. ** by enclosing in double-quotes) so as not to confuse the parser.
  7937. **
  7938. ** The sqlite3_keyword_count() interface returns the number of distinct
  7939. ** keywords understood by SQLite.
  7940. **
  7941. ** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
  7942. ** makes *Z point to that keyword expressed as UTF8 and writes the number
  7943. ** of bytes in the keyword into *L. The string that *Z points to is not
  7944. ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
  7945. ** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
  7946. ** or L are NULL or invalid pointers then calls to
  7947. ** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
  7948. **
  7949. ** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
  7950. ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
  7951. ** if it is and zero if not.
  7952. **
  7953. ** The parser used by SQLite is forgiving. It is often possible to use
  7954. ** a keyword as an identifier as long as such use does not result in a
  7955. ** parsing ambiguity. For example, the statement
  7956. ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  7957. ** creates a new table named "BEGIN" with three columns named
  7958. ** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
  7959. ** using keywords as identifiers. Common techniques used to avoid keyword
  7960. ** name collisions include:
  7961. ** <ul>
  7962. ** <li> Put all identifier names inside double-quotes. This is the official
  7963. ** SQL way to escape identifier names.
  7964. ** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
  7965. ** but it is what SQL Server does and so lots of programmers use this
  7966. ** technique.
  7967. ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  7968. ** with "Z".
  7969. ** <li> Include a digit somewhere in every identifier name.
  7970. ** </ul>
  7971. **
  7972. ** Note that the number of keywords understood by SQLite can depend on
  7973. ** compile-time options. For example, "VACUUM" is not a keyword if
  7974. ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
  7975. ** new keywords may be added to future releases of SQLite.
  7976. */
  7977. SQLITE_API int sqlite3_keyword_count(void);
  7978. SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  7979. SQLITE_API int sqlite3_keyword_check(const char*,int);
  7980. /*
  7981. ** CAPI3REF: Dynamic String Object
  7982. ** KEYWORDS: {dynamic string}
  7983. **
  7984. ** An instance of the sqlite3_str object contains a dynamically-sized
  7985. ** string under construction.
  7986. **
  7987. ** The lifecycle of an sqlite3_str object is as follows:
  7988. ** <ol>
  7989. ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  7990. ** <li> ^Text is appended to the sqlite3_str object using various
  7991. ** methods, such as [sqlite3_str_appendf()].
  7992. ** <li> ^The sqlite3_str object is destroyed and the string it created
  7993. ** is returned using the [sqlite3_str_finish()] interface.
  7994. ** </ol>
  7995. */
  7996. typedef struct sqlite3_str sqlite3_str;
  7997. /*
  7998. ** CAPI3REF: Create A New Dynamic String Object
  7999. ** CONSTRUCTOR: sqlite3_str
  8000. **
  8001. ** ^The [sqlite3_str_new(D)] interface allocates and initializes
  8002. ** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
  8003. ** [sqlite3_str_new()] must be freed by a subsequent call to
  8004. ** [sqlite3_str_finish(X)].
  8005. **
  8006. ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  8007. ** valid [sqlite3_str] object, though in the event of an out-of-memory
  8008. ** error the returned object might be a special singleton that will
  8009. ** silently reject new text, always return SQLITE_NOMEM from
  8010. ** [sqlite3_str_errcode()], always return 0 for
  8011. ** [sqlite3_str_length()], and always return NULL from
  8012. ** [sqlite3_str_finish(X)]. It is always safe to use the value
  8013. ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  8014. ** to any of the other [sqlite3_str] methods.
  8015. **
  8016. ** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
  8017. ** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  8018. ** length of the string contained in the [sqlite3_str] object will be
  8019. ** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  8020. ** of [SQLITE_MAX_LENGTH].
  8021. */
  8022. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  8023. /*
  8024. ** CAPI3REF: Finalize A Dynamic String
  8025. ** DESTRUCTOR: sqlite3_str
  8026. **
  8027. ** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  8028. ** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  8029. ** that contains the constructed string. The calling application should
  8030. ** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  8031. ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  8032. ** errors were encountered during construction of the string. ^The
  8033. ** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  8034. ** string in [sqlite3_str] object X is zero bytes long.
  8035. */
  8036. SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  8037. /*
  8038. ** CAPI3REF: Add Content To A Dynamic String
  8039. ** METHOD: sqlite3_str
  8040. **
  8041. ** These interfaces add content to an sqlite3_str object previously obtained
  8042. ** from [sqlite3_str_new()].
  8043. **
  8044. ** ^The [sqlite3_str_appendf(X,F,...)] and
  8045. ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  8046. ** functionality of SQLite to append formatted text onto the end of
  8047. ** [sqlite3_str] object X.
  8048. **
  8049. ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  8050. ** onto the end of the [sqlite3_str] object X. N must be non-negative.
  8051. ** S must contain at least N non-zero bytes of content. To append a
  8052. ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  8053. ** method instead.
  8054. **
  8055. ** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  8056. ** zero-terminated string S onto the end of [sqlite3_str] object X.
  8057. **
  8058. ** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  8059. ** single-byte character C onto the end of [sqlite3_str] object X.
  8060. ** ^This method can be used, for example, to add whitespace indentation.
  8061. **
  8062. ** ^The [sqlite3_str_reset(X)] method resets the string under construction
  8063. ** inside [sqlite3_str] object X back to zero bytes in length.
  8064. **
  8065. ** These methods do not return a result code. ^If an error occurs, that fact
  8066. ** is recorded in the [sqlite3_str] object and can be recovered by a
  8067. ** subsequent call to [sqlite3_str_errcode(X)].
  8068. */
  8069. SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  8070. SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  8071. SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  8072. SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  8073. SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  8074. SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  8075. /*
  8076. ** CAPI3REF: Status Of A Dynamic String
  8077. ** METHOD: sqlite3_str
  8078. **
  8079. ** These interfaces return the current status of an [sqlite3_str] object.
  8080. **
  8081. ** ^If any prior errors have occurred while constructing the dynamic string
  8082. ** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  8083. ** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
  8084. ** [SQLITE_NOMEM] following any out-of-memory error, or
  8085. ** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  8086. ** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  8087. **
  8088. ** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  8089. ** of the dynamic string under construction in [sqlite3_str] object X.
  8090. ** ^The length returned by [sqlite3_str_length(X)] does not include the
  8091. ** zero-termination byte.
  8092. **
  8093. ** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  8094. ** content of the dynamic string under construction in X. The value
  8095. ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  8096. ** and might be freed or altered by any subsequent method on the same
  8097. ** [sqlite3_str] object. Applications must not used the pointer returned
  8098. ** [sqlite3_str_value(X)] after any subsequent method call on the same
  8099. ** object. ^Applications may change the content of the string returned
  8100. ** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  8101. ** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  8102. ** write any byte after any subsequent sqlite3_str method call.
  8103. */
  8104. SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  8105. SQLITE_API int sqlite3_str_length(sqlite3_str*);
  8106. SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  8107. /*
  8108. ** CAPI3REF: SQLite Runtime Status
  8109. **
  8110. ** ^These interfaces are used to retrieve runtime status information
  8111. ** about the performance of SQLite, and optionally to reset various
  8112. ** highwater marks. ^The first argument is an integer code for
  8113. ** the specific parameter to measure. ^(Recognized integer codes
  8114. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  8115. ** ^The current value of the parameter is returned into *pCurrent.
  8116. ** ^The highest recorded value is returned in *pHighwater. ^If the
  8117. ** resetFlag is true, then the highest record value is reset after
  8118. ** *pHighwater is written. ^(Some parameters do not record the highest
  8119. ** value. For those parameters
  8120. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  8121. ** ^(Other parameters record only the highwater mark and not the current
  8122. ** value. For these latter parameters nothing is written into *pCurrent.)^
  8123. **
  8124. ** ^The sqlite3_status() and sqlite3_status64() routines return
  8125. ** SQLITE_OK on success and a non-zero [error code] on failure.
  8126. **
  8127. ** If either the current value or the highwater mark is too large to
  8128. ** be represented by a 32-bit integer, then the values returned by
  8129. ** sqlite3_status() are undefined.
  8130. **
  8131. ** See also: [sqlite3_db_status()]
  8132. */
  8133. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  8134. SQLITE_API int sqlite3_status64(
  8135. int op,
  8136. sqlite3_int64 *pCurrent,
  8137. sqlite3_int64 *pHighwater,
  8138. int resetFlag
  8139. );
  8140. /*
  8141. ** CAPI3REF: Status Parameters
  8142. ** KEYWORDS: {status parameters}
  8143. **
  8144. ** These integer constants designate various run-time status parameters
  8145. ** that can be returned by [sqlite3_status()].
  8146. **
  8147. ** <dl>
  8148. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  8149. ** <dd>This parameter is the current amount of memory checked out
  8150. ** using [sqlite3_malloc()], either directly or indirectly. The
  8151. ** figure includes calls made to [sqlite3_malloc()] by the application
  8152. ** and internal memory usage by the SQLite library. Auxiliary page-cache
  8153. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  8154. ** this parameter. The amount returned is the sum of the allocation
  8155. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  8156. **
  8157. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  8158. ** <dd>This parameter records the largest memory allocation request
  8159. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  8160. ** internal equivalents). Only the value returned in the
  8161. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8162. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8163. **
  8164. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  8165. ** <dd>This parameter records the number of separate memory allocations
  8166. ** currently checked out.</dd>)^
  8167. **
  8168. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  8169. ** <dd>This parameter returns the number of pages used out of the
  8170. ** [pagecache memory allocator] that was configured using
  8171. ** [SQLITE_CONFIG_PAGECACHE]. The
  8172. ** value returned is in pages, not in bytes.</dd>)^
  8173. **
  8174. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  8175. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  8176. ** <dd>This parameter returns the number of bytes of page cache
  8177. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  8178. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  8179. ** returned value includes allocations that overflowed because they
  8180. ** where too large (they were larger than the "sz" parameter to
  8181. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  8182. ** no space was left in the page cache.</dd>)^
  8183. **
  8184. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  8185. ** <dd>This parameter records the largest memory allocation request
  8186. ** handed to [pagecache memory allocator]. Only the value returned in the
  8187. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8188. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8189. **
  8190. ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  8191. ** <dd>No longer used.</dd>
  8192. **
  8193. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  8194. ** <dd>No longer used.</dd>
  8195. **
  8196. ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  8197. ** <dd>No longer used.</dd>
  8198. **
  8199. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  8200. ** <dd>The *pHighwater parameter records the deepest parser stack.
  8201. ** The *pCurrent value is undefined. The *pHighwater value is only
  8202. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  8203. ** </dl>
  8204. **
  8205. ** New status parameters may be added from time to time.
  8206. */
  8207. #define SQLITE_STATUS_MEMORY_USED 0
  8208. #define SQLITE_STATUS_PAGECACHE_USED 1
  8209. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  8210. #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
  8211. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
  8212. #define SQLITE_STATUS_MALLOC_SIZE 5
  8213. #define SQLITE_STATUS_PARSER_STACK 6
  8214. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  8215. #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
  8216. #define SQLITE_STATUS_MALLOC_COUNT 9
  8217. /*
  8218. ** CAPI3REF: Database Connection Status
  8219. ** METHOD: sqlite3
  8220. **
  8221. ** ^This interface is used to retrieve runtime status information
  8222. ** about a single [database connection]. ^The first argument is the
  8223. ** database connection object to be interrogated. ^The second argument
  8224. ** is an integer constant, taken from the set of
  8225. ** [SQLITE_DBSTATUS options], that
  8226. ** determines the parameter to interrogate. The set of
  8227. ** [SQLITE_DBSTATUS options] is likely
  8228. ** to grow in future releases of SQLite.
  8229. **
  8230. ** ^The current value of the requested parameter is written into *pCur
  8231. ** and the highest instantaneous value is written into *pHiwtr. ^If
  8232. ** the resetFlg is true, then the highest instantaneous value is
  8233. ** reset back down to the current value.
  8234. **
  8235. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  8236. ** non-zero [error code] on failure.
  8237. **
  8238. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  8239. */
  8240. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  8241. /*
  8242. ** CAPI3REF: Status Parameters for database connections
  8243. ** KEYWORDS: {SQLITE_DBSTATUS options}
  8244. **
  8245. ** These constants are the available integer "verbs" that can be passed as
  8246. ** the second argument to the [sqlite3_db_status()] interface.
  8247. **
  8248. ** New verbs may be added in future releases of SQLite. Existing verbs
  8249. ** might be discontinued. Applications should check the return code from
  8250. ** [sqlite3_db_status()] to make sure that the call worked.
  8251. ** The [sqlite3_db_status()] interface will return a non-zero error code
  8252. ** if a discontinued or unsupported verb is invoked.
  8253. **
  8254. ** <dl>
  8255. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8256. ** <dd>This parameter returns the number of lookaside memory slots currently
  8257. ** checked out.</dd>)^
  8258. **
  8259. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8260. ** <dd>This parameter returns the number malloc attempts that were
  8261. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8262. ** the current value is always zero.)^
  8263. **
  8264. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8265. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8266. ** <dd>This parameter returns the number malloc attempts that might have
  8267. ** been satisfied using lookaside memory but failed due to the amount of
  8268. ** memory requested being larger than the lookaside slot size.
  8269. ** Only the high-water value is meaningful;
  8270. ** the current value is always zero.)^
  8271. **
  8272. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8273. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8274. ** <dd>This parameter returns the number malloc attempts that might have
  8275. ** been satisfied using lookaside memory but failed due to all lookaside
  8276. ** memory already being in use.
  8277. ** Only the high-water value is meaningful;
  8278. ** the current value is always zero.)^
  8279. **
  8280. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8281. ** <dd>This parameter returns the approximate number of bytes of heap
  8282. ** memory used by all pager caches associated with the database connection.)^
  8283. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8284. **
  8285. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  8286. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8287. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8288. ** pager cache is shared between two or more connections the bytes of heap
  8289. ** memory used by that pager cache is divided evenly between the attached
  8290. ** connections.)^ In other words, if none of the pager caches associated
  8291. ** with the database connection are shared, this request returns the same
  8292. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8293. ** shared, the value returned by this call will be smaller than that returned
  8294. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8295. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8296. **
  8297. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8298. ** <dd>This parameter returns the approximate number of bytes of heap
  8299. ** memory used to store the schema for all databases associated
  8300. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  8301. ** ^The full amount of memory used by the schemas is reported, even if the
  8302. ** schema memory is shared with other database connections due to
  8303. ** [shared cache mode] being enabled.
  8304. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8305. **
  8306. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8307. ** <dd>This parameter returns the approximate number of bytes of heap
  8308. ** and lookaside memory used by all prepared statements associated with
  8309. ** the database connection.)^
  8310. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8311. ** </dd>
  8312. **
  8313. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8314. ** <dd>This parameter returns the number of pager cache hits that have
  8315. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  8316. ** is always 0.
  8317. ** </dd>
  8318. **
  8319. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8320. ** <dd>This parameter returns the number of pager cache misses that have
  8321. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  8322. ** is always 0.
  8323. ** </dd>
  8324. **
  8325. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8326. ** <dd>This parameter returns the number of dirty cache entries that have
  8327. ** been written to disk. Specifically, the number of pages written to the
  8328. ** wal file in wal mode databases, or the number of pages written to the
  8329. ** database file in rollback mode databases. Any pages written as part of
  8330. ** transaction rollback or database recovery operations are not included.
  8331. ** If an IO or other error occurs while writing a page to disk, the effect
  8332. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8333. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8334. ** </dd>
  8335. **
  8336. ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
  8337. ** <dd>This parameter returns the number of dirty cache entries that have
  8338. ** been written to disk in the middle of a transaction due to the page
  8339. ** cache overflowing. Transactions are more efficient if they are written
  8340. ** to disk all at once. When pages spill mid-transaction, that introduces
  8341. ** additional overhead. This parameter can be used help identify
  8342. ** inefficiencies that can be resolve by increasing the cache size.
  8343. ** </dd>
  8344. **
  8345. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8346. ** <dd>This parameter returns zero for the current value if and only if
  8347. ** all foreign key constraints (deferred or immediate) have been
  8348. ** resolved.)^ ^The highwater mark is always 0.
  8349. ** </dd>
  8350. ** </dl>
  8351. */
  8352. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  8353. #define SQLITE_DBSTATUS_CACHE_USED 1
  8354. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  8355. #define SQLITE_DBSTATUS_STMT_USED 3
  8356. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  8357. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  8358. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  8359. #define SQLITE_DBSTATUS_CACHE_HIT 7
  8360. #define SQLITE_DBSTATUS_CACHE_MISS 8
  8361. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  8362. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  8363. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  8364. #define SQLITE_DBSTATUS_CACHE_SPILL 12
  8365. #define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
  8366. /*
  8367. ** CAPI3REF: Prepared Statement Status
  8368. ** METHOD: sqlite3_stmt
  8369. **
  8370. ** ^(Each prepared statement maintains various
  8371. ** [SQLITE_STMTSTATUS counters] that measure the number
  8372. ** of times it has performed specific operations.)^ These counters can
  8373. ** be used to monitor the performance characteristics of the prepared
  8374. ** statements. For example, if the number of table steps greatly exceeds
  8375. ** the number of table searches or result rows, that would tend to indicate
  8376. ** that the prepared statement is using a full table scan rather than
  8377. ** an index.
  8378. **
  8379. ** ^(This interface is used to retrieve and reset counter values from
  8380. ** a [prepared statement]. The first argument is the prepared statement
  8381. ** object to be interrogated. The second argument
  8382. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8383. ** to be interrogated.)^
  8384. ** ^The current value of the requested counter is returned.
  8385. ** ^If the resetFlg is true, then the counter is reset to zero after this
  8386. ** interface call returns.
  8387. **
  8388. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8389. */
  8390. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8391. /*
  8392. ** CAPI3REF: Status Parameters for prepared statements
  8393. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8394. **
  8395. ** These preprocessor macros define integer codes that name counter
  8396. ** values associated with the [sqlite3_stmt_status()] interface.
  8397. ** The meanings of the various counters are as follows:
  8398. **
  8399. ** <dl>
  8400. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8401. ** <dd>^This is the number of times that SQLite has stepped forward in
  8402. ** a table as part of a full table scan. Large numbers for this counter
  8403. ** may indicate opportunities for performance improvement through
  8404. ** careful use of indices.</dd>
  8405. **
  8406. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8407. ** <dd>^This is the number of sort operations that have occurred.
  8408. ** A non-zero value in this counter may indicate an opportunity to
  8409. ** improvement performance through careful use of indices.</dd>
  8410. **
  8411. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8412. ** <dd>^This is the number of rows inserted into transient indices that
  8413. ** were created automatically in order to help joins run faster.
  8414. ** A non-zero value in this counter may indicate an opportunity to
  8415. ** improvement performance by adding permanent indices that do not
  8416. ** need to be reinitialized each time the statement is run.</dd>
  8417. **
  8418. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8419. ** <dd>^This is the number of virtual machine operations executed
  8420. ** by the prepared statement if that number is less than or equal
  8421. ** to 2147483647. The number of virtual machine operations can be
  8422. ** used as a proxy for the total work done by the prepared statement.
  8423. ** If the number of virtual machine operations exceeds 2147483647
  8424. ** then the value returned by this statement status code is undefined.
  8425. **
  8426. ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8427. ** <dd>^This is the number of times that the prepare statement has been
  8428. ** automatically regenerated due to schema changes or change to
  8429. ** [bound parameters] that might affect the query plan.
  8430. **
  8431. ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8432. ** <dd>^This is the number of times that the prepared statement has
  8433. ** been run. A single "run" for the purposes of this counter is one
  8434. ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8435. ** The counter is incremented on the first [sqlite3_step()] call of each
  8436. ** cycle.
  8437. **
  8438. ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8439. ** <dd>^This is the approximate number of bytes of heap memory
  8440. ** used to store the prepared statement. ^This value is not actually
  8441. ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8442. ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8443. ** </dd>
  8444. ** </dl>
  8445. */
  8446. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  8447. #define SQLITE_STMTSTATUS_SORT 2
  8448. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  8449. #define SQLITE_STMTSTATUS_VM_STEP 4
  8450. #define SQLITE_STMTSTATUS_REPREPARE 5
  8451. #define SQLITE_STMTSTATUS_RUN 6
  8452. #define SQLITE_STMTSTATUS_MEMUSED 99
  8453. /*
  8454. ** CAPI3REF: Custom Page Cache Object
  8455. **
  8456. ** The sqlite3_pcache type is opaque. It is implemented by
  8457. ** the pluggable module. The SQLite core has no knowledge of
  8458. ** its size or internal structure and never deals with the
  8459. ** sqlite3_pcache object except by holding and passing pointers
  8460. ** to the object.
  8461. **
  8462. ** See [sqlite3_pcache_methods2] for additional information.
  8463. */
  8464. typedef struct sqlite3_pcache sqlite3_pcache;
  8465. /*
  8466. ** CAPI3REF: Custom Page Cache Object
  8467. **
  8468. ** The sqlite3_pcache_page object represents a single page in the
  8469. ** page cache. The page cache will allocate instances of this
  8470. ** object. Various methods of the page cache use pointers to instances
  8471. ** of this object as parameters or as their return value.
  8472. **
  8473. ** See [sqlite3_pcache_methods2] for additional information.
  8474. */
  8475. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8476. struct sqlite3_pcache_page {
  8477. void *pBuf; /* The content of the page */
  8478. void *pExtra; /* Extra information associated with the page */
  8479. };
  8480. /*
  8481. ** CAPI3REF: Application Defined Page Cache.
  8482. ** KEYWORDS: {page cache}
  8483. **
  8484. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8485. ** register an alternative page cache implementation by passing in an
  8486. ** instance of the sqlite3_pcache_methods2 structure.)^
  8487. ** In many applications, most of the heap memory allocated by
  8488. ** SQLite is used for the page cache.
  8489. ** By implementing a
  8490. ** custom page cache using this API, an application can better control
  8491. ** the amount of memory consumed by SQLite, the way in which
  8492. ** that memory is allocated and released, and the policies used to
  8493. ** determine exactly which parts of a database file are cached and for
  8494. ** how long.
  8495. **
  8496. ** The alternative page cache mechanism is an
  8497. ** extreme measure that is only needed by the most demanding applications.
  8498. ** The built-in page cache is recommended for most uses.
  8499. **
  8500. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8501. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  8502. ** the application may discard the parameter after the call to
  8503. ** [sqlite3_config()] returns.)^
  8504. **
  8505. ** [[the xInit() page cache method]]
  8506. ** ^(The xInit() method is called once for each effective
  8507. ** call to [sqlite3_initialize()])^
  8508. ** (usually only once during the lifetime of the process). ^(The xInit()
  8509. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8510. ** The intent of the xInit() method is to set up global data structures
  8511. ** required by the custom page cache implementation.
  8512. ** ^(If the xInit() method is NULL, then the
  8513. ** built-in default page cache is used instead of the application defined
  8514. ** page cache.)^
  8515. **
  8516. ** [[the xShutdown() page cache method]]
  8517. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8518. ** It can be used to clean up
  8519. ** any outstanding resources before process shutdown, if required.
  8520. ** ^The xShutdown() method may be NULL.
  8521. **
  8522. ** ^SQLite automatically serializes calls to the xInit method,
  8523. ** so the xInit method need not be threadsafe. ^The
  8524. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8525. ** not need to be threadsafe either. All other methods must be threadsafe
  8526. ** in multithreaded applications.
  8527. **
  8528. ** ^SQLite will never invoke xInit() more than once without an intervening
  8529. ** call to xShutdown().
  8530. **
  8531. ** [[the xCreate() page cache methods]]
  8532. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8533. ** SQLite will typically create one cache instance for each open database file,
  8534. ** though this is not guaranteed. ^The
  8535. ** first parameter, szPage, is the size in bytes of the pages that must
  8536. ** be allocated by the cache. ^szPage will always a power of two. ^The
  8537. ** second parameter szExtra is a number of bytes of extra storage
  8538. ** associated with each page cache entry. ^The szExtra parameter will
  8539. ** a number less than 250. SQLite will use the
  8540. ** extra szExtra bytes on each page to store metadata about the underlying
  8541. ** database page on disk. The value passed into szExtra depends
  8542. ** on the SQLite version, the target platform, and how SQLite was compiled.
  8543. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8544. ** created will be used to cache database pages of a file stored on disk, or
  8545. ** false if it is used for an in-memory database. The cache implementation
  8546. ** does not have to do anything special based with the value of bPurgeable;
  8547. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  8548. ** never invoke xUnpin() except to deliberately delete a page.
  8549. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8550. ** false will always have the "discard" flag set to true.
  8551. ** ^Hence, a cache created with bPurgeable false will
  8552. ** never contain any unpinned pages.
  8553. **
  8554. ** [[the xCachesize() page cache method]]
  8555. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  8556. ** suggested maximum cache-size (number of pages stored by) the cache
  8557. ** instance passed as the first argument. This is the value configured using
  8558. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  8559. ** parameter, the implementation is not required to do anything with this
  8560. ** value; it is advisory only.
  8561. **
  8562. ** [[the xPagecount() page cache methods]]
  8563. ** The xPagecount() method must return the number of pages currently
  8564. ** stored in the cache, both pinned and unpinned.
  8565. **
  8566. ** [[the xFetch() page cache methods]]
  8567. ** The xFetch() method locates a page in the cache and returns a pointer to
  8568. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  8569. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  8570. ** pointer to a buffer of szPage bytes used to store the content of a
  8571. ** single database page. The pExtra element of sqlite3_pcache_page will be
  8572. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  8573. ** for each entry in the page cache.
  8574. **
  8575. ** The page to be fetched is determined by the key. ^The minimum key value
  8576. ** is 1. After it has been retrieved using xFetch, the page is considered
  8577. ** to be "pinned".
  8578. **
  8579. ** If the requested page is already in the page cache, then the page cache
  8580. ** implementation must return a pointer to the page buffer with its content
  8581. ** intact. If the requested page is not already in the cache, then the
  8582. ** cache implementation should use the value of the createFlag
  8583. ** parameter to help it determined what action to take:
  8584. **
  8585. ** <table border=1 width=85% align=center>
  8586. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  8587. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  8588. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  8589. ** Otherwise return NULL.
  8590. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  8591. ** NULL if allocating a new page is effectively impossible.
  8592. ** </table>
  8593. **
  8594. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  8595. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  8596. ** failed.)^ In between the to xFetch() calls, SQLite may
  8597. ** attempt to unpin one or more cache pages by spilling the content of
  8598. ** pinned pages to disk and synching the operating system disk cache.
  8599. **
  8600. ** [[the xUnpin() page cache method]]
  8601. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  8602. ** as its second argument. If the third parameter, discard, is non-zero,
  8603. ** then the page must be evicted from the cache.
  8604. ** ^If the discard parameter is
  8605. ** zero, then the page may be discarded or retained at the discretion of
  8606. ** page cache implementation. ^The page cache implementation
  8607. ** may choose to evict unpinned pages at any time.
  8608. **
  8609. ** The cache must not perform any reference counting. A single
  8610. ** call to xUnpin() unpins the page regardless of the number of prior calls
  8611. ** to xFetch().
  8612. **
  8613. ** [[the xRekey() page cache methods]]
  8614. ** The xRekey() method is used to change the key value associated with the
  8615. ** page passed as the second argument. If the cache
  8616. ** previously contains an entry associated with newKey, it must be
  8617. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  8618. ** to be pinned.
  8619. **
  8620. ** When SQLite calls the xTruncate() method, the cache must discard all
  8621. ** existing cache entries with page numbers (keys) greater than or equal
  8622. ** to the value of the iLimit parameter passed to xTruncate(). If any
  8623. ** of these pages are pinned, they are implicitly unpinned, meaning that
  8624. ** they can be safely discarded.
  8625. **
  8626. ** [[the xDestroy() page cache method]]
  8627. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  8628. ** All resources associated with the specified cache should be freed. ^After
  8629. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  8630. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  8631. ** functions.
  8632. **
  8633. ** [[the xShrink() page cache method]]
  8634. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  8635. ** free up as much of heap memory as possible. The page cache implementation
  8636. ** is not obligated to free any memory, but well-behaved implementations should
  8637. ** do their best.
  8638. */
  8639. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  8640. struct sqlite3_pcache_methods2 {
  8641. int iVersion;
  8642. void *pArg;
  8643. int (*xInit)(void*);
  8644. void (*xShutdown)(void*);
  8645. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  8646. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8647. int (*xPagecount)(sqlite3_pcache*);
  8648. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8649. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  8650. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  8651. unsigned oldKey, unsigned newKey);
  8652. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8653. void (*xDestroy)(sqlite3_pcache*);
  8654. void (*xShrink)(sqlite3_pcache*);
  8655. };
  8656. /*
  8657. ** This is the obsolete pcache_methods object that has now been replaced
  8658. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  8659. ** retained in the header file for backwards compatibility only.
  8660. */
  8661. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  8662. struct sqlite3_pcache_methods {
  8663. void *pArg;
  8664. int (*xInit)(void*);
  8665. void (*xShutdown)(void*);
  8666. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  8667. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8668. int (*xPagecount)(sqlite3_pcache*);
  8669. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8670. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  8671. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  8672. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8673. void (*xDestroy)(sqlite3_pcache*);
  8674. };
  8675. /*
  8676. ** CAPI3REF: Online Backup Object
  8677. **
  8678. ** The sqlite3_backup object records state information about an ongoing
  8679. ** online backup operation. ^The sqlite3_backup object is created by
  8680. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  8681. ** [sqlite3_backup_finish()].
  8682. **
  8683. ** See Also: [Using the SQLite Online Backup API]
  8684. */
  8685. typedef struct sqlite3_backup sqlite3_backup;
  8686. /*
  8687. ** CAPI3REF: Online Backup API.
  8688. **
  8689. ** The backup API copies the content of one database into another.
  8690. ** It is useful either for creating backups of databases or
  8691. ** for copying in-memory databases to or from persistent files.
  8692. **
  8693. ** See Also: [Using the SQLite Online Backup API]
  8694. **
  8695. ** ^SQLite holds a write transaction open on the destination database file
  8696. ** for the duration of the backup operation.
  8697. ** ^The source database is read-locked only while it is being read;
  8698. ** it is not locked continuously for the entire backup operation.
  8699. ** ^Thus, the backup may be performed on a live source database without
  8700. ** preventing other database connections from
  8701. ** reading or writing to the source database while the backup is underway.
  8702. **
  8703. ** ^(To perform a backup operation:
  8704. ** <ol>
  8705. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  8706. ** backup,
  8707. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  8708. ** the data between the two databases, and finally
  8709. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  8710. ** associated with the backup operation.
  8711. ** </ol>)^
  8712. ** There should be exactly one call to sqlite3_backup_finish() for each
  8713. ** successful call to sqlite3_backup_init().
  8714. **
  8715. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  8716. **
  8717. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  8718. ** [database connection] associated with the destination database
  8719. ** and the database name, respectively.
  8720. ** ^The database name is "main" for the main database, "temp" for the
  8721. ** temporary database, or the name specified after the AS keyword in
  8722. ** an [ATTACH] statement for an attached database.
  8723. ** ^The S and M arguments passed to
  8724. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  8725. ** and database name of the source database, respectively.
  8726. ** ^The source and destination [database connections] (parameters S and D)
  8727. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  8728. ** an error.
  8729. **
  8730. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  8731. ** there is already a read or read-write transaction open on the
  8732. ** destination database.
  8733. **
  8734. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  8735. ** returned and an error code and error message are stored in the
  8736. ** destination [database connection] D.
  8737. ** ^The error code and message for the failed call to sqlite3_backup_init()
  8738. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  8739. ** [sqlite3_errmsg16()] functions.
  8740. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  8741. ** [sqlite3_backup] object.
  8742. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  8743. ** sqlite3_backup_finish() functions to perform the specified backup
  8744. ** operation.
  8745. **
  8746. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  8747. **
  8748. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  8749. ** the source and destination databases specified by [sqlite3_backup] object B.
  8750. ** ^If N is negative, all remaining source pages are copied.
  8751. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  8752. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  8753. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  8754. ** from source to destination, then it returns [SQLITE_DONE].
  8755. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  8756. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  8757. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  8758. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  8759. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  8760. **
  8761. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  8762. ** <ol>
  8763. ** <li> the destination database was opened read-only, or
  8764. ** <li> the destination database is using write-ahead-log journaling
  8765. ** and the destination and source page sizes differ, or
  8766. ** <li> the destination database is an in-memory database and the
  8767. ** destination and source page sizes differ.
  8768. ** </ol>)^
  8769. **
  8770. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  8771. ** the [sqlite3_busy_handler | busy-handler function]
  8772. ** is invoked (if one is specified). ^If the
  8773. ** busy-handler returns non-zero before the lock is available, then
  8774. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  8775. ** sqlite3_backup_step() can be retried later. ^If the source
  8776. ** [database connection]
  8777. ** is being used to write to the source database when sqlite3_backup_step()
  8778. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  8779. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  8780. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  8781. ** [SQLITE_READONLY] is returned, then
  8782. ** there is no point in retrying the call to sqlite3_backup_step(). These
  8783. ** errors are considered fatal.)^ The application must accept
  8784. ** that the backup operation has failed and pass the backup operation handle
  8785. ** to the sqlite3_backup_finish() to release associated resources.
  8786. **
  8787. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  8788. ** on the destination file. ^The exclusive lock is not released until either
  8789. ** sqlite3_backup_finish() is called or the backup operation is complete
  8790. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  8791. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  8792. ** lasts for the duration of the sqlite3_backup_step() call.
  8793. ** ^Because the source database is not locked between calls to
  8794. ** sqlite3_backup_step(), the source database may be modified mid-way
  8795. ** through the backup process. ^If the source database is modified by an
  8796. ** external process or via a database connection other than the one being
  8797. ** used by the backup operation, then the backup will be automatically
  8798. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  8799. ** database is modified by the using the same database connection as is used
  8800. ** by the backup operation, then the backup database is automatically
  8801. ** updated at the same time.
  8802. **
  8803. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  8804. **
  8805. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  8806. ** application wishes to abandon the backup operation, the application
  8807. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  8808. ** ^The sqlite3_backup_finish() interfaces releases all
  8809. ** resources associated with the [sqlite3_backup] object.
  8810. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  8811. ** active write-transaction on the destination database is rolled back.
  8812. ** The [sqlite3_backup] object is invalid
  8813. ** and may not be used following a call to sqlite3_backup_finish().
  8814. **
  8815. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  8816. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  8817. ** sqlite3_backup_step() completed.
  8818. ** ^If an out-of-memory condition or IO error occurred during any prior
  8819. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  8820. ** sqlite3_backup_finish() returns the corresponding [error code].
  8821. **
  8822. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  8823. ** is not a permanent error and does not affect the return value of
  8824. ** sqlite3_backup_finish().
  8825. **
  8826. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  8827. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  8828. **
  8829. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  8830. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  8831. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  8832. ** in the source database at the conclusion of the most recent
  8833. ** sqlite3_backup_step().
  8834. ** ^(The values returned by these functions are only updated by
  8835. ** sqlite3_backup_step(). If the source database is modified in a way that
  8836. ** changes the size of the source database or the number of pages remaining,
  8837. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  8838. ** and sqlite3_backup_remaining() until after the next
  8839. ** sqlite3_backup_step().)^
  8840. **
  8841. ** <b>Concurrent Usage of Database Handles</b>
  8842. **
  8843. ** ^The source [database connection] may be used by the application for other
  8844. ** purposes while a backup operation is underway or being initialized.
  8845. ** ^If SQLite is compiled and configured to support threadsafe database
  8846. ** connections, then the source database connection may be used concurrently
  8847. ** from within other threads.
  8848. **
  8849. ** However, the application must guarantee that the destination
  8850. ** [database connection] is not passed to any other API (by any thread) after
  8851. ** sqlite3_backup_init() is called and before the corresponding call to
  8852. ** sqlite3_backup_finish(). SQLite does not currently check to see
  8853. ** if the application incorrectly accesses the destination [database connection]
  8854. ** and so no error code is reported, but the operations may malfunction
  8855. ** nevertheless. Use of the destination database connection while a
  8856. ** backup is in progress might also also cause a mutex deadlock.
  8857. **
  8858. ** If running in [shared cache mode], the application must
  8859. ** guarantee that the shared cache used by the destination database
  8860. ** is not accessed while the backup is running. In practice this means
  8861. ** that the application must guarantee that the disk file being
  8862. ** backed up to is not accessed by any connection within the process,
  8863. ** not just the specific connection that was passed to sqlite3_backup_init().
  8864. **
  8865. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  8866. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  8867. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  8868. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  8869. ** same time as another thread is invoking sqlite3_backup_step() it is
  8870. ** possible that they return invalid values.
  8871. */
  8872. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  8873. sqlite3 *pDest, /* Destination database handle */
  8874. const char *zDestName, /* Destination database name */
  8875. sqlite3 *pSource, /* Source database handle */
  8876. const char *zSourceName /* Source database name */
  8877. );
  8878. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  8879. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  8880. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  8881. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  8882. /*
  8883. ** CAPI3REF: Unlock Notification
  8884. ** METHOD: sqlite3
  8885. **
  8886. ** ^When running in shared-cache mode, a database operation may fail with
  8887. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  8888. ** individual tables within the shared-cache cannot be obtained. See
  8889. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  8890. ** ^This API may be used to register a callback that SQLite will invoke
  8891. ** when the connection currently holding the required lock relinquishes it.
  8892. ** ^This API is only available if the library was compiled with the
  8893. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  8894. **
  8895. ** See Also: [Using the SQLite Unlock Notification Feature].
  8896. **
  8897. ** ^Shared-cache locks are released when a database connection concludes
  8898. ** its current transaction, either by committing it or rolling it back.
  8899. **
  8900. ** ^When a connection (known as the blocked connection) fails to obtain a
  8901. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  8902. ** identity of the database connection (the blocking connection) that
  8903. ** has locked the required resource is stored internally. ^After an
  8904. ** application receives an SQLITE_LOCKED error, it may call the
  8905. ** sqlite3_unlock_notify() method with the blocked connection handle as
  8906. ** the first argument to register for a callback that will be invoked
  8907. ** when the blocking connections current transaction is concluded. ^The
  8908. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  8909. ** call that concludes the blocking connections transaction.
  8910. **
  8911. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  8912. ** there is a chance that the blocking connection will have already
  8913. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  8914. ** If this happens, then the specified callback is invoked immediately,
  8915. ** from within the call to sqlite3_unlock_notify().)^
  8916. **
  8917. ** ^If the blocked connection is attempting to obtain a write-lock on a
  8918. ** shared-cache table, and more than one other connection currently holds
  8919. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  8920. ** the other connections to use as the blocking connection.
  8921. **
  8922. ** ^(There may be at most one unlock-notify callback registered by a
  8923. ** blocked connection. If sqlite3_unlock_notify() is called when the
  8924. ** blocked connection already has a registered unlock-notify callback,
  8925. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  8926. ** called with a NULL pointer as its second argument, then any existing
  8927. ** unlock-notify callback is canceled. ^The blocked connections
  8928. ** unlock-notify callback may also be canceled by closing the blocked
  8929. ** connection using [sqlite3_close()].
  8930. **
  8931. ** The unlock-notify callback is not reentrant. If an application invokes
  8932. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  8933. ** crash or deadlock may be the result.
  8934. **
  8935. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  8936. ** returns SQLITE_OK.
  8937. **
  8938. ** <b>Callback Invocation Details</b>
  8939. **
  8940. ** When an unlock-notify callback is registered, the application provides a
  8941. ** single void* pointer that is passed to the callback when it is invoked.
  8942. ** However, the signature of the callback function allows SQLite to pass
  8943. ** it an array of void* context pointers. The first argument passed to
  8944. ** an unlock-notify callback is a pointer to an array of void* pointers,
  8945. ** and the second is the number of entries in the array.
  8946. **
  8947. ** When a blocking connections transaction is concluded, there may be
  8948. ** more than one blocked connection that has registered for an unlock-notify
  8949. ** callback. ^If two or more such blocked connections have specified the
  8950. ** same callback function, then instead of invoking the callback function
  8951. ** multiple times, it is invoked once with the set of void* context pointers
  8952. ** specified by the blocked connections bundled together into an array.
  8953. ** This gives the application an opportunity to prioritize any actions
  8954. ** related to the set of unblocked database connections.
  8955. **
  8956. ** <b>Deadlock Detection</b>
  8957. **
  8958. ** Assuming that after registering for an unlock-notify callback a
  8959. ** database waits for the callback to be issued before taking any further
  8960. ** action (a reasonable assumption), then using this API may cause the
  8961. ** application to deadlock. For example, if connection X is waiting for
  8962. ** connection Y's transaction to be concluded, and similarly connection
  8963. ** Y is waiting on connection X's transaction, then neither connection
  8964. ** will proceed and the system may remain deadlocked indefinitely.
  8965. **
  8966. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  8967. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  8968. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  8969. ** unlock-notify callback is registered. The system is said to be in
  8970. ** a deadlocked state if connection A has registered for an unlock-notify
  8971. ** callback on the conclusion of connection B's transaction, and connection
  8972. ** B has itself registered for an unlock-notify callback when connection
  8973. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  8974. ** the system is also considered to be deadlocked if connection B has
  8975. ** registered for an unlock-notify callback on the conclusion of connection
  8976. ** C's transaction, where connection C is waiting on connection A. ^Any
  8977. ** number of levels of indirection are allowed.
  8978. **
  8979. ** <b>The "DROP TABLE" Exception</b>
  8980. **
  8981. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  8982. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  8983. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  8984. ** SQLite checks if there are any currently executing SELECT statements
  8985. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  8986. ** returned. In this case there is no "blocking connection", so invoking
  8987. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  8988. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  8989. ** or "DROP INDEX" query, an infinite loop might be the result.
  8990. **
  8991. ** One way around this problem is to check the extended error code returned
  8992. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  8993. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  8994. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  8995. ** SQLITE_LOCKED.)^
  8996. */
  8997. SQLITE_API int sqlite3_unlock_notify(
  8998. sqlite3 *pBlocked, /* Waiting connection */
  8999. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  9000. void *pNotifyArg /* Argument to pass to xNotify */
  9001. );
  9002. /*
  9003. ** CAPI3REF: String Comparison
  9004. **
  9005. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  9006. ** and extensions to compare the contents of two buffers containing UTF-8
  9007. ** strings in a case-independent fashion, using the same definition of "case
  9008. ** independence" that SQLite uses internally when comparing identifiers.
  9009. */
  9010. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  9011. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  9012. /*
  9013. ** CAPI3REF: String Globbing
  9014. *
  9015. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  9016. ** string X matches the [GLOB] pattern P.
  9017. ** ^The definition of [GLOB] pattern matching used in
  9018. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  9019. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  9020. ** is case sensitive.
  9021. **
  9022. ** Note that this routine returns zero on a match and non-zero if the strings
  9023. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9024. **
  9025. ** See also: [sqlite3_strlike()].
  9026. */
  9027. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  9028. /*
  9029. ** CAPI3REF: String LIKE Matching
  9030. *
  9031. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  9032. ** string X matches the [LIKE] pattern P with escape character E.
  9033. ** ^The definition of [LIKE] pattern matching used in
  9034. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  9035. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  9036. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  9037. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  9038. ** insensitive - equivalent upper and lower case ASCII characters match
  9039. ** one another.
  9040. **
  9041. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  9042. ** only ASCII characters are case folded.
  9043. **
  9044. ** Note that this routine returns zero on a match and non-zero if the strings
  9045. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9046. **
  9047. ** See also: [sqlite3_strglob()].
  9048. */
  9049. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  9050. /*
  9051. ** CAPI3REF: Error Logging Interface
  9052. **
  9053. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  9054. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  9055. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  9056. ** used with [sqlite3_snprintf()] to generate the final output string.
  9057. **
  9058. ** The sqlite3_log() interface is intended for use by extensions such as
  9059. ** virtual tables, collating functions, and SQL functions. While there is
  9060. ** nothing to prevent an application from calling sqlite3_log(), doing so
  9061. ** is considered bad form.
  9062. **
  9063. ** The zFormat string must not be NULL.
  9064. **
  9065. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  9066. ** will not use dynamically allocated memory. The log message is stored in
  9067. ** a fixed-length buffer on the stack. If the log message is longer than
  9068. ** a few hundred characters, it will be truncated to the length of the
  9069. ** buffer.
  9070. */
  9071. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  9072. /*
  9073. ** CAPI3REF: Write-Ahead Log Commit Hook
  9074. ** METHOD: sqlite3
  9075. **
  9076. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  9077. ** is invoked each time data is committed to a database in wal mode.
  9078. **
  9079. ** ^(The callback is invoked by SQLite after the commit has taken place and
  9080. ** the associated write-lock on the database released)^, so the implementation
  9081. ** may read, write or [checkpoint] the database as required.
  9082. **
  9083. ** ^The first parameter passed to the callback function when it is invoked
  9084. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  9085. ** registering the callback. ^The second is a copy of the database handle.
  9086. ** ^The third parameter is the name of the database that was written to -
  9087. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  9088. ** is the number of pages currently in the write-ahead log file,
  9089. ** including those that were just committed.
  9090. **
  9091. ** The callback function should normally return [SQLITE_OK]. ^If an error
  9092. ** code is returned, that error will propagate back up through the
  9093. ** SQLite code base to cause the statement that provoked the callback
  9094. ** to report an error, though the commit will have still occurred. If the
  9095. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  9096. ** that does not correspond to any valid SQLite error code, the results
  9097. ** are undefined.
  9098. **
  9099. ** A single database handle may have at most a single write-ahead log callback
  9100. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  9101. ** previously registered write-ahead log callback. ^Note that the
  9102. ** [sqlite3_wal_autocheckpoint()] interface and the
  9103. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  9104. ** overwrite any prior [sqlite3_wal_hook()] settings.
  9105. */
  9106. SQLITE_API void *sqlite3_wal_hook(
  9107. sqlite3*,
  9108. int(*)(void *,sqlite3*,const char*,int),
  9109. void*
  9110. );
  9111. /*
  9112. ** CAPI3REF: Configure an auto-checkpoint
  9113. ** METHOD: sqlite3
  9114. **
  9115. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  9116. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  9117. ** to automatically [checkpoint]
  9118. ** after committing a transaction if there are N or
  9119. ** more frames in the [write-ahead log] file. ^Passing zero or
  9120. ** a negative value as the nFrame parameter disables automatic
  9121. ** checkpoints entirely.
  9122. **
  9123. ** ^The callback registered by this function replaces any existing callback
  9124. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  9125. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  9126. ** configured by this function.
  9127. **
  9128. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  9129. ** from SQL.
  9130. **
  9131. ** ^Checkpoints initiated by this mechanism are
  9132. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  9133. **
  9134. ** ^Every new [database connection] defaults to having the auto-checkpoint
  9135. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  9136. ** pages. The use of this interface
  9137. ** is only necessary if the default setting is found to be suboptimal
  9138. ** for a particular application.
  9139. */
  9140. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  9141. /*
  9142. ** CAPI3REF: Checkpoint a database
  9143. ** METHOD: sqlite3
  9144. **
  9145. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  9146. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  9147. **
  9148. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  9149. ** [write-ahead log] for database X on [database connection] D to be
  9150. ** transferred into the database file and for the write-ahead log to
  9151. ** be reset. See the [checkpointing] documentation for addition
  9152. ** information.
  9153. **
  9154. ** This interface used to be the only way to cause a checkpoint to
  9155. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  9156. ** interface was added. This interface is retained for backwards
  9157. ** compatibility and as a convenience for applications that need to manually
  9158. ** start a callback but which do not need the full power (and corresponding
  9159. ** complication) of [sqlite3_wal_checkpoint_v2()].
  9160. */
  9161. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  9162. /*
  9163. ** CAPI3REF: Checkpoint a database
  9164. ** METHOD: sqlite3
  9165. **
  9166. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  9167. ** operation on database X of [database connection] D in mode M. Status
  9168. ** information is written back into integers pointed to by L and C.)^
  9169. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  9170. **
  9171. ** <dl>
  9172. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  9173. ** ^Checkpoint as many frames as possible without waiting for any database
  9174. ** readers or writers to finish, then sync the database file if all frames
  9175. ** in the log were checkpointed. ^The [busy-handler callback]
  9176. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  9177. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  9178. ** if there are concurrent readers or writers.
  9179. **
  9180. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  9181. ** ^This mode blocks (it invokes the
  9182. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  9183. ** database writer and all readers are reading from the most recent database
  9184. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  9185. ** database file. ^This mode blocks new database writers while it is pending,
  9186. ** but new database readers are allowed to continue unimpeded.
  9187. **
  9188. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  9189. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  9190. ** that after checkpointing the log file it blocks (calls the
  9191. ** [busy-handler callback])
  9192. ** until all readers are reading from the database file only. ^This ensures
  9193. ** that the next writer will restart the log file from the beginning.
  9194. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  9195. ** database writer attempts while it is pending, but does not impede readers.
  9196. **
  9197. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  9198. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  9199. ** addition that it also truncates the log file to zero bytes just prior
  9200. ** to a successful return.
  9201. ** </dl>
  9202. **
  9203. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  9204. ** the log file or to -1 if the checkpoint could not run because
  9205. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  9206. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  9207. ** log file (including any that were already checkpointed before the function
  9208. ** was called) or to -1 if the checkpoint could not run due to an error or
  9209. ** because the database is not in WAL mode. ^Note that upon successful
  9210. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  9211. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  9212. **
  9213. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  9214. ** any other process is running a checkpoint operation at the same time, the
  9215. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  9216. ** busy-handler configured, it will not be invoked in this case.
  9217. **
  9218. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  9219. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  9220. ** obtained immediately, and a busy-handler is configured, it is invoked and
  9221. ** the writer lock retried until either the busy-handler returns 0 or the lock
  9222. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  9223. ** database readers as described above. ^If the busy-handler returns 0 before
  9224. ** the writer lock is obtained or while waiting for database readers, the
  9225. ** checkpoint operation proceeds from that point in the same way as
  9226. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  9227. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  9228. **
  9229. ** ^If parameter zDb is NULL or points to a zero length string, then the
  9230. ** specified operation is attempted on all WAL databases [attached] to
  9231. ** [database connection] db. In this case the
  9232. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  9233. ** an SQLITE_BUSY error is encountered when processing one or more of the
  9234. ** attached WAL databases, the operation is still attempted on any remaining
  9235. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  9236. ** error occurs while processing an attached database, processing is abandoned
  9237. ** and the error code is returned to the caller immediately. ^If no error
  9238. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  9239. ** databases, SQLITE_OK is returned.
  9240. **
  9241. ** ^If database zDb is the name of an attached database that is not in WAL
  9242. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  9243. ** zDb is not NULL (or a zero length string) and is not the name of any
  9244. ** attached database, SQLITE_ERROR is returned to the caller.
  9245. **
  9246. ** ^Unless it returns SQLITE_MISUSE,
  9247. ** the sqlite3_wal_checkpoint_v2() interface
  9248. ** sets the error information that is queried by
  9249. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  9250. **
  9251. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9252. ** from SQL.
  9253. */
  9254. SQLITE_API int sqlite3_wal_checkpoint_v2(
  9255. sqlite3 *db, /* Database handle */
  9256. const char *zDb, /* Name of attached database (or NULL) */
  9257. int eMode, /* SQLITE_CHECKPOINT_* value */
  9258. int *pnLog, /* OUT: Size of WAL log in frames */
  9259. int *pnCkpt /* OUT: Total number of frames checkpointed */
  9260. );
  9261. /*
  9262. ** CAPI3REF: Checkpoint Mode Values
  9263. ** KEYWORDS: {checkpoint mode}
  9264. **
  9265. ** These constants define all valid values for the "checkpoint mode" passed
  9266. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9267. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9268. ** meaning of each of these checkpoint modes.
  9269. */
  9270. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  9271. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  9272. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  9273. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  9274. /*
  9275. ** CAPI3REF: Virtual Table Interface Configuration
  9276. **
  9277. ** This function may be called by either the [xConnect] or [xCreate] method
  9278. ** of a [virtual table] implementation to configure
  9279. ** various facets of the virtual table interface.
  9280. **
  9281. ** If this interface is invoked outside the context of an xConnect or
  9282. ** xCreate virtual table method then the behavior is undefined.
  9283. **
  9284. ** At present, there is only one option that may be configured using
  9285. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  9286. ** may be added in the future.
  9287. */
  9288. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9289. /*
  9290. ** CAPI3REF: Virtual Table Configuration Options
  9291. **
  9292. ** These macros define the various options to the
  9293. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9294. ** can use to customize and optimize their behavior.
  9295. **
  9296. ** <dl>
  9297. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9298. ** <dd>Calls of the form
  9299. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9300. ** where X is an integer. If X is zero, then the [virtual table] whose
  9301. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9302. ** support constraints. In this configuration (which is the default) if
  9303. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9304. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9305. ** specified as part of the users SQL statement, regardless of the actual
  9306. ** ON CONFLICT mode specified.
  9307. **
  9308. ** If X is non-zero, then the virtual table implementation guarantees
  9309. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9310. ** any modifications to internal or persistent data structures have been made.
  9311. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  9312. ** is able to roll back a statement or database transaction, and abandon
  9313. ** or continue processing the current SQL statement as appropriate.
  9314. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9315. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9316. ** had been ABORT.
  9317. **
  9318. ** Virtual table implementations that are required to handle OR REPLACE
  9319. ** must do so within the [xUpdate] method. If a call to the
  9320. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  9321. ** CONFLICT policy is REPLACE, the virtual table implementation should
  9322. ** silently replace the appropriate rows within the xUpdate callback and
  9323. ** return SQLITE_OK. Or, if this is not possible, it may return
  9324. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  9325. ** constraint handling.
  9326. ** </dl>
  9327. */
  9328. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9329. /*
  9330. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9331. **
  9332. ** This function may only be called from within a call to the [xUpdate] method
  9333. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9334. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9335. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9336. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9337. ** [virtual table].
  9338. */
  9339. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9340. /*
  9341. ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  9342. **
  9343. ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  9344. ** method of a [virtual table], then it returns true if and only if the
  9345. ** column is being fetched as part of an UPDATE operation during which the
  9346. ** column value will not change. Applications might use this to substitute
  9347. ** a return value that is less expensive to compute and that the corresponding
  9348. ** [xUpdate] method understands as a "no-change" value.
  9349. **
  9350. ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  9351. ** the column is not changed by the UPDATE statement, then the xColumn
  9352. ** method can optionally return without setting a result, without calling
  9353. ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  9354. ** In that case, [sqlite3_value_nochange(X)] will return true for the
  9355. ** same column in the [xUpdate] method.
  9356. */
  9357. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  9358. /*
  9359. ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
  9360. **
  9361. ** This function may only be called from within a call to the [xBestIndex]
  9362. ** method of a [virtual table].
  9363. **
  9364. ** The first argument must be the sqlite3_index_info object that is the
  9365. ** first parameter to the xBestIndex() method. The second argument must be
  9366. ** an index into the aConstraint[] array belonging to the sqlite3_index_info
  9367. ** structure passed to xBestIndex. This function returns a pointer to a buffer
  9368. ** containing the name of the collation sequence for the corresponding
  9369. ** constraint.
  9370. */
  9371. SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
  9372. /*
  9373. ** CAPI3REF: Conflict resolution modes
  9374. ** KEYWORDS: {conflict resolution mode}
  9375. **
  9376. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9377. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9378. ** is for the SQL statement being evaluated.
  9379. **
  9380. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9381. ** return value from the [sqlite3_set_authorizer()] callback and that
  9382. ** [SQLITE_ABORT] is also a [result code].
  9383. */
  9384. #define SQLITE_ROLLBACK 1
  9385. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9386. #define SQLITE_FAIL 3
  9387. /* #define SQLITE_ABORT 4 // Also an error code */
  9388. #define SQLITE_REPLACE 5
  9389. /*
  9390. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9391. ** KEYWORDS: {scanstatus options}
  9392. **
  9393. ** The following constants can be used for the T parameter to the
  9394. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  9395. ** different metric for sqlite3_stmt_scanstatus() to return.
  9396. **
  9397. ** When the value returned to V is a string, space to hold that string is
  9398. ** managed by the prepared statement S and will be automatically freed when
  9399. ** S is finalized.
  9400. **
  9401. ** <dl>
  9402. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9403. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9404. ** set to the total number of times that the X-th loop has run.</dd>
  9405. **
  9406. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9407. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9408. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9409. **
  9410. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9411. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9412. ** query planner's estimate for the average number of rows output from each
  9413. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  9414. ** then this value will approximate the quotient NVISIT/NLOOP and the
  9415. ** product of this value for all prior loops with the same SELECTID will
  9416. ** be the NLOOP value for the current loop.
  9417. **
  9418. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9419. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9420. ** to a zero-terminated UTF-8 string containing the name of the index or table
  9421. ** used for the X-th loop.
  9422. **
  9423. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9424. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9425. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9426. ** description for the X-th loop.
  9427. **
  9428. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9429. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9430. ** "select-id" for the X-th loop. The select-id identifies which query or
  9431. ** subquery the loop is part of. The main query has a select-id of zero.
  9432. ** The select-id is the same value as is output in the first column
  9433. ** of an [EXPLAIN QUERY PLAN] query.
  9434. ** </dl>
  9435. */
  9436. #define SQLITE_SCANSTAT_NLOOP 0
  9437. #define SQLITE_SCANSTAT_NVISIT 1
  9438. #define SQLITE_SCANSTAT_EST 2
  9439. #define SQLITE_SCANSTAT_NAME 3
  9440. #define SQLITE_SCANSTAT_EXPLAIN 4
  9441. #define SQLITE_SCANSTAT_SELECTID 5
  9442. /*
  9443. ** CAPI3REF: Prepared Statement Scan Status
  9444. ** METHOD: sqlite3_stmt
  9445. **
  9446. ** This interface returns information about the predicted and measured
  9447. ** performance for pStmt. Advanced applications can use this
  9448. ** interface to compare the predicted and the measured performance and
  9449. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9450. **
  9451. ** Since this interface is expected to be rarely used, it is only
  9452. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9453. ** compile-time option.
  9454. **
  9455. ** The "iScanStatusOp" parameter determines which status information to return.
  9456. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9457. ** of this interface is undefined.
  9458. ** ^The requested measurement is written into a variable pointed to by
  9459. ** the "pOut" parameter.
  9460. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9461. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9462. ** zero or greater than or equal to the total number of loops used to implement
  9463. ** the statement - a non-zero value is returned and the variable that pOut
  9464. ** points to is unchanged.
  9465. **
  9466. ** ^Statistics might not be available for all loops in all statements. ^In cases
  9467. ** where there exist loops with no available statistics, this function behaves
  9468. ** as if the loop did not exist - it returns non-zero and leave the variable
  9469. ** that pOut points to unchanged.
  9470. **
  9471. ** See also: [sqlite3_stmt_scanstatus_reset()]
  9472. */
  9473. SQLITE_API int sqlite3_stmt_scanstatus(
  9474. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  9475. int idx, /* Index of loop to report on */
  9476. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  9477. void *pOut /* Result written here */
  9478. );
  9479. /*
  9480. ** CAPI3REF: Zero Scan-Status Counters
  9481. ** METHOD: sqlite3_stmt
  9482. **
  9483. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9484. **
  9485. ** This API is only available if the library is built with pre-processor
  9486. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9487. */
  9488. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9489. /*
  9490. ** CAPI3REF: Flush caches to disk mid-transaction
  9491. **
  9492. ** ^If a write-transaction is open on [database connection] D when the
  9493. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9494. ** pages in the pager-cache that are not currently in use are written out
  9495. ** to disk. A dirty page may be in use if a database cursor created by an
  9496. ** active SQL statement is reading from it, or if it is page 1 of a database
  9497. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  9498. ** interface flushes caches for all schemas - "main", "temp", and
  9499. ** any [attached] databases.
  9500. **
  9501. ** ^If this function needs to obtain extra database locks before dirty pages
  9502. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  9503. ** immediately and there is a busy-handler callback configured, it is invoked
  9504. ** in the usual manner. ^If the required lock still cannot be obtained, then
  9505. ** the database is skipped and an attempt made to flush any dirty pages
  9506. ** belonging to the next (if any) database. ^If any databases are skipped
  9507. ** because locks cannot be obtained, but no other error occurs, this
  9508. ** function returns SQLITE_BUSY.
  9509. **
  9510. ** ^If any other error occurs while flushing dirty pages to disk (for
  9511. ** example an IO error or out-of-memory condition), then processing is
  9512. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9513. **
  9514. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9515. **
  9516. ** ^This function does not set the database handle error code or message
  9517. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9518. */
  9519. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9520. /*
  9521. ** CAPI3REF: The pre-update hook.
  9522. **
  9523. ** ^These interfaces are only available if SQLite is compiled using the
  9524. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9525. **
  9526. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9527. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  9528. ** on a database table.
  9529. ** ^At most one preupdate hook may be registered at a time on a single
  9530. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  9531. ** the previous setting.
  9532. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  9533. ** with a NULL pointer as the second parameter.
  9534. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  9535. ** the first parameter to callbacks.
  9536. **
  9537. ** ^The preupdate hook only fires for changes to real database tables; the
  9538. ** preupdate hook is not invoked for changes to [virtual tables] or to
  9539. ** system tables like sqlite_master or sqlite_stat1.
  9540. **
  9541. ** ^The second parameter to the preupdate callback is a pointer to
  9542. ** the [database connection] that registered the preupdate hook.
  9543. ** ^The third parameter to the preupdate callback is one of the constants
  9544. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  9545. ** kind of update operation that is about to occur.
  9546. ** ^(The fourth parameter to the preupdate callback is the name of the
  9547. ** database within the database connection that is being modified. This
  9548. ** will be "main" for the main database or "temp" for TEMP tables or
  9549. ** the name given after the AS keyword in the [ATTACH] statement for attached
  9550. ** databases.)^
  9551. ** ^The fifth parameter to the preupdate callback is the name of the
  9552. ** table that is being modified.
  9553. **
  9554. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  9555. ** parameter passed to the preupdate callback is the initial [rowid] of the
  9556. ** row being modified or deleted. For an INSERT operation on a rowid table,
  9557. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  9558. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  9559. ** seventh parameter is the final rowid value of the row being inserted
  9560. ** or updated. The value of the seventh parameter passed to the callback
  9561. ** function is not defined for operations on WITHOUT ROWID tables, or for
  9562. ** INSERT operations on rowid tables.
  9563. **
  9564. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  9565. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  9566. ** provide additional information about a preupdate event. These routines
  9567. ** may only be called from within a preupdate callback. Invoking any of
  9568. ** these routines from outside of a preupdate callback or with a
  9569. ** [database connection] pointer that is different from the one supplied
  9570. ** to the preupdate callback results in undefined and probably undesirable
  9571. ** behavior.
  9572. **
  9573. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  9574. ** in the row that is being inserted, updated, or deleted.
  9575. **
  9576. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  9577. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9578. ** the table row before it is updated. The N parameter must be between 0
  9579. ** and one less than the number of columns or the behavior will be
  9580. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  9581. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  9582. ** behavior is undefined. The [sqlite3_value] that P points to
  9583. ** will be destroyed when the preupdate callback returns.
  9584. **
  9585. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  9586. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9587. ** the table row after it is updated. The N parameter must be between 0
  9588. ** and one less than the number of columns or the behavior will be
  9589. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  9590. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  9591. ** behavior is undefined. The [sqlite3_value] that P points to
  9592. ** will be destroyed when the preupdate callback returns.
  9593. **
  9594. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  9595. ** callback was invoked as a result of a direct insert, update, or delete
  9596. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  9597. ** triggers; or 2 for changes resulting from triggers called by top-level
  9598. ** triggers; and so forth.
  9599. **
  9600. ** See also: [sqlite3_update_hook()]
  9601. */
  9602. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  9603. SQLITE_API void *sqlite3_preupdate_hook(
  9604. sqlite3 *db,
  9605. void(*xPreUpdate)(
  9606. void *pCtx, /* Copy of third arg to preupdate_hook() */
  9607. sqlite3 *db, /* Database handle */
  9608. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  9609. char const *zDb, /* Database name */
  9610. char const *zName, /* Table name */
  9611. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  9612. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  9613. ),
  9614. void*
  9615. );
  9616. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  9617. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  9618. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  9619. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  9620. #endif
  9621. /*
  9622. ** CAPI3REF: Low-level system error code
  9623. **
  9624. ** ^Attempt to return the underlying operating system error code or error
  9625. ** number that caused the most recent I/O error or failure to open a file.
  9626. ** The return value is OS-dependent. For example, on unix systems, after
  9627. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  9628. ** called to get back the underlying "errno" that caused the problem, such
  9629. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  9630. */
  9631. SQLITE_API int sqlite3_system_errno(sqlite3*);
  9632. /*
  9633. ** CAPI3REF: Database Snapshot
  9634. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  9635. ** EXPERIMENTAL
  9636. **
  9637. ** An instance of the snapshot object records the state of a [WAL mode]
  9638. ** database for some specific point in history.
  9639. **
  9640. ** In [WAL mode], multiple [database connections] that are open on the
  9641. ** same database file can each be reading a different historical version
  9642. ** of the database file. When a [database connection] begins a read
  9643. ** transaction, that connection sees an unchanging copy of the database
  9644. ** as it existed for the point in time when the transaction first started.
  9645. ** Subsequent changes to the database from other connections are not seen
  9646. ** by the reader until a new read transaction is started.
  9647. **
  9648. ** The sqlite3_snapshot object records state information about an historical
  9649. ** version of the database file so that it is possible to later open a new read
  9650. ** transaction that sees that historical version of the database rather than
  9651. ** the most recent version.
  9652. **
  9653. ** The constructor for this object is [sqlite3_snapshot_get()]. The
  9654. ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  9655. ** to an historical snapshot (if possible). The destructor for
  9656. ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  9657. */
  9658. typedef struct sqlite3_snapshot {
  9659. unsigned char hidden[48];
  9660. } sqlite3_snapshot;
  9661. /*
  9662. ** CAPI3REF: Record A Database Snapshot
  9663. ** EXPERIMENTAL
  9664. **
  9665. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  9666. ** new [sqlite3_snapshot] object that records the current state of
  9667. ** schema S in database connection D. ^On success, the
  9668. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  9669. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  9670. ** If there is not already a read-transaction open on schema S when
  9671. ** this function is called, one is opened automatically.
  9672. **
  9673. ** The following must be true for this function to succeed. If any of
  9674. ** the following statements are false when sqlite3_snapshot_get() is
  9675. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  9676. ** in this case.
  9677. **
  9678. ** <ul>
  9679. ** <li> The database handle must be in [autocommit mode].
  9680. **
  9681. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  9682. **
  9683. ** <li> There must not be a write transaction open on schema S of database
  9684. ** connection D.
  9685. **
  9686. ** <li> One or more transactions must have been written to the current wal
  9687. ** file since it was created on disk (by any connection). This means
  9688. ** that a snapshot cannot be taken on a wal mode database with no wal
  9689. ** file immediately after it is first opened. At least one transaction
  9690. ** must be written to it first.
  9691. ** </ul>
  9692. **
  9693. ** This function may also return SQLITE_NOMEM. If it is called with the
  9694. ** database handle in autocommit mode but fails for some other reason,
  9695. ** whether or not a read transaction is opened on schema S is undefined.
  9696. **
  9697. ** The [sqlite3_snapshot] object returned from a successful call to
  9698. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  9699. ** to avoid a memory leak.
  9700. **
  9701. ** The [sqlite3_snapshot_get()] interface is only available when the
  9702. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9703. */
  9704. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  9705. sqlite3 *db,
  9706. const char *zSchema,
  9707. sqlite3_snapshot **ppSnapshot
  9708. );
  9709. /*
  9710. ** CAPI3REF: Start a read transaction on an historical snapshot
  9711. ** EXPERIMENTAL
  9712. **
  9713. ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
  9714. ** read transaction for schema S of
  9715. ** [database connection] D such that the read transaction
  9716. ** refers to historical [snapshot] P, rather than the most
  9717. ** recent change to the database.
  9718. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  9719. ** or an appropriate [error code] if it fails.
  9720. **
  9721. ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  9722. ** the first operation following the [BEGIN] that takes the schema S
  9723. ** out of [autocommit mode].
  9724. ** ^In other words, schema S must not currently be in
  9725. ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
  9726. ** database connection D must be out of [autocommit mode].
  9727. ** ^A [snapshot] will fail to open if it has been overwritten by a
  9728. ** [checkpoint].
  9729. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  9730. ** database connection D does not know that the database file for
  9731. ** schema S is in [WAL mode]. A database connection might not know
  9732. ** that the database file is in [WAL mode] if there has been no prior
  9733. ** I/O on that database connection, or if the database entered [WAL mode]
  9734. ** after the most recent I/O on the database connection.)^
  9735. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  9736. ** database connection in order to make it ready to use snapshots.)
  9737. **
  9738. ** The [sqlite3_snapshot_open()] interface is only available when the
  9739. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9740. */
  9741. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  9742. sqlite3 *db,
  9743. const char *zSchema,
  9744. sqlite3_snapshot *pSnapshot
  9745. );
  9746. /*
  9747. ** CAPI3REF: Destroy a snapshot
  9748. ** EXPERIMENTAL
  9749. **
  9750. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  9751. ** The application must eventually free every [sqlite3_snapshot] object
  9752. ** using this routine to avoid a memory leak.
  9753. **
  9754. ** The [sqlite3_snapshot_free()] interface is only available when the
  9755. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9756. */
  9757. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  9758. /*
  9759. ** CAPI3REF: Compare the ages of two snapshot handles.
  9760. ** EXPERIMENTAL
  9761. **
  9762. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  9763. ** of two valid snapshot handles.
  9764. **
  9765. ** If the two snapshot handles are not associated with the same database
  9766. ** file, the result of the comparison is undefined.
  9767. **
  9768. ** Additionally, the result of the comparison is only valid if both of the
  9769. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  9770. ** last time the wal file was deleted. The wal file is deleted when the
  9771. ** database is changed back to rollback mode or when the number of database
  9772. ** clients drops to zero. If either snapshot handle was obtained before the
  9773. ** wal file was last deleted, the value returned by this function
  9774. ** is undefined.
  9775. **
  9776. ** Otherwise, this API returns a negative value if P1 refers to an older
  9777. ** snapshot than P2, zero if the two handles refer to the same database
  9778. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  9779. */
  9780. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  9781. sqlite3_snapshot *p1,
  9782. sqlite3_snapshot *p2
  9783. );
  9784. /*
  9785. ** CAPI3REF: Recover snapshots from a wal file
  9786. ** EXPERIMENTAL
  9787. **
  9788. ** If all connections disconnect from a database file but do not perform
  9789. ** a checkpoint, the existing wal file is opened along with the database
  9790. ** file the next time the database is opened. At this point it is only
  9791. ** possible to successfully call sqlite3_snapshot_open() to open the most
  9792. ** recent snapshot of the database (the one at the head of the wal file),
  9793. ** even though the wal file may contain other valid snapshots for which
  9794. ** clients have sqlite3_snapshot handles.
  9795. **
  9796. ** This function attempts to scan the wal file associated with database zDb
  9797. ** of database handle db and make all valid snapshots available to
  9798. ** sqlite3_snapshot_open(). It is an error if there is already a read
  9799. ** transaction open on the database, or if the database is not a wal mode
  9800. ** database.
  9801. **
  9802. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  9803. */
  9804. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  9805. /*
  9806. ** CAPI3REF: Serialize a database
  9807. **
  9808. ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
  9809. ** that is a serialization of the S database on [database connection] D.
  9810. ** If P is not a NULL pointer, then the size of the database in bytes
  9811. ** is written into *P.
  9812. **
  9813. ** For an ordinary on-disk database file, the serialization is just a
  9814. ** copy of the disk file. For an in-memory database or a "TEMP" database,
  9815. ** the serialization is the same sequence of bytes which would be written
  9816. ** to disk if that database where backed up to disk.
  9817. **
  9818. ** The usual case is that sqlite3_serialize() copies the serialization of
  9819. ** the database into memory obtained from [sqlite3_malloc64()] and returns
  9820. ** a pointer to that memory. The caller is responsible for freeing the
  9821. ** returned value to avoid a memory leak. However, if the F argument
  9822. ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
  9823. ** are made, and the sqlite3_serialize() function will return a pointer
  9824. ** to the contiguous memory representation of the database that SQLite
  9825. ** is currently using for that database, or NULL if the no such contiguous
  9826. ** memory representation of the database exists. A contiguous memory
  9827. ** representation of the database will usually only exist if there has
  9828. ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
  9829. ** values of D and S.
  9830. ** The size of the database is written into *P even if the
  9831. ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
  9832. ** of the database exists.
  9833. **
  9834. ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
  9835. ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
  9836. ** allocation error occurs.
  9837. **
  9838. ** This interface is only available if SQLite is compiled with the
  9839. ** [SQLITE_ENABLE_DESERIALIZE] option.
  9840. */
  9841. SQLITE_API unsigned char *sqlite3_serialize(
  9842. sqlite3 *db, /* The database connection */
  9843. const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
  9844. sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
  9845. unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
  9846. );
  9847. /*
  9848. ** CAPI3REF: Flags for sqlite3_serialize
  9849. **
  9850. ** Zero or more of the following constants can be OR-ed together for
  9851. ** the F argument to [sqlite3_serialize(D,S,P,F)].
  9852. **
  9853. ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
  9854. ** a pointer to contiguous in-memory database that it is currently using,
  9855. ** without making a copy of the database. If SQLite is not currently using
  9856. ** a contiguous in-memory database, then this option causes
  9857. ** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
  9858. ** using a contiguous in-memory database if it has been initialized by a
  9859. ** prior call to [sqlite3_deserialize()].
  9860. */
  9861. #define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
  9862. /*
  9863. ** CAPI3REF: Deserialize a database
  9864. **
  9865. ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
  9866. ** [database connection] D to disconnect from database S and then
  9867. ** reopen S as an in-memory database based on the serialization contained
  9868. ** in P. The serialized database P is N bytes in size. M is the size of
  9869. ** the buffer P, which might be larger than N. If M is larger than N, and
  9870. ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
  9871. ** permitted to add content to the in-memory database as long as the total
  9872. ** size does not exceed M bytes.
  9873. **
  9874. ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
  9875. ** invoke sqlite3_free() on the serialization buffer when the database
  9876. ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
  9877. ** SQLite will try to increase the buffer size using sqlite3_realloc64()
  9878. ** if writes on the database cause it to grow larger than M bytes.
  9879. **
  9880. ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
  9881. ** database is currently in a read transaction or is involved in a backup
  9882. ** operation.
  9883. **
  9884. ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
  9885. ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
  9886. ** [sqlite3_free()] is invoked on argument P prior to returning.
  9887. **
  9888. ** This interface is only available if SQLite is compiled with the
  9889. ** [SQLITE_ENABLE_DESERIALIZE] option.
  9890. */
  9891. SQLITE_API int sqlite3_deserialize(
  9892. sqlite3 *db, /* The database connection */
  9893. const char *zSchema, /* Which DB to reopen with the deserialization */
  9894. unsigned char *pData, /* The serialized database content */
  9895. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  9896. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  9897. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  9898. );
  9899. /*
  9900. ** CAPI3REF: Flags for sqlite3_deserialize()
  9901. **
  9902. ** The following are allowed values for 6th argument (the F argument) to
  9903. ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
  9904. **
  9905. ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
  9906. ** in the P argument is held in memory obtained from [sqlite3_malloc64()]
  9907. ** and that SQLite should take ownership of this memory and automatically
  9908. ** free it when it has finished using it. Without this flag, the caller
  9909. ** is resposible for freeing any dynamically allocated memory.
  9910. **
  9911. ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
  9912. ** grow the size of the database using calls to [sqlite3_realloc64()]. This
  9913. ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
  9914. ** Without this flag, the deserialized database cannot increase in size beyond
  9915. ** the number of bytes specified by the M parameter.
  9916. **
  9917. ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
  9918. ** should be treated as read-only.
  9919. */
  9920. #define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
  9921. #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
  9922. #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
  9923. /*
  9924. ** Undo the hack that converts floating point types to integer for
  9925. ** builds on processors without floating point support.
  9926. */
  9927. #ifdef SQLITE_OMIT_FLOATING_POINT
  9928. # undef double
  9929. #endif
  9930. #if 0
  9931. } /* End of the 'extern "C"' block */
  9932. #endif
  9933. #endif /* SQLITE3_H */
  9934. /******** Begin file sqlite3rtree.h *********/
  9935. /*
  9936. ** 2010 August 30
  9937. **
  9938. ** The author disclaims copyright to this source code. In place of
  9939. ** a legal notice, here is a blessing:
  9940. **
  9941. ** May you do good and not evil.
  9942. ** May you find forgiveness for yourself and forgive others.
  9943. ** May you share freely, never taking more than you give.
  9944. **
  9945. *************************************************************************
  9946. */
  9947. #ifndef _SQLITE3RTREE_H_
  9948. #define _SQLITE3RTREE_H_
  9949. #if 0
  9950. extern "C" {
  9951. #endif
  9952. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  9953. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  9954. /* The double-precision datatype used by RTree depends on the
  9955. ** SQLITE_RTREE_INT_ONLY compile-time option.
  9956. */
  9957. #ifdef SQLITE_RTREE_INT_ONLY
  9958. typedef sqlite3_int64 sqlite3_rtree_dbl;
  9959. #else
  9960. typedef double sqlite3_rtree_dbl;
  9961. #endif
  9962. /*
  9963. ** Register a geometry callback named zGeom that can be used as part of an
  9964. ** R-Tree geometry query as follows:
  9965. **
  9966. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  9967. */
  9968. SQLITE_API int sqlite3_rtree_geometry_callback(
  9969. sqlite3 *db,
  9970. const char *zGeom,
  9971. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  9972. void *pContext
  9973. );
  9974. /*
  9975. ** A pointer to a structure of the following type is passed as the first
  9976. ** argument to callbacks registered using rtree_geometry_callback().
  9977. */
  9978. struct sqlite3_rtree_geometry {
  9979. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  9980. int nParam; /* Size of array aParam[] */
  9981. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  9982. void *pUser; /* Callback implementation user data */
  9983. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  9984. };
  9985. /*
  9986. ** Register a 2nd-generation geometry callback named zScore that can be
  9987. ** used as part of an R-Tree geometry query as follows:
  9988. **
  9989. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  9990. */
  9991. SQLITE_API int sqlite3_rtree_query_callback(
  9992. sqlite3 *db,
  9993. const char *zQueryFunc,
  9994. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  9995. void *pContext,
  9996. void (*xDestructor)(void*)
  9997. );
  9998. /*
  9999. ** A pointer to a structure of the following type is passed as the
  10000. ** argument to scored geometry callback registered using
  10001. ** sqlite3_rtree_query_callback().
  10002. **
  10003. ** Note that the first 5 fields of this structure are identical to
  10004. ** sqlite3_rtree_geometry. This structure is a subclass of
  10005. ** sqlite3_rtree_geometry.
  10006. */
  10007. struct sqlite3_rtree_query_info {
  10008. void *pContext; /* pContext from when function registered */
  10009. int nParam; /* Number of function parameters */
  10010. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  10011. void *pUser; /* callback can use this, if desired */
  10012. void (*xDelUser)(void*); /* function to free pUser */
  10013. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  10014. unsigned int *anQueue; /* Number of pending entries in the queue */
  10015. int nCoord; /* Number of coordinates */
  10016. int iLevel; /* Level of current node or entry */
  10017. int mxLevel; /* The largest iLevel value in the tree */
  10018. sqlite3_int64 iRowid; /* Rowid for current entry */
  10019. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  10020. int eParentWithin; /* Visibility of parent node */
  10021. int eWithin; /* OUT: Visiblity */
  10022. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  10023. /* The following fields are only available in 3.8.11 and later */
  10024. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  10025. };
  10026. /*
  10027. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  10028. */
  10029. #define NOT_WITHIN 0 /* Object completely outside of query region */
  10030. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  10031. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  10032. #if 0
  10033. } /* end of the 'extern "C"' block */
  10034. #endif
  10035. #endif /* ifndef _SQLITE3RTREE_H_ */
  10036. /******** End of sqlite3rtree.h *********/
  10037. /******** Begin file sqlite3session.h *********/
  10038. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  10039. #define __SQLITESESSION_H_ 1
  10040. /*
  10041. ** Make sure we can call this stuff from C++.
  10042. */
  10043. #if 0
  10044. extern "C" {
  10045. #endif
  10046. /*
  10047. ** CAPI3REF: Session Object Handle
  10048. **
  10049. ** An instance of this object is a [session] that can be used to
  10050. ** record changes to a database.
  10051. */
  10052. typedef struct sqlite3_session sqlite3_session;
  10053. /*
  10054. ** CAPI3REF: Changeset Iterator Handle
  10055. **
  10056. ** An instance of this object acts as a cursor for iterating
  10057. ** over the elements of a [changeset] or [patchset].
  10058. */
  10059. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  10060. /*
  10061. ** CAPI3REF: Create A New Session Object
  10062. ** CONSTRUCTOR: sqlite3_session
  10063. **
  10064. ** Create a new session object attached to database handle db. If successful,
  10065. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  10066. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  10067. ** error code (e.g. SQLITE_NOMEM) is returned.
  10068. **
  10069. ** It is possible to create multiple session objects attached to a single
  10070. ** database handle.
  10071. **
  10072. ** Session objects created using this function should be deleted using the
  10073. ** [sqlite3session_delete()] function before the database handle that they
  10074. ** are attached to is itself closed. If the database handle is closed before
  10075. ** the session object is deleted, then the results of calling any session
  10076. ** module function, including [sqlite3session_delete()] on the session object
  10077. ** are undefined.
  10078. **
  10079. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  10080. ** is not possible for an application to register a pre-update hook on a
  10081. ** database handle that has one or more session objects attached. Nor is
  10082. ** it possible to create a session object attached to a database handle for
  10083. ** which a pre-update hook is already defined. The results of attempting
  10084. ** either of these things are undefined.
  10085. **
  10086. ** The session object will be used to create changesets for tables in
  10087. ** database zDb, where zDb is either "main", or "temp", or the name of an
  10088. ** attached database. It is not an error if database zDb is not attached
  10089. ** to the database when the session object is created.
  10090. */
  10091. SQLITE_API int sqlite3session_create(
  10092. sqlite3 *db, /* Database handle */
  10093. const char *zDb, /* Name of db (e.g. "main") */
  10094. sqlite3_session **ppSession /* OUT: New session object */
  10095. );
  10096. /*
  10097. ** CAPI3REF: Delete A Session Object
  10098. ** DESTRUCTOR: sqlite3_session
  10099. **
  10100. ** Delete a session object previously allocated using
  10101. ** [sqlite3session_create()]. Once a session object has been deleted, the
  10102. ** results of attempting to use pSession with any other session module
  10103. ** function are undefined.
  10104. **
  10105. ** Session objects must be deleted before the database handle to which they
  10106. ** are attached is closed. Refer to the documentation for
  10107. ** [sqlite3session_create()] for details.
  10108. */
  10109. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  10110. /*
  10111. ** CAPI3REF: Enable Or Disable A Session Object
  10112. ** METHOD: sqlite3_session
  10113. **
  10114. ** Enable or disable the recording of changes by a session object. When
  10115. ** enabled, a session object records changes made to the database. When
  10116. ** disabled - it does not. A newly created session object is enabled.
  10117. ** Refer to the documentation for [sqlite3session_changeset()] for further
  10118. ** details regarding how enabling and disabling a session object affects
  10119. ** the eventual changesets.
  10120. **
  10121. ** Passing zero to this function disables the session. Passing a value
  10122. ** greater than zero enables it. Passing a value less than zero is a
  10123. ** no-op, and may be used to query the current state of the session.
  10124. **
  10125. ** The return value indicates the final state of the session object: 0 if
  10126. ** the session is disabled, or 1 if it is enabled.
  10127. */
  10128. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  10129. /*
  10130. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  10131. ** METHOD: sqlite3_session
  10132. **
  10133. ** Each change recorded by a session object is marked as either direct or
  10134. ** indirect. A change is marked as indirect if either:
  10135. **
  10136. ** <ul>
  10137. ** <li> The session object "indirect" flag is set when the change is
  10138. ** made, or
  10139. ** <li> The change is made by an SQL trigger or foreign key action
  10140. ** instead of directly as a result of a users SQL statement.
  10141. ** </ul>
  10142. **
  10143. ** If a single row is affected by more than one operation within a session,
  10144. ** then the change is considered indirect if all operations meet the criteria
  10145. ** for an indirect change above, or direct otherwise.
  10146. **
  10147. ** This function is used to set, clear or query the session object indirect
  10148. ** flag. If the second argument passed to this function is zero, then the
  10149. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  10150. ** is set. Passing a value less than zero does not modify the current value
  10151. ** of the indirect flag, and may be used to query the current state of the
  10152. ** indirect flag for the specified session object.
  10153. **
  10154. ** The return value indicates the final state of the indirect flag: 0 if
  10155. ** it is clear, or 1 if it is set.
  10156. */
  10157. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  10158. /*
  10159. ** CAPI3REF: Attach A Table To A Session Object
  10160. ** METHOD: sqlite3_session
  10161. **
  10162. ** If argument zTab is not NULL, then it is the name of a table to attach
  10163. ** to the session object passed as the first argument. All subsequent changes
  10164. ** made to the table while the session object is enabled will be recorded. See
  10165. ** documentation for [sqlite3session_changeset()] for further details.
  10166. **
  10167. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  10168. ** in the database. If additional tables are added to the database (by
  10169. ** executing "CREATE TABLE" statements) after this call is made, changes for
  10170. ** the new tables are also recorded.
  10171. **
  10172. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  10173. ** defined as part of their CREATE TABLE statement. It does not matter if the
  10174. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  10175. ** KEY may consist of a single column, or may be a composite key.
  10176. **
  10177. ** It is not an error if the named table does not exist in the database. Nor
  10178. ** is it an error if the named table does not have a PRIMARY KEY. However,
  10179. ** no changes will be recorded in either of these scenarios.
  10180. **
  10181. ** Changes are not recorded for individual rows that have NULL values stored
  10182. ** in one or more of their PRIMARY KEY columns.
  10183. **
  10184. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  10185. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  10186. **
  10187. ** <h3>Special sqlite_stat1 Handling</h3>
  10188. **
  10189. ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
  10190. ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
  10191. ** <pre>
  10192. ** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
  10193. ** </pre>
  10194. **
  10195. ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
  10196. ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
  10197. ** are recorded for rows for which (idx IS NULL) is true. However, for such
  10198. ** rows a zero-length blob (SQL value X'') is stored in the changeset or
  10199. ** patchset instead of a NULL value. This allows such changesets to be
  10200. ** manipulated by legacy implementations of sqlite3changeset_invert(),
  10201. ** concat() and similar.
  10202. **
  10203. ** The sqlite3changeset_apply() function automatically converts the
  10204. ** zero-length blob back to a NULL value when updating the sqlite_stat1
  10205. ** table. However, if the application calls sqlite3changeset_new(),
  10206. ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
  10207. ** iterator directly (including on a changeset iterator passed to a
  10208. ** conflict-handler callback) then the X'' value is returned. The application
  10209. ** must translate X'' to NULL itself if required.
  10210. **
  10211. ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
  10212. ** changes made to the sqlite_stat1 table. Legacy versions of the
  10213. ** sqlite3changeset_apply() function silently ignore any modifications to the
  10214. ** sqlite_stat1 table that are part of a changeset or patchset.
  10215. */
  10216. SQLITE_API int sqlite3session_attach(
  10217. sqlite3_session *pSession, /* Session object */
  10218. const char *zTab /* Table name */
  10219. );
  10220. /*
  10221. ** CAPI3REF: Set a table filter on a Session Object.
  10222. ** METHOD: sqlite3_session
  10223. **
  10224. ** The second argument (xFilter) is the "filter callback". For changes to rows
  10225. ** in tables that are not attached to the Session object, the filter is called
  10226. ** to determine whether changes to the table's rows should be tracked or not.
  10227. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  10228. ** attached, xFilter will not be called again.
  10229. */
  10230. SQLITE_API void sqlite3session_table_filter(
  10231. sqlite3_session *pSession, /* Session object */
  10232. int(*xFilter)(
  10233. void *pCtx, /* Copy of third arg to _filter_table() */
  10234. const char *zTab /* Table name */
  10235. ),
  10236. void *pCtx /* First argument passed to xFilter */
  10237. );
  10238. /*
  10239. ** CAPI3REF: Generate A Changeset From A Session Object
  10240. ** METHOD: sqlite3_session
  10241. **
  10242. ** Obtain a changeset containing changes to the tables attached to the
  10243. ** session object passed as the first argument. If successful,
  10244. ** set *ppChangeset to point to a buffer containing the changeset
  10245. ** and *pnChangeset to the size of the changeset in bytes before returning
  10246. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  10247. ** zero and return an SQLite error code.
  10248. **
  10249. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  10250. ** each representing a change to a single row of an attached table. An INSERT
  10251. ** change contains the values of each field of a new database row. A DELETE
  10252. ** contains the original values of each field of a deleted database row. An
  10253. ** UPDATE change contains the original values of each field of an updated
  10254. ** database row along with the updated values for each updated non-primary-key
  10255. ** column. It is not possible for an UPDATE change to represent a change that
  10256. ** modifies the values of primary key columns. If such a change is made, it
  10257. ** is represented in a changeset as a DELETE followed by an INSERT.
  10258. **
  10259. ** Changes are not recorded for rows that have NULL values stored in one or
  10260. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  10261. ** no corresponding change is present in the changesets returned by this
  10262. ** function. If an existing row with one or more NULL values stored in
  10263. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  10264. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  10265. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  10266. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  10267. ** DELETE change only.
  10268. **
  10269. ** The contents of a changeset may be traversed using an iterator created
  10270. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  10271. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  10272. ** API.
  10273. **
  10274. ** Within a changeset generated by this function, all changes related to a
  10275. ** single table are grouped together. In other words, when iterating through
  10276. ** a changeset or when applying a changeset to a database, all changes related
  10277. ** to a single table are processed before moving on to the next table. Tables
  10278. ** are sorted in the same order in which they were attached (or auto-attached)
  10279. ** to the sqlite3_session object. The order in which the changes related to
  10280. ** a single table are stored is undefined.
  10281. **
  10282. ** Following a successful call to this function, it is the responsibility of
  10283. ** the caller to eventually free the buffer that *ppChangeset points to using
  10284. ** [sqlite3_free()].
  10285. **
  10286. ** <h3>Changeset Generation</h3>
  10287. **
  10288. ** Once a table has been attached to a session object, the session object
  10289. ** records the primary key values of all new rows inserted into the table.
  10290. ** It also records the original primary key and other column values of any
  10291. ** deleted or updated rows. For each unique primary key value, data is only
  10292. ** recorded once - the first time a row with said primary key is inserted,
  10293. ** updated or deleted in the lifetime of the session.
  10294. **
  10295. ** There is one exception to the previous paragraph: when a row is inserted,
  10296. ** updated or deleted, if one or more of its primary key columns contain a
  10297. ** NULL value, no record of the change is made.
  10298. **
  10299. ** The session object therefore accumulates two types of records - those
  10300. ** that consist of primary key values only (created when the user inserts
  10301. ** a new record) and those that consist of the primary key values and the
  10302. ** original values of other table columns (created when the users deletes
  10303. ** or updates a record).
  10304. **
  10305. ** When this function is called, the requested changeset is created using
  10306. ** both the accumulated records and the current contents of the database
  10307. ** file. Specifically:
  10308. **
  10309. ** <ul>
  10310. ** <li> For each record generated by an insert, the database is queried
  10311. ** for a row with a matching primary key. If one is found, an INSERT
  10312. ** change is added to the changeset. If no such row is found, no change
  10313. ** is added to the changeset.
  10314. **
  10315. ** <li> For each record generated by an update or delete, the database is
  10316. ** queried for a row with a matching primary key. If such a row is
  10317. ** found and one or more of the non-primary key fields have been
  10318. ** modified from their original values, an UPDATE change is added to
  10319. ** the changeset. Or, if no such row is found in the table, a DELETE
  10320. ** change is added to the changeset. If there is a row with a matching
  10321. ** primary key in the database, but all fields contain their original
  10322. ** values, no change is added to the changeset.
  10323. ** </ul>
  10324. **
  10325. ** This means, amongst other things, that if a row is inserted and then later
  10326. ** deleted while a session object is active, neither the insert nor the delete
  10327. ** will be present in the changeset. Or if a row is deleted and then later a
  10328. ** row with the same primary key values inserted while a session object is
  10329. ** active, the resulting changeset will contain an UPDATE change instead of
  10330. ** a DELETE and an INSERT.
  10331. **
  10332. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  10333. ** it does not accumulate records when rows are inserted, updated or deleted.
  10334. ** This may appear to have some counter-intuitive effects if a single row
  10335. ** is written to more than once during a session. For example, if a row
  10336. ** is inserted while a session object is enabled, then later deleted while
  10337. ** the same session object is disabled, no INSERT record will appear in the
  10338. ** changeset, even though the delete took place while the session was disabled.
  10339. ** Or, if one field of a row is updated while a session is disabled, and
  10340. ** another field of the same row is updated while the session is enabled, the
  10341. ** resulting changeset will contain an UPDATE change that updates both fields.
  10342. */
  10343. SQLITE_API int sqlite3session_changeset(
  10344. sqlite3_session *pSession, /* Session object */
  10345. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  10346. void **ppChangeset /* OUT: Buffer containing changeset */
  10347. );
  10348. /*
  10349. ** CAPI3REF: Load The Difference Between Tables Into A Session
  10350. ** METHOD: sqlite3_session
  10351. **
  10352. ** If it is not already attached to the session object passed as the first
  10353. ** argument, this function attaches table zTbl in the same manner as the
  10354. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  10355. ** does not have a primary key, this function is a no-op (but does not return
  10356. ** an error).
  10357. **
  10358. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  10359. ** attached to the same database handle as the session object that contains
  10360. ** a table compatible with the table attached to the session by this function.
  10361. ** A table is considered compatible if it:
  10362. **
  10363. ** <ul>
  10364. ** <li> Has the same name,
  10365. ** <li> Has the same set of columns declared in the same order, and
  10366. ** <li> Has the same PRIMARY KEY definition.
  10367. ** </ul>
  10368. **
  10369. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  10370. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  10371. ** but no changes are added to the session object. As with other session
  10372. ** APIs, tables without PRIMARY KEYs are simply ignored.
  10373. **
  10374. ** This function adds a set of changes to the session object that could be
  10375. ** used to update the table in database zFrom (call this the "from-table")
  10376. ** so that its content is the same as the table attached to the session
  10377. ** object (call this the "to-table"). Specifically:
  10378. **
  10379. ** <ul>
  10380. ** <li> For each row (primary key) that exists in the to-table but not in
  10381. ** the from-table, an INSERT record is added to the session object.
  10382. **
  10383. ** <li> For each row (primary key) that exists in the to-table but not in
  10384. ** the from-table, a DELETE record is added to the session object.
  10385. **
  10386. ** <li> For each row (primary key) that exists in both tables, but features
  10387. ** different non-PK values in each, an UPDATE record is added to the
  10388. ** session.
  10389. ** </ul>
  10390. **
  10391. ** To clarify, if this function is called and then a changeset constructed
  10392. ** using [sqlite3session_changeset()], then after applying that changeset to
  10393. ** database zFrom the contents of the two compatible tables would be
  10394. ** identical.
  10395. **
  10396. ** It an error if database zFrom does not exist or does not contain the
  10397. ** required compatible table.
  10398. **
  10399. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  10400. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  10401. ** may be set to point to a buffer containing an English language error
  10402. ** message. It is the responsibility of the caller to free this buffer using
  10403. ** sqlite3_free().
  10404. */
  10405. SQLITE_API int sqlite3session_diff(
  10406. sqlite3_session *pSession,
  10407. const char *zFromDb,
  10408. const char *zTbl,
  10409. char **pzErrMsg
  10410. );
  10411. /*
  10412. ** CAPI3REF: Generate A Patchset From A Session Object
  10413. ** METHOD: sqlite3_session
  10414. **
  10415. ** The differences between a patchset and a changeset are that:
  10416. **
  10417. ** <ul>
  10418. ** <li> DELETE records consist of the primary key fields only. The
  10419. ** original values of other fields are omitted.
  10420. ** <li> The original values of any modified fields are omitted from
  10421. ** UPDATE records.
  10422. ** </ul>
  10423. **
  10424. ** A patchset blob may be used with up to date versions of all
  10425. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  10426. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  10427. ** attempting to use a patchset blob with old versions of the
  10428. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  10429. **
  10430. ** Because the non-primary key "old.*" fields are omitted, no
  10431. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  10432. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  10433. ** in the same way as for changesets.
  10434. **
  10435. ** Changes within a patchset are ordered in the same way as for changesets
  10436. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  10437. ** a single table are grouped together, tables appear in the order in which
  10438. ** they were attached to the session object).
  10439. */
  10440. SQLITE_API int sqlite3session_patchset(
  10441. sqlite3_session *pSession, /* Session object */
  10442. int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
  10443. void **ppPatchset /* OUT: Buffer containing patchset */
  10444. );
  10445. /*
  10446. ** CAPI3REF: Test if a changeset has recorded any changes.
  10447. **
  10448. ** Return non-zero if no changes to attached tables have been recorded by
  10449. ** the session object passed as the first argument. Otherwise, if one or
  10450. ** more changes have been recorded, return zero.
  10451. **
  10452. ** Even if this function returns zero, it is possible that calling
  10453. ** [sqlite3session_changeset()] on the session handle may still return a
  10454. ** changeset that contains no changes. This can happen when a row in
  10455. ** an attached table is modified and then later on the original values
  10456. ** are restored. However, if this function returns non-zero, then it is
  10457. ** guaranteed that a call to sqlite3session_changeset() will return a
  10458. ** changeset containing zero changes.
  10459. */
  10460. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  10461. /*
  10462. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  10463. ** CONSTRUCTOR: sqlite3_changeset_iter
  10464. **
  10465. ** Create an iterator used to iterate through the contents of a changeset.
  10466. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  10467. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  10468. ** SQLite error code is returned.
  10469. **
  10470. ** The following functions can be used to advance and query a changeset
  10471. ** iterator created by this function:
  10472. **
  10473. ** <ul>
  10474. ** <li> [sqlite3changeset_next()]
  10475. ** <li> [sqlite3changeset_op()]
  10476. ** <li> [sqlite3changeset_new()]
  10477. ** <li> [sqlite3changeset_old()]
  10478. ** </ul>
  10479. **
  10480. ** It is the responsibility of the caller to eventually destroy the iterator
  10481. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  10482. ** changeset (pChangeset) must remain valid until after the iterator is
  10483. ** destroyed.
  10484. **
  10485. ** Assuming the changeset blob was created by one of the
  10486. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  10487. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  10488. ** that apply to a single table are grouped together. This means that when
  10489. ** an application iterates through a changeset using an iterator created by
  10490. ** this function, all changes that relate to a single table are visited
  10491. ** consecutively. There is no chance that the iterator will visit a change
  10492. ** the applies to table X, then one for table Y, and then later on visit
  10493. ** another change for table X.
  10494. */
  10495. SQLITE_API int sqlite3changeset_start(
  10496. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10497. int nChangeset, /* Size of changeset blob in bytes */
  10498. void *pChangeset /* Pointer to blob containing changeset */
  10499. );
  10500. /*
  10501. ** CAPI3REF: Advance A Changeset Iterator
  10502. ** METHOD: sqlite3_changeset_iter
  10503. **
  10504. ** This function may only be used with iterators created by function
  10505. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  10506. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  10507. ** is returned and the call has no effect.
  10508. **
  10509. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  10510. ** does not point to any change in the changeset. Assuming the changeset
  10511. ** is not empty, the first call to this function advances the iterator to
  10512. ** point to the first change in the changeset. Each subsequent call advances
  10513. ** the iterator to point to the next change in the changeset (if any). If
  10514. ** no error occurs and the iterator points to a valid change after a call
  10515. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  10516. ** Otherwise, if all changes in the changeset have already been visited,
  10517. ** SQLITE_DONE is returned.
  10518. **
  10519. ** If an error occurs, an SQLite error code is returned. Possible error
  10520. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  10521. ** SQLITE_NOMEM.
  10522. */
  10523. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  10524. /*
  10525. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  10526. ** METHOD: sqlite3_changeset_iter
  10527. **
  10528. ** The pIter argument passed to this function may either be an iterator
  10529. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10530. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10531. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  10532. ** is not the case, this function returns [SQLITE_MISUSE].
  10533. **
  10534. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  10535. ** nul-terminated utf-8 encoded string containing the name of the table
  10536. ** affected by the current change. The buffer remains valid until either
  10537. ** sqlite3changeset_next() is called on the iterator or until the
  10538. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  10539. ** set to the number of columns in the table affected by the change. If
  10540. ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
  10541. ** is an indirect change, or false (0) otherwise. See the documentation for
  10542. ** [sqlite3session_indirect()] for a description of direct and indirect
  10543. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  10544. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  10545. ** type of change that the iterator currently points to.
  10546. **
  10547. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  10548. ** SQLite error code is returned. The values of the output variables may not
  10549. ** be trusted in this case.
  10550. */
  10551. SQLITE_API int sqlite3changeset_op(
  10552. sqlite3_changeset_iter *pIter, /* Iterator object */
  10553. const char **pzTab, /* OUT: Pointer to table name */
  10554. int *pnCol, /* OUT: Number of columns in table */
  10555. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  10556. int *pbIndirect /* OUT: True for an 'indirect' change */
  10557. );
  10558. /*
  10559. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  10560. ** METHOD: sqlite3_changeset_iter
  10561. **
  10562. ** For each modified table, a changeset includes the following:
  10563. **
  10564. ** <ul>
  10565. ** <li> The number of columns in the table, and
  10566. ** <li> Which of those columns make up the tables PRIMARY KEY.
  10567. ** </ul>
  10568. **
  10569. ** This function is used to find which columns comprise the PRIMARY KEY of
  10570. ** the table modified by the change that iterator pIter currently points to.
  10571. ** If successful, *pabPK is set to point to an array of nCol entries, where
  10572. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  10573. ** 0x01 if the corresponding column is part of the tables primary key, or
  10574. ** 0x00 if it is not.
  10575. **
  10576. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  10577. ** in the table.
  10578. **
  10579. ** If this function is called when the iterator does not point to a valid
  10580. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  10581. ** SQLITE_OK is returned and the output variables populated as described
  10582. ** above.
  10583. */
  10584. SQLITE_API int sqlite3changeset_pk(
  10585. sqlite3_changeset_iter *pIter, /* Iterator object */
  10586. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  10587. int *pnCol /* OUT: Number of entries in output array */
  10588. );
  10589. /*
  10590. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  10591. ** METHOD: sqlite3_changeset_iter
  10592. **
  10593. ** The pIter argument passed to this function may either be an iterator
  10594. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10595. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10596. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10597. ** Furthermore, it may only be called if the type of change that the iterator
  10598. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  10599. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10600. **
  10601. ** Argument iVal must be greater than or equal to 0, and less than the number
  10602. ** of columns in the table affected by the current change. Otherwise,
  10603. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10604. **
  10605. ** If successful, this function sets *ppValue to point to a protected
  10606. ** sqlite3_value object containing the iVal'th value from the vector of
  10607. ** original row values stored as part of the UPDATE or DELETE change and
  10608. ** returns SQLITE_OK. The name of the function comes from the fact that this
  10609. ** is similar to the "old.*" columns available to update or delete triggers.
  10610. **
  10611. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10612. ** is returned and *ppValue is set to NULL.
  10613. */
  10614. SQLITE_API int sqlite3changeset_old(
  10615. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10616. int iVal, /* Column number */
  10617. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  10618. );
  10619. /*
  10620. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  10621. ** METHOD: sqlite3_changeset_iter
  10622. **
  10623. ** The pIter argument passed to this function may either be an iterator
  10624. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10625. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10626. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10627. ** Furthermore, it may only be called if the type of change that the iterator
  10628. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  10629. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10630. **
  10631. ** Argument iVal must be greater than or equal to 0, and less than the number
  10632. ** of columns in the table affected by the current change. Otherwise,
  10633. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10634. **
  10635. ** If successful, this function sets *ppValue to point to a protected
  10636. ** sqlite3_value object containing the iVal'th value from the vector of
  10637. ** new row values stored as part of the UPDATE or INSERT change and
  10638. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  10639. ** a new value for the requested column, *ppValue is set to NULL and
  10640. ** SQLITE_OK returned. The name of the function comes from the fact that
  10641. ** this is similar to the "new.*" columns available to update or delete
  10642. ** triggers.
  10643. **
  10644. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10645. ** is returned and *ppValue is set to NULL.
  10646. */
  10647. SQLITE_API int sqlite3changeset_new(
  10648. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10649. int iVal, /* Column number */
  10650. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  10651. );
  10652. /*
  10653. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  10654. ** METHOD: sqlite3_changeset_iter
  10655. **
  10656. ** This function should only be used with iterator objects passed to a
  10657. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  10658. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  10659. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  10660. ** is set to NULL.
  10661. **
  10662. ** Argument iVal must be greater than or equal to 0, and less than the number
  10663. ** of columns in the table affected by the current change. Otherwise,
  10664. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10665. **
  10666. ** If successful, this function sets *ppValue to point to a protected
  10667. ** sqlite3_value object containing the iVal'th value from the
  10668. ** "conflicting row" associated with the current conflict-handler callback
  10669. ** and returns SQLITE_OK.
  10670. **
  10671. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10672. ** is returned and *ppValue is set to NULL.
  10673. */
  10674. SQLITE_API int sqlite3changeset_conflict(
  10675. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10676. int iVal, /* Column number */
  10677. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  10678. );
  10679. /*
  10680. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  10681. ** METHOD: sqlite3_changeset_iter
  10682. **
  10683. ** This function may only be called with an iterator passed to an
  10684. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  10685. ** it sets the output variable to the total number of known foreign key
  10686. ** violations in the destination database and returns SQLITE_OK.
  10687. **
  10688. ** In all other cases this function returns SQLITE_MISUSE.
  10689. */
  10690. SQLITE_API int sqlite3changeset_fk_conflicts(
  10691. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10692. int *pnOut /* OUT: Number of FK violations */
  10693. );
  10694. /*
  10695. ** CAPI3REF: Finalize A Changeset Iterator
  10696. ** METHOD: sqlite3_changeset_iter
  10697. **
  10698. ** This function is used to finalize an iterator allocated with
  10699. ** [sqlite3changeset_start()].
  10700. **
  10701. ** This function should only be called on iterators created using the
  10702. ** [sqlite3changeset_start()] function. If an application calls this
  10703. ** function with an iterator passed to a conflict-handler by
  10704. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  10705. ** call has no effect.
  10706. **
  10707. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  10708. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  10709. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  10710. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  10711. ** returned. This is to allow the following pattern (pseudo-code):
  10712. **
  10713. ** <pre>
  10714. ** sqlite3changeset_start();
  10715. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  10716. ** // Do something with change.
  10717. ** }
  10718. ** rc = sqlite3changeset_finalize();
  10719. ** if( rc!=SQLITE_OK ){
  10720. ** // An error has occurred
  10721. ** }
  10722. ** </pre>
  10723. */
  10724. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  10725. /*
  10726. ** CAPI3REF: Invert A Changeset
  10727. **
  10728. ** This function is used to "invert" a changeset object. Applying an inverted
  10729. ** changeset to a database reverses the effects of applying the uninverted
  10730. ** changeset. Specifically:
  10731. **
  10732. ** <ul>
  10733. ** <li> Each DELETE change is changed to an INSERT, and
  10734. ** <li> Each INSERT change is changed to a DELETE, and
  10735. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  10736. ** </ul>
  10737. **
  10738. ** This function does not change the order in which changes appear within
  10739. ** the changeset. It merely reverses the sense of each individual change.
  10740. **
  10741. ** If successful, a pointer to a buffer containing the inverted changeset
  10742. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  10743. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  10744. ** zeroed and an SQLite error code returned.
  10745. **
  10746. ** It is the responsibility of the caller to eventually call sqlite3_free()
  10747. ** on the *ppOut pointer to free the buffer allocation following a successful
  10748. ** call to this function.
  10749. **
  10750. ** WARNING/TODO: This function currently assumes that the input is a valid
  10751. ** changeset. If it is not, the results are undefined.
  10752. */
  10753. SQLITE_API int sqlite3changeset_invert(
  10754. int nIn, const void *pIn, /* Input changeset */
  10755. int *pnOut, void **ppOut /* OUT: Inverse of input */
  10756. );
  10757. /*
  10758. ** CAPI3REF: Concatenate Two Changeset Objects
  10759. **
  10760. ** This function is used to concatenate two changesets, A and B, into a
  10761. ** single changeset. The result is a changeset equivalent to applying
  10762. ** changeset A followed by changeset B.
  10763. **
  10764. ** This function combines the two input changesets using an
  10765. ** sqlite3_changegroup object. Calling it produces similar results as the
  10766. ** following code fragment:
  10767. **
  10768. ** <pre>
  10769. ** sqlite3_changegroup *pGrp;
  10770. ** rc = sqlite3_changegroup_new(&pGrp);
  10771. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  10772. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  10773. ** if( rc==SQLITE_OK ){
  10774. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  10775. ** }else{
  10776. ** *ppOut = 0;
  10777. ** *pnOut = 0;
  10778. ** }
  10779. ** </pre>
  10780. **
  10781. ** Refer to the sqlite3_changegroup documentation below for details.
  10782. */
  10783. SQLITE_API int sqlite3changeset_concat(
  10784. int nA, /* Number of bytes in buffer pA */
  10785. void *pA, /* Pointer to buffer containing changeset A */
  10786. int nB, /* Number of bytes in buffer pB */
  10787. void *pB, /* Pointer to buffer containing changeset B */
  10788. int *pnOut, /* OUT: Number of bytes in output changeset */
  10789. void **ppOut /* OUT: Buffer containing output changeset */
  10790. );
  10791. /*
  10792. ** CAPI3REF: Changegroup Handle
  10793. **
  10794. ** A changegroup is an object used to combine two or more
  10795. ** [changesets] or [patchsets]
  10796. */
  10797. typedef struct sqlite3_changegroup sqlite3_changegroup;
  10798. /*
  10799. ** CAPI3REF: Create A New Changegroup Object
  10800. ** CONSTRUCTOR: sqlite3_changegroup
  10801. **
  10802. ** An sqlite3_changegroup object is used to combine two or more changesets
  10803. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  10804. ** object may combine changesets or patchsets, but not both. The output is
  10805. ** always in the same format as the input.
  10806. **
  10807. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  10808. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  10809. ** should eventually free the returned object using a call to
  10810. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  10811. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  10812. **
  10813. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  10814. **
  10815. ** <ul>
  10816. ** <li> It is created using a call to sqlite3changegroup_new().
  10817. **
  10818. ** <li> Zero or more changesets (or patchsets) are added to the object
  10819. ** by calling sqlite3changegroup_add().
  10820. **
  10821. ** <li> The result of combining all input changesets together is obtained
  10822. ** by the application via a call to sqlite3changegroup_output().
  10823. **
  10824. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  10825. ** </ul>
  10826. **
  10827. ** Any number of calls to add() and output() may be made between the calls to
  10828. ** new() and delete(), and in any order.
  10829. **
  10830. ** As well as the regular sqlite3changegroup_add() and
  10831. ** sqlite3changegroup_output() functions, also available are the streaming
  10832. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  10833. */
  10834. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  10835. /*
  10836. ** CAPI3REF: Add A Changeset To A Changegroup
  10837. ** METHOD: sqlite3_changegroup
  10838. **
  10839. ** Add all changes within the changeset (or patchset) in buffer pData (size
  10840. ** nData bytes) to the changegroup.
  10841. **
  10842. ** If the buffer contains a patchset, then all prior calls to this function
  10843. ** on the same changegroup object must also have specified patchsets. Or, if
  10844. ** the buffer contains a changeset, so must have the earlier calls to this
  10845. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  10846. ** to the changegroup.
  10847. **
  10848. ** Rows within the changeset and changegroup are identified by the values in
  10849. ** their PRIMARY KEY columns. A change in the changeset is considered to
  10850. ** apply to the same row as a change already present in the changegroup if
  10851. ** the two rows have the same primary key.
  10852. **
  10853. ** Changes to rows that do not already appear in the changegroup are
  10854. ** simply copied into it. Or, if both the new changeset and the changegroup
  10855. ** contain changes that apply to a single row, the final contents of the
  10856. ** changegroup depends on the type of each change, as follows:
  10857. **
  10858. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  10859. ** <tr><th style="white-space:pre">Existing Change </th>
  10860. ** <th style="white-space:pre">New Change </th>
  10861. ** <th>Output Change
  10862. ** <tr><td>INSERT <td>INSERT <td>
  10863. ** The new change is ignored. This case does not occur if the new
  10864. ** changeset was recorded immediately after the changesets already
  10865. ** added to the changegroup.
  10866. ** <tr><td>INSERT <td>UPDATE <td>
  10867. ** The INSERT change remains in the changegroup. The values in the
  10868. ** INSERT change are modified as if the row was inserted by the
  10869. ** existing change and then updated according to the new change.
  10870. ** <tr><td>INSERT <td>DELETE <td>
  10871. ** The existing INSERT is removed from the changegroup. The DELETE is
  10872. ** not added.
  10873. ** <tr><td>UPDATE <td>INSERT <td>
  10874. ** The new change is ignored. This case does not occur if the new
  10875. ** changeset was recorded immediately after the changesets already
  10876. ** added to the changegroup.
  10877. ** <tr><td>UPDATE <td>UPDATE <td>
  10878. ** The existing UPDATE remains within the changegroup. It is amended
  10879. ** so that the accompanying values are as if the row was updated once
  10880. ** by the existing change and then again by the new change.
  10881. ** <tr><td>UPDATE <td>DELETE <td>
  10882. ** The existing UPDATE is replaced by the new DELETE within the
  10883. ** changegroup.
  10884. ** <tr><td>DELETE <td>INSERT <td>
  10885. ** If one or more of the column values in the row inserted by the
  10886. ** new change differ from those in the row deleted by the existing
  10887. ** change, the existing DELETE is replaced by an UPDATE within the
  10888. ** changegroup. Otherwise, if the inserted row is exactly the same
  10889. ** as the deleted row, the existing DELETE is simply discarded.
  10890. ** <tr><td>DELETE <td>UPDATE <td>
  10891. ** The new change is ignored. This case does not occur if the new
  10892. ** changeset was recorded immediately after the changesets already
  10893. ** added to the changegroup.
  10894. ** <tr><td>DELETE <td>DELETE <td>
  10895. ** The new change is ignored. This case does not occur if the new
  10896. ** changeset was recorded immediately after the changesets already
  10897. ** added to the changegroup.
  10898. ** </table>
  10899. **
  10900. ** If the new changeset contains changes to a table that is already present
  10901. ** in the changegroup, then the number of columns and the position of the
  10902. ** primary key columns for the table must be consistent. If this is not the
  10903. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  10904. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  10905. ** returned. Or, if an out-of-memory condition occurs during processing, this
  10906. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  10907. ** final contents of the changegroup is undefined.
  10908. **
  10909. ** If no error occurs, SQLITE_OK is returned.
  10910. */
  10911. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  10912. /*
  10913. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  10914. ** METHOD: sqlite3_changegroup
  10915. **
  10916. ** Obtain a buffer containing a changeset (or patchset) representing the
  10917. ** current contents of the changegroup. If the inputs to the changegroup
  10918. ** were themselves changesets, the output is a changeset. Or, if the
  10919. ** inputs were patchsets, the output is also a patchset.
  10920. **
  10921. ** As with the output of the sqlite3session_changeset() and
  10922. ** sqlite3session_patchset() functions, all changes related to a single
  10923. ** table are grouped together in the output of this function. Tables appear
  10924. ** in the same order as for the very first changeset added to the changegroup.
  10925. ** If the second or subsequent changesets added to the changegroup contain
  10926. ** changes for tables that do not appear in the first changeset, they are
  10927. ** appended onto the end of the output changeset, again in the order in
  10928. ** which they are first encountered.
  10929. **
  10930. ** If an error occurs, an SQLite error code is returned and the output
  10931. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  10932. ** is returned and the output variables are set to the size of and a
  10933. ** pointer to the output buffer, respectively. In this case it is the
  10934. ** responsibility of the caller to eventually free the buffer using a
  10935. ** call to sqlite3_free().
  10936. */
  10937. SQLITE_API int sqlite3changegroup_output(
  10938. sqlite3_changegroup*,
  10939. int *pnData, /* OUT: Size of output buffer in bytes */
  10940. void **ppData /* OUT: Pointer to output buffer */
  10941. );
  10942. /*
  10943. ** CAPI3REF: Delete A Changegroup Object
  10944. ** DESTRUCTOR: sqlite3_changegroup
  10945. */
  10946. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  10947. /*
  10948. ** CAPI3REF: Apply A Changeset To A Database
  10949. **
  10950. ** Apply a changeset or patchset to a database. These functions attempt to
  10951. ** update the "main" database attached to handle db with the changes found in
  10952. ** the changeset passed via the second and third arguments.
  10953. **
  10954. ** The fourth argument (xFilter) passed to these functions is the "filter
  10955. ** callback". If it is not NULL, then for each table affected by at least one
  10956. ** change in the changeset, the filter callback is invoked with
  10957. ** the table name as the second argument, and a copy of the context pointer
  10958. ** passed as the sixth argument as the first. If the "filter callback"
  10959. ** returns zero, then no attempt is made to apply any changes to the table.
  10960. ** Otherwise, if the return value is non-zero or the xFilter argument to
  10961. ** is NULL, all changes related to the table are attempted.
  10962. **
  10963. ** For each table that is not excluded by the filter callback, this function
  10964. ** tests that the target database contains a compatible table. A table is
  10965. ** considered compatible if all of the following are true:
  10966. **
  10967. ** <ul>
  10968. ** <li> The table has the same name as the name recorded in the
  10969. ** changeset, and
  10970. ** <li> The table has at least as many columns as recorded in the
  10971. ** changeset, and
  10972. ** <li> The table has primary key columns in the same position as
  10973. ** recorded in the changeset.
  10974. ** </ul>
  10975. **
  10976. ** If there is no compatible table, it is not an error, but none of the
  10977. ** changes associated with the table are applied. A warning message is issued
  10978. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  10979. ** one such warning is issued for each table in the changeset.
  10980. **
  10981. ** For each change for which there is a compatible table, an attempt is made
  10982. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  10983. ** change. If a change cannot be applied cleanly, the conflict handler
  10984. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  10985. ** invoked. A description of exactly when the conflict handler is invoked for
  10986. ** each type of change is below.
  10987. **
  10988. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  10989. ** of passing anything other than a valid function pointer as the xConflict
  10990. ** argument are undefined.
  10991. **
  10992. ** Each time the conflict handler function is invoked, it must return one
  10993. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  10994. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  10995. ** if the second argument passed to the conflict handler is either
  10996. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  10997. ** returns an illegal value, any changes already made are rolled back and
  10998. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  10999. ** actions are taken by sqlite3changeset_apply() depending on the value
  11000. ** returned by each invocation of the conflict-handler function. Refer to
  11001. ** the documentation for the three
  11002. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  11003. **
  11004. ** <dl>
  11005. ** <dt>DELETE Changes<dd>
  11006. ** For each DELETE change, the function checks if the target database
  11007. ** contains a row with the same primary key value (or values) as the
  11008. ** original row values stored in the changeset. If it does, and the values
  11009. ** stored in all non-primary key columns also match the values stored in
  11010. ** the changeset the row is deleted from the target database.
  11011. **
  11012. ** If a row with matching primary key values is found, but one or more of
  11013. ** the non-primary key fields contains a value different from the original
  11014. ** row value stored in the changeset, the conflict-handler function is
  11015. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  11016. ** database table has more columns than are recorded in the changeset,
  11017. ** only the values of those non-primary key fields are compared against
  11018. ** the current database contents - any trailing database table columns
  11019. ** are ignored.
  11020. **
  11021. ** If no row with matching primary key values is found in the database,
  11022. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11023. ** passed as the second argument.
  11024. **
  11025. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  11026. ** (which can only happen if a foreign key constraint is violated), the
  11027. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  11028. ** passed as the second argument. This includes the case where the DELETE
  11029. ** operation is attempted because an earlier call to the conflict handler
  11030. ** function returned [SQLITE_CHANGESET_REPLACE].
  11031. **
  11032. ** <dt>INSERT Changes<dd>
  11033. ** For each INSERT change, an attempt is made to insert the new row into
  11034. ** the database. If the changeset row contains fewer fields than the
  11035. ** database table, the trailing fields are populated with their default
  11036. ** values.
  11037. **
  11038. ** If the attempt to insert the row fails because the database already
  11039. ** contains a row with the same primary key values, the conflict handler
  11040. ** function is invoked with the second argument set to
  11041. ** [SQLITE_CHANGESET_CONFLICT].
  11042. **
  11043. ** If the attempt to insert the row fails because of some other constraint
  11044. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  11045. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  11046. ** This includes the case where the INSERT operation is re-attempted because
  11047. ** an earlier call to the conflict handler function returned
  11048. ** [SQLITE_CHANGESET_REPLACE].
  11049. **
  11050. ** <dt>UPDATE Changes<dd>
  11051. ** For each UPDATE change, the function checks if the target database
  11052. ** contains a row with the same primary key value (or values) as the
  11053. ** original row values stored in the changeset. If it does, and the values
  11054. ** stored in all modified non-primary key columns also match the values
  11055. ** stored in the changeset the row is updated within the target database.
  11056. **
  11057. ** If a row with matching primary key values is found, but one or more of
  11058. ** the modified non-primary key fields contains a value different from an
  11059. ** original row value stored in the changeset, the conflict-handler function
  11060. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  11061. ** UPDATE changes only contain values for non-primary key fields that are
  11062. ** to be modified, only those fields need to match the original values to
  11063. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  11064. **
  11065. ** If no row with matching primary key values is found in the database,
  11066. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11067. ** passed as the second argument.
  11068. **
  11069. ** If the UPDATE operation is attempted, but SQLite returns
  11070. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  11071. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  11072. ** This includes the case where the UPDATE operation is attempted after
  11073. ** an earlier call to the conflict handler function returned
  11074. ** [SQLITE_CHANGESET_REPLACE].
  11075. ** </dl>
  11076. **
  11077. ** It is safe to execute SQL statements, including those that write to the
  11078. ** table that the callback related to, from within the xConflict callback.
  11079. ** This can be used to further customize the applications conflict
  11080. ** resolution strategy.
  11081. **
  11082. ** All changes made by these functions are enclosed in a savepoint transaction.
  11083. ** If any other error (aside from a constraint failure when attempting to
  11084. ** write to the target database) occurs, then the savepoint transaction is
  11085. ** rolled back, restoring the target database to its original state, and an
  11086. ** SQLite error code returned.
  11087. **
  11088. ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
  11089. ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
  11090. ** may set (*ppRebase) to point to a "rebase" that may be used with the
  11091. ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
  11092. ** is set to the size of the buffer in bytes. It is the responsibility of the
  11093. ** caller to eventually free any such buffer using sqlite3_free(). The buffer
  11094. ** is only allocated and populated if one or more conflicts were encountered
  11095. ** while applying the patchset. See comments surrounding the sqlite3_rebaser
  11096. ** APIs for further details.
  11097. **
  11098. ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
  11099. ** may be modified by passing a combination of
  11100. ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
  11101. **
  11102. ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
  11103. ** and therefore subject to change.
  11104. */
  11105. SQLITE_API int sqlite3changeset_apply(
  11106. sqlite3 *db, /* Apply change to "main" db of this handle */
  11107. int nChangeset, /* Size of changeset in bytes */
  11108. void *pChangeset, /* Changeset blob */
  11109. int(*xFilter)(
  11110. void *pCtx, /* Copy of sixth arg to _apply() */
  11111. const char *zTab /* Table name */
  11112. ),
  11113. int(*xConflict)(
  11114. void *pCtx, /* Copy of sixth arg to _apply() */
  11115. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11116. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11117. ),
  11118. void *pCtx /* First argument passed to xConflict */
  11119. );
  11120. SQLITE_API int sqlite3changeset_apply_v2(
  11121. sqlite3 *db, /* Apply change to "main" db of this handle */
  11122. int nChangeset, /* Size of changeset in bytes */
  11123. void *pChangeset, /* Changeset blob */
  11124. int(*xFilter)(
  11125. void *pCtx, /* Copy of sixth arg to _apply() */
  11126. const char *zTab /* Table name */
  11127. ),
  11128. int(*xConflict)(
  11129. void *pCtx, /* Copy of sixth arg to _apply() */
  11130. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11131. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11132. ),
  11133. void *pCtx, /* First argument passed to xConflict */
  11134. void **ppRebase, int *pnRebase, /* OUT: Rebase data */
  11135. int flags /* Combination of SESSION_APPLY_* flags */
  11136. );
  11137. /*
  11138. ** CAPI3REF: Flags for sqlite3changeset_apply_v2
  11139. **
  11140. ** The following flags may passed via the 9th parameter to
  11141. ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
  11142. **
  11143. ** <dl>
  11144. ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
  11145. ** Usually, the sessions module encloses all operations performed by
  11146. ** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
  11147. ** SAVEPOINT is committed if the changeset or patchset is successfully
  11148. ** applied, or rolled back if an error occurs. Specifying this flag
  11149. ** causes the sessions module to omit this savepoint. In this case, if the
  11150. ** caller has an open transaction or savepoint when apply_v2() is called,
  11151. ** it may revert the partially applied changeset by rolling it back.
  11152. */
  11153. #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
  11154. /*
  11155. ** CAPI3REF: Constants Passed To The Conflict Handler
  11156. **
  11157. ** Values that may be passed as the second argument to a conflict-handler.
  11158. **
  11159. ** <dl>
  11160. ** <dt>SQLITE_CHANGESET_DATA<dd>
  11161. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  11162. ** when processing a DELETE or UPDATE change if a row with the required
  11163. ** PRIMARY KEY fields is present in the database, but one or more other
  11164. ** (non primary-key) fields modified by the update do not contain the
  11165. ** expected "before" values.
  11166. **
  11167. ** The conflicting row, in this case, is the database row with the matching
  11168. ** primary key.
  11169. **
  11170. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  11171. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  11172. ** argument when processing a DELETE or UPDATE change if a row with the
  11173. ** required PRIMARY KEY fields is not present in the database.
  11174. **
  11175. ** There is no conflicting row in this case. The results of invoking the
  11176. ** sqlite3changeset_conflict() API are undefined.
  11177. **
  11178. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  11179. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  11180. ** handler while processing an INSERT change if the operation would result
  11181. ** in duplicate primary key values.
  11182. **
  11183. ** The conflicting row in this case is the database row with the matching
  11184. ** primary key.
  11185. **
  11186. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  11187. ** If foreign key handling is enabled, and applying a changeset leaves the
  11188. ** database in a state containing foreign key violations, the conflict
  11189. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  11190. ** exactly once before the changeset is committed. If the conflict handler
  11191. ** returns CHANGESET_OMIT, the changes, including those that caused the
  11192. ** foreign key constraint violation, are committed. Or, if it returns
  11193. ** CHANGESET_ABORT, the changeset is rolled back.
  11194. **
  11195. ** No current or conflicting row information is provided. The only function
  11196. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  11197. ** is sqlite3changeset_fk_conflicts().
  11198. **
  11199. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  11200. ** If any other constraint violation occurs while applying a change (i.e.
  11201. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  11202. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  11203. **
  11204. ** There is no conflicting row in this case. The results of invoking the
  11205. ** sqlite3changeset_conflict() API are undefined.
  11206. **
  11207. ** </dl>
  11208. */
  11209. #define SQLITE_CHANGESET_DATA 1
  11210. #define SQLITE_CHANGESET_NOTFOUND 2
  11211. #define SQLITE_CHANGESET_CONFLICT 3
  11212. #define SQLITE_CHANGESET_CONSTRAINT 4
  11213. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  11214. /*
  11215. ** CAPI3REF: Constants Returned By The Conflict Handler
  11216. **
  11217. ** A conflict handler callback must return one of the following three values.
  11218. **
  11219. ** <dl>
  11220. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  11221. ** If a conflict handler returns this value no special action is taken. The
  11222. ** change that caused the conflict is not applied. The session module
  11223. ** continues to the next change in the changeset.
  11224. **
  11225. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  11226. ** This value may only be returned if the second argument to the conflict
  11227. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  11228. ** is not the case, any changes applied so far are rolled back and the
  11229. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  11230. **
  11231. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  11232. ** handler, then the conflicting row is either updated or deleted, depending
  11233. ** on the type of change.
  11234. **
  11235. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  11236. ** handler, then the conflicting row is removed from the database and a
  11237. ** second attempt to apply the change is made. If this second attempt fails,
  11238. ** the original row is restored to the database before continuing.
  11239. **
  11240. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  11241. ** If this value is returned, any changes applied so far are rolled back
  11242. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  11243. ** </dl>
  11244. */
  11245. #define SQLITE_CHANGESET_OMIT 0
  11246. #define SQLITE_CHANGESET_REPLACE 1
  11247. #define SQLITE_CHANGESET_ABORT 2
  11248. /*
  11249. ** CAPI3REF: Rebasing changesets
  11250. ** EXPERIMENTAL
  11251. **
  11252. ** Suppose there is a site hosting a database in state S0. And that
  11253. ** modifications are made that move that database to state S1 and a
  11254. ** changeset recorded (the "local" changeset). Then, a changeset based
  11255. ** on S0 is received from another site (the "remote" changeset) and
  11256. ** applied to the database. The database is then in state
  11257. ** (S1+"remote"), where the exact state depends on any conflict
  11258. ** resolution decisions (OMIT or REPLACE) made while applying "remote".
  11259. ** Rebasing a changeset is to update it to take those conflict
  11260. ** resolution decisions into account, so that the same conflicts
  11261. ** do not have to be resolved elsewhere in the network.
  11262. **
  11263. ** For example, if both the local and remote changesets contain an
  11264. ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
  11265. **
  11266. ** local: INSERT INTO t1 VALUES(1, 'v1');
  11267. ** remote: INSERT INTO t1 VALUES(1, 'v2');
  11268. **
  11269. ** and the conflict resolution is REPLACE, then the INSERT change is
  11270. ** removed from the local changeset (it was overridden). Or, if the
  11271. ** conflict resolution was "OMIT", then the local changeset is modified
  11272. ** to instead contain:
  11273. **
  11274. ** UPDATE t1 SET b = 'v2' WHERE a=1;
  11275. **
  11276. ** Changes within the local changeset are rebased as follows:
  11277. **
  11278. ** <dl>
  11279. ** <dt>Local INSERT<dd>
  11280. ** This may only conflict with a remote INSERT. If the conflict
  11281. ** resolution was OMIT, then add an UPDATE change to the rebased
  11282. ** changeset. Or, if the conflict resolution was REPLACE, add
  11283. ** nothing to the rebased changeset.
  11284. **
  11285. ** <dt>Local DELETE<dd>
  11286. ** This may conflict with a remote UPDATE or DELETE. In both cases the
  11287. ** only possible resolution is OMIT. If the remote operation was a
  11288. ** DELETE, then add no change to the rebased changeset. If the remote
  11289. ** operation was an UPDATE, then the old.* fields of change are updated
  11290. ** to reflect the new.* values in the UPDATE.
  11291. **
  11292. ** <dt>Local UPDATE<dd>
  11293. ** This may conflict with a remote UPDATE or DELETE. If it conflicts
  11294. ** with a DELETE, and the conflict resolution was OMIT, then the update
  11295. ** is changed into an INSERT. Any undefined values in the new.* record
  11296. ** from the update change are filled in using the old.* values from
  11297. ** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
  11298. ** the UPDATE change is simply omitted from the rebased changeset.
  11299. **
  11300. ** If conflict is with a remote UPDATE and the resolution is OMIT, then
  11301. ** the old.* values are rebased using the new.* values in the remote
  11302. ** change. Or, if the resolution is REPLACE, then the change is copied
  11303. ** into the rebased changeset with updates to columns also updated by
  11304. ** the conflicting remote UPDATE removed. If this means no columns would
  11305. ** be updated, the change is omitted.
  11306. ** </dl>
  11307. **
  11308. ** A local change may be rebased against multiple remote changes
  11309. ** simultaneously. If a single key is modified by multiple remote
  11310. ** changesets, they are combined as follows before the local changeset
  11311. ** is rebased:
  11312. **
  11313. ** <ul>
  11314. ** <li> If there has been one or more REPLACE resolutions on a
  11315. ** key, it is rebased according to a REPLACE.
  11316. **
  11317. ** <li> If there have been no REPLACE resolutions on a key, then
  11318. ** the local changeset is rebased according to the most recent
  11319. ** of the OMIT resolutions.
  11320. ** </ul>
  11321. **
  11322. ** Note that conflict resolutions from multiple remote changesets are
  11323. ** combined on a per-field basis, not per-row. This means that in the
  11324. ** case of multiple remote UPDATE operations, some fields of a single
  11325. ** local change may be rebased for REPLACE while others are rebased for
  11326. ** OMIT.
  11327. **
  11328. ** In order to rebase a local changeset, the remote changeset must first
  11329. ** be applied to the local database using sqlite3changeset_apply_v2() and
  11330. ** the buffer of rebase information captured. Then:
  11331. **
  11332. ** <ol>
  11333. ** <li> An sqlite3_rebaser object is created by calling
  11334. ** sqlite3rebaser_create().
  11335. ** <li> The new object is configured with the rebase buffer obtained from
  11336. ** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
  11337. ** If the local changeset is to be rebased against multiple remote
  11338. ** changesets, then sqlite3rebaser_configure() should be called
  11339. ** multiple times, in the same order that the multiple
  11340. ** sqlite3changeset_apply_v2() calls were made.
  11341. ** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
  11342. ** <li> The sqlite3_rebaser object is deleted by calling
  11343. ** sqlite3rebaser_delete().
  11344. ** </ol>
  11345. */
  11346. typedef struct sqlite3_rebaser sqlite3_rebaser;
  11347. /*
  11348. ** CAPI3REF: Create a changeset rebaser object.
  11349. ** EXPERIMENTAL
  11350. **
  11351. ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
  11352. ** point to the new object and return SQLITE_OK. Otherwise, if an error
  11353. ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
  11354. ** to NULL.
  11355. */
  11356. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
  11357. /*
  11358. ** CAPI3REF: Configure a changeset rebaser object.
  11359. ** EXPERIMENTAL
  11360. **
  11361. ** Configure the changeset rebaser object to rebase changesets according
  11362. ** to the conflict resolutions described by buffer pRebase (size nRebase
  11363. ** bytes), which must have been obtained from a previous call to
  11364. ** sqlite3changeset_apply_v2().
  11365. */
  11366. SQLITE_API int sqlite3rebaser_configure(
  11367. sqlite3_rebaser*,
  11368. int nRebase, const void *pRebase
  11369. );
  11370. /*
  11371. ** CAPI3REF: Rebase a changeset
  11372. ** EXPERIMENTAL
  11373. **
  11374. ** Argument pIn must point to a buffer containing a changeset nIn bytes
  11375. ** in size. This function allocates and populates a buffer with a copy
  11376. ** of the changeset rebased rebased according to the configuration of the
  11377. ** rebaser object passed as the first argument. If successful, (*ppOut)
  11378. ** is set to point to the new buffer containing the rebased changset and
  11379. ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
  11380. ** responsibility of the caller to eventually free the new buffer using
  11381. ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
  11382. ** are set to zero and an SQLite error code returned.
  11383. */
  11384. SQLITE_API int sqlite3rebaser_rebase(
  11385. sqlite3_rebaser*,
  11386. int nIn, const void *pIn,
  11387. int *pnOut, void **ppOut
  11388. );
  11389. /*
  11390. ** CAPI3REF: Delete a changeset rebaser object.
  11391. ** EXPERIMENTAL
  11392. **
  11393. ** Delete the changeset rebaser object and all associated resources. There
  11394. ** should be one call to this function for each successful invocation
  11395. ** of sqlite3rebaser_create().
  11396. */
  11397. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
  11398. /*
  11399. ** CAPI3REF: Streaming Versions of API functions.
  11400. **
  11401. ** The six streaming API xxx_strm() functions serve similar purposes to the
  11402. ** corresponding non-streaming API functions:
  11403. **
  11404. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11405. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  11406. ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
  11407. ** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
  11408. ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
  11409. ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
  11410. ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
  11411. ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
  11412. ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
  11413. ** </table>
  11414. **
  11415. ** Non-streaming functions that accept changesets (or patchsets) as input
  11416. ** require that the entire changeset be stored in a single buffer in memory.
  11417. ** Similarly, those that return a changeset or patchset do so by returning
  11418. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  11419. ** Normally this is convenient. However, if an application running in a
  11420. ** low-memory environment is required to handle very large changesets, the
  11421. ** large contiguous memory allocations required can become onerous.
  11422. **
  11423. ** In order to avoid this problem, instead of a single large buffer, input
  11424. ** is passed to a streaming API functions by way of a callback function that
  11425. ** the sessions module invokes to incrementally request input data as it is
  11426. ** required. In all cases, a pair of API function parameters such as
  11427. **
  11428. ** <pre>
  11429. ** &nbsp; int nChangeset,
  11430. ** &nbsp; void *pChangeset,
  11431. ** </pre>
  11432. **
  11433. ** Is replaced by:
  11434. **
  11435. ** <pre>
  11436. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  11437. ** &nbsp; void *pIn,
  11438. ** </pre>
  11439. **
  11440. ** Each time the xInput callback is invoked by the sessions module, the first
  11441. ** argument passed is a copy of the supplied pIn context pointer. The second
  11442. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  11443. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  11444. ** into the buffer and set (*pnData) to the actual number of bytes copied
  11445. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  11446. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  11447. ** error code should be returned. In all cases, if an xInput callback returns
  11448. ** an error, all processing is abandoned and the streaming API function
  11449. ** returns a copy of the error code to the caller.
  11450. **
  11451. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  11452. ** invoked by the sessions module at any point during the lifetime of the
  11453. ** iterator. If such an xInput callback returns an error, the iterator enters
  11454. ** an error state, whereby all subsequent calls to iterator functions
  11455. ** immediately fail with the same error code as returned by xInput.
  11456. **
  11457. ** Similarly, streaming API functions that return changesets (or patchsets)
  11458. ** return them in chunks by way of a callback function instead of via a
  11459. ** pointer to a single large buffer. In this case, a pair of parameters such
  11460. ** as:
  11461. **
  11462. ** <pre>
  11463. ** &nbsp; int *pnChangeset,
  11464. ** &nbsp; void **ppChangeset,
  11465. ** </pre>
  11466. **
  11467. ** Is replaced by:
  11468. **
  11469. ** <pre>
  11470. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  11471. ** &nbsp; void *pOut
  11472. ** </pre>
  11473. **
  11474. ** The xOutput callback is invoked zero or more times to return data to
  11475. ** the application. The first parameter passed to each call is a copy of the
  11476. ** pOut pointer supplied by the application. The second parameter, pData,
  11477. ** points to a buffer nData bytes in size containing the chunk of output
  11478. ** data being returned. If the xOutput callback successfully processes the
  11479. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  11480. ** it should return some other SQLite error code. In this case processing
  11481. ** is immediately abandoned and the streaming API function returns a copy
  11482. ** of the xOutput error code to the application.
  11483. **
  11484. ** The sessions module never invokes an xOutput callback with the third
  11485. ** parameter set to a value less than or equal to zero. Other than this,
  11486. ** no guarantees are made as to the size of the chunks of data returned.
  11487. */
  11488. SQLITE_API int sqlite3changeset_apply_strm(
  11489. sqlite3 *db, /* Apply change to "main" db of this handle */
  11490. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11491. void *pIn, /* First arg for xInput */
  11492. int(*xFilter)(
  11493. void *pCtx, /* Copy of sixth arg to _apply() */
  11494. const char *zTab /* Table name */
  11495. ),
  11496. int(*xConflict)(
  11497. void *pCtx, /* Copy of sixth arg to _apply() */
  11498. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11499. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11500. ),
  11501. void *pCtx /* First argument passed to xConflict */
  11502. );
  11503. SQLITE_API int sqlite3changeset_apply_v2_strm(
  11504. sqlite3 *db, /* Apply change to "main" db of this handle */
  11505. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11506. void *pIn, /* First arg for xInput */
  11507. int(*xFilter)(
  11508. void *pCtx, /* Copy of sixth arg to _apply() */
  11509. const char *zTab /* Table name */
  11510. ),
  11511. int(*xConflict)(
  11512. void *pCtx, /* Copy of sixth arg to _apply() */
  11513. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11514. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11515. ),
  11516. void *pCtx, /* First argument passed to xConflict */
  11517. void **ppRebase, int *pnRebase,
  11518. int flags
  11519. );
  11520. SQLITE_API int sqlite3changeset_concat_strm(
  11521. int (*xInputA)(void *pIn, void *pData, int *pnData),
  11522. void *pInA,
  11523. int (*xInputB)(void *pIn, void *pData, int *pnData),
  11524. void *pInB,
  11525. int (*xOutput)(void *pOut, const void *pData, int nData),
  11526. void *pOut
  11527. );
  11528. SQLITE_API int sqlite3changeset_invert_strm(
  11529. int (*xInput)(void *pIn, void *pData, int *pnData),
  11530. void *pIn,
  11531. int (*xOutput)(void *pOut, const void *pData, int nData),
  11532. void *pOut
  11533. );
  11534. SQLITE_API int sqlite3changeset_start_strm(
  11535. sqlite3_changeset_iter **pp,
  11536. int (*xInput)(void *pIn, void *pData, int *pnData),
  11537. void *pIn
  11538. );
  11539. SQLITE_API int sqlite3session_changeset_strm(
  11540. sqlite3_session *pSession,
  11541. int (*xOutput)(void *pOut, const void *pData, int nData),
  11542. void *pOut
  11543. );
  11544. SQLITE_API int sqlite3session_patchset_strm(
  11545. sqlite3_session *pSession,
  11546. int (*xOutput)(void *pOut, const void *pData, int nData),
  11547. void *pOut
  11548. );
  11549. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  11550. int (*xInput)(void *pIn, void *pData, int *pnData),
  11551. void *pIn
  11552. );
  11553. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  11554. int (*xOutput)(void *pOut, const void *pData, int nData),
  11555. void *pOut
  11556. );
  11557. SQLITE_API int sqlite3rebaser_rebase_strm(
  11558. sqlite3_rebaser *pRebaser,
  11559. int (*xInput)(void *pIn, void *pData, int *pnData),
  11560. void *pIn,
  11561. int (*xOutput)(void *pOut, const void *pData, int nData),
  11562. void *pOut
  11563. );
  11564. /*
  11565. ** Make sure we can call this stuff from C++.
  11566. */
  11567. #if 0
  11568. }
  11569. #endif
  11570. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  11571. /******** End of sqlite3session.h *********/
  11572. /******** Begin file fts5.h *********/
  11573. /*
  11574. ** 2014 May 31
  11575. **
  11576. ** The author disclaims copyright to this source code. In place of
  11577. ** a legal notice, here is a blessing:
  11578. **
  11579. ** May you do good and not evil.
  11580. ** May you find forgiveness for yourself and forgive others.
  11581. ** May you share freely, never taking more than you give.
  11582. **
  11583. ******************************************************************************
  11584. **
  11585. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  11586. ** FTS5 may be extended with:
  11587. **
  11588. ** * custom tokenizers, and
  11589. ** * custom auxiliary functions.
  11590. */
  11591. #ifndef _FTS5_H
  11592. #define _FTS5_H
  11593. #if 0
  11594. extern "C" {
  11595. #endif
  11596. /*************************************************************************
  11597. ** CUSTOM AUXILIARY FUNCTIONS
  11598. **
  11599. ** Virtual table implementations may overload SQL functions by implementing
  11600. ** the sqlite3_module.xFindFunction() method.
  11601. */
  11602. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  11603. typedef struct Fts5Context Fts5Context;
  11604. typedef struct Fts5PhraseIter Fts5PhraseIter;
  11605. typedef void (*fts5_extension_function)(
  11606. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  11607. Fts5Context *pFts, /* First arg to pass to pApi functions */
  11608. sqlite3_context *pCtx, /* Context for returning result/error */
  11609. int nVal, /* Number of values in apVal[] array */
  11610. sqlite3_value **apVal /* Array of trailing arguments */
  11611. );
  11612. struct Fts5PhraseIter {
  11613. const unsigned char *a;
  11614. const unsigned char *b;
  11615. };
  11616. /*
  11617. ** EXTENSION API FUNCTIONS
  11618. **
  11619. ** xUserData(pFts):
  11620. ** Return a copy of the context pointer the extension function was
  11621. ** registered with.
  11622. **
  11623. ** xColumnTotalSize(pFts, iCol, pnToken):
  11624. ** If parameter iCol is less than zero, set output variable *pnToken
  11625. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  11626. ** non-negative but less than the number of columns in the table, return
  11627. ** the total number of tokens in column iCol, considering all rows in
  11628. ** the FTS5 table.
  11629. **
  11630. ** If parameter iCol is greater than or equal to the number of columns
  11631. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11632. ** an OOM condition or IO error), an appropriate SQLite error code is
  11633. ** returned.
  11634. **
  11635. ** xColumnCount(pFts):
  11636. ** Return the number of columns in the table.
  11637. **
  11638. ** xColumnSize(pFts, iCol, pnToken):
  11639. ** If parameter iCol is less than zero, set output variable *pnToken
  11640. ** to the total number of tokens in the current row. Or, if iCol is
  11641. ** non-negative but less than the number of columns in the table, set
  11642. ** *pnToken to the number of tokens in column iCol of the current row.
  11643. **
  11644. ** If parameter iCol is greater than or equal to the number of columns
  11645. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11646. ** an OOM condition or IO error), an appropriate SQLite error code is
  11647. ** returned.
  11648. **
  11649. ** This function may be quite inefficient if used with an FTS5 table
  11650. ** created with the "columnsize=0" option.
  11651. **
  11652. ** xColumnText:
  11653. ** This function attempts to retrieve the text of column iCol of the
  11654. ** current document. If successful, (*pz) is set to point to a buffer
  11655. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  11656. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  11657. ** if an error occurs, an SQLite error code is returned and the final values
  11658. ** of (*pz) and (*pn) are undefined.
  11659. **
  11660. ** xPhraseCount:
  11661. ** Returns the number of phrases in the current query expression.
  11662. **
  11663. ** xPhraseSize:
  11664. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  11665. ** are numbered starting from zero.
  11666. **
  11667. ** xInstCount:
  11668. ** Set *pnInst to the total number of occurrences of all phrases within
  11669. ** the query within the current row. Return SQLITE_OK if successful, or
  11670. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  11671. **
  11672. ** This API can be quite slow if used with an FTS5 table created with the
  11673. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  11674. ** with either "detail=none" or "detail=column" and "content=" option
  11675. ** (i.e. if it is a contentless table), then this API always returns 0.
  11676. **
  11677. ** xInst:
  11678. ** Query for the details of phrase match iIdx within the current row.
  11679. ** Phrase matches are numbered starting from zero, so the iIdx argument
  11680. ** should be greater than or equal to zero and smaller than the value
  11681. ** output by xInstCount().
  11682. **
  11683. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  11684. ** to the column in which it occurs and *piOff the token offset of the
  11685. ** first token of the phrase. The exception is if the table was created
  11686. ** with the offsets=0 option specified. In this case *piOff is always
  11687. ** set to -1.
  11688. **
  11689. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  11690. ** if an error occurs.
  11691. **
  11692. ** This API can be quite slow if used with an FTS5 table created with the
  11693. ** "detail=none" or "detail=column" option.
  11694. **
  11695. ** xRowid:
  11696. ** Returns the rowid of the current row.
  11697. **
  11698. ** xTokenize:
  11699. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  11700. **
  11701. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  11702. ** This API function is used to query the FTS table for phrase iPhrase
  11703. ** of the current query. Specifically, a query equivalent to:
  11704. **
  11705. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  11706. **
  11707. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  11708. ** current query is executed. Any column filter that applies to
  11709. ** phrase iPhrase of the current query is included in $p. For each
  11710. ** row visited, the callback function passed as the fourth argument
  11711. ** is invoked. The context and API objects passed to the callback
  11712. ** function may be used to access the properties of each matched row.
  11713. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  11714. ** the third argument to pUserData.
  11715. **
  11716. ** If the callback function returns any value other than SQLITE_OK, the
  11717. ** query is abandoned and the xQueryPhrase function returns immediately.
  11718. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  11719. ** Otherwise, the error code is propagated upwards.
  11720. **
  11721. ** If the query runs to completion without incident, SQLITE_OK is returned.
  11722. ** Or, if some error occurs before the query completes or is aborted by
  11723. ** the callback, an SQLite error code is returned.
  11724. **
  11725. **
  11726. ** xSetAuxdata(pFts5, pAux, xDelete)
  11727. **
  11728. ** Save the pointer passed as the second argument as the extension functions
  11729. ** "auxiliary data". The pointer may then be retrieved by the current or any
  11730. ** future invocation of the same fts5 extension function made as part of
  11731. ** of the same MATCH query using the xGetAuxdata() API.
  11732. **
  11733. ** Each extension function is allocated a single auxiliary data slot for
  11734. ** each FTS query (MATCH expression). If the extension function is invoked
  11735. ** more than once for a single FTS query, then all invocations share a
  11736. ** single auxiliary data context.
  11737. **
  11738. ** If there is already an auxiliary data pointer when this function is
  11739. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  11740. ** was specified along with the original pointer, it is invoked at this
  11741. ** point.
  11742. **
  11743. ** The xDelete callback, if one is specified, is also invoked on the
  11744. ** auxiliary data pointer after the FTS5 query has finished.
  11745. **
  11746. ** If an error (e.g. an OOM condition) occurs within this function, an
  11747. ** the auxiliary data is set to NULL and an error code returned. If the
  11748. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  11749. ** pointer before returning.
  11750. **
  11751. **
  11752. ** xGetAuxdata(pFts5, bClear)
  11753. **
  11754. ** Returns the current auxiliary data pointer for the fts5 extension
  11755. ** function. See the xSetAuxdata() method for details.
  11756. **
  11757. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  11758. ** (set to NULL) before this function returns. In this case the xDelete,
  11759. ** if any, is not invoked.
  11760. **
  11761. **
  11762. ** xRowCount(pFts5, pnRow)
  11763. **
  11764. ** This function is used to retrieve the total number of rows in the table.
  11765. ** In other words, the same value that would be returned by:
  11766. **
  11767. ** SELECT count(*) FROM ftstable;
  11768. **
  11769. ** xPhraseFirst()
  11770. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  11771. ** method, to iterate through all instances of a single query phrase within
  11772. ** the current row. This is the same information as is accessible via the
  11773. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  11774. ** to use, this API may be faster under some circumstances. To iterate
  11775. ** through instances of phrase iPhrase, use the following code:
  11776. **
  11777. ** Fts5PhraseIter iter;
  11778. ** int iCol, iOff;
  11779. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  11780. ** iCol>=0;
  11781. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  11782. ** ){
  11783. ** // An instance of phrase iPhrase at offset iOff of column iCol
  11784. ** }
  11785. **
  11786. ** The Fts5PhraseIter structure is defined above. Applications should not
  11787. ** modify this structure directly - it should only be used as shown above
  11788. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  11789. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  11790. **
  11791. ** This API can be quite slow if used with an FTS5 table created with the
  11792. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  11793. ** with either "detail=none" or "detail=column" and "content=" option
  11794. ** (i.e. if it is a contentless table), then this API always iterates
  11795. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  11796. **
  11797. ** xPhraseNext()
  11798. ** See xPhraseFirst above.
  11799. **
  11800. ** xPhraseFirstColumn()
  11801. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  11802. ** and xPhraseNext() APIs described above. The difference is that instead
  11803. ** of iterating through all instances of a phrase in the current row, these
  11804. ** APIs are used to iterate through the set of columns in the current row
  11805. ** that contain one or more instances of a specified phrase. For example:
  11806. **
  11807. ** Fts5PhraseIter iter;
  11808. ** int iCol;
  11809. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  11810. ** iCol>=0;
  11811. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  11812. ** ){
  11813. ** // Column iCol contains at least one instance of phrase iPhrase
  11814. ** }
  11815. **
  11816. ** This API can be quite slow if used with an FTS5 table created with the
  11817. ** "detail=none" option. If the FTS5 table is created with either
  11818. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  11819. ** then this API always iterates through an empty set (all calls to
  11820. ** xPhraseFirstColumn() set iCol to -1).
  11821. **
  11822. ** The information accessed using this API and its companion
  11823. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  11824. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  11825. ** significantly more efficient than those alternatives when used with
  11826. ** "detail=column" tables.
  11827. **
  11828. ** xPhraseNextColumn()
  11829. ** See xPhraseFirstColumn above.
  11830. */
  11831. struct Fts5ExtensionApi {
  11832. int iVersion; /* Currently always set to 3 */
  11833. void *(*xUserData)(Fts5Context*);
  11834. int (*xColumnCount)(Fts5Context*);
  11835. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  11836. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  11837. int (*xTokenize)(Fts5Context*,
  11838. const char *pText, int nText, /* Text to tokenize */
  11839. void *pCtx, /* Context passed to xToken() */
  11840. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  11841. );
  11842. int (*xPhraseCount)(Fts5Context*);
  11843. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  11844. int (*xInstCount)(Fts5Context*, int *pnInst);
  11845. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  11846. sqlite3_int64 (*xRowid)(Fts5Context*);
  11847. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  11848. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  11849. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  11850. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  11851. );
  11852. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  11853. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  11854. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  11855. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  11856. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  11857. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  11858. };
  11859. /*
  11860. ** CUSTOM AUXILIARY FUNCTIONS
  11861. *************************************************************************/
  11862. /*************************************************************************
  11863. ** CUSTOM TOKENIZERS
  11864. **
  11865. ** Applications may also register custom tokenizer types. A tokenizer
  11866. ** is registered by providing fts5 with a populated instance of the
  11867. ** following structure. All structure methods must be defined, setting
  11868. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  11869. ** behaviour. The structure methods are expected to function as follows:
  11870. **
  11871. ** xCreate:
  11872. ** This function is used to allocate and initialize a tokenizer instance.
  11873. ** A tokenizer instance is required to actually tokenize text.
  11874. **
  11875. ** The first argument passed to this function is a copy of the (void*)
  11876. ** pointer provided by the application when the fts5_tokenizer object
  11877. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  11878. ** The second and third arguments are an array of nul-terminated strings
  11879. ** containing the tokenizer arguments, if any, specified following the
  11880. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  11881. ** to create the FTS5 table.
  11882. **
  11883. ** The final argument is an output variable. If successful, (*ppOut)
  11884. ** should be set to point to the new tokenizer handle and SQLITE_OK
  11885. ** returned. If an error occurs, some value other than SQLITE_OK should
  11886. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  11887. ** is undefined.
  11888. **
  11889. ** xDelete:
  11890. ** This function is invoked to delete a tokenizer handle previously
  11891. ** allocated using xCreate(). Fts5 guarantees that this function will
  11892. ** be invoked exactly once for each successful call to xCreate().
  11893. **
  11894. ** xTokenize:
  11895. ** This function is expected to tokenize the nText byte string indicated
  11896. ** by argument pText. pText may or may not be nul-terminated. The first
  11897. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  11898. ** returned by an earlier call to xCreate().
  11899. **
  11900. ** The second argument indicates the reason that FTS5 is requesting
  11901. ** tokenization of the supplied text. This is always one of the following
  11902. ** four values:
  11903. **
  11904. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  11905. ** or removed from the FTS table. The tokenizer is being invoked to
  11906. ** determine the set of tokens to add to (or delete from) the
  11907. ** FTS index.
  11908. **
  11909. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  11910. ** against the FTS index. The tokenizer is being called to tokenize
  11911. ** a bareword or quoted string specified as part of the query.
  11912. **
  11913. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  11914. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  11915. ** followed by a "*" character, indicating that the last token
  11916. ** returned by the tokenizer will be treated as a token prefix.
  11917. **
  11918. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  11919. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  11920. ** function. Or an fts5_api.xColumnSize() request made by the same
  11921. ** on a columnsize=0 database.
  11922. ** </ul>
  11923. **
  11924. ** For each token in the input string, the supplied callback xToken() must
  11925. ** be invoked. The first argument to it should be a copy of the pointer
  11926. ** passed as the second argument to xTokenize(). The third and fourth
  11927. ** arguments are a pointer to a buffer containing the token text, and the
  11928. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  11929. ** of the first byte of and first byte immediately following the text from
  11930. ** which the token is derived within the input.
  11931. **
  11932. ** The second argument passed to the xToken() callback ("tflags") should
  11933. ** normally be set to 0. The exception is if the tokenizer supports
  11934. ** synonyms. In this case see the discussion below for details.
  11935. **
  11936. ** FTS5 assumes the xToken() callback is invoked for each token in the
  11937. ** order that they occur within the input text.
  11938. **
  11939. ** If an xToken() callback returns any value other than SQLITE_OK, then
  11940. ** the tokenization should be abandoned and the xTokenize() method should
  11941. ** immediately return a copy of the xToken() return value. Or, if the
  11942. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  11943. ** if an error occurs with the xTokenize() implementation itself, it
  11944. ** may abandon the tokenization and return any error code other than
  11945. ** SQLITE_OK or SQLITE_DONE.
  11946. **
  11947. ** SYNONYM SUPPORT
  11948. **
  11949. ** Custom tokenizers may also support synonyms. Consider a case in which a
  11950. ** user wishes to query for a phrase such as "first place". Using the
  11951. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  11952. ** of "first place" within the document set, but not alternative forms
  11953. ** such as "1st place". In some applications, it would be better to match
  11954. ** all instances of "first place" or "1st place" regardless of which form
  11955. ** the user specified in the MATCH query text.
  11956. **
  11957. ** There are several ways to approach this in FTS5:
  11958. **
  11959. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  11960. ** In the above example, this means that the tokenizer returns the
  11961. ** same token for inputs "first" and "1st". Say that token is in
  11962. ** fact "first", so that when the user inserts the document "I won
  11963. ** 1st place" entries are added to the index for tokens "i", "won",
  11964. ** "first" and "place". If the user then queries for '1st + place',
  11965. ** the tokenizer substitutes "first" for "1st" and the query works
  11966. ** as expected.
  11967. **
  11968. ** <li> By adding multiple synonyms for a single term to the FTS index.
  11969. ** In this case, when tokenizing query text, the tokenizer may
  11970. ** provide multiple synonyms for a single term within the document.
  11971. ** FTS5 then queries the index for each synonym individually. For
  11972. ** example, faced with the query:
  11973. **
  11974. ** <codeblock>
  11975. ** ... MATCH 'first place'</codeblock>
  11976. **
  11977. ** the tokenizer offers both "1st" and "first" as synonyms for the
  11978. ** first token in the MATCH query and FTS5 effectively runs a query
  11979. ** similar to:
  11980. **
  11981. ** <codeblock>
  11982. ** ... MATCH '(first OR 1st) place'</codeblock>
  11983. **
  11984. ** except that, for the purposes of auxiliary functions, the query
  11985. ** still appears to contain just two phrases - "(first OR 1st)"
  11986. ** being treated as a single phrase.
  11987. **
  11988. ** <li> By adding multiple synonyms for a single term to the FTS index.
  11989. ** Using this method, when tokenizing document text, the tokenizer
  11990. ** provides multiple synonyms for each token. So that when a
  11991. ** document such as "I won first place" is tokenized, entries are
  11992. ** added to the FTS index for "i", "won", "first", "1st" and
  11993. ** "place".
  11994. **
  11995. ** This way, even if the tokenizer does not provide synonyms
  11996. ** when tokenizing query text (it should not - to do would be
  11997. ** inefficient), it doesn't matter if the user queries for
  11998. ** 'first + place' or '1st + place', as there are entires in the
  11999. ** FTS index corresponding to both forms of the first token.
  12000. ** </ol>
  12001. **
  12002. ** Whether it is parsing document or query text, any call to xToken that
  12003. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  12004. ** is considered to supply a synonym for the previous token. For example,
  12005. ** when parsing the document "I won first place", a tokenizer that supports
  12006. ** synonyms would call xToken() 5 times, as follows:
  12007. **
  12008. ** <codeblock>
  12009. ** xToken(pCtx, 0, "i", 1, 0, 1);
  12010. ** xToken(pCtx, 0, "won", 3, 2, 5);
  12011. ** xToken(pCtx, 0, "first", 5, 6, 11);
  12012. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  12013. ** xToken(pCtx, 0, "place", 5, 12, 17);
  12014. **</codeblock>
  12015. **
  12016. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  12017. ** xToken() is called. Multiple synonyms may be specified for a single token
  12018. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  12019. ** There is no limit to the number of synonyms that may be provided for a
  12020. ** single token.
  12021. **
  12022. ** In many cases, method (1) above is the best approach. It does not add
  12023. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  12024. ** so it is efficient in terms of disk space and query speed. However, it
  12025. ** does not support prefix queries very well. If, as suggested above, the
  12026. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  12027. **
  12028. ** <codeblock>
  12029. ** ... MATCH '1s*'</codeblock>
  12030. **
  12031. ** will not match documents that contain the token "1st" (as the tokenizer
  12032. ** will probably not map "1s" to any prefix of "first").
  12033. **
  12034. ** For full prefix support, method (3) may be preferred. In this case,
  12035. ** because the index contains entries for both "first" and "1st", prefix
  12036. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  12037. ** extra entries are added to the FTS index, this method uses more space
  12038. ** within the database.
  12039. **
  12040. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  12041. ** a query such as '1s*' will match documents that contain the literal
  12042. ** token "1st", but not "first" (assuming the tokenizer is not able to
  12043. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  12044. ** will match against "1st" and "first". This method does not require
  12045. ** extra disk space, as no extra entries are added to the FTS index.
  12046. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  12047. ** as separate queries of the FTS index are required for each synonym.
  12048. **
  12049. ** When using methods (2) or (3), it is important that the tokenizer only
  12050. ** provide synonyms when tokenizing document text (method (2)) or query
  12051. ** text (method (3)), not both. Doing so will not cause any errors, but is
  12052. ** inefficient.
  12053. */
  12054. typedef struct Fts5Tokenizer Fts5Tokenizer;
  12055. typedef struct fts5_tokenizer fts5_tokenizer;
  12056. struct fts5_tokenizer {
  12057. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  12058. void (*xDelete)(Fts5Tokenizer*);
  12059. int (*xTokenize)(Fts5Tokenizer*,
  12060. void *pCtx,
  12061. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  12062. const char *pText, int nText,
  12063. int (*xToken)(
  12064. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  12065. int tflags, /* Mask of FTS5_TOKEN_* flags */
  12066. const char *pToken, /* Pointer to buffer containing token */
  12067. int nToken, /* Size of token in bytes */
  12068. int iStart, /* Byte offset of token within input text */
  12069. int iEnd /* Byte offset of end of token within input text */
  12070. )
  12071. );
  12072. };
  12073. /* Flags that may be passed as the third argument to xTokenize() */
  12074. #define FTS5_TOKENIZE_QUERY 0x0001
  12075. #define FTS5_TOKENIZE_PREFIX 0x0002
  12076. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  12077. #define FTS5_TOKENIZE_AUX 0x0008
  12078. /* Flags that may be passed by the tokenizer implementation back to FTS5
  12079. ** as the third argument to the supplied xToken callback. */
  12080. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  12081. /*
  12082. ** END OF CUSTOM TOKENIZERS
  12083. *************************************************************************/
  12084. /*************************************************************************
  12085. ** FTS5 EXTENSION REGISTRATION API
  12086. */
  12087. typedef struct fts5_api fts5_api;
  12088. struct fts5_api {
  12089. int iVersion; /* Currently always set to 2 */
  12090. /* Create a new tokenizer */
  12091. int (*xCreateTokenizer)(
  12092. fts5_api *pApi,
  12093. const char *zName,
  12094. void *pContext,
  12095. fts5_tokenizer *pTokenizer,
  12096. void (*xDestroy)(void*)
  12097. );
  12098. /* Find an existing tokenizer */
  12099. int (*xFindTokenizer)(
  12100. fts5_api *pApi,
  12101. const char *zName,
  12102. void **ppContext,
  12103. fts5_tokenizer *pTokenizer
  12104. );
  12105. /* Create a new auxiliary function */
  12106. int (*xCreateFunction)(
  12107. fts5_api *pApi,
  12108. const char *zName,
  12109. void *pContext,
  12110. fts5_extension_function xFunction,
  12111. void (*xDestroy)(void*)
  12112. );
  12113. };
  12114. /*
  12115. ** END OF REGISTRATION API
  12116. *************************************************************************/
  12117. #if 0
  12118. } /* end of the 'extern "C"' block */
  12119. #endif
  12120. #endif /* _FTS5_H */
  12121. /******** End of fts5.h *********/
  12122. /************** End of sqlite3.h *********************************************/
  12123. /************** Continuing where we left off in sqliteInt.h ******************/
  12124. /*
  12125. ** Include the configuration header output by 'configure' if we're using the
  12126. ** autoconf-based build
  12127. */
  12128. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  12129. /* #include "config.h" */
  12130. #define SQLITECONFIG_H 1
  12131. #endif
  12132. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  12133. /************** Begin file sqliteLimit.h *************************************/
  12134. /*
  12135. ** 2007 May 7
  12136. **
  12137. ** The author disclaims copyright to this source code. In place of
  12138. ** a legal notice, here is a blessing:
  12139. **
  12140. ** May you do good and not evil.
  12141. ** May you find forgiveness for yourself and forgive others.
  12142. ** May you share freely, never taking more than you give.
  12143. **
  12144. *************************************************************************
  12145. **
  12146. ** This file defines various limits of what SQLite can process.
  12147. */
  12148. /*
  12149. ** The maximum length of a TEXT or BLOB in bytes. This also
  12150. ** limits the size of a row in a table or index.
  12151. **
  12152. ** The hard limit is the ability of a 32-bit signed integer
  12153. ** to count the size: 2^31-1 or 2147483647.
  12154. */
  12155. #ifndef SQLITE_MAX_LENGTH
  12156. # define SQLITE_MAX_LENGTH 1000000000
  12157. #endif
  12158. /*
  12159. ** This is the maximum number of
  12160. **
  12161. ** * Columns in a table
  12162. ** * Columns in an index
  12163. ** * Columns in a view
  12164. ** * Terms in the SET clause of an UPDATE statement
  12165. ** * Terms in the result set of a SELECT statement
  12166. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  12167. ** * Terms in the VALUES clause of an INSERT statement
  12168. **
  12169. ** The hard upper limit here is 32676. Most database people will
  12170. ** tell you that in a well-normalized database, you usually should
  12171. ** not have more than a dozen or so columns in any table. And if
  12172. ** that is the case, there is no point in having more than a few
  12173. ** dozen values in any of the other situations described above.
  12174. */
  12175. #ifndef SQLITE_MAX_COLUMN
  12176. # define SQLITE_MAX_COLUMN 2000
  12177. #endif
  12178. /*
  12179. ** The maximum length of a single SQL statement in bytes.
  12180. **
  12181. ** It used to be the case that setting this value to zero would
  12182. ** turn the limit off. That is no longer true. It is not possible
  12183. ** to turn this limit off.
  12184. */
  12185. #ifndef SQLITE_MAX_SQL_LENGTH
  12186. # define SQLITE_MAX_SQL_LENGTH 1000000000
  12187. #endif
  12188. /*
  12189. ** The maximum depth of an expression tree. This is limited to
  12190. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  12191. ** want to place more severe limits on the complexity of an
  12192. ** expression.
  12193. **
  12194. ** A value of 0 used to mean that the limit was not enforced.
  12195. ** But that is no longer true. The limit is now strictly enforced
  12196. ** at all times.
  12197. */
  12198. #ifndef SQLITE_MAX_EXPR_DEPTH
  12199. # define SQLITE_MAX_EXPR_DEPTH 1000
  12200. #endif
  12201. /*
  12202. ** The maximum number of terms in a compound SELECT statement.
  12203. ** The code generator for compound SELECT statements does one
  12204. ** level of recursion for each term. A stack overflow can result
  12205. ** if the number of terms is too large. In practice, most SQL
  12206. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  12207. ** any limit on the number of terms in a compount SELECT.
  12208. */
  12209. #ifndef SQLITE_MAX_COMPOUND_SELECT
  12210. # define SQLITE_MAX_COMPOUND_SELECT 500
  12211. #endif
  12212. /*
  12213. ** The maximum number of opcodes in a VDBE program.
  12214. ** Not currently enforced.
  12215. */
  12216. #ifndef SQLITE_MAX_VDBE_OP
  12217. # define SQLITE_MAX_VDBE_OP 250000000
  12218. #endif
  12219. /*
  12220. ** The maximum number of arguments to an SQL function.
  12221. */
  12222. #ifndef SQLITE_MAX_FUNCTION_ARG
  12223. # define SQLITE_MAX_FUNCTION_ARG 127
  12224. #endif
  12225. /*
  12226. ** The suggested maximum number of in-memory pages to use for
  12227. ** the main database table and for temporary tables.
  12228. **
  12229. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  12230. ** which means the cache size is limited to 2048000 bytes of memory.
  12231. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  12232. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  12233. */
  12234. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  12235. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  12236. #endif
  12237. /*
  12238. ** The default number of frames to accumulate in the log file before
  12239. ** checkpointing the database in WAL mode.
  12240. */
  12241. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  12242. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  12243. #endif
  12244. /*
  12245. ** The maximum number of attached databases. This must be between 0
  12246. ** and 125. The upper bound of 125 is because the attached databases are
  12247. ** counted using a signed 8-bit integer which has a maximum value of 127
  12248. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  12249. */
  12250. #ifndef SQLITE_MAX_ATTACHED
  12251. # define SQLITE_MAX_ATTACHED 10
  12252. #endif
  12253. /*
  12254. ** The maximum value of a ?nnn wildcard that the parser will accept.
  12255. */
  12256. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  12257. # define SQLITE_MAX_VARIABLE_NUMBER 999
  12258. #endif
  12259. /* Maximum page size. The upper bound on this value is 65536. This a limit
  12260. ** imposed by the use of 16-bit offsets within each page.
  12261. **
  12262. ** Earlier versions of SQLite allowed the user to change this value at
  12263. ** compile time. This is no longer permitted, on the grounds that it creates
  12264. ** a library that is technically incompatible with an SQLite library
  12265. ** compiled with a different limit. If a process operating on a database
  12266. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  12267. ** compiled with the default page-size limit will not be able to rollback
  12268. ** the aborted transaction. This could lead to database corruption.
  12269. */
  12270. #ifdef SQLITE_MAX_PAGE_SIZE
  12271. # undef SQLITE_MAX_PAGE_SIZE
  12272. #endif
  12273. #define SQLITE_MAX_PAGE_SIZE 65536
  12274. /*
  12275. ** The default size of a database page.
  12276. */
  12277. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  12278. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  12279. #endif
  12280. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12281. # undef SQLITE_DEFAULT_PAGE_SIZE
  12282. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12283. #endif
  12284. /*
  12285. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  12286. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  12287. ** device characteristics (sector-size and atomic write() support),
  12288. ** SQLite may choose a larger value. This constant is the maximum value
  12289. ** SQLite will choose on its own.
  12290. */
  12291. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12292. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  12293. #endif
  12294. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12295. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12296. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12297. #endif
  12298. /*
  12299. ** Maximum number of pages in one database file.
  12300. **
  12301. ** This is really just the default value for the max_page_count pragma.
  12302. ** This value can be lowered (or raised) at run-time using that the
  12303. ** max_page_count macro.
  12304. */
  12305. #ifndef SQLITE_MAX_PAGE_COUNT
  12306. # define SQLITE_MAX_PAGE_COUNT 1073741823
  12307. #endif
  12308. /*
  12309. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  12310. ** operator.
  12311. */
  12312. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  12313. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  12314. #endif
  12315. /*
  12316. ** Maximum depth of recursion for triggers.
  12317. **
  12318. ** A value of 1 means that a trigger program will not be able to itself
  12319. ** fire any triggers. A value of 0 means that no trigger programs at all
  12320. ** may be executed.
  12321. */
  12322. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  12323. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  12324. #endif
  12325. /************** End of sqliteLimit.h *****************************************/
  12326. /************** Continuing where we left off in sqliteInt.h ******************/
  12327. /* Disable nuisance warnings on Borland compilers */
  12328. #if defined(__BORLANDC__)
  12329. #pragma warn -rch /* unreachable code */
  12330. #pragma warn -ccc /* Condition is always true or false */
  12331. #pragma warn -aus /* Assigned value is never used */
  12332. #pragma warn -csu /* Comparing signed and unsigned */
  12333. #pragma warn -spa /* Suspicious pointer arithmetic */
  12334. #endif
  12335. /*
  12336. ** Include standard header files as necessary
  12337. */
  12338. #ifdef HAVE_STDINT_H
  12339. #include <stdint.h>
  12340. #endif
  12341. #ifdef HAVE_INTTYPES_H
  12342. #include <inttypes.h>
  12343. #endif
  12344. /*
  12345. ** The following macros are used to cast pointers to integers and
  12346. ** integers to pointers. The way you do this varies from one compiler
  12347. ** to the next, so we have developed the following set of #if statements
  12348. ** to generate appropriate macros for a wide range of compilers.
  12349. **
  12350. ** The correct "ANSI" way to do this is to use the intptr_t type.
  12351. ** Unfortunately, that typedef is not available on all compilers, or
  12352. ** if it is available, it requires an #include of specific headers
  12353. ** that vary from one machine to the next.
  12354. **
  12355. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  12356. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  12357. ** So we have to define the macros in different ways depending on the
  12358. ** compiler.
  12359. */
  12360. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  12361. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  12362. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  12363. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  12364. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  12365. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  12366. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  12367. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  12368. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  12369. #else /* Generates a warning - but it always works */
  12370. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  12371. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  12372. #endif
  12373. /*
  12374. ** A macro to hint to the compiler that a function should not be
  12375. ** inlined.
  12376. */
  12377. #if defined(__GNUC__)
  12378. # define SQLITE_NOINLINE __attribute__((noinline))
  12379. #elif defined(_MSC_VER) && _MSC_VER>=1310
  12380. # define SQLITE_NOINLINE __declspec(noinline)
  12381. #else
  12382. # define SQLITE_NOINLINE
  12383. #endif
  12384. /*
  12385. ** Make sure that the compiler intrinsics we desire are enabled when
  12386. ** compiling with an appropriate version of MSVC unless prevented by
  12387. ** the SQLITE_DISABLE_INTRINSIC define.
  12388. */
  12389. #if !defined(SQLITE_DISABLE_INTRINSIC)
  12390. # if defined(_MSC_VER) && _MSC_VER>=1400
  12391. # if !defined(_WIN32_WCE)
  12392. # include <intrin.h>
  12393. # pragma intrinsic(_byteswap_ushort)
  12394. # pragma intrinsic(_byteswap_ulong)
  12395. # pragma intrinsic(_byteswap_uint64)
  12396. # pragma intrinsic(_ReadWriteBarrier)
  12397. # else
  12398. # include <cmnintrin.h>
  12399. # endif
  12400. # endif
  12401. #endif
  12402. /*
  12403. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  12404. ** 0 means mutexes are permanently disable and the library is never
  12405. ** threadsafe. 1 means the library is serialized which is the highest
  12406. ** level of threadsafety. 2 means the library is multithreaded - multiple
  12407. ** threads can use SQLite as long as no two threads try to use the same
  12408. ** database connection at the same time.
  12409. **
  12410. ** Older versions of SQLite used an optional THREADSAFE macro.
  12411. ** We support that for legacy.
  12412. **
  12413. ** To ensure that the correct value of "THREADSAFE" is reported when querying
  12414. ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
  12415. ** logic is partially replicated in ctime.c. If it is updated here, it should
  12416. ** also be updated there.
  12417. */
  12418. #if !defined(SQLITE_THREADSAFE)
  12419. # if defined(THREADSAFE)
  12420. # define SQLITE_THREADSAFE THREADSAFE
  12421. # else
  12422. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  12423. # endif
  12424. #endif
  12425. /*
  12426. ** Powersafe overwrite is on by default. But can be turned off using
  12427. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  12428. */
  12429. #ifndef SQLITE_POWERSAFE_OVERWRITE
  12430. # define SQLITE_POWERSAFE_OVERWRITE 1
  12431. #endif
  12432. /*
  12433. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  12434. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  12435. ** which case memory allocation statistics are disabled by default.
  12436. */
  12437. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  12438. # define SQLITE_DEFAULT_MEMSTATUS 1
  12439. #endif
  12440. /*
  12441. ** Exactly one of the following macros must be defined in order to
  12442. ** specify which memory allocation subsystem to use.
  12443. **
  12444. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  12445. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  12446. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  12447. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  12448. **
  12449. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  12450. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  12451. ** will cause HeapValidate to be called. If heap validation should fail, an
  12452. ** assertion will be triggered.
  12453. **
  12454. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  12455. ** the default.
  12456. */
  12457. #if defined(SQLITE_SYSTEM_MALLOC) \
  12458. + defined(SQLITE_WIN32_MALLOC) \
  12459. + defined(SQLITE_ZERO_MALLOC) \
  12460. + defined(SQLITE_MEMDEBUG)>1
  12461. # error "Two or more of the following compile-time configuration options\
  12462. are defined but at most one is allowed:\
  12463. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  12464. SQLITE_ZERO_MALLOC"
  12465. #endif
  12466. #if defined(SQLITE_SYSTEM_MALLOC) \
  12467. + defined(SQLITE_WIN32_MALLOC) \
  12468. + defined(SQLITE_ZERO_MALLOC) \
  12469. + defined(SQLITE_MEMDEBUG)==0
  12470. # define SQLITE_SYSTEM_MALLOC 1
  12471. #endif
  12472. /*
  12473. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  12474. ** sizes of memory allocations below this value where possible.
  12475. */
  12476. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  12477. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  12478. #endif
  12479. /*
  12480. ** We need to define _XOPEN_SOURCE as follows in order to enable
  12481. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  12482. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  12483. ** it.
  12484. */
  12485. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  12486. # define _XOPEN_SOURCE 600
  12487. #endif
  12488. /*
  12489. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  12490. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  12491. ** make it true by defining or undefining NDEBUG.
  12492. **
  12493. ** Setting NDEBUG makes the code smaller and faster by disabling the
  12494. ** assert() statements in the code. So we want the default action
  12495. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  12496. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  12497. ** feature.
  12498. */
  12499. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  12500. # define NDEBUG 1
  12501. #endif
  12502. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  12503. # undef NDEBUG
  12504. #endif
  12505. /*
  12506. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  12507. */
  12508. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  12509. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  12510. #endif
  12511. /*
  12512. ** The testcase() macro is used to aid in coverage testing. When
  12513. ** doing coverage testing, the condition inside the argument to
  12514. ** testcase() must be evaluated both true and false in order to
  12515. ** get full branch coverage. The testcase() macro is inserted
  12516. ** to help ensure adequate test coverage in places where simple
  12517. ** condition/decision coverage is inadequate. For example, testcase()
  12518. ** can be used to make sure boundary values are tested. For
  12519. ** bitmask tests, testcase() can be used to make sure each bit
  12520. ** is significant and used at least once. On switch statements
  12521. ** where multiple cases go to the same block of code, testcase()
  12522. ** can insure that all cases are evaluated.
  12523. **
  12524. */
  12525. #ifdef SQLITE_COVERAGE_TEST
  12526. SQLITE_PRIVATE void sqlite3Coverage(int);
  12527. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  12528. #else
  12529. # define testcase(X)
  12530. #endif
  12531. /*
  12532. ** The TESTONLY macro is used to enclose variable declarations or
  12533. ** other bits of code that are needed to support the arguments
  12534. ** within testcase() and assert() macros.
  12535. */
  12536. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  12537. # define TESTONLY(X) X
  12538. #else
  12539. # define TESTONLY(X)
  12540. #endif
  12541. /*
  12542. ** Sometimes we need a small amount of code such as a variable initialization
  12543. ** to setup for a later assert() statement. We do not want this code to
  12544. ** appear when assert() is disabled. The following macro is therefore
  12545. ** used to contain that setup code. The "VVA" acronym stands for
  12546. ** "Verification, Validation, and Accreditation". In other words, the
  12547. ** code within VVA_ONLY() will only run during verification processes.
  12548. */
  12549. #ifndef NDEBUG
  12550. # define VVA_ONLY(X) X
  12551. #else
  12552. # define VVA_ONLY(X)
  12553. #endif
  12554. /*
  12555. ** The ALWAYS and NEVER macros surround boolean expressions which
  12556. ** are intended to always be true or false, respectively. Such
  12557. ** expressions could be omitted from the code completely. But they
  12558. ** are included in a few cases in order to enhance the resilience
  12559. ** of SQLite to unexpected behavior - to make the code "self-healing"
  12560. ** or "ductile" rather than being "brittle" and crashing at the first
  12561. ** hint of unplanned behavior.
  12562. **
  12563. ** In other words, ALWAYS and NEVER are added for defensive code.
  12564. **
  12565. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  12566. ** be true and false so that the unreachable code they specify will
  12567. ** not be counted as untested code.
  12568. */
  12569. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  12570. # define ALWAYS(X) (1)
  12571. # define NEVER(X) (0)
  12572. #elif !defined(NDEBUG)
  12573. # define ALWAYS(X) ((X)?1:(assert(0),0))
  12574. # define NEVER(X) ((X)?(assert(0),1):0)
  12575. #else
  12576. # define ALWAYS(X) (X)
  12577. # define NEVER(X) (X)
  12578. #endif
  12579. /*
  12580. ** Some conditionals are optimizations only. In other words, if the
  12581. ** conditionals are replaced with a constant 1 (true) or 0 (false) then
  12582. ** the correct answer is still obtained, though perhaps not as quickly.
  12583. **
  12584. ** The following macros mark these optimizations conditionals.
  12585. */
  12586. #if defined(SQLITE_MUTATION_TEST)
  12587. # define OK_IF_ALWAYS_TRUE(X) (1)
  12588. # define OK_IF_ALWAYS_FALSE(X) (0)
  12589. #else
  12590. # define OK_IF_ALWAYS_TRUE(X) (X)
  12591. # define OK_IF_ALWAYS_FALSE(X) (X)
  12592. #endif
  12593. /*
  12594. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  12595. ** defined. We need to defend against those failures when testing with
  12596. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  12597. ** during a normal build. The following macro can be used to disable tests
  12598. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  12599. */
  12600. #if defined(SQLITE_TEST_REALLOC_STRESS)
  12601. # define ONLY_IF_REALLOC_STRESS(X) (X)
  12602. #elif !defined(NDEBUG)
  12603. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  12604. #else
  12605. # define ONLY_IF_REALLOC_STRESS(X) (0)
  12606. #endif
  12607. /*
  12608. ** Declarations used for tracing the operating system interfaces.
  12609. */
  12610. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  12611. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12612. extern int sqlite3OSTrace;
  12613. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  12614. # define SQLITE_HAVE_OS_TRACE
  12615. #else
  12616. # define OSTRACE(X)
  12617. # undef SQLITE_HAVE_OS_TRACE
  12618. #endif
  12619. /*
  12620. ** Is the sqlite3ErrName() function needed in the build? Currently,
  12621. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  12622. ** OSTRACE is enabled), and by several "test*.c" files (which are
  12623. ** compiled using SQLITE_TEST).
  12624. */
  12625. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  12626. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12627. # define SQLITE_NEED_ERR_NAME
  12628. #else
  12629. # undef SQLITE_NEED_ERR_NAME
  12630. #endif
  12631. /*
  12632. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  12633. */
  12634. #ifdef SQLITE_OMIT_EXPLAIN
  12635. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12636. #endif
  12637. /*
  12638. ** Return true (non-zero) if the input is an integer that is too large
  12639. ** to fit in 32-bits. This macro is used inside of various testcase()
  12640. ** macros to verify that we have tested SQLite for large-file support.
  12641. */
  12642. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  12643. /*
  12644. ** The macro unlikely() is a hint that surrounds a boolean
  12645. ** expression that is usually false. Macro likely() surrounds
  12646. ** a boolean expression that is usually true. These hints could,
  12647. ** in theory, be used by the compiler to generate better code, but
  12648. ** currently they are just comments for human readers.
  12649. */
  12650. #define likely(X) (X)
  12651. #define unlikely(X) (X)
  12652. /************** Include hash.h in the middle of sqliteInt.h ******************/
  12653. /************** Begin file hash.h ********************************************/
  12654. /*
  12655. ** 2001 September 22
  12656. **
  12657. ** The author disclaims copyright to this source code. In place of
  12658. ** a legal notice, here is a blessing:
  12659. **
  12660. ** May you do good and not evil.
  12661. ** May you find forgiveness for yourself and forgive others.
  12662. ** May you share freely, never taking more than you give.
  12663. **
  12664. *************************************************************************
  12665. ** This is the header file for the generic hash-table implementation
  12666. ** used in SQLite.
  12667. */
  12668. #ifndef SQLITE_HASH_H
  12669. #define SQLITE_HASH_H
  12670. /* Forward declarations of structures. */
  12671. typedef struct Hash Hash;
  12672. typedef struct HashElem HashElem;
  12673. /* A complete hash table is an instance of the following structure.
  12674. ** The internals of this structure are intended to be opaque -- client
  12675. ** code should not attempt to access or modify the fields of this structure
  12676. ** directly. Change this structure only by using the routines below.
  12677. ** However, some of the "procedures" and "functions" for modifying and
  12678. ** accessing this structure are really macros, so we can't really make
  12679. ** this structure opaque.
  12680. **
  12681. ** All elements of the hash table are on a single doubly-linked list.
  12682. ** Hash.first points to the head of this list.
  12683. **
  12684. ** There are Hash.htsize buckets. Each bucket points to a spot in
  12685. ** the global doubly-linked list. The contents of the bucket are the
  12686. ** element pointed to plus the next _ht.count-1 elements in the list.
  12687. **
  12688. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  12689. ** by a linear search of the global list. For small tables, the
  12690. ** Hash.ht table is never allocated because if there are few elements
  12691. ** in the table, it is faster to do a linear search than to manage
  12692. ** the hash table.
  12693. */
  12694. struct Hash {
  12695. unsigned int htsize; /* Number of buckets in the hash table */
  12696. unsigned int count; /* Number of entries in this table */
  12697. HashElem *first; /* The first element of the array */
  12698. struct _ht { /* the hash table */
  12699. int count; /* Number of entries with this hash */
  12700. HashElem *chain; /* Pointer to first entry with this hash */
  12701. } *ht;
  12702. };
  12703. /* Each element in the hash table is an instance of the following
  12704. ** structure. All elements are stored on a single doubly-linked list.
  12705. **
  12706. ** Again, this structure is intended to be opaque, but it can't really
  12707. ** be opaque because it is used by macros.
  12708. */
  12709. struct HashElem {
  12710. HashElem *next, *prev; /* Next and previous elements in the table */
  12711. void *data; /* Data associated with this element */
  12712. const char *pKey; /* Key associated with this element */
  12713. };
  12714. /*
  12715. ** Access routines. To delete, insert a NULL pointer.
  12716. */
  12717. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  12718. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  12719. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  12720. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  12721. /*
  12722. ** Macros for looping over all elements of a hash table. The idiom is
  12723. ** like this:
  12724. **
  12725. ** Hash h;
  12726. ** HashElem *p;
  12727. ** ...
  12728. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  12729. ** SomeStructure *pData = sqliteHashData(p);
  12730. ** // do something with pData
  12731. ** }
  12732. */
  12733. #define sqliteHashFirst(H) ((H)->first)
  12734. #define sqliteHashNext(E) ((E)->next)
  12735. #define sqliteHashData(E) ((E)->data)
  12736. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  12737. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  12738. /*
  12739. ** Number of entries in a hash table
  12740. */
  12741. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  12742. #endif /* SQLITE_HASH_H */
  12743. /************** End of hash.h ************************************************/
  12744. /************** Continuing where we left off in sqliteInt.h ******************/
  12745. /************** Include parse.h in the middle of sqliteInt.h *****************/
  12746. /************** Begin file parse.h *******************************************/
  12747. #define TK_SEMI 1
  12748. #define TK_EXPLAIN 2
  12749. #define TK_QUERY 3
  12750. #define TK_PLAN 4
  12751. #define TK_BEGIN 5
  12752. #define TK_TRANSACTION 6
  12753. #define TK_DEFERRED 7
  12754. #define TK_IMMEDIATE 8
  12755. #define TK_EXCLUSIVE 9
  12756. #define TK_COMMIT 10
  12757. #define TK_END 11
  12758. #define TK_ROLLBACK 12
  12759. #define TK_SAVEPOINT 13
  12760. #define TK_RELEASE 14
  12761. #define TK_TO 15
  12762. #define TK_TABLE 16
  12763. #define TK_CREATE 17
  12764. #define TK_IF 18
  12765. #define TK_NOT 19
  12766. #define TK_EXISTS 20
  12767. #define TK_TEMP 21
  12768. #define TK_LP 22
  12769. #define TK_RP 23
  12770. #define TK_AS 24
  12771. #define TK_WITHOUT 25
  12772. #define TK_COMMA 26
  12773. #define TK_ABORT 27
  12774. #define TK_ACTION 28
  12775. #define TK_AFTER 29
  12776. #define TK_ANALYZE 30
  12777. #define TK_ASC 31
  12778. #define TK_ATTACH 32
  12779. #define TK_BEFORE 33
  12780. #define TK_BY 34
  12781. #define TK_CASCADE 35
  12782. #define TK_CAST 36
  12783. #define TK_CONFLICT 37
  12784. #define TK_DATABASE 38
  12785. #define TK_DESC 39
  12786. #define TK_DETACH 40
  12787. #define TK_EACH 41
  12788. #define TK_FAIL 42
  12789. #define TK_OR 43
  12790. #define TK_AND 44
  12791. #define TK_IS 45
  12792. #define TK_MATCH 46
  12793. #define TK_LIKE_KW 47
  12794. #define TK_BETWEEN 48
  12795. #define TK_IN 49
  12796. #define TK_ISNULL 50
  12797. #define TK_NOTNULL 51
  12798. #define TK_NE 52
  12799. #define TK_EQ 53
  12800. #define TK_GT 54
  12801. #define TK_LE 55
  12802. #define TK_LT 56
  12803. #define TK_GE 57
  12804. #define TK_ESCAPE 58
  12805. #define TK_ID 59
  12806. #define TK_COLUMNKW 60
  12807. #define TK_DO 61
  12808. #define TK_FOR 62
  12809. #define TK_IGNORE 63
  12810. #define TK_INITIALLY 64
  12811. #define TK_INSTEAD 65
  12812. #define TK_NO 66
  12813. #define TK_KEY 67
  12814. #define TK_OF 68
  12815. #define TK_OFFSET 69
  12816. #define TK_PRAGMA 70
  12817. #define TK_RAISE 71
  12818. #define TK_RECURSIVE 72
  12819. #define TK_REPLACE 73
  12820. #define TK_RESTRICT 74
  12821. #define TK_ROW 75
  12822. #define TK_TRIGGER 76
  12823. #define TK_VACUUM 77
  12824. #define TK_VIEW 78
  12825. #define TK_VIRTUAL 79
  12826. #define TK_WITH 80
  12827. #define TK_REINDEX 81
  12828. #define TK_RENAME 82
  12829. #define TK_CTIME_KW 83
  12830. #define TK_ANY 84
  12831. #define TK_BITAND 85
  12832. #define TK_BITOR 86
  12833. #define TK_LSHIFT 87
  12834. #define TK_RSHIFT 88
  12835. #define TK_PLUS 89
  12836. #define TK_MINUS 90
  12837. #define TK_STAR 91
  12838. #define TK_SLASH 92
  12839. #define TK_REM 93
  12840. #define TK_CONCAT 94
  12841. #define TK_COLLATE 95
  12842. #define TK_BITNOT 96
  12843. #define TK_ON 97
  12844. #define TK_INDEXED 98
  12845. #define TK_STRING 99
  12846. #define TK_JOIN_KW 100
  12847. #define TK_CONSTRAINT 101
  12848. #define TK_DEFAULT 102
  12849. #define TK_NULL 103
  12850. #define TK_PRIMARY 104
  12851. #define TK_UNIQUE 105
  12852. #define TK_CHECK 106
  12853. #define TK_REFERENCES 107
  12854. #define TK_AUTOINCR 108
  12855. #define TK_INSERT 109
  12856. #define TK_DELETE 110
  12857. #define TK_UPDATE 111
  12858. #define TK_SET 112
  12859. #define TK_DEFERRABLE 113
  12860. #define TK_FOREIGN 114
  12861. #define TK_DROP 115
  12862. #define TK_UNION 116
  12863. #define TK_ALL 117
  12864. #define TK_EXCEPT 118
  12865. #define TK_INTERSECT 119
  12866. #define TK_SELECT 120
  12867. #define TK_VALUES 121
  12868. #define TK_DISTINCT 122
  12869. #define TK_DOT 123
  12870. #define TK_FROM 124
  12871. #define TK_JOIN 125
  12872. #define TK_USING 126
  12873. #define TK_ORDER 127
  12874. #define TK_GROUP 128
  12875. #define TK_HAVING 129
  12876. #define TK_LIMIT 130
  12877. #define TK_WHERE 131
  12878. #define TK_INTO 132
  12879. #define TK_NOTHING 133
  12880. #define TK_FLOAT 134
  12881. #define TK_BLOB 135
  12882. #define TK_INTEGER 136
  12883. #define TK_VARIABLE 137
  12884. #define TK_CASE 138
  12885. #define TK_WHEN 139
  12886. #define TK_THEN 140
  12887. #define TK_ELSE 141
  12888. #define TK_INDEX 142
  12889. #define TK_ALTER 143
  12890. #define TK_ADD 144
  12891. #define TK_TRUEFALSE 145
  12892. #define TK_ISNOT 146
  12893. #define TK_FUNCTION 147
  12894. #define TK_COLUMN 148
  12895. #define TK_AGG_FUNCTION 149
  12896. #define TK_AGG_COLUMN 150
  12897. #define TK_UMINUS 151
  12898. #define TK_UPLUS 152
  12899. #define TK_TRUTH 153
  12900. #define TK_REGISTER 154
  12901. #define TK_VECTOR 155
  12902. #define TK_SELECT_COLUMN 156
  12903. #define TK_IF_NULL_ROW 157
  12904. #define TK_ASTERISK 158
  12905. #define TK_SPAN 159
  12906. #define TK_END_OF_FILE 160
  12907. #define TK_UNCLOSED_STRING 161
  12908. #define TK_SPACE 162
  12909. #define TK_ILLEGAL 163
  12910. /* The token codes above must all fit in 8 bits */
  12911. #define TKFLG_MASK 0xff
  12912. /* Flags that can be added to a token code when it is not
  12913. ** being stored in a u8: */
  12914. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  12915. /************** End of parse.h ***********************************************/
  12916. /************** Continuing where we left off in sqliteInt.h ******************/
  12917. #include <stdio.h>
  12918. #include <stdlib.h>
  12919. #include <string.h>
  12920. #include <assert.h>
  12921. #include <stddef.h>
  12922. /*
  12923. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  12924. ** This allows better measurements of where memcpy() is used when running
  12925. ** cachegrind. But this macro version of memcpy() is very slow so it
  12926. ** should not be used in production. This is a performance measurement
  12927. ** hack only.
  12928. */
  12929. #ifdef SQLITE_INLINE_MEMCPY
  12930. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  12931. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  12932. #endif
  12933. /*
  12934. ** If compiling for a processor that lacks floating point support,
  12935. ** substitute integer for floating-point
  12936. */
  12937. #ifdef SQLITE_OMIT_FLOATING_POINT
  12938. # define double sqlite_int64
  12939. # define float sqlite_int64
  12940. # define LONGDOUBLE_TYPE sqlite_int64
  12941. # ifndef SQLITE_BIG_DBL
  12942. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  12943. # endif
  12944. # define SQLITE_OMIT_DATETIME_FUNCS 1
  12945. # define SQLITE_OMIT_TRACE 1
  12946. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12947. # undef SQLITE_HAVE_ISNAN
  12948. #endif
  12949. #ifndef SQLITE_BIG_DBL
  12950. # define SQLITE_BIG_DBL (1e99)
  12951. #endif
  12952. /*
  12953. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  12954. ** afterward. Having this macro allows us to cause the C compiler
  12955. ** to omit code used by TEMP tables without messy #ifndef statements.
  12956. */
  12957. #ifdef SQLITE_OMIT_TEMPDB
  12958. #define OMIT_TEMPDB 1
  12959. #else
  12960. #define OMIT_TEMPDB 0
  12961. #endif
  12962. /*
  12963. ** The "file format" number is an integer that is incremented whenever
  12964. ** the VDBE-level file format changes. The following macros define the
  12965. ** the default file format for new databases and the maximum file format
  12966. ** that the library can read.
  12967. */
  12968. #define SQLITE_MAX_FILE_FORMAT 4
  12969. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  12970. # define SQLITE_DEFAULT_FILE_FORMAT 4
  12971. #endif
  12972. /*
  12973. ** Determine whether triggers are recursive by default. This can be
  12974. ** changed at run-time using a pragma.
  12975. */
  12976. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  12977. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  12978. #endif
  12979. /*
  12980. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  12981. ** on the command-line
  12982. */
  12983. #ifndef SQLITE_TEMP_STORE
  12984. # define SQLITE_TEMP_STORE 1
  12985. #endif
  12986. /*
  12987. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  12988. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  12989. ** to zero.
  12990. */
  12991. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  12992. # undef SQLITE_MAX_WORKER_THREADS
  12993. # define SQLITE_MAX_WORKER_THREADS 0
  12994. #endif
  12995. #ifndef SQLITE_MAX_WORKER_THREADS
  12996. # define SQLITE_MAX_WORKER_THREADS 8
  12997. #endif
  12998. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  12999. # define SQLITE_DEFAULT_WORKER_THREADS 0
  13000. #endif
  13001. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  13002. # undef SQLITE_MAX_WORKER_THREADS
  13003. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  13004. #endif
  13005. /*
  13006. ** The default initial allocation for the pagecache when using separate
  13007. ** pagecaches for each database connection. A positive number is the
  13008. ** number of pages. A negative number N translations means that a buffer
  13009. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  13010. **
  13011. ** The default value of "20" was choosen to minimize the run-time of the
  13012. ** speedtest1 test program with options: --shrink-memory --reprepare
  13013. */
  13014. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  13015. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  13016. #endif
  13017. /*
  13018. ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
  13019. */
  13020. #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
  13021. # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
  13022. #endif
  13023. /*
  13024. ** The compile-time options SQLITE_MMAP_READWRITE and
  13025. ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
  13026. ** You must choose one or the other (or neither) but not both.
  13027. */
  13028. #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  13029. #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  13030. #endif
  13031. /*
  13032. ** GCC does not define the offsetof() macro so we'll have to do it
  13033. ** ourselves.
  13034. */
  13035. #ifndef offsetof
  13036. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  13037. #endif
  13038. /*
  13039. ** Macros to compute minimum and maximum of two numbers.
  13040. */
  13041. #ifndef MIN
  13042. # define MIN(A,B) ((A)<(B)?(A):(B))
  13043. #endif
  13044. #ifndef MAX
  13045. # define MAX(A,B) ((A)>(B)?(A):(B))
  13046. #endif
  13047. /*
  13048. ** Swap two objects of type TYPE.
  13049. */
  13050. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  13051. /*
  13052. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  13053. ** not, there are still machines out there that use EBCDIC.)
  13054. */
  13055. #if 'A' == '\301'
  13056. # define SQLITE_EBCDIC 1
  13057. #else
  13058. # define SQLITE_ASCII 1
  13059. #endif
  13060. /*
  13061. ** Integers of known sizes. These typedefs might change for architectures
  13062. ** where the sizes very. Preprocessor macros are available so that the
  13063. ** types can be conveniently redefined at compile-type. Like this:
  13064. **
  13065. ** cc '-DUINTPTR_TYPE=long long int' ...
  13066. */
  13067. #ifndef UINT32_TYPE
  13068. # ifdef HAVE_UINT32_T
  13069. # define UINT32_TYPE uint32_t
  13070. # else
  13071. # define UINT32_TYPE unsigned int
  13072. # endif
  13073. #endif
  13074. #ifndef UINT16_TYPE
  13075. # ifdef HAVE_UINT16_T
  13076. # define UINT16_TYPE uint16_t
  13077. # else
  13078. # define UINT16_TYPE unsigned short int
  13079. # endif
  13080. #endif
  13081. #ifndef INT16_TYPE
  13082. # ifdef HAVE_INT16_T
  13083. # define INT16_TYPE int16_t
  13084. # else
  13085. # define INT16_TYPE short int
  13086. # endif
  13087. #endif
  13088. #ifndef UINT8_TYPE
  13089. # ifdef HAVE_UINT8_T
  13090. # define UINT8_TYPE uint8_t
  13091. # else
  13092. # define UINT8_TYPE unsigned char
  13093. # endif
  13094. #endif
  13095. #ifndef INT8_TYPE
  13096. # ifdef HAVE_INT8_T
  13097. # define INT8_TYPE int8_t
  13098. # else
  13099. # define INT8_TYPE signed char
  13100. # endif
  13101. #endif
  13102. #ifndef LONGDOUBLE_TYPE
  13103. # define LONGDOUBLE_TYPE long double
  13104. #endif
  13105. typedef sqlite_int64 i64; /* 8-byte signed integer */
  13106. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  13107. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  13108. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  13109. typedef INT16_TYPE i16; /* 2-byte signed integer */
  13110. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  13111. typedef INT8_TYPE i8; /* 1-byte signed integer */
  13112. /*
  13113. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  13114. ** that can be stored in a u32 without loss of data. The value
  13115. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  13116. ** have to specify the value in the less intuitive manner shown:
  13117. */
  13118. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  13119. /*
  13120. ** The datatype used to store estimates of the number of rows in a
  13121. ** table or index. This is an unsigned integer type. For 99.9% of
  13122. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  13123. ** can be used at compile-time if desired.
  13124. */
  13125. #ifdef SQLITE_64BIT_STATS
  13126. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  13127. #else
  13128. typedef u32 tRowcnt; /* 32-bit is the default */
  13129. #endif
  13130. /*
  13131. ** Estimated quantities used for query planning are stored as 16-bit
  13132. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  13133. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  13134. ** But the allowed values are "grainy". Not every value is representable.
  13135. ** For example, quantities 16 and 17 are both represented by a LogEst
  13136. ** of 40. However, since LogEst quantities are suppose to be estimates,
  13137. ** not exact values, this imprecision is not a problem.
  13138. **
  13139. ** "LogEst" is short for "Logarithmic Estimate".
  13140. **
  13141. ** Examples:
  13142. ** 1 -> 0 20 -> 43 10000 -> 132
  13143. ** 2 -> 10 25 -> 46 25000 -> 146
  13144. ** 3 -> 16 100 -> 66 1000000 -> 199
  13145. ** 4 -> 20 1000 -> 99 1048576 -> 200
  13146. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  13147. **
  13148. ** The LogEst can be negative to indicate fractional values.
  13149. ** Examples:
  13150. **
  13151. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  13152. */
  13153. typedef INT16_TYPE LogEst;
  13154. /*
  13155. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  13156. */
  13157. #ifndef SQLITE_PTRSIZE
  13158. # if defined(__SIZEOF_POINTER__)
  13159. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  13160. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13161. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  13162. # define SQLITE_PTRSIZE 4
  13163. # else
  13164. # define SQLITE_PTRSIZE 8
  13165. # endif
  13166. #endif
  13167. /* The uptr type is an unsigned integer large enough to hold a pointer
  13168. */
  13169. #if defined(HAVE_STDINT_H)
  13170. typedef uintptr_t uptr;
  13171. #elif SQLITE_PTRSIZE==4
  13172. typedef u32 uptr;
  13173. #else
  13174. typedef u64 uptr;
  13175. #endif
  13176. /*
  13177. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  13178. ** something between S (inclusive) and E (exclusive).
  13179. **
  13180. ** In other words, S is a buffer and E is a pointer to the first byte after
  13181. ** the end of buffer S. This macro returns true if P points to something
  13182. ** contained within the buffer S.
  13183. */
  13184. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  13185. /*
  13186. ** Macros to determine whether the machine is big or little endian,
  13187. ** and whether or not that determination is run-time or compile-time.
  13188. **
  13189. ** For best performance, an attempt is made to guess at the byte-order
  13190. ** using C-preprocessor macros. If that is unsuccessful, or if
  13191. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  13192. ** at run-time.
  13193. */
  13194. #ifndef SQLITE_BYTEORDER
  13195. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13196. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  13197. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  13198. defined(__arm__)
  13199. # define SQLITE_BYTEORDER 1234
  13200. # elif defined(sparc) || defined(__ppc__)
  13201. # define SQLITE_BYTEORDER 4321
  13202. # else
  13203. # define SQLITE_BYTEORDER 0
  13204. # endif
  13205. #endif
  13206. #if SQLITE_BYTEORDER==4321
  13207. # define SQLITE_BIGENDIAN 1
  13208. # define SQLITE_LITTLEENDIAN 0
  13209. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  13210. #elif SQLITE_BYTEORDER==1234
  13211. # define SQLITE_BIGENDIAN 0
  13212. # define SQLITE_LITTLEENDIAN 1
  13213. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  13214. #else
  13215. # ifdef SQLITE_AMALGAMATION
  13216. const int sqlite3one = 1;
  13217. # else
  13218. extern const int sqlite3one;
  13219. # endif
  13220. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  13221. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  13222. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  13223. #endif
  13224. /*
  13225. ** Constants for the largest and smallest possible 64-bit signed integers.
  13226. ** These macros are designed to work correctly on both 32-bit and 64-bit
  13227. ** compilers.
  13228. */
  13229. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  13230. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  13231. /*
  13232. ** Round up a number to the next larger multiple of 8. This is used
  13233. ** to force 8-byte alignment on 64-bit architectures.
  13234. */
  13235. #define ROUND8(x) (((x)+7)&~7)
  13236. /*
  13237. ** Round down to the nearest multiple of 8
  13238. */
  13239. #define ROUNDDOWN8(x) ((x)&~7)
  13240. /*
  13241. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  13242. ** macro is used only within assert() to verify that the code gets
  13243. ** all alignment restrictions correct.
  13244. **
  13245. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  13246. ** underlying malloc() implementation might return us 4-byte aligned
  13247. ** pointers. In that case, only verify 4-byte alignment.
  13248. */
  13249. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  13250. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  13251. #else
  13252. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  13253. #endif
  13254. /*
  13255. ** Disable MMAP on platforms where it is known to not work
  13256. */
  13257. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  13258. # undef SQLITE_MAX_MMAP_SIZE
  13259. # define SQLITE_MAX_MMAP_SIZE 0
  13260. #endif
  13261. /*
  13262. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  13263. */
  13264. #ifdef __APPLE__
  13265. # include <TargetConditionals.h>
  13266. #endif
  13267. #ifndef SQLITE_MAX_MMAP_SIZE
  13268. # if defined(__linux__) \
  13269. || defined(_WIN32) \
  13270. || (defined(__APPLE__) && defined(__MACH__)) \
  13271. || defined(__sun) \
  13272. || defined(__FreeBSD__) \
  13273. || defined(__DragonFly__)
  13274. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  13275. # else
  13276. # define SQLITE_MAX_MMAP_SIZE 0
  13277. # endif
  13278. #endif
  13279. /*
  13280. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  13281. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  13282. ** not exceed the maximum mmap size.
  13283. */
  13284. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  13285. # define SQLITE_DEFAULT_MMAP_SIZE 0
  13286. #endif
  13287. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  13288. # undef SQLITE_DEFAULT_MMAP_SIZE
  13289. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  13290. #endif
  13291. /*
  13292. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  13293. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  13294. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  13295. */
  13296. #ifdef SQLITE_ENABLE_STAT4
  13297. # undef SQLITE_ENABLE_STAT3
  13298. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13299. #elif SQLITE_ENABLE_STAT3
  13300. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13301. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  13302. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  13303. #endif
  13304. /*
  13305. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  13306. ** the Select query generator tracing logic is turned on.
  13307. */
  13308. #if defined(SQLITE_ENABLE_SELECTTRACE)
  13309. # define SELECTTRACE_ENABLED 1
  13310. #else
  13311. # define SELECTTRACE_ENABLED 0
  13312. #endif
  13313. /*
  13314. ** An instance of the following structure is used to store the busy-handler
  13315. ** callback for a given sqlite handle.
  13316. **
  13317. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  13318. ** callback for the database handle. Each pager opened via the sqlite
  13319. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  13320. ** callback is currently invoked only from within pager.c.
  13321. */
  13322. typedef struct BusyHandler BusyHandler;
  13323. struct BusyHandler {
  13324. int (*xBusyHandler)(void *,int); /* The busy callback */
  13325. void *pBusyArg; /* First arg to busy callback */
  13326. int nBusy; /* Incremented with each busy call */
  13327. u8 bExtraFileArg; /* Include sqlite3_file as callback arg */
  13328. };
  13329. /*
  13330. ** Name of the master database table. The master database table
  13331. ** is a special table that holds the names and attributes of all
  13332. ** user tables and indices.
  13333. */
  13334. #define MASTER_NAME "sqlite_master"
  13335. #define TEMP_MASTER_NAME "sqlite_temp_master"
  13336. /*
  13337. ** The root-page of the master database table.
  13338. */
  13339. #define MASTER_ROOT 1
  13340. /*
  13341. ** The name of the schema table.
  13342. */
  13343. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  13344. /*
  13345. ** A convenience macro that returns the number of elements in
  13346. ** an array.
  13347. */
  13348. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  13349. /*
  13350. ** Determine if the argument is a power of two
  13351. */
  13352. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  13353. /*
  13354. ** The following value as a destructor means to use sqlite3DbFree().
  13355. ** The sqlite3DbFree() routine requires two parameters instead of the
  13356. ** one parameter that destructors normally want. So we have to introduce
  13357. ** this magic value that the code knows to handle differently. Any
  13358. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  13359. ** and SQLITE_TRANSIENT.
  13360. */
  13361. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  13362. /*
  13363. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  13364. ** not support Writable Static Data (WSD) such as global and static variables.
  13365. ** All variables must either be on the stack or dynamically allocated from
  13366. ** the heap. When WSD is unsupported, the variable declarations scattered
  13367. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  13368. ** macro is used for this purpose. And instead of referencing the variable
  13369. ** directly, we use its constant as a key to lookup the run-time allocated
  13370. ** buffer that holds real variable. The constant is also the initializer
  13371. ** for the run-time allocated buffer.
  13372. **
  13373. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  13374. ** macros become no-ops and have zero performance impact.
  13375. */
  13376. #ifdef SQLITE_OMIT_WSD
  13377. #define SQLITE_WSD const
  13378. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  13379. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  13380. SQLITE_API int sqlite3_wsd_init(int N, int J);
  13381. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  13382. #else
  13383. #define SQLITE_WSD
  13384. #define GLOBAL(t,v) v
  13385. #define sqlite3GlobalConfig sqlite3Config
  13386. #endif
  13387. /*
  13388. ** The following macros are used to suppress compiler warnings and to
  13389. ** make it clear to human readers when a function parameter is deliberately
  13390. ** left unused within the body of a function. This usually happens when
  13391. ** a function is called via a function pointer. For example the
  13392. ** implementation of an SQL aggregate step callback may not use the
  13393. ** parameter indicating the number of arguments passed to the aggregate,
  13394. ** if it knows that this is enforced elsewhere.
  13395. **
  13396. ** When a function parameter is not used at all within the body of a function,
  13397. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  13398. ** However, these macros may also be used to suppress warnings related to
  13399. ** parameters that may or may not be used depending on compilation options.
  13400. ** For example those parameters only used in assert() statements. In these
  13401. ** cases the parameters are named as per the usual conventions.
  13402. */
  13403. #define UNUSED_PARAMETER(x) (void)(x)
  13404. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  13405. /*
  13406. ** Forward references to structures
  13407. */
  13408. typedef struct AggInfo AggInfo;
  13409. typedef struct AuthContext AuthContext;
  13410. typedef struct AutoincInfo AutoincInfo;
  13411. typedef struct Bitvec Bitvec;
  13412. typedef struct CollSeq CollSeq;
  13413. typedef struct Column Column;
  13414. typedef struct Db Db;
  13415. typedef struct Schema Schema;
  13416. typedef struct Expr Expr;
  13417. typedef struct ExprList ExprList;
  13418. typedef struct FKey FKey;
  13419. typedef struct FuncDestructor FuncDestructor;
  13420. typedef struct FuncDef FuncDef;
  13421. typedef struct FuncDefHash FuncDefHash;
  13422. typedef struct IdList IdList;
  13423. typedef struct Index Index;
  13424. typedef struct IndexSample IndexSample;
  13425. typedef struct KeyClass KeyClass;
  13426. typedef struct KeyInfo KeyInfo;
  13427. typedef struct Lookaside Lookaside;
  13428. typedef struct LookasideSlot LookasideSlot;
  13429. typedef struct Module Module;
  13430. typedef struct NameContext NameContext;
  13431. typedef struct Parse Parse;
  13432. typedef struct PreUpdate PreUpdate;
  13433. typedef struct PrintfArguments PrintfArguments;
  13434. typedef struct RowSet RowSet;
  13435. typedef struct Savepoint Savepoint;
  13436. typedef struct Select Select;
  13437. typedef struct SQLiteThread SQLiteThread;
  13438. typedef struct SelectDest SelectDest;
  13439. typedef struct SrcList SrcList;
  13440. typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
  13441. typedef struct Table Table;
  13442. typedef struct TableLock TableLock;
  13443. typedef struct Token Token;
  13444. typedef struct TreeView TreeView;
  13445. typedef struct Trigger Trigger;
  13446. typedef struct TriggerPrg TriggerPrg;
  13447. typedef struct TriggerStep TriggerStep;
  13448. typedef struct UnpackedRecord UnpackedRecord;
  13449. typedef struct Upsert Upsert;
  13450. typedef struct VTable VTable;
  13451. typedef struct VtabCtx VtabCtx;
  13452. typedef struct Walker Walker;
  13453. typedef struct WhereInfo WhereInfo;
  13454. typedef struct With With;
  13455. /* A VList object records a mapping between parameters/variables/wildcards
  13456. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  13457. ** variable number associated with that parameter. See the format description
  13458. ** on the sqlite3VListAdd() routine for more information. A VList is really
  13459. ** just an array of integers.
  13460. */
  13461. typedef int VList;
  13462. /*
  13463. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  13464. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  13465. ** pointer types (i.e. FuncDef) defined above.
  13466. */
  13467. /************** Include btree.h in the middle of sqliteInt.h *****************/
  13468. /************** Begin file btree.h *******************************************/
  13469. /*
  13470. ** 2001 September 15
  13471. **
  13472. ** The author disclaims copyright to this source code. In place of
  13473. ** a legal notice, here is a blessing:
  13474. **
  13475. ** May you do good and not evil.
  13476. ** May you find forgiveness for yourself and forgive others.
  13477. ** May you share freely, never taking more than you give.
  13478. **
  13479. *************************************************************************
  13480. ** This header file defines the interface that the sqlite B-Tree file
  13481. ** subsystem. See comments in the source code for a detailed description
  13482. ** of what each interface routine does.
  13483. */
  13484. #ifndef SQLITE_BTREE_H
  13485. #define SQLITE_BTREE_H
  13486. /* TODO: This definition is just included so other modules compile. It
  13487. ** needs to be revisited.
  13488. */
  13489. #define SQLITE_N_BTREE_META 16
  13490. /*
  13491. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  13492. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  13493. */
  13494. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  13495. #define SQLITE_DEFAULT_AUTOVACUUM 0
  13496. #endif
  13497. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  13498. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  13499. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  13500. /*
  13501. ** Forward declarations of structure
  13502. */
  13503. typedef struct Btree Btree;
  13504. typedef struct BtCursor BtCursor;
  13505. typedef struct BtShared BtShared;
  13506. typedef struct BtreePayload BtreePayload;
  13507. SQLITE_PRIVATE int sqlite3BtreeOpen(
  13508. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  13509. const char *zFilename, /* Name of database file to open */
  13510. sqlite3 *db, /* Associated database connection */
  13511. Btree **ppBtree, /* Return open Btree* here */
  13512. int flags, /* Flags */
  13513. int vfsFlags /* Flags passed through to VFS open */
  13514. );
  13515. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  13516. ** following values.
  13517. **
  13518. ** NOTE: These values must match the corresponding PAGER_ values in
  13519. ** pager.h.
  13520. */
  13521. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  13522. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  13523. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  13524. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  13525. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  13526. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  13527. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  13528. #if SQLITE_MAX_MMAP_SIZE>0
  13529. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  13530. #endif
  13531. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  13532. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  13533. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  13534. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  13535. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  13536. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  13537. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  13538. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  13539. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  13540. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  13541. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  13542. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  13543. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  13544. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  13545. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  13546. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  13547. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  13548. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  13549. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  13550. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  13551. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  13552. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  13553. #ifndef SQLITE_OMIT_SHARED_CACHE
  13554. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  13555. #endif
  13556. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  13557. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  13558. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  13559. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  13560. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  13561. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  13562. ** of the flags shown below.
  13563. **
  13564. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  13565. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  13566. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  13567. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  13568. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  13569. ** indices.)
  13570. */
  13571. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  13572. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  13573. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  13574. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  13575. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  13576. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  13577. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  13578. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  13579. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  13580. /*
  13581. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  13582. ** should be one of the following values. The integer values are assigned
  13583. ** to constants so that the offset of the corresponding field in an
  13584. ** SQLite database header may be found using the following formula:
  13585. **
  13586. ** offset = 36 + (idx * 4)
  13587. **
  13588. ** For example, the free-page-count field is located at byte offset 36 of
  13589. ** the database file header. The incr-vacuum-flag field is located at
  13590. ** byte offset 64 (== 36+4*7).
  13591. **
  13592. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  13593. ** It is a read-only number computed by the pager. But we merge it with
  13594. ** the header value access routines since its access pattern is the same.
  13595. ** Call it a "virtual meta value".
  13596. */
  13597. #define BTREE_FREE_PAGE_COUNT 0
  13598. #define BTREE_SCHEMA_VERSION 1
  13599. #define BTREE_FILE_FORMAT 2
  13600. #define BTREE_DEFAULT_CACHE_SIZE 3
  13601. #define BTREE_LARGEST_ROOT_PAGE 4
  13602. #define BTREE_TEXT_ENCODING 5
  13603. #define BTREE_USER_VERSION 6
  13604. #define BTREE_INCR_VACUUM 7
  13605. #define BTREE_APPLICATION_ID 8
  13606. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  13607. /*
  13608. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  13609. ** interface.
  13610. **
  13611. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  13612. **
  13613. ** The first argument is an Expr* (which is guaranteed to be constant for
  13614. ** the lifetime of the cursor) that defines constraints on which rows
  13615. ** might be fetched with this cursor. The Expr* tree may contain
  13616. ** TK_REGISTER nodes that refer to values stored in the array of registers
  13617. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  13618. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  13619. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  13620. ** column of the b-tree of the cursor. The Expr tree will not contain
  13621. ** any function calls nor subqueries nor references to b-trees other than
  13622. ** the cursor being hinted.
  13623. **
  13624. ** The design of the _RANGE hint is aid b-tree implementations that try
  13625. ** to prefetch content from remote machines - to provide those
  13626. ** implementations with limits on what needs to be prefetched and thereby
  13627. ** reduce network bandwidth.
  13628. **
  13629. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  13630. ** standard SQLite. The other hints are provided for extentions that use
  13631. ** the SQLite parser and code generator but substitute their own storage
  13632. ** engine.
  13633. */
  13634. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  13635. /*
  13636. ** Values that may be OR'd together to form the argument to the
  13637. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  13638. **
  13639. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  13640. ** to be filled with content that is already in sorted order.
  13641. **
  13642. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  13643. ** OP_SeekLE opcodes for a range search, but where the range of entries
  13644. ** selected will all have the same key. In other words, the cursor will
  13645. ** be used only for equality key searches.
  13646. **
  13647. */
  13648. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  13649. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  13650. /*
  13651. ** Flags passed as the third argument to sqlite3BtreeCursor().
  13652. **
  13653. ** For read-only cursors the wrFlag argument is always zero. For read-write
  13654. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  13655. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  13656. ** only be used by SQLite for the following:
  13657. **
  13658. ** * to seek to and then delete specific entries, and/or
  13659. **
  13660. ** * to read values that will be used to create keys that other
  13661. ** BTREE_FORDELETE cursors will seek to and delete.
  13662. **
  13663. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  13664. ** by this, the native b-tree engine of SQLite, but it is available to
  13665. ** alternative storage engines that might be substituted in place of this
  13666. ** b-tree system. For alternative storage engines in which a delete of
  13667. ** the main table row automatically deletes corresponding index rows,
  13668. ** the FORDELETE flag hint allows those alternative storage engines to
  13669. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  13670. ** and DELETE operations as no-ops, and any READ operation against a
  13671. ** FORDELETE cursor may return a null row: 0x01 0x00.
  13672. */
  13673. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  13674. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  13675. SQLITE_PRIVATE int sqlite3BtreeCursor(
  13676. Btree*, /* BTree containing table to open */
  13677. int iTable, /* Index of root page */
  13678. int wrFlag, /* 1 for writing. 0 for read-only */
  13679. struct KeyInfo*, /* First argument to compare function */
  13680. BtCursor *pCursor /* Space to write cursor structure */
  13681. );
  13682. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
  13683. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  13684. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  13685. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  13686. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13687. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  13688. #endif
  13689. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  13690. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  13691. BtCursor*,
  13692. UnpackedRecord *pUnKey,
  13693. i64 intKey,
  13694. int bias,
  13695. int *pRes
  13696. );
  13697. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  13698. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  13699. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  13700. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  13701. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  13702. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  13703. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  13704. /* An instance of the BtreePayload object describes the content of a single
  13705. ** entry in either an index or table btree.
  13706. **
  13707. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  13708. ** an arbitrary key and no data. These btrees have pKey,nKey set to the
  13709. ** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
  13710. ** fields give an array of Mem objects that are a decomposition of the key.
  13711. ** The nMem field might be zero, indicating that no decomposition is available.
  13712. **
  13713. ** Table btrees (used for rowid tables) contain an integer rowid used as
  13714. ** the key and passed in the nKey field. The pKey field is zero.
  13715. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  13716. ** are appended to the end of the content when constructing the entry.
  13717. ** The aMem,nMem fields are uninitialized for table btrees.
  13718. **
  13719. ** Field usage summary:
  13720. **
  13721. ** Table BTrees Index Btrees
  13722. **
  13723. ** pKey always NULL encoded key
  13724. ** nKey the ROWID length of pKey
  13725. ** pData data not used
  13726. ** aMem not used decomposed key value
  13727. ** nMem not used entries in aMem
  13728. ** nData length of pData not used
  13729. ** nZero extra zeros after pData not used
  13730. **
  13731. ** This object is used to pass information into sqlite3BtreeInsert(). The
  13732. ** same information used to be passed as five separate parameters. But placing
  13733. ** the information into this object helps to keep the interface more
  13734. ** organized and understandable, and it also helps the resulting code to
  13735. ** run a little faster by using fewer registers for parameter passing.
  13736. */
  13737. struct BtreePayload {
  13738. const void *pKey; /* Key content for indexes. NULL for tables */
  13739. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  13740. const void *pData; /* Data for tables. */
  13741. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  13742. u16 nMem; /* Number of aMem[] value. Might be zero */
  13743. int nData; /* Size of pData. 0 if none. */
  13744. int nZero; /* Extra zero data appended after pData,nData */
  13745. };
  13746. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  13747. int flags, int seekResult);
  13748. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  13749. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  13750. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
  13751. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  13752. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
  13753. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  13754. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  13755. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
  13756. #endif
  13757. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  13758. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  13759. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  13760. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  13761. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  13762. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  13763. #ifndef SQLITE_OMIT_INCRBLOB
  13764. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  13765. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  13766. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  13767. #endif
  13768. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  13769. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  13770. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  13771. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  13772. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  13773. #ifndef NDEBUG
  13774. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  13775. #endif
  13776. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  13777. #ifndef SQLITE_OMIT_BTREECOUNT
  13778. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  13779. #endif
  13780. #ifdef SQLITE_TEST
  13781. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  13782. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  13783. #endif
  13784. #ifndef SQLITE_OMIT_WAL
  13785. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  13786. #endif
  13787. /*
  13788. ** If we are not using shared cache, then there is no need to
  13789. ** use mutexes to access the BtShared structures. So make the
  13790. ** Enter and Leave procedures no-ops.
  13791. */
  13792. #ifndef SQLITE_OMIT_SHARED_CACHE
  13793. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  13794. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  13795. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  13796. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  13797. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  13798. #else
  13799. # define sqlite3BtreeEnter(X)
  13800. # define sqlite3BtreeEnterAll(X)
  13801. # define sqlite3BtreeSharable(X) 0
  13802. # define sqlite3BtreeEnterCursor(X)
  13803. # define sqlite3BtreeConnectionCount(X) 1
  13804. #endif
  13805. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  13806. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  13807. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  13808. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  13809. #ifndef NDEBUG
  13810. /* These routines are used inside assert() statements only. */
  13811. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  13812. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  13813. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  13814. #endif
  13815. #else
  13816. # define sqlite3BtreeLeave(X)
  13817. # define sqlite3BtreeLeaveCursor(X)
  13818. # define sqlite3BtreeLeaveAll(X)
  13819. # define sqlite3BtreeHoldsMutex(X) 1
  13820. # define sqlite3BtreeHoldsAllMutexes(X) 1
  13821. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  13822. #endif
  13823. #endif /* SQLITE_BTREE_H */
  13824. /************** End of btree.h ***********************************************/
  13825. /************** Continuing where we left off in sqliteInt.h ******************/
  13826. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  13827. /************** Begin file vdbe.h ********************************************/
  13828. /*
  13829. ** 2001 September 15
  13830. **
  13831. ** The author disclaims copyright to this source code. In place of
  13832. ** a legal notice, here is a blessing:
  13833. **
  13834. ** May you do good and not evil.
  13835. ** May you find forgiveness for yourself and forgive others.
  13836. ** May you share freely, never taking more than you give.
  13837. **
  13838. *************************************************************************
  13839. ** Header file for the Virtual DataBase Engine (VDBE)
  13840. **
  13841. ** This header defines the interface to the virtual database engine
  13842. ** or VDBE. The VDBE implements an abstract machine that runs a
  13843. ** simple program to access and modify the underlying database.
  13844. */
  13845. #ifndef SQLITE_VDBE_H
  13846. #define SQLITE_VDBE_H
  13847. /* #include <stdio.h> */
  13848. /*
  13849. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  13850. ** in the source file sqliteVdbe.c are allowed to see the insides
  13851. ** of this structure.
  13852. */
  13853. typedef struct Vdbe Vdbe;
  13854. /*
  13855. ** The names of the following types declared in vdbeInt.h are required
  13856. ** for the VdbeOp definition.
  13857. */
  13858. typedef struct sqlite3_value Mem;
  13859. typedef struct SubProgram SubProgram;
  13860. /*
  13861. ** A single instruction of the virtual machine has an opcode
  13862. ** and as many as three operands. The instruction is recorded
  13863. ** as an instance of the following structure:
  13864. */
  13865. struct VdbeOp {
  13866. u8 opcode; /* What operation to perform */
  13867. signed char p4type; /* One of the P4_xxx constants for p4 */
  13868. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  13869. int p1; /* First operand */
  13870. int p2; /* Second parameter (often the jump destination) */
  13871. int p3; /* The third parameter */
  13872. union p4union { /* fourth parameter */
  13873. int i; /* Integer value if p4type==P4_INT32 */
  13874. void *p; /* Generic pointer */
  13875. char *z; /* Pointer to data for string (char array) types */
  13876. i64 *pI64; /* Used when p4type is P4_INT64 */
  13877. double *pReal; /* Used when p4type is P4_REAL */
  13878. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  13879. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  13880. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  13881. Mem *pMem; /* Used when p4type is P4_MEM */
  13882. VTable *pVtab; /* Used when p4type is P4_VTAB */
  13883. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  13884. int *ai; /* Used when p4type is P4_INTARRAY */
  13885. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  13886. Table *pTab; /* Used when p4type is P4_TABLE */
  13887. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13888. Expr *pExpr; /* Used when p4type is P4_EXPR */
  13889. #endif
  13890. int (*xAdvance)(BtCursor *, int);
  13891. } p4;
  13892. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  13893. char *zComment; /* Comment to improve readability */
  13894. #endif
  13895. #ifdef VDBE_PROFILE
  13896. u32 cnt; /* Number of times this instruction was executed */
  13897. u64 cycles; /* Total time spent executing this instruction */
  13898. #endif
  13899. #ifdef SQLITE_VDBE_COVERAGE
  13900. int iSrcLine; /* Source-code line that generated this opcode */
  13901. #endif
  13902. };
  13903. typedef struct VdbeOp VdbeOp;
  13904. /*
  13905. ** A sub-routine used to implement a trigger program.
  13906. */
  13907. struct SubProgram {
  13908. VdbeOp *aOp; /* Array of opcodes for sub-program */
  13909. int nOp; /* Elements in aOp[] */
  13910. int nMem; /* Number of memory cells required */
  13911. int nCsr; /* Number of cursors required */
  13912. u8 *aOnce; /* Array of OP_Once flags */
  13913. void *token; /* id that may be used to recursive triggers */
  13914. SubProgram *pNext; /* Next sub-program already visited */
  13915. };
  13916. /*
  13917. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  13918. ** it takes up less space.
  13919. */
  13920. struct VdbeOpList {
  13921. u8 opcode; /* What operation to perform */
  13922. signed char p1; /* First operand */
  13923. signed char p2; /* Second parameter (often the jump destination) */
  13924. signed char p3; /* Third parameter */
  13925. };
  13926. typedef struct VdbeOpList VdbeOpList;
  13927. /*
  13928. ** Allowed values of VdbeOp.p4type
  13929. */
  13930. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  13931. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  13932. #define P4_STATIC (-1) /* Pointer to a static string */
  13933. #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
  13934. #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
  13935. #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
  13936. #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  13937. #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
  13938. /* Above do not own any resources. Must free those below */
  13939. #define P4_FREE_IF_LE (-7)
  13940. #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
  13941. #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
  13942. #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
  13943. #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
  13944. #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
  13945. #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
  13946. #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
  13947. #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
  13948. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  13949. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  13950. #define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
  13951. /* Error message codes for OP_Halt */
  13952. #define P5_ConstraintNotNull 1
  13953. #define P5_ConstraintUnique 2
  13954. #define P5_ConstraintCheck 3
  13955. #define P5_ConstraintFK 4
  13956. /*
  13957. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  13958. ** number of columns of data returned by the statement.
  13959. */
  13960. #define COLNAME_NAME 0
  13961. #define COLNAME_DECLTYPE 1
  13962. #define COLNAME_DATABASE 2
  13963. #define COLNAME_TABLE 3
  13964. #define COLNAME_COLUMN 4
  13965. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  13966. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  13967. #else
  13968. # ifdef SQLITE_OMIT_DECLTYPE
  13969. # define COLNAME_N 1 /* Store only the name */
  13970. # else
  13971. # define COLNAME_N 2 /* Store the name and decltype */
  13972. # endif
  13973. #endif
  13974. /*
  13975. ** The following macro converts a relative address in the p2 field
  13976. ** of a VdbeOp structure into a negative number so that
  13977. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  13978. ** the macro again restores the address.
  13979. */
  13980. #define ADDR(X) (-1-(X))
  13981. /*
  13982. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  13983. ** header file that defines a number for each opcode used by the VDBE.
  13984. */
  13985. /************** Include opcodes.h in the middle of vdbe.h ********************/
  13986. /************** Begin file opcodes.h *****************************************/
  13987. /* Automatically generated. Do not edit */
  13988. /* See the tool/mkopcodeh.tcl script for details */
  13989. #define OP_Savepoint 0
  13990. #define OP_AutoCommit 1
  13991. #define OP_Transaction 2
  13992. #define OP_SorterNext 3 /* jump */
  13993. #define OP_PrevIfOpen 4 /* jump */
  13994. #define OP_NextIfOpen 5 /* jump */
  13995. #define OP_Prev 6 /* jump */
  13996. #define OP_Next 7 /* jump */
  13997. #define OP_Checkpoint 8
  13998. #define OP_JournalMode 9
  13999. #define OP_Vacuum 10
  14000. #define OP_VFilter 11 /* jump, synopsis: iplan=r[P3] zplan='P4' */
  14001. #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
  14002. #define OP_Goto 13 /* jump */
  14003. #define OP_Gosub 14 /* jump */
  14004. #define OP_InitCoroutine 15 /* jump */
  14005. #define OP_Yield 16 /* jump */
  14006. #define OP_MustBeInt 17 /* jump */
  14007. #define OP_Jump 18 /* jump */
  14008. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  14009. #define OP_Once 20 /* jump */
  14010. #define OP_If 21 /* jump */
  14011. #define OP_IfNot 22 /* jump */
  14012. #define OP_IfNullRow 23 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  14013. #define OP_SeekLT 24 /* jump, synopsis: key=r[P3@P4] */
  14014. #define OP_SeekLE 25 /* jump, synopsis: key=r[P3@P4] */
  14015. #define OP_SeekGE 26 /* jump, synopsis: key=r[P3@P4] */
  14016. #define OP_SeekGT 27 /* jump, synopsis: key=r[P3@P4] */
  14017. #define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */
  14018. #define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */
  14019. #define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */
  14020. #define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */
  14021. #define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */
  14022. #define OP_Last 33 /* jump */
  14023. #define OP_IfSmaller 34 /* jump */
  14024. #define OP_SorterSort 35 /* jump */
  14025. #define OP_Sort 36 /* jump */
  14026. #define OP_Rewind 37 /* jump */
  14027. #define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */
  14028. #define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */
  14029. #define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */
  14030. #define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */
  14031. #define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */
  14032. #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  14033. #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  14034. #define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
  14035. #define OP_Program 46 /* jump */
  14036. #define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
  14037. #define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  14038. #define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  14039. #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  14040. #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  14041. #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  14042. #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  14043. #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
  14044. #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  14045. #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
  14046. #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  14047. #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
  14048. #define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */
  14049. #define OP_IncrVacuum 60 /* jump */
  14050. #define OP_VNext 61 /* jump */
  14051. #define OP_Init 62 /* jump, synopsis: Start at P2 */
  14052. #define OP_Return 63
  14053. #define OP_EndCoroutine 64
  14054. #define OP_HaltIfNull 65 /* synopsis: if r[P3]=null halt */
  14055. #define OP_Halt 66
  14056. #define OP_Integer 67 /* synopsis: r[P2]=P1 */
  14057. #define OP_Int64 68 /* synopsis: r[P2]=P4 */
  14058. #define OP_String 69 /* synopsis: r[P2]='P4' (len=P1) */
  14059. #define OP_Null 70 /* synopsis: r[P2..P3]=NULL */
  14060. #define OP_SoftNull 71 /* synopsis: r[P1]=NULL */
  14061. #define OP_Blob 72 /* synopsis: r[P2]=P4 (len=P1) */
  14062. #define OP_Variable 73 /* synopsis: r[P2]=parameter(P1,P4) */
  14063. #define OP_Move 74 /* synopsis: r[P2@P3]=r[P1@P3] */
  14064. #define OP_Copy 75 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  14065. #define OP_SCopy 76 /* synopsis: r[P2]=r[P1] */
  14066. #define OP_IntCopy 77 /* synopsis: r[P2]=r[P1] */
  14067. #define OP_ResultRow 78 /* synopsis: output=r[P1@P2] */
  14068. #define OP_CollSeq 79
  14069. #define OP_AddImm 80 /* synopsis: r[P1]=r[P1]+P2 */
  14070. #define OP_RealAffinity 81
  14071. #define OP_Cast 82 /* synopsis: affinity(r[P1]) */
  14072. #define OP_Permutation 83
  14073. #define OP_Compare 84 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  14074. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  14075. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  14076. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  14077. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  14078. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  14079. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  14080. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  14081. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  14082. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  14083. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  14084. #define OP_IsTrue 95 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
  14085. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  14086. #define OP_Offset 97 /* synopsis: r[P3] = sqlite_offset(P1) */
  14087. #define OP_Column 98 /* synopsis: r[P3]=PX */
  14088. #define OP_String8 99 /* same as TK_STRING, synopsis: r[P2]='P4' */
  14089. #define OP_Affinity 100 /* synopsis: affinity(r[P1@P2]) */
  14090. #define OP_MakeRecord 101 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  14091. #define OP_Count 102 /* synopsis: r[P2]=count() */
  14092. #define OP_ReadCookie 103
  14093. #define OP_SetCookie 104
  14094. #define OP_ReopenIdx 105 /* synopsis: root=P2 iDb=P3 */
  14095. #define OP_OpenRead 106 /* synopsis: root=P2 iDb=P3 */
  14096. #define OP_OpenWrite 107 /* synopsis: root=P2 iDb=P3 */
  14097. #define OP_OpenDup 108
  14098. #define OP_OpenAutoindex 109 /* synopsis: nColumn=P2 */
  14099. #define OP_OpenEphemeral 110 /* synopsis: nColumn=P2 */
  14100. #define OP_SorterOpen 111
  14101. #define OP_SequenceTest 112 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  14102. #define OP_OpenPseudo 113 /* synopsis: P3 columns in r[P2] */
  14103. #define OP_Close 114
  14104. #define OP_ColumnsUsed 115
  14105. #define OP_Sequence 116 /* synopsis: r[P2]=cursor[P1].ctr++ */
  14106. #define OP_NewRowid 117 /* synopsis: r[P2]=rowid */
  14107. #define OP_Insert 118 /* synopsis: intkey=r[P3] data=r[P2] */
  14108. #define OP_InsertInt 119 /* synopsis: intkey=P3 data=r[P2] */
  14109. #define OP_Delete 120
  14110. #define OP_ResetCount 121
  14111. #define OP_SorterCompare 122 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  14112. #define OP_SorterData 123 /* synopsis: r[P2]=data */
  14113. #define OP_RowData 124 /* synopsis: r[P2]=data */
  14114. #define OP_Rowid 125 /* synopsis: r[P2]=rowid */
  14115. #define OP_NullRow 126
  14116. #define OP_SeekEnd 127
  14117. #define OP_SorterInsert 128 /* synopsis: key=r[P2] */
  14118. #define OP_IdxInsert 129 /* synopsis: key=r[P2] */
  14119. #define OP_IdxDelete 130 /* synopsis: key=r[P2@P3] */
  14120. #define OP_DeferredSeek 131 /* synopsis: Move P3 to P1.rowid if needed */
  14121. #define OP_IdxRowid 132 /* synopsis: r[P2]=rowid */
  14122. #define OP_Destroy 133
  14123. #define OP_Real 134 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  14124. #define OP_Clear 135
  14125. #define OP_ResetSorter 136
  14126. #define OP_CreateBtree 137 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
  14127. #define OP_SqlExec 138
  14128. #define OP_ParseSchema 139
  14129. #define OP_LoadAnalysis 140
  14130. #define OP_DropTable 141
  14131. #define OP_DropIndex 142
  14132. #define OP_DropTrigger 143
  14133. #define OP_IntegrityCk 144
  14134. #define OP_RowSetAdd 145 /* synopsis: rowset(P1)=r[P2] */
  14135. #define OP_Param 146
  14136. #define OP_FkCounter 147 /* synopsis: fkctr[P1]+=P2 */
  14137. #define OP_MemMax 148 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  14138. #define OP_OffsetLimit 149 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  14139. #define OP_AggStep0 150 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14140. #define OP_AggStep 151 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14141. #define OP_AggFinal 152 /* synopsis: accum=r[P1] N=P2 */
  14142. #define OP_Expire 153
  14143. #define OP_TableLock 154 /* synopsis: iDb=P1 root=P2 write=P3 */
  14144. #define OP_VBegin 155
  14145. #define OP_VCreate 156
  14146. #define OP_VDestroy 157
  14147. #define OP_VOpen 158
  14148. #define OP_VColumn 159 /* synopsis: r[P3]=vcolumn(P2) */
  14149. #define OP_VRename 160
  14150. #define OP_Pagecount 161
  14151. #define OP_MaxPgcnt 162
  14152. #define OP_PureFunc0 163
  14153. #define OP_Function0 164 /* synopsis: r[P3]=func(r[P2@P5]) */
  14154. #define OP_PureFunc 165
  14155. #define OP_Function 166 /* synopsis: r[P3]=func(r[P2@P5]) */
  14156. #define OP_Trace 167
  14157. #define OP_CursorHint 168
  14158. #define OP_Noop 169
  14159. #define OP_Explain 170
  14160. #define OP_Abortable 171
  14161. /* Properties such as "out2" or "jump" that are specified in
  14162. ** comments following the "case" for each opcode in the vdbe.c
  14163. ** are encoded into bitvectors as follows:
  14164. */
  14165. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  14166. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  14167. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  14168. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  14169. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  14170. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  14171. #define OPFLG_INITIALIZER {\
  14172. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
  14173. /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
  14174. /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
  14175. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  14176. /* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  14177. /* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
  14178. /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
  14179. /* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x02,\
  14180. /* 64 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
  14181. /* 72 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  14182. /* 80 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x26, 0x26, 0x26,\
  14183. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x12,\
  14184. /* 96 */ 0x12, 0x20, 0x00, 0x10, 0x00, 0x00, 0x10, 0x10,\
  14185. /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14186. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  14187. /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,\
  14188. /* 128 */ 0x04, 0x04, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00,\
  14189. /* 136 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14190. /* 144 */ 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00,\
  14191. /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14192. /* 160 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14193. /* 168 */ 0x00, 0x00, 0x00, 0x00,}
  14194. /* The sqlite3P2Values() routine is able to run faster if it knows
  14195. ** the value of the largest JUMP opcode. The smaller the maximum
  14196. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  14197. ** generated this include file strives to group all JUMP opcodes
  14198. ** together near the beginning of the list.
  14199. */
  14200. #define SQLITE_MX_JUMP_OPCODE 62 /* Maximum JUMP opcode */
  14201. /************** End of opcodes.h *********************************************/
  14202. /************** Continuing where we left off in vdbe.h ***********************/
  14203. /*
  14204. ** Additional non-public SQLITE_PREPARE_* flags
  14205. */
  14206. #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
  14207. #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
  14208. /*
  14209. ** Prototypes for the VDBE interface. See comments on the implementation
  14210. ** for a description of what each of these routines does.
  14211. */
  14212. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  14213. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  14214. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  14215. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  14216. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  14217. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  14218. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  14219. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  14220. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  14221. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  14222. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  14223. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  14224. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  14225. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  14226. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  14227. #else
  14228. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  14229. # define sqlite3VdbeVerifyNoResultRow(A)
  14230. #endif
  14231. #if defined(SQLITE_DEBUG)
  14232. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
  14233. #else
  14234. # define sqlite3VdbeVerifyAbortable(A,B)
  14235. #endif
  14236. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
  14237. #ifndef SQLITE_OMIT_EXPLAIN
  14238. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
  14239. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
  14240. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
  14241. # define ExplainQueryPlan(P) sqlite3VdbeExplain P
  14242. # define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
  14243. # define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
  14244. #else
  14245. # define ExplainQueryPlan(P)
  14246. # define ExplainQueryPlanPop(P)
  14247. # define ExplainQueryPlanParent(P) 0
  14248. #endif
  14249. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  14250. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  14251. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  14252. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  14253. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  14254. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  14255. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  14256. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  14257. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  14258. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  14259. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  14260. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  14261. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  14262. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  14263. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  14264. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  14265. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  14266. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  14267. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  14268. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  14269. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  14270. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  14271. #ifdef SQLITE_COVERAGE_TEST
  14272. SQLITE_PRIVATE int sqlite3VdbeLabelHasBeenResolved(Vdbe*,int);
  14273. #endif
  14274. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  14275. #ifdef SQLITE_DEBUG
  14276. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  14277. #endif
  14278. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  14279. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  14280. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  14281. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  14282. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  14283. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  14284. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  14285. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
  14286. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
  14287. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  14288. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  14289. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  14290. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  14291. #ifndef SQLITE_OMIT_TRACE
  14292. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  14293. #endif
  14294. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  14295. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  14296. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  14297. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  14298. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  14299. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  14300. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  14301. #ifndef SQLITE_OMIT_TRIGGER
  14302. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  14303. #endif
  14304. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
  14305. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  14306. ** each VDBE opcode.
  14307. **
  14308. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  14309. ** comments in VDBE programs that show key decision points in the code
  14310. ** generator.
  14311. */
  14312. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14313. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  14314. # define VdbeComment(X) sqlite3VdbeComment X
  14315. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  14316. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  14317. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  14318. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  14319. # else
  14320. # define VdbeModuleComment(X)
  14321. # endif
  14322. #else
  14323. # define VdbeComment(X)
  14324. # define VdbeNoopComment(X)
  14325. # define VdbeModuleComment(X)
  14326. #endif
  14327. /*
  14328. ** The VdbeCoverage macros are used to set a coverage testing point
  14329. ** for VDBE branch instructions. The coverage testing points are line
  14330. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  14331. ** only works with an amalagmation build. That's ok since a VDBE branch
  14332. ** coverage build designed for testing the test suite only. No application
  14333. ** should ever ship with VDBE branch coverage measuring turned on.
  14334. **
  14335. ** VdbeCoverage(v) // Mark the previously coded instruction
  14336. ** // as a branch
  14337. **
  14338. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  14339. **
  14340. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  14341. **
  14342. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  14343. **
  14344. ** Every VDBE branch operation must be tagged with one of the macros above.
  14345. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  14346. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  14347. ** routine in vdbe.c, alerting the developer to the missed tag.
  14348. */
  14349. #ifdef SQLITE_VDBE_COVERAGE
  14350. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  14351. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  14352. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  14353. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  14354. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  14355. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  14356. #else
  14357. # define VdbeCoverage(v)
  14358. # define VdbeCoverageIf(v,x)
  14359. # define VdbeCoverageAlwaysTaken(v)
  14360. # define VdbeCoverageNeverTaken(v)
  14361. # define VDBE_OFFSET_LINENO(x) 0
  14362. #endif
  14363. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14364. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  14365. #else
  14366. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  14367. #endif
  14368. #endif /* SQLITE_VDBE_H */
  14369. /************** End of vdbe.h ************************************************/
  14370. /************** Continuing where we left off in sqliteInt.h ******************/
  14371. /************** Include pager.h in the middle of sqliteInt.h *****************/
  14372. /************** Begin file pager.h *******************************************/
  14373. /*
  14374. ** 2001 September 15
  14375. **
  14376. ** The author disclaims copyright to this source code. In place of
  14377. ** a legal notice, here is a blessing:
  14378. **
  14379. ** May you do good and not evil.
  14380. ** May you find forgiveness for yourself and forgive others.
  14381. ** May you share freely, never taking more than you give.
  14382. **
  14383. *************************************************************************
  14384. ** This header file defines the interface that the sqlite page cache
  14385. ** subsystem. The page cache subsystem reads and writes a file a page
  14386. ** at a time and provides a journal for rollback.
  14387. */
  14388. #ifndef SQLITE_PAGER_H
  14389. #define SQLITE_PAGER_H
  14390. /*
  14391. ** Default maximum size for persistent journal files. A negative
  14392. ** value means no limit. This value may be overridden using the
  14393. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  14394. */
  14395. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  14396. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  14397. #endif
  14398. /*
  14399. ** The type used to represent a page number. The first page in a file
  14400. ** is called page 1. 0 is used to represent "not a page".
  14401. */
  14402. typedef u32 Pgno;
  14403. /*
  14404. ** Each open file is managed by a separate instance of the "Pager" structure.
  14405. */
  14406. typedef struct Pager Pager;
  14407. /*
  14408. ** Handle type for pages.
  14409. */
  14410. typedef struct PgHdr DbPage;
  14411. /*
  14412. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  14413. ** reserved for working around a windows/posix incompatibility). It is
  14414. ** used in the journal to signify that the remainder of the journal file
  14415. ** is devoted to storing a master journal name - there are no more pages to
  14416. ** roll back. See comments for function writeMasterJournal() in pager.c
  14417. ** for details.
  14418. */
  14419. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  14420. /*
  14421. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  14422. **
  14423. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  14424. */
  14425. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  14426. #define PAGER_MEMORY 0x0002 /* In-memory database */
  14427. /*
  14428. ** Valid values for the second argument to sqlite3PagerLockingMode().
  14429. */
  14430. #define PAGER_LOCKINGMODE_QUERY -1
  14431. #define PAGER_LOCKINGMODE_NORMAL 0
  14432. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  14433. /*
  14434. ** Numeric constants that encode the journalmode.
  14435. **
  14436. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  14437. ** are exposed in the API via the "PRAGMA journal_mode" command and
  14438. ** therefore cannot be changed without a compatibility break.
  14439. */
  14440. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  14441. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  14442. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  14443. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  14444. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  14445. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  14446. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  14447. /*
  14448. ** Flags that make up the mask passed to sqlite3PagerGet().
  14449. */
  14450. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  14451. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  14452. /*
  14453. ** Flags for sqlite3PagerSetFlags()
  14454. **
  14455. ** Value constraints (enforced via assert()):
  14456. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  14457. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  14458. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  14459. */
  14460. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  14461. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  14462. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  14463. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  14464. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  14465. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  14466. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  14467. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  14468. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  14469. /*
  14470. ** The remainder of this file contains the declarations of the functions
  14471. ** that make up the Pager sub-system API. See source code comments for
  14472. ** a detailed description of each routine.
  14473. */
  14474. /* Open and close a Pager connection. */
  14475. SQLITE_PRIVATE int sqlite3PagerOpen(
  14476. sqlite3_vfs*,
  14477. Pager **ppPager,
  14478. const char*,
  14479. int,
  14480. int,
  14481. int,
  14482. void(*)(DbPage*)
  14483. );
  14484. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  14485. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  14486. /* Functions used to configure a Pager object. */
  14487. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
  14488. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  14489. #ifdef SQLITE_HAS_CODEC
  14490. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  14491. #endif
  14492. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  14493. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  14494. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  14495. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  14496. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  14497. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  14498. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  14499. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  14500. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  14501. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  14502. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  14503. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  14504. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  14505. /* Functions used to obtain and release page references. */
  14506. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  14507. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  14508. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  14509. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  14510. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  14511. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
  14512. /* Operations on page references. */
  14513. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  14514. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  14515. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  14516. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  14517. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  14518. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  14519. /* Functions used to manage pager transactions and savepoints. */
  14520. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  14521. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  14522. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  14523. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  14524. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  14525. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  14526. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  14527. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  14528. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  14529. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  14530. #ifndef SQLITE_OMIT_WAL
  14531. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  14532. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  14533. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  14534. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  14535. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  14536. # ifdef SQLITE_DIRECT_OVERFLOW_READ
  14537. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno);
  14538. # endif
  14539. # ifdef SQLITE_ENABLE_SNAPSHOT
  14540. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  14541. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14542. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  14543. # endif
  14544. #else
  14545. # define sqlite3PagerUseWal(x,y) 0
  14546. #endif
  14547. #ifdef SQLITE_ENABLE_ZIPVFS
  14548. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  14549. #endif
  14550. /* Functions used to query pager state and configuration. */
  14551. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  14552. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  14553. #ifdef SQLITE_DEBUG
  14554. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  14555. #endif
  14556. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  14557. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  14558. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  14559. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  14560. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  14561. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  14562. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  14563. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  14564. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  14565. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  14566. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  14567. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  14568. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
  14569. #else
  14570. # define sqlite3PagerResetLockTimeout(X)
  14571. #endif
  14572. /* Functions used to truncate the database file. */
  14573. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  14574. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  14575. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  14576. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  14577. #endif
  14578. /* Functions to support testing and debugging. */
  14579. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  14580. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  14581. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  14582. #endif
  14583. #ifdef SQLITE_TEST
  14584. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  14585. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  14586. void disable_simulated_io_errors(void);
  14587. void enable_simulated_io_errors(void);
  14588. #else
  14589. # define disable_simulated_io_errors()
  14590. # define enable_simulated_io_errors()
  14591. #endif
  14592. #endif /* SQLITE_PAGER_H */
  14593. /************** End of pager.h ***********************************************/
  14594. /************** Continuing where we left off in sqliteInt.h ******************/
  14595. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  14596. /************** Begin file pcache.h ******************************************/
  14597. /*
  14598. ** 2008 August 05
  14599. **
  14600. ** The author disclaims copyright to this source code. In place of
  14601. ** a legal notice, here is a blessing:
  14602. **
  14603. ** May you do good and not evil.
  14604. ** May you find forgiveness for yourself and forgive others.
  14605. ** May you share freely, never taking more than you give.
  14606. **
  14607. *************************************************************************
  14608. ** This header file defines the interface that the sqlite page cache
  14609. ** subsystem.
  14610. */
  14611. #ifndef _PCACHE_H_
  14612. typedef struct PgHdr PgHdr;
  14613. typedef struct PCache PCache;
  14614. /*
  14615. ** Every page in the cache is controlled by an instance of the following
  14616. ** structure.
  14617. */
  14618. struct PgHdr {
  14619. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  14620. void *pData; /* Page data */
  14621. void *pExtra; /* Extra content */
  14622. PCache *pCache; /* PRIVATE: Cache that owns this page */
  14623. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  14624. Pager *pPager; /* The pager this page is part of */
  14625. Pgno pgno; /* Page number for this page */
  14626. #ifdef SQLITE_CHECK_PAGES
  14627. u32 pageHash; /* Hash of page content */
  14628. #endif
  14629. u16 flags; /* PGHDR flags defined below */
  14630. /**********************************************************************
  14631. ** Elements above, except pCache, are public. All that follow are
  14632. ** private to pcache.c and should not be accessed by other modules.
  14633. ** pCache is grouped with the public elements for efficiency.
  14634. */
  14635. i16 nRef; /* Number of users of this page */
  14636. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  14637. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  14638. /* NB: pDirtyNext and pDirtyPrev are undefined if the
  14639. ** PgHdr object is not dirty */
  14640. };
  14641. /* Bit values for PgHdr.flags */
  14642. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  14643. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  14644. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  14645. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  14646. ** writing this page to the database */
  14647. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  14648. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  14649. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  14650. /* Initialize and shutdown the page cache subsystem */
  14651. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  14652. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  14653. /* Page cache buffer management:
  14654. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  14655. */
  14656. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  14657. /* Create a new pager cache.
  14658. ** Under memory stress, invoke xStress to try to make pages clean.
  14659. ** Only clean and unpinned pages can be reclaimed.
  14660. */
  14661. SQLITE_PRIVATE int sqlite3PcacheOpen(
  14662. int szPage, /* Size of every page */
  14663. int szExtra, /* Extra space associated with each page */
  14664. int bPurgeable, /* True if pages are on backing store */
  14665. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  14666. void *pStress, /* Argument to xStress */
  14667. PCache *pToInit /* Preallocated space for the PCache */
  14668. );
  14669. /* Modify the page-size after the cache has been created. */
  14670. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  14671. /* Return the size in bytes of a PCache object. Used to preallocate
  14672. ** storage space.
  14673. */
  14674. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  14675. /* One release per successful fetch. Page is pinned until released.
  14676. ** Reference counted.
  14677. */
  14678. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  14679. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  14680. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  14681. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  14682. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  14683. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  14684. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  14685. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  14686. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  14687. /* Change a page number. Used by incr-vacuum. */
  14688. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  14689. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  14690. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  14691. /* Get a list of all dirty pages in the cache, sorted by page number */
  14692. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  14693. /* Reset and close the cache object */
  14694. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  14695. /* Clear flags from pages of the page cache */
  14696. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  14697. /* Discard the contents of the cache */
  14698. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  14699. /* Return the total number of outstanding page references */
  14700. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  14701. /* Increment the reference count of an existing page */
  14702. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  14703. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  14704. /* Return the total number of pages stored in the cache */
  14705. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  14706. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  14707. /* Iterate through all dirty pages currently stored in the cache. This
  14708. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  14709. ** library is built.
  14710. */
  14711. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  14712. #endif
  14713. #if defined(SQLITE_DEBUG)
  14714. /* Check invariants on a PgHdr object */
  14715. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  14716. #endif
  14717. /* Set and get the suggested cache-size for the specified pager-cache.
  14718. **
  14719. ** If no global maximum is configured, then the system attempts to limit
  14720. ** the total number of pages cached by purgeable pager-caches to the sum
  14721. ** of the suggested cache-sizes.
  14722. */
  14723. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  14724. #ifdef SQLITE_TEST
  14725. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  14726. #endif
  14727. /* Set or get the suggested spill-size for the specified pager-cache.
  14728. **
  14729. ** The spill-size is the minimum number of pages in cache before the cache
  14730. ** will attempt to spill dirty pages by calling xStress.
  14731. */
  14732. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  14733. /* Free up as much memory as possible from the page cache */
  14734. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  14735. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  14736. /* Try to return memory used by the pcache module to the main memory heap */
  14737. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  14738. #endif
  14739. #ifdef SQLITE_TEST
  14740. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  14741. #endif
  14742. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  14743. /* Return the header size */
  14744. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  14745. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  14746. /* Number of dirty pages as a percentage of the configured cache size */
  14747. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  14748. #endif /* _PCACHE_H_ */
  14749. /************** End of pcache.h **********************************************/
  14750. /************** Continuing where we left off in sqliteInt.h ******************/
  14751. /************** Include os.h in the middle of sqliteInt.h ********************/
  14752. /************** Begin file os.h **********************************************/
  14753. /*
  14754. ** 2001 September 16
  14755. **
  14756. ** The author disclaims copyright to this source code. In place of
  14757. ** a legal notice, here is a blessing:
  14758. **
  14759. ** May you do good and not evil.
  14760. ** May you find forgiveness for yourself and forgive others.
  14761. ** May you share freely, never taking more than you give.
  14762. **
  14763. ******************************************************************************
  14764. **
  14765. ** This header file (together with is companion C source-code file
  14766. ** "os.c") attempt to abstract the underlying operating system so that
  14767. ** the SQLite library will work on both POSIX and windows systems.
  14768. **
  14769. ** This header file is #include-ed by sqliteInt.h and thus ends up
  14770. ** being included by every source file.
  14771. */
  14772. #ifndef _SQLITE_OS_H_
  14773. #define _SQLITE_OS_H_
  14774. /*
  14775. ** Attempt to automatically detect the operating system and setup the
  14776. ** necessary pre-processor macros for it.
  14777. */
  14778. /************** Include os_setup.h in the middle of os.h *********************/
  14779. /************** Begin file os_setup.h ****************************************/
  14780. /*
  14781. ** 2013 November 25
  14782. **
  14783. ** The author disclaims copyright to this source code. In place of
  14784. ** a legal notice, here is a blessing:
  14785. **
  14786. ** May you do good and not evil.
  14787. ** May you find forgiveness for yourself and forgive others.
  14788. ** May you share freely, never taking more than you give.
  14789. **
  14790. ******************************************************************************
  14791. **
  14792. ** This file contains pre-processor directives related to operating system
  14793. ** detection and/or setup.
  14794. */
  14795. #ifndef SQLITE_OS_SETUP_H
  14796. #define SQLITE_OS_SETUP_H
  14797. /*
  14798. ** Figure out if we are dealing with Unix, Windows, or some other operating
  14799. ** system.
  14800. **
  14801. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  14802. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  14803. ** the three will be 1. The other two will be 0.
  14804. */
  14805. #if defined(SQLITE_OS_OTHER)
  14806. # if SQLITE_OS_OTHER==1
  14807. # undef SQLITE_OS_UNIX
  14808. # define SQLITE_OS_UNIX 0
  14809. # undef SQLITE_OS_WIN
  14810. # define SQLITE_OS_WIN 0
  14811. # else
  14812. # undef SQLITE_OS_OTHER
  14813. # endif
  14814. #endif
  14815. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  14816. # define SQLITE_OS_OTHER 0
  14817. # ifndef SQLITE_OS_WIN
  14818. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  14819. defined(__MINGW32__) || defined(__BORLANDC__)
  14820. # define SQLITE_OS_WIN 1
  14821. # define SQLITE_OS_UNIX 0
  14822. # else
  14823. # define SQLITE_OS_WIN 0
  14824. # define SQLITE_OS_UNIX 1
  14825. # endif
  14826. # else
  14827. # define SQLITE_OS_UNIX 0
  14828. # endif
  14829. #else
  14830. # ifndef SQLITE_OS_WIN
  14831. # define SQLITE_OS_WIN 0
  14832. # endif
  14833. #endif
  14834. #endif /* SQLITE_OS_SETUP_H */
  14835. /************** End of os_setup.h ********************************************/
  14836. /************** Continuing where we left off in os.h *************************/
  14837. /* If the SET_FULLSYNC macro is not defined above, then make it
  14838. ** a no-op
  14839. */
  14840. #ifndef SET_FULLSYNC
  14841. # define SET_FULLSYNC(x,y)
  14842. #endif
  14843. /*
  14844. ** The default size of a disk sector
  14845. */
  14846. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  14847. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  14848. #endif
  14849. /*
  14850. ** Temporary files are named starting with this prefix followed by 16 random
  14851. ** alphanumeric characters, and no file extension. They are stored in the
  14852. ** OS's standard temporary file directory, and are deleted prior to exit.
  14853. ** If sqlite is being embedded in another program, you may wish to change the
  14854. ** prefix to reflect your program's name, so that if your program exits
  14855. ** prematurely, old temporary files can be easily identified. This can be done
  14856. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  14857. **
  14858. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  14859. ** Mcafee started using SQLite in their anti-virus product and it
  14860. ** started putting files with the "sqlite" name in the c:/temp folder.
  14861. ** This annoyed many windows users. Those users would then do a
  14862. ** Google search for "sqlite", find the telephone numbers of the
  14863. ** developers and call to wake them up at night and complain.
  14864. ** For this reason, the default name prefix is changed to be "sqlite"
  14865. ** spelled backwards. So the temp files are still identified, but
  14866. ** anybody smart enough to figure out the code is also likely smart
  14867. ** enough to know that calling the developer will not help get rid
  14868. ** of the file.
  14869. */
  14870. #ifndef SQLITE_TEMP_FILE_PREFIX
  14871. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  14872. #endif
  14873. /*
  14874. ** The following values may be passed as the second argument to
  14875. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  14876. **
  14877. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  14878. ** RESERVED: A single process may hold a RESERVED lock on a file at
  14879. ** any time. Other processes may hold and obtain new SHARED locks.
  14880. ** PENDING: A single process may hold a PENDING lock on a file at
  14881. ** any one time. Existing SHARED locks may persist, but no new
  14882. ** SHARED locks may be obtained by other processes.
  14883. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  14884. **
  14885. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  14886. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  14887. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  14888. ** sqlite3OsLock().
  14889. */
  14890. #define NO_LOCK 0
  14891. #define SHARED_LOCK 1
  14892. #define RESERVED_LOCK 2
  14893. #define PENDING_LOCK 3
  14894. #define EXCLUSIVE_LOCK 4
  14895. /*
  14896. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  14897. **
  14898. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  14899. ** those functions are not available. So we use only LockFile() and
  14900. ** UnlockFile().
  14901. **
  14902. ** LockFile() prevents not just writing but also reading by other processes.
  14903. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  14904. ** byte out of a specific range of bytes. The lock byte is obtained at
  14905. ** random so two separate readers can probably access the file at the
  14906. ** same time, unless they are unlucky and choose the same lock byte.
  14907. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  14908. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  14909. ** a single byte of the file that is designated as the reserved lock byte.
  14910. ** A PENDING_LOCK is obtained by locking a designated byte different from
  14911. ** the RESERVED_LOCK byte.
  14912. **
  14913. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  14914. ** which means we can use reader/writer locks. When reader/writer locks
  14915. ** are used, the lock is placed on the same range of bytes that is used
  14916. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  14917. ** will support two or more Win95 readers or two or more WinNT readers.
  14918. ** But a single Win95 reader will lock out all WinNT readers and a single
  14919. ** WinNT reader will lock out all other Win95 readers.
  14920. **
  14921. ** The following #defines specify the range of bytes used for locking.
  14922. ** SHARED_SIZE is the number of bytes available in the pool from which
  14923. ** a random byte is selected for a shared lock. The pool of bytes for
  14924. ** shared locks begins at SHARED_FIRST.
  14925. **
  14926. ** The same locking strategy and
  14927. ** byte ranges are used for Unix. This leaves open the possibility of having
  14928. ** clients on win95, winNT, and unix all talking to the same shared file
  14929. ** and all locking correctly. To do so would require that samba (or whatever
  14930. ** tool is being used for file sharing) implements locks correctly between
  14931. ** windows and unix. I'm guessing that isn't likely to happen, but by
  14932. ** using the same locking range we are at least open to the possibility.
  14933. **
  14934. ** Locking in windows is manditory. For this reason, we cannot store
  14935. ** actual data in the bytes used for locking. The pager never allocates
  14936. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  14937. ** that all locks will fit on a single page even at the minimum page size.
  14938. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  14939. ** is set high so that we don't have to allocate an unused page except
  14940. ** for very large databases. But one should test the page skipping logic
  14941. ** by setting PENDING_BYTE low and running the entire regression suite.
  14942. **
  14943. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  14944. ** file format. Depending on how it is changed, you might not notice
  14945. ** the incompatibility right away, even running a full regression test.
  14946. ** The default location of PENDING_BYTE is the first byte past the
  14947. ** 1GB boundary.
  14948. **
  14949. */
  14950. #ifdef SQLITE_OMIT_WSD
  14951. # define PENDING_BYTE (0x40000000)
  14952. #else
  14953. # define PENDING_BYTE sqlite3PendingByte
  14954. #endif
  14955. #define RESERVED_BYTE (PENDING_BYTE+1)
  14956. #define SHARED_FIRST (PENDING_BYTE+2)
  14957. #define SHARED_SIZE 510
  14958. /*
  14959. ** Wrapper around OS specific sqlite3_os_init() function.
  14960. */
  14961. SQLITE_PRIVATE int sqlite3OsInit(void);
  14962. /*
  14963. ** Functions for accessing sqlite3_file methods
  14964. */
  14965. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  14966. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  14967. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  14968. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  14969. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  14970. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  14971. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  14972. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  14973. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  14974. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  14975. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  14976. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  14977. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  14978. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  14979. #ifndef SQLITE_OMIT_WAL
  14980. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  14981. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  14982. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  14983. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  14984. #endif /* SQLITE_OMIT_WAL */
  14985. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  14986. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  14987. /*
  14988. ** Functions for accessing sqlite3_vfs methods
  14989. */
  14990. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  14991. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  14992. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  14993. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  14994. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14995. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  14996. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  14997. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  14998. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  14999. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15000. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  15001. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  15002. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  15003. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  15004. /*
  15005. ** Convenience functions for opening and closing files using
  15006. ** sqlite3_malloc() to obtain space for the file-handle structure.
  15007. */
  15008. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  15009. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  15010. #endif /* _SQLITE_OS_H_ */
  15011. /************** End of os.h **************************************************/
  15012. /************** Continuing where we left off in sqliteInt.h ******************/
  15013. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  15014. /************** Begin file mutex.h *******************************************/
  15015. /*
  15016. ** 2007 August 28
  15017. **
  15018. ** The author disclaims copyright to this source code. In place of
  15019. ** a legal notice, here is a blessing:
  15020. **
  15021. ** May you do good and not evil.
  15022. ** May you find forgiveness for yourself and forgive others.
  15023. ** May you share freely, never taking more than you give.
  15024. **
  15025. *************************************************************************
  15026. **
  15027. ** This file contains the common header for all mutex implementations.
  15028. ** The sqliteInt.h header #includes this file so that it is available
  15029. ** to all source files. We break it out in an effort to keep the code
  15030. ** better organized.
  15031. **
  15032. ** NOTE: source files should *not* #include this header file directly.
  15033. ** Source files should #include the sqliteInt.h file and let that file
  15034. ** include this one indirectly.
  15035. */
  15036. /*
  15037. ** Figure out what version of the code to use. The choices are
  15038. **
  15039. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  15040. ** mutexes implementation cannot be overridden
  15041. ** at start-time.
  15042. **
  15043. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  15044. ** mutual exclusion is provided. But this
  15045. ** implementation can be overridden at
  15046. ** start-time.
  15047. **
  15048. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  15049. **
  15050. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  15051. */
  15052. #if !SQLITE_THREADSAFE
  15053. # define SQLITE_MUTEX_OMIT
  15054. #endif
  15055. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  15056. # if SQLITE_OS_UNIX
  15057. # define SQLITE_MUTEX_PTHREADS
  15058. # elif SQLITE_OS_WIN
  15059. # define SQLITE_MUTEX_W32
  15060. # else
  15061. # define SQLITE_MUTEX_NOOP
  15062. # endif
  15063. #endif
  15064. #ifdef SQLITE_MUTEX_OMIT
  15065. /*
  15066. ** If this is a no-op implementation, implement everything as macros.
  15067. */
  15068. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  15069. #define sqlite3_mutex_free(X)
  15070. #define sqlite3_mutex_enter(X)
  15071. #define sqlite3_mutex_try(X) SQLITE_OK
  15072. #define sqlite3_mutex_leave(X)
  15073. #define sqlite3_mutex_held(X) ((void)(X),1)
  15074. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  15075. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  15076. #define sqlite3MutexInit() SQLITE_OK
  15077. #define sqlite3MutexEnd()
  15078. #define MUTEX_LOGIC(X)
  15079. #else
  15080. #define MUTEX_LOGIC(X) X
  15081. #endif /* defined(SQLITE_MUTEX_OMIT) */
  15082. /************** End of mutex.h ***********************************************/
  15083. /************** Continuing where we left off in sqliteInt.h ******************/
  15084. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  15085. ** synchronous setting to EXTRA. It is no longer supported.
  15086. */
  15087. #ifdef SQLITE_EXTRA_DURABLE
  15088. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  15089. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  15090. #endif
  15091. /*
  15092. ** Default synchronous levels.
  15093. **
  15094. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  15095. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  15096. **
  15097. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  15098. ** OFF 1 0
  15099. ** NORMAL 2 1
  15100. ** FULL 3 2
  15101. ** EXTRA 4 3
  15102. **
  15103. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  15104. ** In other words, the zero-based numbers are used for all external interfaces
  15105. ** and the one-based values are used internally.
  15106. */
  15107. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  15108. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  15109. #endif
  15110. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  15111. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  15112. #endif
  15113. /*
  15114. ** Each database file to be accessed by the system is an instance
  15115. ** of the following structure. There are normally two of these structures
  15116. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  15117. ** aDb[1] is the database file used to hold temporary tables. Additional
  15118. ** databases may be attached.
  15119. */
  15120. struct Db {
  15121. char *zDbSName; /* Name of this database. (schema name, not filename) */
  15122. Btree *pBt; /* The B*Tree structure for this database file */
  15123. u8 safety_level; /* How aggressive at syncing data to disk */
  15124. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  15125. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  15126. };
  15127. /*
  15128. ** An instance of the following structure stores a database schema.
  15129. **
  15130. ** Most Schema objects are associated with a Btree. The exception is
  15131. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  15132. ** In shared cache mode, a single Schema object can be shared by multiple
  15133. ** Btrees that refer to the same underlying BtShared object.
  15134. **
  15135. ** Schema objects are automatically deallocated when the last Btree that
  15136. ** references them is destroyed. The TEMP Schema is manually freed by
  15137. ** sqlite3_close().
  15138. *
  15139. ** A thread must be holding a mutex on the corresponding Btree in order
  15140. ** to access Schema content. This implies that the thread must also be
  15141. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  15142. ** For a TEMP Schema, only the connection mutex is required.
  15143. */
  15144. struct Schema {
  15145. int schema_cookie; /* Database schema version number for this file */
  15146. int iGeneration; /* Generation counter. Incremented with each change */
  15147. Hash tblHash; /* All tables indexed by name */
  15148. Hash idxHash; /* All (named) indices indexed by name */
  15149. Hash trigHash; /* All triggers indexed by name */
  15150. Hash fkeyHash; /* All foreign keys by referenced table name */
  15151. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  15152. u8 file_format; /* Schema format version for this file */
  15153. u8 enc; /* Text encoding used by this database */
  15154. u16 schemaFlags; /* Flags associated with this schema */
  15155. int cache_size; /* Number of pages to use in the cache */
  15156. };
  15157. /*
  15158. ** These macros can be used to test, set, or clear bits in the
  15159. ** Db.pSchema->flags field.
  15160. */
  15161. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  15162. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  15163. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  15164. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  15165. /*
  15166. ** Allowed values for the DB.pSchema->flags field.
  15167. **
  15168. ** The DB_SchemaLoaded flag is set after the database schema has been
  15169. ** read into internal hash tables.
  15170. **
  15171. ** DB_UnresetViews means that one or more views have column names that
  15172. ** have been filled out. If the schema changes, these column names might
  15173. ** changes and so the view will need to be reset.
  15174. */
  15175. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  15176. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  15177. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  15178. #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
  15179. /*
  15180. ** The number of different kinds of things that can be limited
  15181. ** using the sqlite3_limit() interface.
  15182. */
  15183. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  15184. /*
  15185. ** Lookaside malloc is a set of fixed-size buffers that can be used
  15186. ** to satisfy small transient memory allocation requests for objects
  15187. ** associated with a particular database connection. The use of
  15188. ** lookaside malloc provides a significant performance enhancement
  15189. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  15190. ** SQL statements.
  15191. **
  15192. ** The Lookaside structure holds configuration information about the
  15193. ** lookaside malloc subsystem. Each available memory allocation in
  15194. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  15195. ** objects.
  15196. **
  15197. ** Lookaside allocations are only allowed for objects that are associated
  15198. ** with a particular database connection. Hence, schema information cannot
  15199. ** be stored in lookaside because in shared cache mode the schema information
  15200. ** is shared by multiple database connections. Therefore, while parsing
  15201. ** schema information, the Lookaside.bEnabled flag is cleared so that
  15202. ** lookaside allocations are not used to construct the schema objects.
  15203. */
  15204. struct Lookaside {
  15205. u32 bDisable; /* Only operate the lookaside when zero */
  15206. u16 sz; /* Size of each buffer in bytes */
  15207. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  15208. u32 nSlot; /* Number of lookaside slots allocated */
  15209. u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  15210. LookasideSlot *pInit; /* List of buffers not previously used */
  15211. LookasideSlot *pFree; /* List of available buffers */
  15212. void *pStart; /* First byte of available memory space */
  15213. void *pEnd; /* First byte past end of available space */
  15214. };
  15215. struct LookasideSlot {
  15216. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  15217. };
  15218. /*
  15219. ** A hash table for built-in function definitions. (Application-defined
  15220. ** functions use a regular table table from hash.h.)
  15221. **
  15222. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  15223. ** Collisions are on the FuncDef.u.pHash chain.
  15224. */
  15225. #define SQLITE_FUNC_HASH_SZ 23
  15226. struct FuncDefHash {
  15227. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  15228. };
  15229. #ifdef SQLITE_USER_AUTHENTICATION
  15230. /*
  15231. ** Information held in the "sqlite3" database connection object and used
  15232. ** to manage user authentication.
  15233. */
  15234. typedef struct sqlite3_userauth sqlite3_userauth;
  15235. struct sqlite3_userauth {
  15236. u8 authLevel; /* Current authentication level */
  15237. int nAuthPW; /* Size of the zAuthPW in bytes */
  15238. char *zAuthPW; /* Password used to authenticate */
  15239. char *zAuthUser; /* User name used to authenticate */
  15240. };
  15241. /* Allowed values for sqlite3_userauth.authLevel */
  15242. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  15243. #define UAUTH_Fail 1 /* User authentication failed */
  15244. #define UAUTH_User 2 /* Authenticated as a normal user */
  15245. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  15246. /* Functions used only by user authorization logic */
  15247. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  15248. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  15249. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  15250. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  15251. #endif /* SQLITE_USER_AUTHENTICATION */
  15252. /*
  15253. ** typedef for the authorization callback function.
  15254. */
  15255. #ifdef SQLITE_USER_AUTHENTICATION
  15256. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15257. const char*, const char*);
  15258. #else
  15259. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15260. const char*);
  15261. #endif
  15262. #ifndef SQLITE_OMIT_DEPRECATED
  15263. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  15264. ** in the style of sqlite3_trace()
  15265. */
  15266. #define SQLITE_TRACE_LEGACY 0x80
  15267. #else
  15268. #define SQLITE_TRACE_LEGACY 0
  15269. #endif /* SQLITE_OMIT_DEPRECATED */
  15270. /*
  15271. ** Each database connection is an instance of the following structure.
  15272. */
  15273. struct sqlite3 {
  15274. sqlite3_vfs *pVfs; /* OS Interface */
  15275. struct Vdbe *pVdbe; /* List of active virtual machines */
  15276. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  15277. sqlite3_mutex *mutex; /* Connection mutex */
  15278. Db *aDb; /* All backends */
  15279. int nDb; /* Number of backends currently in use */
  15280. u32 mDbFlags; /* flags recording internal state */
  15281. u32 flags; /* flags settable by pragmas. See below */
  15282. i64 lastRowid; /* ROWID of most recent insert (see above) */
  15283. i64 szMmap; /* Default mmap_size setting */
  15284. u32 nSchemaLock; /* Do not reset the schema when non-zero */
  15285. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  15286. int errCode; /* Most recent error code (SQLITE_*) */
  15287. int errMask; /* & result codes with this before returning */
  15288. int iSysErrno; /* Errno value from last system error */
  15289. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  15290. u8 enc; /* Text encoding */
  15291. u8 autoCommit; /* The auto-commit flag. */
  15292. u8 temp_store; /* 1: file 2: memory 0: default */
  15293. u8 mallocFailed; /* True if we have seen a malloc failure */
  15294. u8 bBenignMalloc; /* Do not require OOMs if true */
  15295. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  15296. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  15297. u8 suppressErr; /* Do not issue error messages if true */
  15298. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  15299. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  15300. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  15301. u8 noSharedCache; /* True if no shared-cache backends */
  15302. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  15303. int nextPagesize; /* Pagesize after VACUUM if >0 */
  15304. u32 magic; /* Magic number for detect library misuse */
  15305. int nChange; /* Value returned by sqlite3_changes() */
  15306. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  15307. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  15308. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  15309. struct sqlite3InitInfo { /* Information used during initialization */
  15310. int newTnum; /* Rootpage of table being initialized */
  15311. u8 iDb; /* Which db file is being initialized */
  15312. u8 busy; /* TRUE if currently initializing */
  15313. unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
  15314. unsigned imposterTable : 1; /* Building an imposter table */
  15315. unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
  15316. } init;
  15317. int nVdbeActive; /* Number of VDBEs currently running */
  15318. int nVdbeRead; /* Number of active VDBEs that read or write */
  15319. int nVdbeWrite; /* Number of active VDBEs that read and write */
  15320. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  15321. int nVDestroy; /* Number of active OP_VDestroy operations */
  15322. int nExtension; /* Number of loaded extensions */
  15323. void **aExtension; /* Array of shared library handles */
  15324. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  15325. void *pTraceArg; /* Argument to the trace function */
  15326. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  15327. void *pProfileArg; /* Argument to profile function */
  15328. void *pCommitArg; /* Argument to xCommitCallback() */
  15329. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  15330. void *pRollbackArg; /* Argument to xRollbackCallback() */
  15331. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  15332. void *pUpdateArg;
  15333. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  15334. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  15335. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  15336. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  15337. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  15338. );
  15339. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  15340. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  15341. #ifndef SQLITE_OMIT_WAL
  15342. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  15343. void *pWalArg;
  15344. #endif
  15345. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  15346. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  15347. void *pCollNeededArg;
  15348. sqlite3_value *pErr; /* Most recent error message */
  15349. union {
  15350. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  15351. double notUsed1; /* Spacer */
  15352. } u1;
  15353. Lookaside lookaside; /* Lookaside malloc configuration */
  15354. #ifndef SQLITE_OMIT_AUTHORIZATION
  15355. sqlite3_xauth xAuth; /* Access authorization function */
  15356. void *pAuthArg; /* 1st argument to the access auth function */
  15357. #endif
  15358. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  15359. int (*xProgress)(void *); /* The progress callback */
  15360. void *pProgressArg; /* Argument to the progress callback */
  15361. unsigned nProgressOps; /* Number of opcodes for progress callback */
  15362. #endif
  15363. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15364. int nVTrans; /* Allocated size of aVTrans */
  15365. Hash aModule; /* populated by sqlite3_create_module() */
  15366. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  15367. VTable **aVTrans; /* Virtual tables with open transactions */
  15368. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  15369. #endif
  15370. Hash aFunc; /* Hash table of connection functions */
  15371. Hash aCollSeq; /* All collating sequences */
  15372. BusyHandler busyHandler; /* Busy callback */
  15373. Db aDbStatic[2]; /* Static space for the 2 default backends */
  15374. Savepoint *pSavepoint; /* List of active savepoints */
  15375. int busyTimeout; /* Busy handler timeout, in msec */
  15376. int nSavepoint; /* Number of non-transaction savepoints */
  15377. int nStatement; /* Number of nested statement-transactions */
  15378. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  15379. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  15380. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  15381. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  15382. /* The following variables are all protected by the STATIC_MASTER
  15383. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  15384. **
  15385. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  15386. ** unlock so that it can proceed.
  15387. **
  15388. ** When X.pBlockingConnection==Y, that means that something that X tried
  15389. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  15390. ** held by Y.
  15391. */
  15392. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  15393. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  15394. void *pUnlockArg; /* Argument to xUnlockNotify */
  15395. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  15396. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  15397. #endif
  15398. #ifdef SQLITE_USER_AUTHENTICATION
  15399. sqlite3_userauth auth; /* User authentication information */
  15400. #endif
  15401. };
  15402. /*
  15403. ** A macro to discover the encoding of a database.
  15404. */
  15405. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  15406. #define ENC(db) ((db)->enc)
  15407. /*
  15408. ** Possible values for the sqlite3.flags.
  15409. **
  15410. ** Value constraints (enforced via assert()):
  15411. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  15412. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  15413. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  15414. */
  15415. #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
  15416. #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
  15417. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  15418. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  15419. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  15420. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  15421. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  15422. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  15423. /* DELETE, or UPDATE and return */
  15424. /* the count using a callback. */
  15425. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  15426. /* result set is empty */
  15427. #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
  15428. #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
  15429. #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
  15430. #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
  15431. #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
  15432. #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
  15433. #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
  15434. #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
  15435. #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
  15436. #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
  15437. #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
  15438. #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
  15439. #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
  15440. #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
  15441. #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
  15442. #define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
  15443. #define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
  15444. /* Flags used only if debugging */
  15445. #ifdef SQLITE_DEBUG
  15446. #define SQLITE_SqlTrace 0x08000000 /* Debug print SQL as it executes */
  15447. #define SQLITE_VdbeListing 0x10000000 /* Debug listings of VDBE programs */
  15448. #define SQLITE_VdbeTrace 0x20000000 /* True to trace VDBE execution */
  15449. #define SQLITE_VdbeAddopTrace 0x40000000 /* Trace sqlite3VdbeAddOp() calls */
  15450. #define SQLITE_VdbeEQP 0x80000000 /* Debug EXPLAIN QUERY PLAN */
  15451. #endif
  15452. /*
  15453. ** Allowed values for sqlite3.mDbFlags
  15454. */
  15455. #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
  15456. #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
  15457. #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
  15458. #define DBFLAG_SchemaKnownOk 0x0008 /* Schema is known to be valid */
  15459. /*
  15460. ** Bits of the sqlite3.dbOptFlags field that are used by the
  15461. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  15462. ** selectively disable various optimizations.
  15463. */
  15464. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  15465. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  15466. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  15467. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  15468. #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
  15469. #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
  15470. #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
  15471. #define SQLITE_Transitive 0x0080 /* Transitive constraints */
  15472. #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
  15473. #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
  15474. #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
  15475. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  15476. /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
  15477. #define SQLITE_PushDown 0x1000 /* The push-down optimization */
  15478. #define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
  15479. #define SQLITE_AllOpts 0xffff /* All optimizations */
  15480. /*
  15481. ** Macros for testing whether or not optimizations are enabled or disabled.
  15482. */
  15483. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  15484. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  15485. /*
  15486. ** Return true if it OK to factor constant expressions into the initialization
  15487. ** code. The argument is a Parse object for the code generator.
  15488. */
  15489. #define ConstFactorOk(P) ((P)->okConstFactor)
  15490. /*
  15491. ** Possible values for the sqlite.magic field.
  15492. ** The numbers are obtained at random and have no special meaning, other
  15493. ** than being distinct from one another.
  15494. */
  15495. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  15496. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  15497. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  15498. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  15499. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  15500. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  15501. /*
  15502. ** Each SQL function is defined by an instance of the following
  15503. ** structure. For global built-in functions (ex: substr(), max(), count())
  15504. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  15505. ** For per-connection application-defined functions, a pointer to this
  15506. ** structure is held in the db->aHash hash table.
  15507. **
  15508. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  15509. ** field is used by per-connection app-def functions.
  15510. */
  15511. struct FuncDef {
  15512. i8 nArg; /* Number of arguments. -1 means unlimited */
  15513. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  15514. void *pUserData; /* User data parameter */
  15515. FuncDef *pNext; /* Next function with same name */
  15516. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  15517. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  15518. const char *zName; /* SQL name of the function. */
  15519. union {
  15520. FuncDef *pHash; /* Next with a different name but the same hash */
  15521. FuncDestructor *pDestructor; /* Reference counted destructor function */
  15522. } u;
  15523. };
  15524. /*
  15525. ** This structure encapsulates a user-function destructor callback (as
  15526. ** configured using create_function_v2()) and a reference counter. When
  15527. ** create_function_v2() is called to create a function with a destructor,
  15528. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  15529. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  15530. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  15531. ** member of each of the new FuncDef objects is set to point to the allocated
  15532. ** FuncDestructor.
  15533. **
  15534. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  15535. ** count on this object is decremented. When it reaches 0, the destructor
  15536. ** is invoked and the FuncDestructor structure freed.
  15537. */
  15538. struct FuncDestructor {
  15539. int nRef;
  15540. void (*xDestroy)(void *);
  15541. void *pUserData;
  15542. };
  15543. /*
  15544. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  15545. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  15546. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  15547. ** are assert() statements in the code to verify this.
  15548. **
  15549. ** Value constraints (enforced via assert()):
  15550. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  15551. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  15552. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  15553. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  15554. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  15555. */
  15556. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  15557. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  15558. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  15559. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  15560. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  15561. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  15562. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  15563. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  15564. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  15565. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  15566. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  15567. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  15568. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  15569. ** single query - might change over time */
  15570. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  15571. #define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
  15572. /*
  15573. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  15574. ** used to create the initializers for the FuncDef structures.
  15575. **
  15576. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  15577. ** Used to create a scalar function definition of a function zName
  15578. ** implemented by C function xFunc that accepts nArg arguments. The
  15579. ** value passed as iArg is cast to a (void*) and made available
  15580. ** as the user-data (sqlite3_user_data()) for the function. If
  15581. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  15582. **
  15583. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  15584. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  15585. **
  15586. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  15587. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  15588. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  15589. ** and functions like sqlite_version() that can change, but not during
  15590. ** a single query. The iArg is ignored. The user-data is always set
  15591. ** to a NULL pointer. The bNC parameter is not used.
  15592. **
  15593. ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
  15594. ** Used for "pure" date/time functions, this macro is like DFUNCTION
  15595. ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
  15596. ** ignored and the user-data for these functions is set to an
  15597. ** arbitrary non-NULL pointer. The bNC parameter is not used.
  15598. **
  15599. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  15600. ** Used to create an aggregate function definition implemented by
  15601. ** the C functions xStep and xFinal. The first four parameters
  15602. ** are interpreted in the same way as the first 4 parameters to
  15603. ** FUNCTION().
  15604. **
  15605. ** LIKEFUNC(zName, nArg, pArg, flags)
  15606. ** Used to create a scalar function definition of a function zName
  15607. ** that accepts nArg arguments and is implemented by a call to C
  15608. ** function likeFunc. Argument pArg is cast to a (void *) and made
  15609. ** available as the function user-data (sqlite3_user_data()). The
  15610. ** FuncDef.flags variable is set to the value passed as the flags
  15611. ** parameter.
  15612. */
  15613. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15614. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15615. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  15616. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15617. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15618. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  15619. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15620. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
  15621. 0, 0, xFunc, 0, #zName, {0} }
  15622. #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
  15623. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  15624. (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
  15625. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  15626. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  15627. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  15628. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  15629. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15630. pArg, 0, xFunc, 0, #zName, }
  15631. #define LIKEFUNC(zName, nArg, arg, flags) \
  15632. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  15633. (void *)arg, 0, likeFunc, 0, #zName, {0} }
  15634. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  15635. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  15636. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  15637. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  15638. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  15639. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  15640. /*
  15641. ** All current savepoints are stored in a linked list starting at
  15642. ** sqlite3.pSavepoint. The first element in the list is the most recently
  15643. ** opened savepoint. Savepoints are added to the list by the vdbe
  15644. ** OP_Savepoint instruction.
  15645. */
  15646. struct Savepoint {
  15647. char *zName; /* Savepoint name (nul-terminated) */
  15648. i64 nDeferredCons; /* Number of deferred fk violations */
  15649. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  15650. Savepoint *pNext; /* Parent savepoint (if any) */
  15651. };
  15652. /*
  15653. ** The following are used as the second parameter to sqlite3Savepoint(),
  15654. ** and as the P1 argument to the OP_Savepoint instruction.
  15655. */
  15656. #define SAVEPOINT_BEGIN 0
  15657. #define SAVEPOINT_RELEASE 1
  15658. #define SAVEPOINT_ROLLBACK 2
  15659. /*
  15660. ** Each SQLite module (virtual table definition) is defined by an
  15661. ** instance of the following structure, stored in the sqlite3.aModule
  15662. ** hash table.
  15663. */
  15664. struct Module {
  15665. const sqlite3_module *pModule; /* Callback pointers */
  15666. const char *zName; /* Name passed to create_module() */
  15667. void *pAux; /* pAux passed to create_module() */
  15668. void (*xDestroy)(void *); /* Module destructor function */
  15669. Table *pEpoTab; /* Eponymous table for this module */
  15670. };
  15671. /*
  15672. ** information about each column of an SQL table is held in an instance
  15673. ** of this structure.
  15674. */
  15675. struct Column {
  15676. char *zName; /* Name of this column, \000, then the type */
  15677. Expr *pDflt; /* Default value of this column */
  15678. char *zColl; /* Collating sequence. If NULL, use the default */
  15679. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  15680. char affinity; /* One of the SQLITE_AFF_... values */
  15681. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  15682. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  15683. };
  15684. /* Allowed values for Column.colFlags:
  15685. */
  15686. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  15687. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  15688. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  15689. #define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
  15690. #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
  15691. /*
  15692. ** A "Collating Sequence" is defined by an instance of the following
  15693. ** structure. Conceptually, a collating sequence consists of a name and
  15694. ** a comparison routine that defines the order of that sequence.
  15695. **
  15696. ** If CollSeq.xCmp is NULL, it means that the
  15697. ** collating sequence is undefined. Indices built on an undefined
  15698. ** collating sequence may not be read or written.
  15699. */
  15700. struct CollSeq {
  15701. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  15702. u8 enc; /* Text encoding handled by xCmp() */
  15703. void *pUser; /* First argument to xCmp() */
  15704. int (*xCmp)(void*,int, const void*, int, const void*);
  15705. void (*xDel)(void*); /* Destructor for pUser */
  15706. };
  15707. /*
  15708. ** A sort order can be either ASC or DESC.
  15709. */
  15710. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  15711. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  15712. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  15713. /*
  15714. ** Column affinity types.
  15715. **
  15716. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  15717. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  15718. ** the speed a little by numbering the values consecutively.
  15719. **
  15720. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  15721. ** when multiple affinity types are concatenated into a string and
  15722. ** used as the P4 operand, they will be more readable.
  15723. **
  15724. ** Note also that the numeric types are grouped together so that testing
  15725. ** for a numeric type is a single comparison. And the BLOB type is first.
  15726. */
  15727. #define SQLITE_AFF_BLOB 'A'
  15728. #define SQLITE_AFF_TEXT 'B'
  15729. #define SQLITE_AFF_NUMERIC 'C'
  15730. #define SQLITE_AFF_INTEGER 'D'
  15731. #define SQLITE_AFF_REAL 'E'
  15732. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  15733. /*
  15734. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  15735. ** affinity value.
  15736. */
  15737. #define SQLITE_AFF_MASK 0x47
  15738. /*
  15739. ** Additional bit values that can be ORed with an affinity without
  15740. ** changing the affinity.
  15741. **
  15742. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  15743. ** It causes an assert() to fire if either operand to a comparison
  15744. ** operator is NULL. It is added to certain comparison operators to
  15745. ** prove that the operands are always NOT NULL.
  15746. */
  15747. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  15748. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  15749. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  15750. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  15751. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  15752. /*
  15753. ** An object of this type is created for each virtual table present in
  15754. ** the database schema.
  15755. **
  15756. ** If the database schema is shared, then there is one instance of this
  15757. ** structure for each database connection (sqlite3*) that uses the shared
  15758. ** schema. This is because each database connection requires its own unique
  15759. ** instance of the sqlite3_vtab* handle used to access the virtual table
  15760. ** implementation. sqlite3_vtab* handles can not be shared between
  15761. ** database connections, even when the rest of the in-memory database
  15762. ** schema is shared, as the implementation often stores the database
  15763. ** connection handle passed to it via the xConnect() or xCreate() method
  15764. ** during initialization internally. This database connection handle may
  15765. ** then be used by the virtual table implementation to access real tables
  15766. ** within the database. So that they appear as part of the callers
  15767. ** transaction, these accesses need to be made via the same database
  15768. ** connection as that used to execute SQL operations on the virtual table.
  15769. **
  15770. ** All VTable objects that correspond to a single table in a shared
  15771. ** database schema are initially stored in a linked-list pointed to by
  15772. ** the Table.pVTable member variable of the corresponding Table object.
  15773. ** When an sqlite3_prepare() operation is required to access the virtual
  15774. ** table, it searches the list for the VTable that corresponds to the
  15775. ** database connection doing the preparing so as to use the correct
  15776. ** sqlite3_vtab* handle in the compiled query.
  15777. **
  15778. ** When an in-memory Table object is deleted (for example when the
  15779. ** schema is being reloaded for some reason), the VTable objects are not
  15780. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  15781. ** immediately. Instead, they are moved from the Table.pVTable list to
  15782. ** another linked list headed by the sqlite3.pDisconnect member of the
  15783. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  15784. ** next time a statement is prepared using said sqlite3*. This is done
  15785. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  15786. ** Refer to comments above function sqlite3VtabUnlockList() for an
  15787. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  15788. ** list without holding the corresponding sqlite3.mutex mutex.
  15789. **
  15790. ** The memory for objects of this type is always allocated by
  15791. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  15792. ** the first argument.
  15793. */
  15794. struct VTable {
  15795. sqlite3 *db; /* Database connection associated with this table */
  15796. Module *pMod; /* Pointer to module implementation */
  15797. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  15798. int nRef; /* Number of pointers to this structure */
  15799. u8 bConstraint; /* True if constraints are supported */
  15800. int iSavepoint; /* Depth of the SAVEPOINT stack */
  15801. VTable *pNext; /* Next in linked list (see above) */
  15802. };
  15803. /*
  15804. ** The schema for each SQL table and view is represented in memory
  15805. ** by an instance of the following structure.
  15806. */
  15807. struct Table {
  15808. char *zName; /* Name of the table or view */
  15809. Column *aCol; /* Information about each column */
  15810. Index *pIndex; /* List of SQL indexes on this table. */
  15811. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  15812. FKey *pFKey; /* Linked list of all foreign keys in this table */
  15813. char *zColAff; /* String defining the affinity of each column */
  15814. ExprList *pCheck; /* All CHECK constraints */
  15815. /* ... also used as column name list in a VIEW */
  15816. int tnum; /* Root BTree page for this table */
  15817. u32 nTabRef; /* Number of pointers to this Table */
  15818. u32 tabFlags; /* Mask of TF_* values */
  15819. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  15820. i16 nCol; /* Number of columns in this table */
  15821. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  15822. LogEst szTabRow; /* Estimated size of each table row in bytes */
  15823. #ifdef SQLITE_ENABLE_COSTMULT
  15824. LogEst costMult; /* Cost multiplier for using this table */
  15825. #endif
  15826. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  15827. #ifndef SQLITE_OMIT_ALTERTABLE
  15828. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  15829. #endif
  15830. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15831. int nModuleArg; /* Number of arguments to the module */
  15832. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  15833. VTable *pVTable; /* List of VTable objects. */
  15834. #endif
  15835. Trigger *pTrigger; /* List of triggers stored in pSchema */
  15836. Schema *pSchema; /* Schema that contains this table */
  15837. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  15838. };
  15839. /*
  15840. ** Allowed values for Table.tabFlags.
  15841. **
  15842. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  15843. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  15844. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  15845. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  15846. ** special handling during INSERT processing.
  15847. */
  15848. #define TF_Readonly 0x0001 /* Read-only system table */
  15849. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  15850. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  15851. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  15852. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  15853. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  15854. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  15855. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  15856. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  15857. ** Index.aiRowLogEst[] values */
  15858. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  15859. /*
  15860. ** Test to see whether or not a table is a virtual table. This is
  15861. ** done as a macro so that it will be optimized out when virtual
  15862. ** table support is omitted from the build.
  15863. */
  15864. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15865. # define IsVirtual(X) ((X)->nModuleArg)
  15866. #else
  15867. # define IsVirtual(X) 0
  15868. #endif
  15869. /*
  15870. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  15871. ** only works for non-virtual tables (ordinary tables and views) and is
  15872. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  15873. ** IsHiddenColumn() macro is general purpose.
  15874. */
  15875. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  15876. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15877. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15878. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  15879. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15880. # define IsOrdinaryHiddenColumn(X) 0
  15881. #else
  15882. # define IsHiddenColumn(X) 0
  15883. # define IsOrdinaryHiddenColumn(X) 0
  15884. #endif
  15885. /* Does the table have a rowid */
  15886. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  15887. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  15888. /*
  15889. ** Each foreign key constraint is an instance of the following structure.
  15890. **
  15891. ** A foreign key is associated with two tables. The "from" table is
  15892. ** the table that contains the REFERENCES clause that creates the foreign
  15893. ** key. The "to" table is the table that is named in the REFERENCES clause.
  15894. ** Consider this example:
  15895. **
  15896. ** CREATE TABLE ex1(
  15897. ** a INTEGER PRIMARY KEY,
  15898. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  15899. ** );
  15900. **
  15901. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  15902. ** Equivalent names:
  15903. **
  15904. ** from-table == child-table
  15905. ** to-table == parent-table
  15906. **
  15907. ** Each REFERENCES clause generates an instance of the following structure
  15908. ** which is attached to the from-table. The to-table need not exist when
  15909. ** the from-table is created. The existence of the to-table is not checked.
  15910. **
  15911. ** The list of all parents for child Table X is held at X.pFKey.
  15912. **
  15913. ** A list of all children for a table named Z (which might not even exist)
  15914. ** is held in Schema.fkeyHash with a hash key of Z.
  15915. */
  15916. struct FKey {
  15917. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  15918. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  15919. char *zTo; /* Name of table that the key points to (aka: Parent) */
  15920. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  15921. FKey *pPrevTo; /* Previous with the same zTo */
  15922. int nCol; /* Number of columns in this key */
  15923. /* EV: R-30323-21917 */
  15924. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  15925. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  15926. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  15927. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  15928. int iFrom; /* Index of column in pFrom */
  15929. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  15930. } aCol[1]; /* One entry for each of nCol columns */
  15931. };
  15932. /*
  15933. ** SQLite supports many different ways to resolve a constraint
  15934. ** error. ROLLBACK processing means that a constraint violation
  15935. ** causes the operation in process to fail and for the current transaction
  15936. ** to be rolled back. ABORT processing means the operation in process
  15937. ** fails and any prior changes from that one operation are backed out,
  15938. ** but the transaction is not rolled back. FAIL processing means that
  15939. ** the operation in progress stops and returns an error code. But prior
  15940. ** changes due to the same operation are not backed out and no rollback
  15941. ** occurs. IGNORE means that the particular row that caused the constraint
  15942. ** error is not inserted or updated. Processing continues and no error
  15943. ** is returned. REPLACE means that preexisting database rows that caused
  15944. ** a UNIQUE constraint violation are removed so that the new insert or
  15945. ** update can proceed. Processing continues and no error is reported.
  15946. **
  15947. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  15948. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  15949. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  15950. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  15951. ** referenced table row is propagated into the row that holds the
  15952. ** foreign key.
  15953. **
  15954. ** The following symbolic values are used to record which type
  15955. ** of action to take.
  15956. */
  15957. #define OE_None 0 /* There is no constraint to check */
  15958. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  15959. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  15960. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  15961. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  15962. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  15963. #define OE_Update 6 /* Process as a DO UPDATE in an upsert */
  15964. #define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  15965. #define OE_SetNull 8 /* Set the foreign key value to NULL */
  15966. #define OE_SetDflt 9 /* Set the foreign key value to its default */
  15967. #define OE_Cascade 10 /* Cascade the changes */
  15968. #define OE_Default 11 /* Do whatever the default action is */
  15969. /*
  15970. ** An instance of the following structure is passed as the first
  15971. ** argument to sqlite3VdbeKeyCompare and is used to control the
  15972. ** comparison of the two index keys.
  15973. **
  15974. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  15975. ** are nField slots for the columns of an index then one extra slot
  15976. ** for the rowid at the end.
  15977. */
  15978. struct KeyInfo {
  15979. u32 nRef; /* Number of references to this KeyInfo object */
  15980. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  15981. u16 nKeyField; /* Number of key columns in the index */
  15982. u16 nAllField; /* Total columns, including key plus others */
  15983. sqlite3 *db; /* The database connection */
  15984. u8 *aSortOrder; /* Sort order for each column. */
  15985. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  15986. };
  15987. /*
  15988. ** This object holds a record which has been parsed out into individual
  15989. ** fields, for the purposes of doing a comparison.
  15990. **
  15991. ** A record is an object that contains one or more fields of data.
  15992. ** Records are used to store the content of a table row and to store
  15993. ** the key of an index. A blob encoding of a record is created by
  15994. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  15995. ** OP_Column opcode.
  15996. **
  15997. ** An instance of this object serves as a "key" for doing a search on
  15998. ** an index b+tree. The goal of the search is to find the entry that
  15999. ** is closed to the key described by this object. This object might hold
  16000. ** just a prefix of the key. The number of fields is given by
  16001. ** pKeyInfo->nField.
  16002. **
  16003. ** The r1 and r2 fields are the values to return if this key is less than
  16004. ** or greater than a key in the btree, respectively. These are normally
  16005. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  16006. ** is in DESC order.
  16007. **
  16008. ** The key comparison functions actually return default_rc when they find
  16009. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  16010. ** multiple entries in the b-tree with the same key (when only looking
  16011. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  16012. ** cause the search to find the last match, or +1 to cause the search to
  16013. ** find the first match.
  16014. **
  16015. ** The key comparison functions will set eqSeen to true if they ever
  16016. ** get and equal results when comparing this structure to a b-tree record.
  16017. ** When default_rc!=0, the search might end up on the record immediately
  16018. ** before the first match or immediately after the last match. The
  16019. ** eqSeen field will indicate whether or not an exact match exists in the
  16020. ** b-tree.
  16021. */
  16022. struct UnpackedRecord {
  16023. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  16024. Mem *aMem; /* Values */
  16025. u16 nField; /* Number of entries in apMem[] */
  16026. i8 default_rc; /* Comparison result if keys are equal */
  16027. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  16028. i8 r1; /* Value to return if (lhs < rhs) */
  16029. i8 r2; /* Value to return if (lhs > rhs) */
  16030. u8 eqSeen; /* True if an equality comparison has been seen */
  16031. };
  16032. /*
  16033. ** Each SQL index is represented in memory by an
  16034. ** instance of the following structure.
  16035. **
  16036. ** The columns of the table that are to be indexed are described
  16037. ** by the aiColumn[] field of this structure. For example, suppose
  16038. ** we have the following table and index:
  16039. **
  16040. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  16041. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  16042. **
  16043. ** In the Table structure describing Ex1, nCol==3 because there are
  16044. ** three columns in the table. In the Index structure describing
  16045. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  16046. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  16047. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  16048. ** The second column to be indexed (c1) has an index of 0 in
  16049. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  16050. **
  16051. ** The Index.onError field determines whether or not the indexed columns
  16052. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  16053. ** it means this is not a unique index. Otherwise it is a unique index
  16054. ** and the value of Index.onError indicate the which conflict resolution
  16055. ** algorithm to employ whenever an attempt is made to insert a non-unique
  16056. ** element.
  16057. **
  16058. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  16059. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  16060. ** table as part of parsing an existing database schema), transient instances
  16061. ** of this structure may be created. In this case the Index.tnum variable is
  16062. ** used to store the address of a VDBE instruction, not a database page
  16063. ** number (it cannot - the database page is not allocated until the VDBE
  16064. ** program is executed). See convertToWithoutRowidTable() for details.
  16065. */
  16066. struct Index {
  16067. char *zName; /* Name of this index */
  16068. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  16069. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  16070. Table *pTable; /* The SQL table being indexed */
  16071. char *zColAff; /* String defining the affinity of each column */
  16072. Index *pNext; /* The next index associated with the same table */
  16073. Schema *pSchema; /* Schema containing this index */
  16074. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  16075. const char **azColl; /* Array of collation sequence names for index */
  16076. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  16077. ExprList *aColExpr; /* Column expressions */
  16078. int tnum; /* DB Page containing root of this index */
  16079. LogEst szIdxRow; /* Estimated average row size in bytes */
  16080. u16 nKeyCol; /* Number of columns forming the key */
  16081. u16 nColumn; /* Number of columns stored in the index */
  16082. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  16083. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  16084. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  16085. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  16086. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  16087. unsigned isCovering:1; /* True if this is a covering index */
  16088. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  16089. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  16090. unsigned bNoQuery:1; /* Do not use this index to optimize queries */
  16091. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  16092. int nSample; /* Number of elements in aSample[] */
  16093. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  16094. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  16095. IndexSample *aSample; /* Samples of the left-most key */
  16096. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  16097. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  16098. #endif
  16099. };
  16100. /*
  16101. ** Allowed values for Index.idxType
  16102. */
  16103. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  16104. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  16105. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  16106. /* Return true if index X is a PRIMARY KEY index */
  16107. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  16108. /* Return true if index X is a UNIQUE index */
  16109. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  16110. /* The Index.aiColumn[] values are normally positive integer. But
  16111. ** there are some negative values that have special meaning:
  16112. */
  16113. #define XN_ROWID (-1) /* Indexed column is the rowid */
  16114. #define XN_EXPR (-2) /* Indexed column is an expression */
  16115. /*
  16116. ** Each sample stored in the sqlite_stat3 table is represented in memory
  16117. ** using a structure of this type. See documentation at the top of the
  16118. ** analyze.c source file for additional information.
  16119. */
  16120. struct IndexSample {
  16121. void *p; /* Pointer to sampled record */
  16122. int n; /* Size of record in bytes */
  16123. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  16124. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  16125. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  16126. };
  16127. /*
  16128. ** Each token coming out of the lexer is an instance of
  16129. ** this structure. Tokens are also used as part of an expression.
  16130. **
  16131. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  16132. ** may contain random values. Do not make any assumptions about Token.dyn
  16133. ** and Token.n when Token.z==0.
  16134. */
  16135. struct Token {
  16136. const char *z; /* Text of the token. Not NULL-terminated! */
  16137. unsigned int n; /* Number of characters in this token */
  16138. };
  16139. /*
  16140. ** An instance of this structure contains information needed to generate
  16141. ** code for a SELECT that contains aggregate functions.
  16142. **
  16143. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  16144. ** pointer to this structure. The Expr.iColumn field is the index in
  16145. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  16146. ** code for that node.
  16147. **
  16148. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  16149. ** original Select structure that describes the SELECT statement. These
  16150. ** fields do not need to be freed when deallocating the AggInfo structure.
  16151. */
  16152. struct AggInfo {
  16153. u8 directMode; /* Direct rendering mode means take data directly
  16154. ** from source tables rather than from accumulators */
  16155. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  16156. ** than the source table */
  16157. int sortingIdx; /* Cursor number of the sorting index */
  16158. int sortingIdxPTab; /* Cursor number of pseudo-table */
  16159. int nSortingColumn; /* Number of columns in the sorting index */
  16160. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  16161. ExprList *pGroupBy; /* The group by clause */
  16162. struct AggInfo_col { /* For each column used in source tables */
  16163. Table *pTab; /* Source table */
  16164. int iTable; /* Cursor number of the source table */
  16165. int iColumn; /* Column number within the source table */
  16166. int iSorterColumn; /* Column number in the sorting index */
  16167. int iMem; /* Memory location that acts as accumulator */
  16168. Expr *pExpr; /* The original expression */
  16169. } *aCol;
  16170. int nColumn; /* Number of used entries in aCol[] */
  16171. int nAccumulator; /* Number of columns that show through to the output.
  16172. ** Additional columns are used only as parameters to
  16173. ** aggregate functions */
  16174. struct AggInfo_func { /* For each aggregate function */
  16175. Expr *pExpr; /* Expression encoding the function */
  16176. FuncDef *pFunc; /* The aggregate function implementation */
  16177. int iMem; /* Memory location that acts as accumulator */
  16178. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  16179. } *aFunc;
  16180. int nFunc; /* Number of entries in aFunc[] */
  16181. };
  16182. /*
  16183. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  16184. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  16185. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  16186. ** it uses less memory in the Expr object, which is a big memory user
  16187. ** in systems with lots of prepared statements. And few applications
  16188. ** need more than about 10 or 20 variables. But some extreme users want
  16189. ** to have prepared statements with over 32767 variables, and for them
  16190. ** the option is available (at compile-time).
  16191. */
  16192. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  16193. typedef i16 ynVar;
  16194. #else
  16195. typedef int ynVar;
  16196. #endif
  16197. /*
  16198. ** Each node of an expression in the parse tree is an instance
  16199. ** of this structure.
  16200. **
  16201. ** Expr.op is the opcode. The integer parser token codes are reused
  16202. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  16203. ** code representing the ">=" operator. This same integer code is reused
  16204. ** to represent the greater-than-or-equal-to operator in the expression
  16205. ** tree.
  16206. **
  16207. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  16208. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  16209. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  16210. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  16211. ** then Expr.token contains the name of the function.
  16212. **
  16213. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  16214. ** binary operator. Either or both may be NULL.
  16215. **
  16216. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  16217. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  16218. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  16219. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  16220. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  16221. ** valid.
  16222. **
  16223. ** An expression of the form ID or ID.ID refers to a column in a table.
  16224. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  16225. ** the integer cursor number of a VDBE cursor pointing to that table and
  16226. ** Expr.iColumn is the column number for the specific column. If the
  16227. ** expression is used as a result in an aggregate SELECT, then the
  16228. ** value is also stored in the Expr.iAgg column in the aggregate so that
  16229. ** it can be accessed after all aggregates are computed.
  16230. **
  16231. ** If the expression is an unbound variable marker (a question mark
  16232. ** character '?' in the original SQL) then the Expr.iTable holds the index
  16233. ** number for that variable.
  16234. **
  16235. ** If the expression is a subquery then Expr.iColumn holds an integer
  16236. ** register number containing the result of the subquery. If the
  16237. ** subquery gives a constant result, then iTable is -1. If the subquery
  16238. ** gives a different answer at different times during statement processing
  16239. ** then iTable is the address of a subroutine that computes the subquery.
  16240. **
  16241. ** If the Expr is of type OP_Column, and the table it is selecting from
  16242. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  16243. ** corresponding table definition.
  16244. **
  16245. ** ALLOCATION NOTES:
  16246. **
  16247. ** Expr objects can use a lot of memory space in database schema. To
  16248. ** help reduce memory requirements, sometimes an Expr object will be
  16249. ** truncated. And to reduce the number of memory allocations, sometimes
  16250. ** two or more Expr objects will be stored in a single memory allocation,
  16251. ** together with Expr.zToken strings.
  16252. **
  16253. ** If the EP_Reduced and EP_TokenOnly flags are set when
  16254. ** an Expr object is truncated. When EP_Reduced is set, then all
  16255. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  16256. ** are contained within the same memory allocation. Note, however, that
  16257. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  16258. ** allocated, regardless of whether or not EP_Reduced is set.
  16259. */
  16260. struct Expr {
  16261. u8 op; /* Operation performed by this node */
  16262. char affinity; /* The affinity of the column or 0 if not a column */
  16263. u32 flags; /* Various flags. EP_* See below */
  16264. union {
  16265. char *zToken; /* Token value. Zero terminated and dequoted */
  16266. int iValue; /* Non-negative integer value if EP_IntValue */
  16267. } u;
  16268. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  16269. ** space is allocated for the fields below this point. An attempt to
  16270. ** access them will result in a segfault or malfunction.
  16271. *********************************************************************/
  16272. Expr *pLeft; /* Left subnode */
  16273. Expr *pRight; /* Right subnode */
  16274. union {
  16275. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  16276. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  16277. } x;
  16278. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  16279. ** space is allocated for the fields below this point. An attempt to
  16280. ** access them will result in a segfault or malfunction.
  16281. *********************************************************************/
  16282. #if SQLITE_MAX_EXPR_DEPTH>0
  16283. int nHeight; /* Height of the tree headed by this node */
  16284. #endif
  16285. int iTable; /* TK_COLUMN: cursor number of table holding column
  16286. ** TK_REGISTER: register number
  16287. ** TK_TRIGGER: 1 -> new, 0 -> old
  16288. ** EP_Unlikely: 134217728 times likelihood
  16289. ** TK_SELECT: 1st register of result vector */
  16290. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  16291. ** TK_VARIABLE: variable number (always >= 1).
  16292. ** TK_SELECT_COLUMN: column of the result vector */
  16293. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  16294. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  16295. u8 op2; /* TK_REGISTER: original value of Expr.op
  16296. ** TK_COLUMN: the value of p5 for OP_Column
  16297. ** TK_AGG_FUNCTION: nesting depth */
  16298. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  16299. Table *pTab; /* Table for TK_COLUMN expressions. Can be NULL
  16300. ** for a column of an index on an expression */
  16301. };
  16302. /*
  16303. ** The following are the meanings of bits in the Expr.flags field.
  16304. */
  16305. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  16306. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  16307. #define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
  16308. /* 0x000008 // available for use */
  16309. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  16310. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  16311. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  16312. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  16313. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  16314. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  16315. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  16316. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  16317. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  16318. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  16319. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  16320. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  16321. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  16322. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  16323. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  16324. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  16325. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  16326. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  16327. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  16328. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  16329. /*
  16330. ** The EP_Propagate mask is a set of properties that automatically propagate
  16331. ** upwards into parent nodes.
  16332. */
  16333. #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
  16334. /*
  16335. ** These macros can be used to test, set, or clear bits in the
  16336. ** Expr.flags field.
  16337. */
  16338. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  16339. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  16340. #define ExprSetProperty(E,P) (E)->flags|=(P)
  16341. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  16342. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  16343. ** and Accreditation only. It works like ExprSetProperty() during VVA
  16344. ** processes but is a no-op for delivery.
  16345. */
  16346. #ifdef SQLITE_DEBUG
  16347. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  16348. #else
  16349. # define ExprSetVVAProperty(E,P)
  16350. #endif
  16351. /*
  16352. ** Macros to determine the number of bytes required by a normal Expr
  16353. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  16354. ** and an Expr struct with the EP_TokenOnly flag set.
  16355. */
  16356. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  16357. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  16358. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  16359. /*
  16360. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  16361. ** above sqlite3ExprDup() for details.
  16362. */
  16363. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  16364. /*
  16365. ** A list of expressions. Each expression may optionally have a
  16366. ** name. An expr/name combination can be used in several ways, such
  16367. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  16368. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  16369. ** also be used as the argument to a function, in which case the a.zName
  16370. ** field is not used.
  16371. **
  16372. ** By default the Expr.zSpan field holds a human-readable description of
  16373. ** the expression that is used in the generation of error messages and
  16374. ** column labels. In this case, Expr.zSpan is typically the text of a
  16375. ** column expression as it exists in a SELECT statement. However, if
  16376. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  16377. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  16378. ** form is used for name resolution with nested FROM clauses.
  16379. */
  16380. struct ExprList {
  16381. int nExpr; /* Number of expressions on the list */
  16382. struct ExprList_item { /* For each expression in the list */
  16383. Expr *pExpr; /* The parse tree for this expression */
  16384. char *zName; /* Token associated with this expression */
  16385. char *zSpan; /* Original text of the expression */
  16386. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  16387. unsigned done :1; /* A flag to indicate when processing is finished */
  16388. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  16389. unsigned reusable :1; /* Constant expression is reusable */
  16390. unsigned bSorterRef :1; /* Defer evaluation until after sorting */
  16391. union {
  16392. struct {
  16393. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  16394. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  16395. } x;
  16396. int iConstExprReg; /* Register in which Expr value is cached */
  16397. } u;
  16398. } a[1]; /* One slot for each expression in the list */
  16399. };
  16400. /*
  16401. ** An instance of this structure can hold a simple list of identifiers,
  16402. ** such as the list "a,b,c" in the following statements:
  16403. **
  16404. ** INSERT INTO t(a,b,c) VALUES ...;
  16405. ** CREATE INDEX idx ON t(a,b,c);
  16406. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  16407. **
  16408. ** The IdList.a.idx field is used when the IdList represents the list of
  16409. ** column names after a table name in an INSERT statement. In the statement
  16410. **
  16411. ** INSERT INTO t(a,b,c) ...
  16412. **
  16413. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  16414. */
  16415. struct IdList {
  16416. struct IdList_item {
  16417. char *zName; /* Name of the identifier */
  16418. int idx; /* Index in some Table.aCol[] of a column named zName */
  16419. } *a;
  16420. int nId; /* Number of identifiers on the list */
  16421. };
  16422. /*
  16423. ** The bitmask datatype defined below is used for various optimizations.
  16424. **
  16425. ** Changing this from a 64-bit to a 32-bit type limits the number of
  16426. ** tables in a join to 32 instead of 64. But it also reduces the size
  16427. ** of the library by 738 bytes on ix86.
  16428. */
  16429. #ifdef SQLITE_BITMASK_TYPE
  16430. typedef SQLITE_BITMASK_TYPE Bitmask;
  16431. #else
  16432. typedef u64 Bitmask;
  16433. #endif
  16434. /*
  16435. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  16436. */
  16437. #define BMS ((int)(sizeof(Bitmask)*8))
  16438. /*
  16439. ** A bit in a Bitmask
  16440. */
  16441. #define MASKBIT(n) (((Bitmask)1)<<(n))
  16442. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  16443. #define ALLBITS ((Bitmask)-1)
  16444. /*
  16445. ** The following structure describes the FROM clause of a SELECT statement.
  16446. ** Each table or subquery in the FROM clause is a separate element of
  16447. ** the SrcList.a[] array.
  16448. **
  16449. ** With the addition of multiple database support, the following structure
  16450. ** can also be used to describe a particular table such as the table that
  16451. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  16452. ** such a table must be a simple name: ID. But in SQLite, the table can
  16453. ** now be identified by a database name, a dot, then the table name: ID.ID.
  16454. **
  16455. ** The jointype starts out showing the join type between the current table
  16456. ** and the next table on the list. The parser builds the list this way.
  16457. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  16458. ** jointype expresses the join between the table and the previous table.
  16459. **
  16460. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  16461. ** contains more than 63 columns and the 64-th or later column is used.
  16462. */
  16463. struct SrcList {
  16464. int nSrc; /* Number of tables or subqueries in the FROM clause */
  16465. u32 nAlloc; /* Number of entries allocated in a[] below */
  16466. struct SrcList_item {
  16467. Schema *pSchema; /* Schema to which this item is fixed */
  16468. char *zDatabase; /* Name of database holding this table */
  16469. char *zName; /* Name of the table */
  16470. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  16471. Table *pTab; /* An SQL table corresponding to zName */
  16472. Select *pSelect; /* A SELECT statement used in place of a table name */
  16473. int addrFillSub; /* Address of subroutine to manifest a subquery */
  16474. int regReturn; /* Register holding return address of addrFillSub */
  16475. int regResult; /* Registers holding results of a co-routine */
  16476. struct {
  16477. u8 jointype; /* Type of join between this table and the previous */
  16478. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  16479. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  16480. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  16481. unsigned isCorrelated :1; /* True if sub-query is correlated */
  16482. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  16483. unsigned isRecursive :1; /* True for recursive reference in WITH */
  16484. } fg;
  16485. int iCursor; /* The VDBE cursor number used to access this table */
  16486. Expr *pOn; /* The ON clause of a join */
  16487. IdList *pUsing; /* The USING clause of a join */
  16488. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  16489. union {
  16490. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  16491. ExprList *pFuncArg; /* Arguments to table-valued-function */
  16492. } u1;
  16493. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  16494. } a[1]; /* One entry for each identifier on the list */
  16495. };
  16496. /*
  16497. ** Permitted values of the SrcList.a.jointype field
  16498. */
  16499. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  16500. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  16501. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  16502. #define JT_LEFT 0x0008 /* Left outer join */
  16503. #define JT_RIGHT 0x0010 /* Right outer join */
  16504. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  16505. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  16506. /*
  16507. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  16508. ** and the WhereInfo.wctrlFlags member.
  16509. **
  16510. ** Value constraints (enforced via assert()):
  16511. ** WHERE_USE_LIMIT == SF_FixedLimit
  16512. */
  16513. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  16514. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  16515. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  16516. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  16517. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  16518. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  16519. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  16520. ** the OR optimization */
  16521. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  16522. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  16523. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  16524. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  16525. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  16526. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  16527. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  16528. /* 0x2000 not currently used */
  16529. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  16530. /* 0x8000 not currently used */
  16531. /* Allowed return values from sqlite3WhereIsDistinct()
  16532. */
  16533. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  16534. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  16535. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  16536. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  16537. /*
  16538. ** A NameContext defines a context in which to resolve table and column
  16539. ** names. The context consists of a list of tables (the pSrcList) field and
  16540. ** a list of named expression (pEList). The named expression list may
  16541. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  16542. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  16543. ** pEList corresponds to the result set of a SELECT and is NULL for
  16544. ** other statements.
  16545. **
  16546. ** NameContexts can be nested. When resolving names, the inner-most
  16547. ** context is searched first. If no match is found, the next outer
  16548. ** context is checked. If there is still no match, the next context
  16549. ** is checked. This process continues until either a match is found
  16550. ** or all contexts are check. When a match is found, the nRef member of
  16551. ** the context containing the match is incremented.
  16552. **
  16553. ** Each subquery gets a new NameContext. The pNext field points to the
  16554. ** NameContext in the parent query. Thus the process of scanning the
  16555. ** NameContext list corresponds to searching through successively outer
  16556. ** subqueries looking for a match.
  16557. */
  16558. struct NameContext {
  16559. Parse *pParse; /* The parser */
  16560. SrcList *pSrcList; /* One or more tables used to resolve names */
  16561. union {
  16562. ExprList *pEList; /* Optional list of result-set columns */
  16563. AggInfo *pAggInfo; /* Information about aggregates at this level */
  16564. Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
  16565. } uNC;
  16566. NameContext *pNext; /* Next outer name context. NULL for outermost */
  16567. int nRef; /* Number of names resolved by this context */
  16568. int nErr; /* Number of errors encountered while resolving names */
  16569. u16 ncFlags; /* Zero or more NC_* flags defined below */
  16570. };
  16571. /*
  16572. ** Allowed values for the NameContext, ncFlags field.
  16573. **
  16574. ** Value constraints (all checked via assert()):
  16575. ** NC_HasAgg == SF_HasAgg
  16576. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  16577. **
  16578. */
  16579. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  16580. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  16581. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  16582. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  16583. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  16584. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  16585. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  16586. #define NC_UEList 0x0080 /* True if uNC.pEList is used */
  16587. #define NC_UAggInfo 0x0100 /* True if uNC.pAggInfo is used */
  16588. #define NC_UUpsert 0x0200 /* True if uNC.pUpsert is used */
  16589. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  16590. #define NC_Complex 0x2000 /* True if a function or subquery seen */
  16591. /*
  16592. ** An instance of the following object describes a single ON CONFLICT
  16593. ** clause in an upsert.
  16594. **
  16595. ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
  16596. ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
  16597. ** conflict-target clause.) The pUpsertTargetWhere is the optional
  16598. ** WHERE clause used to identify partial unique indexes.
  16599. **
  16600. ** pUpsertSet is the list of column=expr terms of the UPDATE statement.
  16601. ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
  16602. ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
  16603. ** WHERE clause is omitted.
  16604. */
  16605. struct Upsert {
  16606. ExprList *pUpsertTarget; /* Optional description of conflicting index */
  16607. Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
  16608. ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
  16609. Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
  16610. /* The fields above comprise the parse tree for the upsert clause.
  16611. ** The fields below are used to transfer information from the INSERT
  16612. ** processing down into the UPDATE processing while generating code.
  16613. ** Upsert owns the memory allocated above, but not the memory below. */
  16614. Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */
  16615. SrcList *pUpsertSrc; /* Table to be updated */
  16616. int regData; /* First register holding array of VALUES */
  16617. int iDataCur; /* Index of the data cursor */
  16618. int iIdxCur; /* Index of the first index cursor */
  16619. };
  16620. /*
  16621. ** An instance of the following structure contains all information
  16622. ** needed to generate code for a single SELECT statement.
  16623. **
  16624. ** See the header comment on the computeLimitRegisters() routine for a
  16625. ** detailed description of the meaning of the iLimit and iOffset fields.
  16626. **
  16627. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  16628. ** These addresses must be stored so that we can go back and fill in
  16629. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  16630. ** the number of columns in P2 can be computed at the same time
  16631. ** as the OP_OpenEphm instruction is coded because not
  16632. ** enough information about the compound query is known at that point.
  16633. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  16634. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  16635. ** sequences for the ORDER BY clause.
  16636. */
  16637. struct Select {
  16638. ExprList *pEList; /* The fields of the result */
  16639. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  16640. LogEst nSelectRow; /* Estimated number of result rows */
  16641. u32 selFlags; /* Various SF_* values */
  16642. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  16643. #if SELECTTRACE_ENABLED
  16644. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  16645. #endif
  16646. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  16647. SrcList *pSrc; /* The FROM clause */
  16648. Expr *pWhere; /* The WHERE clause */
  16649. ExprList *pGroupBy; /* The GROUP BY clause */
  16650. Expr *pHaving; /* The HAVING clause */
  16651. ExprList *pOrderBy; /* The ORDER BY clause */
  16652. Select *pPrior; /* Prior select in a compound select statement */
  16653. Select *pNext; /* Next select to the left in a compound */
  16654. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  16655. With *pWith; /* WITH clause attached to this select. Or NULL. */
  16656. };
  16657. /*
  16658. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  16659. ** "Select Flag".
  16660. **
  16661. ** Value constraints (all checked via assert())
  16662. ** SF_HasAgg == NC_HasAgg
  16663. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  16664. ** SF_FixedLimit == WHERE_USE_LIMIT
  16665. */
  16666. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  16667. #define SF_All 0x00002 /* Includes the ALL keyword */
  16668. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  16669. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  16670. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  16671. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  16672. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  16673. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  16674. #define SF_Compound 0x00100 /* Part of a compound query */
  16675. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  16676. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  16677. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  16678. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  16679. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  16680. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  16681. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  16682. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  16683. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  16684. #define SF_ComplexResult 0x40000 /* Result contains subquery or function */
  16685. /*
  16686. ** The results of a SELECT can be distributed in several ways, as defined
  16687. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  16688. ** Type".
  16689. **
  16690. ** SRT_Union Store results as a key in a temporary index
  16691. ** identified by pDest->iSDParm.
  16692. **
  16693. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  16694. **
  16695. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  16696. ** set is not empty.
  16697. **
  16698. ** SRT_Discard Throw the results away. This is used by SELECT
  16699. ** statements within triggers whose only purpose is
  16700. ** the side-effects of functions.
  16701. **
  16702. ** All of the above are free to ignore their ORDER BY clause. Those that
  16703. ** follow must honor the ORDER BY clause.
  16704. **
  16705. ** SRT_Output Generate a row of output (using the OP_ResultRow
  16706. ** opcode) for each row in the result set.
  16707. **
  16708. ** SRT_Mem Only valid if the result is a single column.
  16709. ** Store the first column of the first result row
  16710. ** in register pDest->iSDParm then abandon the rest
  16711. ** of the query. This destination implies "LIMIT 1".
  16712. **
  16713. ** SRT_Set The result must be a single column. Store each
  16714. ** row of result as the key in table pDest->iSDParm.
  16715. ** Apply the affinity pDest->affSdst before storing
  16716. ** results. Used to implement "IN (SELECT ...)".
  16717. **
  16718. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  16719. ** the result there. The cursor is left open after
  16720. ** returning. This is like SRT_Table except that
  16721. ** this destination uses OP_OpenEphemeral to create
  16722. ** the table first.
  16723. **
  16724. ** SRT_Coroutine Generate a co-routine that returns a new row of
  16725. ** results each time it is invoked. The entry point
  16726. ** of the co-routine is stored in register pDest->iSDParm
  16727. ** and the result row is stored in pDest->nDest registers
  16728. ** starting with pDest->iSdst.
  16729. **
  16730. ** SRT_Table Store results in temporary table pDest->iSDParm.
  16731. ** SRT_Fifo This is like SRT_EphemTab except that the table
  16732. ** is assumed to already be open. SRT_Fifo has
  16733. ** the additional property of being able to ignore
  16734. ** the ORDER BY clause.
  16735. **
  16736. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  16737. ** But also use temporary table pDest->iSDParm+1 as
  16738. ** a record of all prior results and ignore any duplicate
  16739. ** rows. Name means: "Distinct Fifo".
  16740. **
  16741. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  16742. ** an index). Append a sequence number so that all entries
  16743. ** are distinct.
  16744. **
  16745. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  16746. ** the same record has never been stored before. The
  16747. ** index at pDest->iSDParm+1 hold all prior stores.
  16748. */
  16749. #define SRT_Union 1 /* Store result as keys in an index */
  16750. #define SRT_Except 2 /* Remove result from a UNION index */
  16751. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  16752. #define SRT_Discard 4 /* Do not save the results anywhere */
  16753. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  16754. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  16755. #define SRT_Queue 7 /* Store result in an queue */
  16756. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  16757. /* The ORDER BY clause is ignored for all of the above */
  16758. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  16759. #define SRT_Output 9 /* Output each row of result */
  16760. #define SRT_Mem 10 /* Store result in a memory cell */
  16761. #define SRT_Set 11 /* Store results as keys in an index */
  16762. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  16763. #define SRT_Coroutine 13 /* Generate a single row of result */
  16764. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  16765. /*
  16766. ** An instance of this object describes where to put of the results of
  16767. ** a SELECT statement.
  16768. */
  16769. struct SelectDest {
  16770. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  16771. int iSDParm; /* A parameter used by the eDest disposal method */
  16772. int iSdst; /* Base register where results are written */
  16773. int nSdst; /* Number of registers allocated */
  16774. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  16775. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  16776. };
  16777. /*
  16778. ** During code generation of statements that do inserts into AUTOINCREMENT
  16779. ** tables, the following information is attached to the Table.u.autoInc.p
  16780. ** pointer of each autoincrement table to record some side information that
  16781. ** the code generator needs. We have to keep per-table autoincrement
  16782. ** information in case inserts are done within triggers. Triggers do not
  16783. ** normally coordinate their activities, but we do need to coordinate the
  16784. ** loading and saving of autoincrement information.
  16785. */
  16786. struct AutoincInfo {
  16787. AutoincInfo *pNext; /* Next info block in a list of them all */
  16788. Table *pTab; /* Table this info block refers to */
  16789. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  16790. int regCtr; /* Memory register holding the rowid counter */
  16791. };
  16792. /*
  16793. ** Size of the column cache
  16794. */
  16795. #ifndef SQLITE_N_COLCACHE
  16796. # define SQLITE_N_COLCACHE 10
  16797. #endif
  16798. /*
  16799. ** At least one instance of the following structure is created for each
  16800. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  16801. ** statement. All such objects are stored in the linked list headed at
  16802. ** Parse.pTriggerPrg and deleted once statement compilation has been
  16803. ** completed.
  16804. **
  16805. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  16806. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  16807. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  16808. ** The Parse.pTriggerPrg list never contains two entries with the same
  16809. ** values for both pTrigger and orconf.
  16810. **
  16811. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  16812. ** accessed (or set to 0 for triggers fired as a result of INSERT
  16813. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  16814. ** a mask of new.* columns used by the program.
  16815. */
  16816. struct TriggerPrg {
  16817. Trigger *pTrigger; /* Trigger this program was coded from */
  16818. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  16819. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  16820. int orconf; /* Default ON CONFLICT policy */
  16821. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  16822. };
  16823. /*
  16824. ** The yDbMask datatype for the bitmask of all attached databases.
  16825. */
  16826. #if SQLITE_MAX_ATTACHED>30
  16827. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  16828. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  16829. # define DbMaskZero(M) memset((M),0,sizeof(M))
  16830. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  16831. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  16832. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  16833. #else
  16834. typedef unsigned int yDbMask;
  16835. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  16836. # define DbMaskZero(M) (M)=0
  16837. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  16838. # define DbMaskAllZero(M) (M)==0
  16839. # define DbMaskNonZero(M) (M)!=0
  16840. #endif
  16841. /*
  16842. ** An SQL parser context. A copy of this structure is passed through
  16843. ** the parser and down into all the parser action routine in order to
  16844. ** carry around information that is global to the entire parse.
  16845. **
  16846. ** The structure is divided into two parts. When the parser and code
  16847. ** generate call themselves recursively, the first part of the structure
  16848. ** is constant but the second part is reset at the beginning and end of
  16849. ** each recursion.
  16850. **
  16851. ** The nTableLock and aTableLock variables are only used if the shared-cache
  16852. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  16853. ** used to store the set of table-locks required by the statement being
  16854. ** compiled. Function sqlite3TableLock() is used to add entries to the
  16855. ** list.
  16856. */
  16857. struct Parse {
  16858. sqlite3 *db; /* The main database structure */
  16859. char *zErrMsg; /* An error message */
  16860. Vdbe *pVdbe; /* An engine for executing database bytecode */
  16861. int rc; /* Return code from execution */
  16862. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  16863. u8 checkSchema; /* Causes schema cookie check after an error */
  16864. u8 nested; /* Number of nested calls to the parser/code generator */
  16865. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  16866. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  16867. u8 mayAbort; /* True if statement may throw an ABORT exception */
  16868. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  16869. u8 okConstFactor; /* OK to factor out constants */
  16870. u8 disableLookaside; /* Number of times lookaside has been disabled */
  16871. u8 nColCache; /* Number of entries in aColCache[] */
  16872. int nRangeReg; /* Size of the temporary register block */
  16873. int iRangeReg; /* First register in temporary register block */
  16874. int nErr; /* Number of errors seen */
  16875. int nTab; /* Number of previously allocated VDBE cursors */
  16876. int nMem; /* Number of memory cells used so far */
  16877. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  16878. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  16879. int iSelfTab; /* Table associated with an index on expr, or negative
  16880. ** of the base register during check-constraint eval */
  16881. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  16882. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  16883. int nLabel; /* Number of labels used */
  16884. int *aLabel; /* Space to hold the labels */
  16885. ExprList *pConstExpr;/* Constant expressions */
  16886. Token constraintName;/* Name of the constraint currently being parsed */
  16887. yDbMask writeMask; /* Start a write transaction on these databases */
  16888. yDbMask cookieMask; /* Bitmask of schema verified databases */
  16889. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  16890. int regRoot; /* Register holding root page number for new objects */
  16891. int nMaxArg; /* Max args passed to user function by sub-program */
  16892. #if SELECTTRACE_ENABLED
  16893. int nSelect; /* Number of SELECT statements seen */
  16894. #endif
  16895. #ifndef SQLITE_OMIT_SHARED_CACHE
  16896. int nTableLock; /* Number of locks in aTableLock */
  16897. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  16898. #endif
  16899. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  16900. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  16901. Table *pTriggerTab; /* Table triggers are being coded for */
  16902. int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
  16903. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  16904. u32 oldmask; /* Mask of old.* columns referenced */
  16905. u32 newmask; /* Mask of new.* columns referenced */
  16906. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  16907. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  16908. u8 disableTriggers; /* True to disable triggers */
  16909. /**************************************************************************
  16910. ** Fields above must be initialized to zero. The fields that follow,
  16911. ** down to the beginning of the recursive section, do not need to be
  16912. ** initialized as they will be set before being used. The boundary is
  16913. ** determined by offsetof(Parse,aColCache).
  16914. **************************************************************************/
  16915. struct yColCache {
  16916. int iTable; /* Table cursor number */
  16917. i16 iColumn; /* Table column number */
  16918. u8 tempReg; /* iReg is a temp register that needs to be freed */
  16919. int iLevel; /* Nesting level */
  16920. int iReg; /* Reg with value of this column. 0 means none. */
  16921. int lru; /* Least recently used entry has the smallest value */
  16922. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  16923. int aTempReg[8]; /* Holding area for temporary registers */
  16924. Token sNameToken; /* Token with unqualified schema object name */
  16925. /************************************************************************
  16926. ** Above is constant between recursions. Below is reset before and after
  16927. ** each recursion. The boundary between these two regions is determined
  16928. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  16929. ** first field in the recursive region.
  16930. ************************************************************************/
  16931. Token sLastToken; /* The last token parsed */
  16932. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  16933. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  16934. u8 explain; /* True if the EXPLAIN flag is found on the query */
  16935. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16936. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  16937. int nVtabLock; /* Number of virtual tables to lock */
  16938. #endif
  16939. int nHeight; /* Expression tree height of current sub-select */
  16940. #ifndef SQLITE_OMIT_EXPLAIN
  16941. int addrExplain; /* Address of current OP_Explain opcode */
  16942. #endif
  16943. VList *pVList; /* Mapping between variable names and numbers */
  16944. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  16945. const char *zTail; /* All SQL text past the last semicolon parsed */
  16946. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  16947. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  16948. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  16949. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16950. Token sArg; /* Complete text of a module argument */
  16951. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  16952. #endif
  16953. Table *pZombieTab; /* List of Table objects to delete after code gen */
  16954. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  16955. With *pWith; /* Current WITH clause, or NULL */
  16956. With *pWithToFree; /* Free this WITH object at the end of the parse */
  16957. };
  16958. /*
  16959. ** Sizes and pointers of various parts of the Parse object.
  16960. */
  16961. #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
  16962. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  16963. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  16964. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  16965. /*
  16966. ** Return true if currently inside an sqlite3_declare_vtab() call.
  16967. */
  16968. #ifdef SQLITE_OMIT_VIRTUALTABLE
  16969. #define IN_DECLARE_VTAB 0
  16970. #else
  16971. #define IN_DECLARE_VTAB (pParse->declareVtab)
  16972. #endif
  16973. /*
  16974. ** An instance of the following structure can be declared on a stack and used
  16975. ** to save the Parse.zAuthContext value so that it can be restored later.
  16976. */
  16977. struct AuthContext {
  16978. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  16979. Parse *pParse; /* The Parse structure */
  16980. };
  16981. /*
  16982. ** Bitfield flags for P5 value in various opcodes.
  16983. **
  16984. ** Value constraints (enforced via assert()):
  16985. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  16986. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  16987. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  16988. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  16989. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  16990. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  16991. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  16992. */
  16993. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  16994. /* Also used in P2 (not P5) of OP_Delete */
  16995. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  16996. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  16997. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  16998. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  16999. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  17000. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  17001. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  17002. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  17003. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  17004. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  17005. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  17006. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  17007. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  17008. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  17009. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  17010. #define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
  17011. /*
  17012. * Each trigger present in the database schema is stored as an instance of
  17013. * struct Trigger.
  17014. *
  17015. * Pointers to instances of struct Trigger are stored in two ways.
  17016. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  17017. * database). This allows Trigger structures to be retrieved by name.
  17018. * 2. All triggers associated with a single table form a linked list, using the
  17019. * pNext member of struct Trigger. A pointer to the first element of the
  17020. * linked list is stored as the "pTrigger" member of the associated
  17021. * struct Table.
  17022. *
  17023. * The "step_list" member points to the first element of a linked list
  17024. * containing the SQL statements specified as the trigger program.
  17025. */
  17026. struct Trigger {
  17027. char *zName; /* The name of the trigger */
  17028. char *table; /* The table or view to which the trigger applies */
  17029. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  17030. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  17031. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  17032. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  17033. the <column-list> is stored here */
  17034. Schema *pSchema; /* Schema containing the trigger */
  17035. Schema *pTabSchema; /* Schema containing the table */
  17036. TriggerStep *step_list; /* Link list of trigger program steps */
  17037. Trigger *pNext; /* Next trigger associated with the table */
  17038. };
  17039. /*
  17040. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  17041. ** determine which.
  17042. **
  17043. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  17044. ** In that cases, the constants below can be ORed together.
  17045. */
  17046. #define TRIGGER_BEFORE 1
  17047. #define TRIGGER_AFTER 2
  17048. /*
  17049. * An instance of struct TriggerStep is used to store a single SQL statement
  17050. * that is a part of a trigger-program.
  17051. *
  17052. * Instances of struct TriggerStep are stored in a singly linked list (linked
  17053. * using the "pNext" member) referenced by the "step_list" member of the
  17054. * associated struct Trigger instance. The first element of the linked list is
  17055. * the first step of the trigger-program.
  17056. *
  17057. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  17058. * "SELECT" statement. The meanings of the other members is determined by the
  17059. * value of "op" as follows:
  17060. *
  17061. * (op == TK_INSERT)
  17062. * orconf -> stores the ON CONFLICT algorithm
  17063. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  17064. * this stores a pointer to the SELECT statement. Otherwise NULL.
  17065. * zTarget -> Dequoted name of the table to insert into.
  17066. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  17067. * this stores values to be inserted. Otherwise NULL.
  17068. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  17069. * statement, then this stores the column-names to be
  17070. * inserted into.
  17071. *
  17072. * (op == TK_DELETE)
  17073. * zTarget -> Dequoted name of the table to delete from.
  17074. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  17075. * Otherwise NULL.
  17076. *
  17077. * (op == TK_UPDATE)
  17078. * zTarget -> Dequoted name of the table to update.
  17079. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  17080. * Otherwise NULL.
  17081. * pExprList -> A list of the columns to update and the expressions to update
  17082. * them to. See sqlite3Update() documentation of "pChanges"
  17083. * argument.
  17084. *
  17085. */
  17086. struct TriggerStep {
  17087. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  17088. u8 orconf; /* OE_Rollback etc. */
  17089. Trigger *pTrig; /* The trigger that this step is a part of */
  17090. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  17091. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  17092. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  17093. ExprList *pExprList; /* SET clause for UPDATE */
  17094. IdList *pIdList; /* Column names for INSERT */
  17095. Upsert *pUpsert; /* Upsert clauses on an INSERT */
  17096. char *zSpan; /* Original SQL text of this command */
  17097. TriggerStep *pNext; /* Next in the link-list */
  17098. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  17099. };
  17100. /*
  17101. ** The following structure contains information used by the sqliteFix...
  17102. ** routines as they walk the parse tree to make database references
  17103. ** explicit.
  17104. */
  17105. typedef struct DbFixer DbFixer;
  17106. struct DbFixer {
  17107. Parse *pParse; /* The parsing context. Error messages written here */
  17108. Schema *pSchema; /* Fix items to this schema */
  17109. int bVarOnly; /* Check for variable references only */
  17110. const char *zDb; /* Make sure all objects are contained in this database */
  17111. const char *zType; /* Type of the container - used for error messages */
  17112. const Token *pName; /* Name of the container - used for error messages */
  17113. };
  17114. /*
  17115. ** An objected used to accumulate the text of a string where we
  17116. ** do not necessarily know how big the string will be in the end.
  17117. */
  17118. struct sqlite3_str {
  17119. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  17120. char *zText; /* The string collected so far */
  17121. u32 nAlloc; /* Amount of space allocated in zText */
  17122. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  17123. u32 nChar; /* Length of the string so far */
  17124. u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
  17125. u8 printfFlags; /* SQLITE_PRINTF flags below */
  17126. };
  17127. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  17128. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  17129. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  17130. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  17131. /*
  17132. ** A pointer to this structure is used to communicate information
  17133. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  17134. */
  17135. typedef struct {
  17136. sqlite3 *db; /* The database being initialized */
  17137. char **pzErrMsg; /* Error message stored here */
  17138. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  17139. int rc; /* Result code stored here */
  17140. } InitData;
  17141. /*
  17142. ** Structure containing global configuration data for the SQLite library.
  17143. **
  17144. ** This structure also contains some state information.
  17145. */
  17146. struct Sqlite3Config {
  17147. int bMemstat; /* True to enable memory status */
  17148. int bCoreMutex; /* True to enable core mutexing */
  17149. int bFullMutex; /* True to enable full mutexing */
  17150. int bOpenUri; /* True to interpret filenames as URIs */
  17151. int bUseCis; /* Use covering indices for full-scans */
  17152. int bSmallMalloc; /* Avoid large memory allocations if true */
  17153. int mxStrlen; /* Maximum string length */
  17154. int neverCorrupt; /* Database is always well-formed */
  17155. int szLookaside; /* Default lookaside buffer size */
  17156. int nLookaside; /* Default lookaside buffer count */
  17157. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  17158. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  17159. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  17160. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  17161. void *pHeap; /* Heap storage space */
  17162. int nHeap; /* Size of pHeap[] */
  17163. int mnReq, mxReq; /* Min and max heap requests sizes */
  17164. sqlite3_int64 szMmap; /* mmap() space per open file */
  17165. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  17166. void *pPage; /* Page cache memory */
  17167. int szPage; /* Size of each page in pPage[] */
  17168. int nPage; /* Number of pages in pPage[] */
  17169. int mxParserStack; /* maximum depth of the parser stack */
  17170. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  17171. u32 szPma; /* Maximum Sorter PMA size */
  17172. /* The above might be initialized to non-zero. The following need to always
  17173. ** initially be zero, however. */
  17174. int isInit; /* True after initialization has finished */
  17175. int inProgress; /* True while initialization in progress */
  17176. int isMutexInit; /* True after mutexes are initialized */
  17177. int isMallocInit; /* True after malloc is initialized */
  17178. int isPCacheInit; /* True after malloc is initialized */
  17179. int nRefInitMutex; /* Number of users of pInitMutex */
  17180. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  17181. void (*xLog)(void*,int,const char*); /* Function for logging */
  17182. void *pLogArg; /* First argument to xLog() */
  17183. #ifdef SQLITE_ENABLE_SQLLOG
  17184. void(*xSqllog)(void*,sqlite3*,const char*, int);
  17185. void *pSqllogArg;
  17186. #endif
  17187. #ifdef SQLITE_VDBE_COVERAGE
  17188. /* The following callback (if not NULL) is invoked on every VDBE branch
  17189. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  17190. */
  17191. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  17192. void *pVdbeBranchArg; /* 1st argument */
  17193. #endif
  17194. #ifndef SQLITE_UNTESTABLE
  17195. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  17196. #endif
  17197. int bLocaltimeFault; /* True to fail localtime() calls */
  17198. int iOnceResetThreshold; /* When to reset OP_Once counters */
  17199. u32 szSorterRef; /* Min size in bytes to use sorter-refs */
  17200. };
  17201. /*
  17202. ** This macro is used inside of assert() statements to indicate that
  17203. ** the assert is only valid on a well-formed database. Instead of:
  17204. **
  17205. ** assert( X );
  17206. **
  17207. ** One writes:
  17208. **
  17209. ** assert( X || CORRUPT_DB );
  17210. **
  17211. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  17212. ** that the database is definitely corrupt, only that it might be corrupt.
  17213. ** For most test cases, CORRUPT_DB is set to false using a special
  17214. ** sqlite3_test_control(). This enables assert() statements to prove
  17215. ** things that are always true for well-formed databases.
  17216. */
  17217. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  17218. /*
  17219. ** Context pointer passed down through the tree-walk.
  17220. */
  17221. struct Walker {
  17222. Parse *pParse; /* Parser context. */
  17223. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  17224. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  17225. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  17226. int walkerDepth; /* Number of subqueries */
  17227. u8 eCode; /* A small processing code */
  17228. union { /* Extra data for callback */
  17229. NameContext *pNC; /* Naming context */
  17230. int n; /* A counter */
  17231. int iCur; /* A cursor number */
  17232. SrcList *pSrcList; /* FROM clause */
  17233. struct SrcCount *pSrcCount; /* Counting column references */
  17234. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  17235. int *aiCol; /* array of column indexes */
  17236. struct IdxCover *pIdxCover; /* Check for index coverage */
  17237. struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
  17238. ExprList *pGroupBy; /* GROUP BY clause */
  17239. Select *pSelect; /* HAVING to WHERE clause ctx */
  17240. } u;
  17241. };
  17242. /* Forward declarations */
  17243. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  17244. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  17245. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  17246. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  17247. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  17248. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  17249. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
  17250. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
  17251. #ifdef SQLITE_DEBUG
  17252. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
  17253. #endif
  17254. /*
  17255. ** Return code from the parse-tree walking primitives and their
  17256. ** callbacks.
  17257. */
  17258. #define WRC_Continue 0 /* Continue down into children */
  17259. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  17260. #define WRC_Abort 2 /* Abandon the tree walk */
  17261. /*
  17262. ** An instance of this structure represents a set of one or more CTEs
  17263. ** (common table expressions) created by a single WITH clause.
  17264. */
  17265. struct With {
  17266. int nCte; /* Number of CTEs in the WITH clause */
  17267. With *pOuter; /* Containing WITH clause, or NULL */
  17268. struct Cte { /* For each CTE in the WITH clause.... */
  17269. char *zName; /* Name of this CTE */
  17270. ExprList *pCols; /* List of explicit column names, or NULL */
  17271. Select *pSelect; /* The definition of this CTE */
  17272. const char *zCteErr; /* Error message for circular references */
  17273. } a[1];
  17274. };
  17275. #ifdef SQLITE_DEBUG
  17276. /*
  17277. ** An instance of the TreeView object is used for printing the content of
  17278. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  17279. */
  17280. struct TreeView {
  17281. int iLevel; /* Which level of the tree we are on */
  17282. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  17283. };
  17284. #endif /* SQLITE_DEBUG */
  17285. /*
  17286. ** Assuming zIn points to the first byte of a UTF-8 character,
  17287. ** advance zIn to point to the first byte of the next UTF-8 character.
  17288. */
  17289. #define SQLITE_SKIP_UTF8(zIn) { \
  17290. if( (*(zIn++))>=0xc0 ){ \
  17291. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  17292. } \
  17293. }
  17294. /*
  17295. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  17296. ** the same name but without the _BKPT suffix. These macros invoke
  17297. ** routines that report the line-number on which the error originated
  17298. ** using sqlite3_log(). The routines also provide a convenient place
  17299. ** to set a debugger breakpoint.
  17300. */
  17301. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
  17302. SQLITE_PRIVATE int sqlite3CorruptError(int);
  17303. SQLITE_PRIVATE int sqlite3MisuseError(int);
  17304. SQLITE_PRIVATE int sqlite3CantopenError(int);
  17305. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  17306. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  17307. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  17308. #ifdef SQLITE_DEBUG
  17309. SQLITE_PRIVATE int sqlite3NomemError(int);
  17310. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  17311. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
  17312. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  17313. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  17314. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
  17315. #else
  17316. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  17317. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  17318. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
  17319. #endif
  17320. /*
  17321. ** FTS3 and FTS4 both require virtual table support
  17322. */
  17323. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  17324. # undef SQLITE_ENABLE_FTS3
  17325. # undef SQLITE_ENABLE_FTS4
  17326. #endif
  17327. /*
  17328. ** FTS4 is really an extension for FTS3. It is enabled using the
  17329. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  17330. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  17331. */
  17332. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  17333. # define SQLITE_ENABLE_FTS3 1
  17334. #endif
  17335. /*
  17336. ** The ctype.h header is needed for non-ASCII systems. It is also
  17337. ** needed by FTS3 when FTS3 is included in the amalgamation.
  17338. */
  17339. #if !defined(SQLITE_ASCII) || \
  17340. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  17341. # include <ctype.h>
  17342. #endif
  17343. /*
  17344. ** The following macros mimic the standard library functions toupper(),
  17345. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  17346. ** sqlite versions only work for ASCII characters, regardless of locale.
  17347. */
  17348. #ifdef SQLITE_ASCII
  17349. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  17350. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  17351. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  17352. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  17353. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  17354. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  17355. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  17356. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  17357. #else
  17358. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  17359. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  17360. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  17361. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  17362. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  17363. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  17364. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  17365. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  17366. #endif
  17367. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  17368. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  17369. #endif
  17370. /*
  17371. ** Internal function prototypes
  17372. */
  17373. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  17374. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  17375. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  17376. #define sqlite3StrNICmp sqlite3_strnicmp
  17377. SQLITE_PRIVATE int sqlite3MallocInit(void);
  17378. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  17379. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  17380. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  17381. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  17382. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  17383. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  17384. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  17385. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  17386. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
  17387. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  17388. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  17389. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  17390. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  17391. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  17392. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  17393. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  17394. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  17395. SQLITE_PRIVATE void sqlite3PageFree(void*);
  17396. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  17397. #ifndef SQLITE_UNTESTABLE
  17398. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  17399. #endif
  17400. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  17401. /*
  17402. ** On systems with ample stack space and that support alloca(), make
  17403. ** use of alloca() to obtain space for large automatic objects. By default,
  17404. ** obtain space from malloc().
  17405. **
  17406. ** The alloca() routine never returns NULL. This will cause code paths
  17407. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  17408. */
  17409. #ifdef SQLITE_USE_ALLOCA
  17410. # define sqlite3StackAllocRaw(D,N) alloca(N)
  17411. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  17412. # define sqlite3StackFree(D,P)
  17413. #else
  17414. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  17415. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  17416. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  17417. #endif
  17418. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  17419. ** are, disable MEMSYS3
  17420. */
  17421. #ifdef SQLITE_ENABLE_MEMSYS5
  17422. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  17423. #undef SQLITE_ENABLE_MEMSYS3
  17424. #endif
  17425. #ifdef SQLITE_ENABLE_MEMSYS3
  17426. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  17427. #endif
  17428. #ifndef SQLITE_MUTEX_OMIT
  17429. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  17430. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  17431. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  17432. SQLITE_PRIVATE int sqlite3MutexInit(void);
  17433. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  17434. #endif
  17435. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  17436. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  17437. #else
  17438. # define sqlite3MemoryBarrier()
  17439. #endif
  17440. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  17441. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  17442. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  17443. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  17444. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
  17445. /* Access to mutexes used by sqlite3_status() */
  17446. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  17447. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  17448. #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
  17449. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
  17450. #else
  17451. # define sqlite3MutexWarnOnContention(x)
  17452. #endif
  17453. #ifndef SQLITE_OMIT_FLOATING_POINT
  17454. SQLITE_PRIVATE int sqlite3IsNaN(double);
  17455. #else
  17456. # define sqlite3IsNaN(X) 0
  17457. #endif
  17458. /*
  17459. ** An instance of the following structure holds information about SQL
  17460. ** functions arguments that are the parameters to the printf() function.
  17461. */
  17462. struct PrintfArguments {
  17463. int nArg; /* Total number of arguments */
  17464. int nUsed; /* Number of arguments used so far */
  17465. sqlite3_value **apArg; /* The argument values */
  17466. };
  17467. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  17468. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  17469. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  17470. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  17471. #endif
  17472. #if defined(SQLITE_TEST)
  17473. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  17474. #endif
  17475. #if defined(SQLITE_DEBUG)
  17476. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  17477. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  17478. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  17479. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  17480. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  17481. #endif
  17482. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  17483. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  17484. SQLITE_PRIVATE void sqlite3Dequote(char*);
  17485. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  17486. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  17487. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  17488. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  17489. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  17490. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  17491. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  17492. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  17493. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  17494. #ifdef SQLITE_DEBUG
  17495. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  17496. #endif
  17497. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  17498. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  17499. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  17500. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  17501. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  17502. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  17503. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  17504. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  17505. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  17506. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  17507. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  17508. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  17509. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  17510. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
  17511. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  17512. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  17513. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  17514. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  17515. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  17516. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17517. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  17518. #endif
  17519. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  17520. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  17521. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  17522. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  17523. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  17524. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  17525. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  17526. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  17527. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  17528. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  17529. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  17530. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  17531. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  17532. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  17533. #else
  17534. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  17535. #endif
  17536. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  17537. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  17538. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  17539. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  17540. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
  17541. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  17542. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  17543. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  17544. sqlite3_vfs**,char**,char **);
  17545. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  17546. #ifdef SQLITE_UNTESTABLE
  17547. # define sqlite3FaultSim(X) SQLITE_OK
  17548. #else
  17549. SQLITE_PRIVATE int sqlite3FaultSim(int);
  17550. #endif
  17551. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  17552. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  17553. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  17554. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  17555. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  17556. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  17557. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  17558. #ifndef SQLITE_UNTESTABLE
  17559. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  17560. #endif
  17561. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  17562. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  17563. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  17564. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  17565. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  17566. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  17567. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  17568. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  17569. #else
  17570. # define sqlite3ViewGetColumnNames(A,B) 0
  17571. #endif
  17572. #if SQLITE_MAX_ATTACHED>30
  17573. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  17574. #endif
  17575. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  17576. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  17577. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  17578. #ifndef SQLITE_OMIT_AUTOINCREMENT
  17579. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  17580. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  17581. #else
  17582. # define sqlite3AutoincrementBegin(X)
  17583. # define sqlite3AutoincrementEnd(X)
  17584. #endif
  17585. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
  17586. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  17587. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  17588. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  17589. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  17590. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  17591. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  17592. Token*, Select*, Expr*, IdList*);
  17593. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  17594. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  17595. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  17596. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  17597. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  17598. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  17599. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  17600. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  17601. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  17602. Expr*, int, int, u8);
  17603. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  17604. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  17605. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  17606. Expr*,ExprList*,u32,Expr*);
  17607. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  17608. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  17609. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  17610. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  17611. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  17612. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
  17613. #endif
  17614. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
  17615. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
  17616. Upsert*);
  17617. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  17618. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  17619. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  17620. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  17621. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  17622. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
  17623. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  17624. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  17625. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  17626. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  17627. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  17628. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  17629. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  17630. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  17631. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  17632. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
  17633. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  17634. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  17635. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  17636. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  17637. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  17638. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  17639. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  17640. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  17641. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  17642. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  17643. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  17644. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  17645. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  17646. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  17647. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  17648. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  17649. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  17650. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  17651. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  17652. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  17653. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  17654. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  17655. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  17656. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  17657. #define LOCATE_VIEW 0x01
  17658. #define LOCATE_NOERR 0x02
  17659. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  17660. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  17661. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  17662. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  17663. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  17664. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
  17665. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
  17666. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  17667. SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
  17668. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  17669. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  17670. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
  17671. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
  17672. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  17673. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  17674. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  17675. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  17676. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  17677. #ifndef SQLITE_UNTESTABLE
  17678. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  17679. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  17680. #endif
  17681. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  17682. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  17683. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  17684. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  17685. SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
  17686. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  17687. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  17688. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  17689. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
  17690. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
  17691. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  17692. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  17693. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  17694. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  17695. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  17696. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  17697. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  17698. #endif
  17699. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  17700. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  17701. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  17702. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  17703. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  17704. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  17705. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  17706. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  17707. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  17708. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  17709. u8,u8,int,int*,int*,Upsert*);
  17710. #ifdef SQLITE_ENABLE_NULL_TRIM
  17711. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  17712. #else
  17713. # define sqlite3SetMakeRecordP5(A,B)
  17714. #endif
  17715. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  17716. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  17717. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  17718. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  17719. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  17720. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  17721. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  17722. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  17723. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  17724. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  17725. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  17726. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  17727. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  17728. #if SELECTTRACE_ENABLED
  17729. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  17730. #else
  17731. # define sqlite3SelectSetName(A,B)
  17732. #endif
  17733. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  17734. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  17735. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  17736. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  17737. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  17738. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  17739. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  17740. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  17741. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  17742. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
  17743. #endif
  17744. #ifndef SQLITE_OMIT_TRIGGER
  17745. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  17746. Expr*,int, int);
  17747. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  17748. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  17749. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  17750. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  17751. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  17752. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  17753. int, int, int);
  17754. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  17755. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  17756. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  17757. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
  17758. const char*,const char*);
  17759. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  17760. Select*,u8,Upsert*,
  17761. const char*,const char*);
  17762. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8,
  17763. const char*,const char*);
  17764. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*,
  17765. const char*,const char*);
  17766. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  17767. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  17768. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  17769. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  17770. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  17771. #else
  17772. # define sqlite3TriggersExist(B,C,D,E,F) 0
  17773. # define sqlite3DeleteTrigger(A,B)
  17774. # define sqlite3DropTriggerPtr(A,B)
  17775. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  17776. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  17777. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  17778. # define sqlite3TriggerList(X, Y) 0
  17779. # define sqlite3ParseToplevel(p) p
  17780. # define sqlite3IsToplevel(p) 1
  17781. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  17782. #endif
  17783. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  17784. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  17785. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  17786. #ifndef SQLITE_OMIT_AUTHORIZATION
  17787. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  17788. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  17789. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  17790. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  17791. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  17792. #else
  17793. # define sqlite3AuthRead(a,b,c,d)
  17794. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  17795. # define sqlite3AuthContextPush(a,b,c)
  17796. # define sqlite3AuthContextPop(a) ((void)(a))
  17797. #endif
  17798. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  17799. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  17800. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  17801. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  17802. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  17803. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  17804. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  17805. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  17806. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  17807. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  17808. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  17809. #ifndef SQLITE_OMIT_UTF16
  17810. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  17811. #endif
  17812. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  17813. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  17814. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  17815. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  17816. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17817. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  17818. #endif
  17819. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  17820. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  17821. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  17822. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  17823. #endif
  17824. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  17825. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  17826. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  17827. /*
  17828. ** Routines to read and write variable-length integers. These used to
  17829. ** be defined locally, but now we use the varint routines in the util.c
  17830. ** file.
  17831. */
  17832. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  17833. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  17834. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  17835. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  17836. /*
  17837. ** The common case is for a varint to be a single byte. They following
  17838. ** macros handle the common case without a procedure call, but then call
  17839. ** the procedure for larger varints.
  17840. */
  17841. #define getVarint32(A,B) \
  17842. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  17843. #define putVarint32(A,B) \
  17844. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  17845. sqlite3PutVarint((A),(B)))
  17846. #define getVarint sqlite3GetVarint
  17847. #define putVarint sqlite3PutVarint
  17848. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  17849. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  17850. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  17851. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  17852. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  17853. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  17854. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  17855. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  17856. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  17857. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  17858. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  17859. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  17860. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  17861. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  17862. #if defined(SQLITE_NEED_ERR_NAME)
  17863. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  17864. #endif
  17865. #ifdef SQLITE_ENABLE_DESERIALIZE
  17866. SQLITE_PRIVATE int sqlite3MemdbInit(void);
  17867. #endif
  17868. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  17869. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  17870. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  17871. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  17872. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  17873. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
  17874. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
  17875. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  17876. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  17877. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  17878. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  17879. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  17880. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  17881. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  17882. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  17883. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  17884. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  17885. #ifdef SQLITE_ENABLE_8_3_NAMES
  17886. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  17887. #else
  17888. # define sqlite3FileSuffix3(X,Y)
  17889. #endif
  17890. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  17891. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  17892. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  17893. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  17894. void(*)(void*));
  17895. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  17896. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  17897. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  17898. #ifndef SQLITE_OMIT_UTF16
  17899. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  17900. #endif
  17901. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  17902. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  17903. #ifndef SQLITE_AMALGAMATION
  17904. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  17905. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  17906. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  17907. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  17908. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  17909. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  17910. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  17911. #ifndef SQLITE_OMIT_WSD
  17912. SQLITE_PRIVATE int sqlite3PendingByte;
  17913. #endif
  17914. #endif
  17915. #ifdef VDBE_PROFILE
  17916. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
  17917. #endif
  17918. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  17919. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  17920. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  17921. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  17922. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  17923. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  17924. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  17925. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
  17926. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  17927. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  17928. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  17929. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  17930. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  17931. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  17932. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  17933. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  17934. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  17935. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  17936. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  17937. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  17938. SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
  17939. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  17940. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
  17941. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  17942. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  17943. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  17944. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  17945. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  17946. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  17947. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  17948. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  17949. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  17950. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  17951. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  17952. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  17953. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  17954. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  17955. #ifdef SQLITE_DEBUG
  17956. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  17957. #endif
  17958. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  17959. void (*)(sqlite3_context*,int,sqlite3_value **),
  17960. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  17961. FuncDestructor *pDestructor
  17962. );
  17963. SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
  17964. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  17965. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  17966. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  17967. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  17968. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  17969. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  17970. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  17971. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  17972. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  17973. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  17974. #ifndef SQLITE_OMIT_SUBQUERY
  17975. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  17976. #else
  17977. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  17978. #endif
  17979. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  17980. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  17981. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  17982. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  17983. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  17984. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  17985. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  17986. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  17987. #endif
  17988. /*
  17989. ** The interface to the LEMON-generated parser
  17990. */
  17991. #ifndef SQLITE_AMALGAMATION
  17992. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
  17993. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  17994. #endif
  17995. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
  17996. #ifdef YYTRACKMAXSTACKDEPTH
  17997. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  17998. #endif
  17999. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  18000. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  18001. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  18002. #else
  18003. # define sqlite3CloseExtensions(X)
  18004. #endif
  18005. #ifndef SQLITE_OMIT_SHARED_CACHE
  18006. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  18007. #else
  18008. #define sqlite3TableLock(v,w,x,y,z)
  18009. #endif
  18010. #ifdef SQLITE_TEST
  18011. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  18012. #endif
  18013. #ifdef SQLITE_OMIT_VIRTUALTABLE
  18014. # define sqlite3VtabClear(Y)
  18015. # define sqlite3VtabSync(X,Y) SQLITE_OK
  18016. # define sqlite3VtabRollback(X)
  18017. # define sqlite3VtabCommit(X)
  18018. # define sqlite3VtabInSync(db) 0
  18019. # define sqlite3VtabLock(X)
  18020. # define sqlite3VtabUnlock(X)
  18021. # define sqlite3VtabUnlockList(X)
  18022. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  18023. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  18024. #else
  18025. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  18026. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  18027. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  18028. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  18029. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  18030. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  18031. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  18032. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  18033. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  18034. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  18035. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  18036. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  18037. sqlite3*,
  18038. const char*,
  18039. const sqlite3_module*,
  18040. void*,
  18041. void(*)(void*)
  18042. );
  18043. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  18044. #endif
  18045. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  18046. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  18047. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  18048. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  18049. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  18050. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  18051. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  18052. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  18053. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  18054. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  18055. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  18056. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  18057. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  18058. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  18059. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  18060. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  18061. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  18062. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  18063. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  18064. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  18065. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  18066. #ifndef SQLITE_OMIT_WAL
  18067. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  18068. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  18069. #endif
  18070. #ifndef SQLITE_OMIT_CTE
  18071. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  18072. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  18073. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  18074. #else
  18075. #define sqlite3WithPush(x,y,z)
  18076. #define sqlite3WithDelete(x,y)
  18077. #endif
  18078. #ifndef SQLITE_OMIT_UPSERT
  18079. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
  18080. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
  18081. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
  18082. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
  18083. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
  18084. #else
  18085. #define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
  18086. #define sqlite3UpsertDelete(x,y)
  18087. #define sqlite3UpsertDup(x,y) ((Upsert*)0)
  18088. #endif
  18089. /* Declarations for functions in fkey.c. All of these are replaced by
  18090. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  18091. ** key functionality is available. If OMIT_TRIGGER is defined but
  18092. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  18093. ** this case foreign keys are parsed, but no other functionality is
  18094. ** provided (enforcement of FK constraints requires the triggers sub-system).
  18095. */
  18096. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  18097. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  18098. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  18099. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  18100. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  18101. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  18102. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  18103. #else
  18104. #define sqlite3FkActions(a,b,c,d,e,f)
  18105. #define sqlite3FkCheck(a,b,c,d,e,f)
  18106. #define sqlite3FkDropTable(a,b,c)
  18107. #define sqlite3FkOldmask(a,b) 0
  18108. #define sqlite3FkRequired(a,b,c,d) 0
  18109. #define sqlite3FkReferences(a) 0
  18110. #endif
  18111. #ifndef SQLITE_OMIT_FOREIGN_KEY
  18112. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  18113. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  18114. #else
  18115. #define sqlite3FkDelete(a,b)
  18116. #define sqlite3FkLocateIndex(a,b,c,d,e)
  18117. #endif
  18118. /*
  18119. ** Available fault injectors. Should be numbered beginning with 0.
  18120. */
  18121. #define SQLITE_FAULTINJECTOR_MALLOC 0
  18122. #define SQLITE_FAULTINJECTOR_COUNT 1
  18123. /*
  18124. ** The interface to the code in fault.c used for identifying "benign"
  18125. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  18126. ** is not defined.
  18127. */
  18128. #ifndef SQLITE_UNTESTABLE
  18129. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  18130. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  18131. #else
  18132. #define sqlite3BeginBenignMalloc()
  18133. #define sqlite3EndBenignMalloc()
  18134. #endif
  18135. /*
  18136. ** Allowed return values from sqlite3FindInIndex()
  18137. */
  18138. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  18139. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  18140. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  18141. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  18142. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  18143. /*
  18144. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  18145. */
  18146. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  18147. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  18148. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  18149. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
  18150. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  18151. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  18152. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  18153. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  18154. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  18155. #endif
  18156. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  18157. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  18158. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  18159. #if SQLITE_MAX_EXPR_DEPTH>0
  18160. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  18161. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  18162. #else
  18163. #define sqlite3SelectExprHeight(x) 0
  18164. #define sqlite3ExprCheckHeight(x,y)
  18165. #endif
  18166. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  18167. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  18168. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  18169. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  18170. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  18171. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  18172. #else
  18173. #define sqlite3ConnectionBlocked(x,y)
  18174. #define sqlite3ConnectionUnlocked(x)
  18175. #define sqlite3ConnectionClosed(x)
  18176. #endif
  18177. #ifdef SQLITE_DEBUG
  18178. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  18179. #endif
  18180. #if defined(YYCOVERAGE)
  18181. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
  18182. #endif
  18183. /*
  18184. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  18185. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  18186. ** print I/O tracing messages.
  18187. */
  18188. #ifdef SQLITE_ENABLE_IOTRACE
  18189. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  18190. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  18191. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  18192. #else
  18193. # define IOTRACE(A)
  18194. # define sqlite3VdbeIOTraceSql(X)
  18195. #endif
  18196. /*
  18197. ** These routines are available for the mem2.c debugging memory allocator
  18198. ** only. They are used to verify that different "types" of memory
  18199. ** allocations are properly tracked by the system.
  18200. **
  18201. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  18202. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  18203. ** a single bit set.
  18204. **
  18205. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  18206. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18207. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  18208. **
  18209. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  18210. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18211. **
  18212. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  18213. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  18214. ** it might have been allocated by lookaside, except the allocation was
  18215. ** too large or lookaside was already full. It is important to verify
  18216. ** that allocations that might have been satisfied by lookaside are not
  18217. ** passed back to non-lookaside free() routines. Asserts such as the
  18218. ** example above are placed on the non-lookaside free() routines to verify
  18219. ** this constraint.
  18220. **
  18221. ** All of this is no-op for a production build. It only comes into
  18222. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  18223. */
  18224. #ifdef SQLITE_MEMDEBUG
  18225. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  18226. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  18227. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  18228. #else
  18229. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  18230. # define sqlite3MemdebugHasType(X,Y) 1
  18231. # define sqlite3MemdebugNoType(X,Y) 1
  18232. #endif
  18233. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  18234. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  18235. #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
  18236. /*
  18237. ** Threading interface
  18238. */
  18239. #if SQLITE_MAX_WORKER_THREADS>0
  18240. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  18241. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  18242. #endif
  18243. #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
  18244. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
  18245. #endif
  18246. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  18247. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  18248. #endif
  18249. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  18250. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  18251. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  18252. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  18253. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  18254. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  18255. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
  18256. #endif
  18257. #endif /* SQLITEINT_H */
  18258. /************** End of sqliteInt.h *******************************************/
  18259. /************** Begin file global.c ******************************************/
  18260. /*
  18261. ** 2008 June 13
  18262. **
  18263. ** The author disclaims copyright to this source code. In place of
  18264. ** a legal notice, here is a blessing:
  18265. **
  18266. ** May you do good and not evil.
  18267. ** May you find forgiveness for yourself and forgive others.
  18268. ** May you share freely, never taking more than you give.
  18269. **
  18270. *************************************************************************
  18271. **
  18272. ** This file contains definitions of global variables and constants.
  18273. */
  18274. /* #include "sqliteInt.h" */
  18275. /* An array to map all upper-case characters into their corresponding
  18276. ** lower-case character.
  18277. **
  18278. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  18279. ** handle case conversions for the UTF character set since the tables
  18280. ** involved are nearly as big or bigger than SQLite itself.
  18281. */
  18282. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  18283. #ifdef SQLITE_ASCII
  18284. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  18285. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  18286. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  18287. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  18288. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  18289. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  18290. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  18291. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  18292. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  18293. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  18294. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  18295. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  18296. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  18297. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  18298. 252,253,254,255
  18299. #endif
  18300. #ifdef SQLITE_EBCDIC
  18301. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  18302. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  18303. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  18304. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  18305. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  18306. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  18307. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  18308. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  18309. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  18310. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  18311. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  18312. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  18313. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  18314. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  18315. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  18316. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  18317. #endif
  18318. };
  18319. /*
  18320. ** The following 256 byte lookup table is used to support SQLites built-in
  18321. ** equivalents to the following standard library functions:
  18322. **
  18323. ** isspace() 0x01
  18324. ** isalpha() 0x02
  18325. ** isdigit() 0x04
  18326. ** isalnum() 0x06
  18327. ** isxdigit() 0x08
  18328. ** toupper() 0x20
  18329. ** SQLite identifier character 0x40
  18330. ** Quote character 0x80
  18331. **
  18332. ** Bit 0x20 is set if the mapped character requires translation to upper
  18333. ** case. i.e. if the character is a lower-case ASCII character.
  18334. ** If x is a lower-case ASCII character, then its upper-case equivalent
  18335. ** is (x - 0x20). Therefore toupper() can be implemented as:
  18336. **
  18337. ** (x & ~(map[x]&0x20))
  18338. **
  18339. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  18340. ** array. tolower() is used more often than toupper() by SQLite.
  18341. **
  18342. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  18343. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  18344. ** non-ASCII UTF character. Hence the test for whether or not a character is
  18345. ** part of an identifier is 0x46.
  18346. */
  18347. #ifdef SQLITE_ASCII
  18348. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  18349. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  18350. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  18351. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  18352. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  18353. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  18354. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  18355. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  18356. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  18357. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  18358. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  18359. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  18360. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  18361. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  18362. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  18363. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  18364. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  18365. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  18366. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  18367. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  18368. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  18369. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  18370. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  18371. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  18372. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  18373. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  18374. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  18375. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  18376. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  18377. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  18378. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  18379. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  18380. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  18381. };
  18382. #endif
  18383. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  18384. ** compatibility for legacy applications, the URI filename capability is
  18385. ** disabled by default.
  18386. **
  18387. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  18388. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  18389. **
  18390. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  18391. ** disabled. The default value may be changed by compiling with the
  18392. ** SQLITE_USE_URI symbol defined.
  18393. **
  18394. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  18395. ** enabled.
  18396. */
  18397. #ifndef SQLITE_USE_URI
  18398. # ifdef SQLITE_HAS_CODEC
  18399. # define SQLITE_USE_URI 1
  18400. # else
  18401. # define SQLITE_USE_URI 0
  18402. # endif
  18403. #endif
  18404. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  18405. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  18406. ** that compile-time option is omitted.
  18407. */
  18408. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  18409. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  18410. #endif
  18411. /* The minimum PMA size is set to this value multiplied by the database
  18412. ** page size in bytes.
  18413. */
  18414. #ifndef SQLITE_SORTER_PMASZ
  18415. # define SQLITE_SORTER_PMASZ 250
  18416. #endif
  18417. /* Statement journals spill to disk when their size exceeds the following
  18418. ** threshold (in bytes). 0 means that statement journals are created and
  18419. ** written to disk immediately (the default behavior for SQLite versions
  18420. ** before 3.12.0). -1 means always keep the entire statement journal in
  18421. ** memory. (The statement journal is also always held entirely in memory
  18422. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  18423. ** setting.)
  18424. */
  18425. #ifndef SQLITE_STMTJRNL_SPILL
  18426. # define SQLITE_STMTJRNL_SPILL (64*1024)
  18427. #endif
  18428. /*
  18429. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  18430. ** number of bytes in each lookaside slot (should be a multiple of 8)
  18431. ** and N is the number of slots. The lookaside-configuration can be
  18432. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  18433. ** or at run-time for an individual database connection using
  18434. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  18435. */
  18436. #ifndef SQLITE_DEFAULT_LOOKASIDE
  18437. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  18438. #endif
  18439. /*
  18440. ** The following singleton contains the global configuration for
  18441. ** the SQLite library.
  18442. */
  18443. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  18444. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  18445. 1, /* bCoreMutex */
  18446. SQLITE_THREADSAFE==1, /* bFullMutex */
  18447. SQLITE_USE_URI, /* bOpenUri */
  18448. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  18449. 0, /* bSmallMalloc */
  18450. 0x7ffffffe, /* mxStrlen */
  18451. 0, /* neverCorrupt */
  18452. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  18453. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  18454. {0,0,0,0,0,0,0,0}, /* m */
  18455. {0,0,0,0,0,0,0,0,0}, /* mutex */
  18456. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  18457. (void*)0, /* pHeap */
  18458. 0, /* nHeap */
  18459. 0, 0, /* mnHeap, mxHeap */
  18460. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  18461. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  18462. (void*)0, /* pPage */
  18463. 0, /* szPage */
  18464. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  18465. 0, /* mxParserStack */
  18466. 0, /* sharedCacheEnabled */
  18467. SQLITE_SORTER_PMASZ, /* szPma */
  18468. /* All the rest should always be initialized to zero */
  18469. 0, /* isInit */
  18470. 0, /* inProgress */
  18471. 0, /* isMutexInit */
  18472. 0, /* isMallocInit */
  18473. 0, /* isPCacheInit */
  18474. 0, /* nRefInitMutex */
  18475. 0, /* pInitMutex */
  18476. 0, /* xLog */
  18477. 0, /* pLogArg */
  18478. #ifdef SQLITE_ENABLE_SQLLOG
  18479. 0, /* xSqllog */
  18480. 0, /* pSqllogArg */
  18481. #endif
  18482. #ifdef SQLITE_VDBE_COVERAGE
  18483. 0, /* xVdbeBranch */
  18484. 0, /* pVbeBranchArg */
  18485. #endif
  18486. #ifndef SQLITE_UNTESTABLE
  18487. 0, /* xTestCallback */
  18488. #endif
  18489. 0, /* bLocaltimeFault */
  18490. 0x7ffffffe, /* iOnceResetThreshold */
  18491. SQLITE_DEFAULT_SORTERREF_SIZE /* szSorterRef */
  18492. };
  18493. /*
  18494. ** Hash table for global functions - functions common to all
  18495. ** database connections. After initialization, this table is
  18496. ** read-only.
  18497. */
  18498. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  18499. /*
  18500. ** Constant tokens for values 0 and 1.
  18501. */
  18502. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  18503. { "0", 1 },
  18504. { "1", 1 }
  18505. };
  18506. #ifdef VDBE_PROFILE
  18507. /*
  18508. ** The following performance counter can be used in place of
  18509. ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
  18510. */
  18511. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
  18512. #endif
  18513. /*
  18514. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  18515. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  18516. ** the database page that contains the pending byte. It never attempts
  18517. ** to read or write that page. The pending byte page is set aside
  18518. ** for use by the VFS layers as space for managing file locks.
  18519. **
  18520. ** During testing, it is often desirable to move the pending byte to
  18521. ** a different position in the file. This allows code that has to
  18522. ** deal with the pending byte to run on files that are much smaller
  18523. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  18524. ** move the pending byte.
  18525. **
  18526. ** IMPORTANT: Changing the pending byte to any value other than
  18527. ** 0x40000000 results in an incompatible database file format!
  18528. ** Changing the pending byte during operation will result in undefined
  18529. ** and incorrect behavior.
  18530. */
  18531. #ifndef SQLITE_OMIT_WSD
  18532. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  18533. #endif
  18534. /* #include "opcodes.h" */
  18535. /*
  18536. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  18537. ** created by mkopcodeh.awk during compilation. Data is obtained
  18538. ** from the comments following the "case OP_xxxx:" statements in
  18539. ** the vdbe.c file.
  18540. */
  18541. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  18542. /*
  18543. ** Name of the default collating sequence
  18544. */
  18545. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  18546. /************** End of global.c **********************************************/
  18547. /************** Begin file status.c ******************************************/
  18548. /*
  18549. ** 2008 June 18
  18550. **
  18551. ** The author disclaims copyright to this source code. In place of
  18552. ** a legal notice, here is a blessing:
  18553. **
  18554. ** May you do good and not evil.
  18555. ** May you find forgiveness for yourself and forgive others.
  18556. ** May you share freely, never taking more than you give.
  18557. **
  18558. *************************************************************************
  18559. **
  18560. ** This module implements the sqlite3_status() interface and related
  18561. ** functionality.
  18562. */
  18563. /* #include "sqliteInt.h" */
  18564. /************** Include vdbeInt.h in the middle of status.c ******************/
  18565. /************** Begin file vdbeInt.h *****************************************/
  18566. /*
  18567. ** 2003 September 6
  18568. **
  18569. ** The author disclaims copyright to this source code. In place of
  18570. ** a legal notice, here is a blessing:
  18571. **
  18572. ** May you do good and not evil.
  18573. ** May you find forgiveness for yourself and forgive others.
  18574. ** May you share freely, never taking more than you give.
  18575. **
  18576. *************************************************************************
  18577. ** This is the header file for information that is private to the
  18578. ** VDBE. This information used to all be at the top of the single
  18579. ** source code file "vdbe.c". When that file became too big (over
  18580. ** 6000 lines long) it was split up into several smaller files and
  18581. ** this header information was factored out.
  18582. */
  18583. #ifndef SQLITE_VDBEINT_H
  18584. #define SQLITE_VDBEINT_H
  18585. /*
  18586. ** The maximum number of times that a statement will try to reparse
  18587. ** itself before giving up and returning SQLITE_SCHEMA.
  18588. */
  18589. #ifndef SQLITE_MAX_SCHEMA_RETRY
  18590. # define SQLITE_MAX_SCHEMA_RETRY 50
  18591. #endif
  18592. /*
  18593. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  18594. ** "explain" P4 display logic is enabled.
  18595. */
  18596. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  18597. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  18598. # define VDBE_DISPLAY_P4 1
  18599. #else
  18600. # define VDBE_DISPLAY_P4 0
  18601. #endif
  18602. /*
  18603. ** SQL is translated into a sequence of instructions to be
  18604. ** executed by a virtual machine. Each instruction is an instance
  18605. ** of the following structure.
  18606. */
  18607. typedef struct VdbeOp Op;
  18608. /*
  18609. ** Boolean values
  18610. */
  18611. typedef unsigned Bool;
  18612. /* Opaque type used by code in vdbesort.c */
  18613. typedef struct VdbeSorter VdbeSorter;
  18614. /* Elements of the linked list at Vdbe.pAuxData */
  18615. typedef struct AuxData AuxData;
  18616. /* Types of VDBE cursors */
  18617. #define CURTYPE_BTREE 0
  18618. #define CURTYPE_SORTER 1
  18619. #define CURTYPE_VTAB 2
  18620. #define CURTYPE_PSEUDO 3
  18621. /*
  18622. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  18623. **
  18624. ** * A b-tree cursor
  18625. ** - In the main database or in an ephemeral database
  18626. ** - On either an index or a table
  18627. ** * A sorter
  18628. ** * A virtual table
  18629. ** * A one-row "pseudotable" stored in a single register
  18630. */
  18631. typedef struct VdbeCursor VdbeCursor;
  18632. struct VdbeCursor {
  18633. u8 eCurType; /* One of the CURTYPE_* values above */
  18634. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  18635. u8 nullRow; /* True if pointing to a row with no data */
  18636. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  18637. u8 isTable; /* True for rowid tables. False for indexes */
  18638. #ifdef SQLITE_DEBUG
  18639. u8 seekOp; /* Most recent seek operation on this cursor */
  18640. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  18641. #endif
  18642. Bool isEphemeral:1; /* True for an ephemeral table */
  18643. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  18644. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  18645. Btree *pBtx; /* Separate file holding temporary table */
  18646. i64 seqCount; /* Sequence counter */
  18647. int *aAltMap; /* Mapping from table to index column numbers */
  18648. /* Cached OP_Column parse information is only valid if cacheStatus matches
  18649. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  18650. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  18651. ** the cache is out of date. */
  18652. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  18653. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  18654. ** if there have been no prior seeks on the cursor. */
  18655. /* seekResult does not distinguish between "no seeks have ever occurred
  18656. ** on this cursor" and "the most recent seek was an exact match".
  18657. ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
  18658. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  18659. ** The fields that follow are uninitialized, and must be individually
  18660. ** initialized prior to first use. */
  18661. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  18662. union {
  18663. BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
  18664. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  18665. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  18666. } uc;
  18667. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  18668. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  18669. Pgno pgnoRoot; /* Root page of the open btree cursor */
  18670. i16 nField; /* Number of fields in the header */
  18671. u16 nHdrParsed; /* Number of header fields parsed so far */
  18672. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  18673. u32 *aOffset; /* Pointer to aType[nField] */
  18674. const u8 *aRow; /* Data for the current row, if all on one page */
  18675. u32 payloadSize; /* Total number of bytes in the record */
  18676. u32 szRow; /* Byte available in aRow */
  18677. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  18678. u64 maskUsed; /* Mask of columns used by this cursor */
  18679. #endif
  18680. /* 2*nField extra array elements allocated for aType[], beyond the one
  18681. ** static element declared in the structure. nField total array slots for
  18682. ** aType[] and nField+1 array slots for aOffset[] */
  18683. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  18684. };
  18685. /*
  18686. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  18687. */
  18688. #define CACHE_STALE 0
  18689. /*
  18690. ** When a sub-program is executed (OP_Program), a structure of this type
  18691. ** is allocated to store the current value of the program counter, as
  18692. ** well as the current memory cell array and various other frame specific
  18693. ** values stored in the Vdbe struct. When the sub-program is finished,
  18694. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  18695. ** restoring the state of the VM to as it was before the sub-program
  18696. ** began executing.
  18697. **
  18698. ** The memory for a VdbeFrame object is allocated and managed by a memory
  18699. ** cell in the parent (calling) frame. When the memory cell is deleted or
  18700. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  18701. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  18702. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  18703. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  18704. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  18705. ** child frame are released.
  18706. **
  18707. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  18708. ** set to NULL if the currently executing frame is the main program.
  18709. */
  18710. typedef struct VdbeFrame VdbeFrame;
  18711. struct VdbeFrame {
  18712. Vdbe *v; /* VM this frame belongs to */
  18713. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  18714. Op *aOp; /* Program instructions for parent frame */
  18715. i64 *anExec; /* Event counters from parent frame */
  18716. Mem *aMem; /* Array of memory cells for parent frame */
  18717. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  18718. u8 *aOnce; /* Bitmask used by OP_Once */
  18719. void *token; /* Copy of SubProgram.token */
  18720. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  18721. AuxData *pAuxData; /* Linked list of auxdata allocations */
  18722. int nCursor; /* Number of entries in apCsr */
  18723. int pc; /* Program Counter in parent (calling) frame */
  18724. int nOp; /* Size of aOp array */
  18725. int nMem; /* Number of entries in aMem */
  18726. int nChildMem; /* Number of memory cells for child frame */
  18727. int nChildCsr; /* Number of cursors for child frame */
  18728. int nChange; /* Statement changes (Vdbe.nChange) */
  18729. int nDbChange; /* Value of db->nChange */
  18730. };
  18731. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  18732. /*
  18733. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  18734. ** structures. Each Mem struct may cache multiple representations (string,
  18735. ** integer etc.) of the same value.
  18736. */
  18737. struct sqlite3_value {
  18738. union MemValue {
  18739. double r; /* Real value used when MEM_Real is set in flags */
  18740. i64 i; /* Integer value used when MEM_Int is set in flags */
  18741. int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
  18742. const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
  18743. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  18744. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  18745. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  18746. } u;
  18747. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  18748. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  18749. u8 eSubtype; /* Subtype for this value */
  18750. int n; /* Number of characters in string value, excluding '\0' */
  18751. char *z; /* String or BLOB value */
  18752. /* ShallowCopy only needs to copy the information above */
  18753. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  18754. int szMalloc; /* Size of the zMalloc allocation */
  18755. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  18756. sqlite3 *db; /* The associated database connection */
  18757. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  18758. #ifdef SQLITE_DEBUG
  18759. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  18760. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  18761. #endif
  18762. };
  18763. /*
  18764. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  18765. ** follows.
  18766. */
  18767. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  18768. /* One or more of the following flags are set to indicate the validOK
  18769. ** representations of the value stored in the Mem struct.
  18770. **
  18771. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  18772. ** For a pointer type created using sqlite3_bind_pointer() or
  18773. ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
  18774. **
  18775. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  18776. ** Usually this is encoded in the same unicode encoding as the main
  18777. ** database (see below for exceptions). If the MEM_Term flag is also
  18778. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  18779. ** flags may coexist with the MEM_Str flag.
  18780. */
  18781. #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
  18782. #define MEM_Str 0x0002 /* Value is a string */
  18783. #define MEM_Int 0x0004 /* Value is an integer */
  18784. #define MEM_Real 0x0008 /* Value is a real number */
  18785. #define MEM_Blob 0x0010 /* Value is a BLOB */
  18786. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  18787. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  18788. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  18789. #define MEM_Undefined 0x0080 /* Value is undefined */
  18790. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  18791. #define MEM_TypeMask 0xc1ff /* Mask of type bits */
  18792. /* Whenever Mem contains a valid string or blob representation, one of
  18793. ** the following flags must be set to determine the memory management
  18794. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  18795. ** string is \000 or \u0000 terminated
  18796. */
  18797. #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
  18798. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  18799. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  18800. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  18801. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  18802. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  18803. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  18804. #ifdef SQLITE_OMIT_INCRBLOB
  18805. #undef MEM_Zero
  18806. #define MEM_Zero 0x0000
  18807. #endif
  18808. /* Return TRUE if Mem X contains dynamically allocated content - anything
  18809. ** that needs to be deallocated to avoid a leak.
  18810. */
  18811. #define VdbeMemDynamic(X) \
  18812. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  18813. /*
  18814. ** Clear any existing type flags from a Mem and replace them with f
  18815. */
  18816. #define MemSetTypeFlag(p, f) \
  18817. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  18818. /*
  18819. ** Return true if a memory cell is not marked as invalid. This macro
  18820. ** is for use inside assert() statements only.
  18821. */
  18822. #ifdef SQLITE_DEBUG
  18823. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  18824. #endif
  18825. /*
  18826. ** Each auxiliary data pointer stored by a user defined function
  18827. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  18828. ** of this structure. All such structures associated with a single VM
  18829. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  18830. ** when the VM is halted (if not before).
  18831. */
  18832. struct AuxData {
  18833. int iAuxOp; /* Instruction number of OP_Function opcode */
  18834. int iAuxArg; /* Index of function argument. */
  18835. void *pAux; /* Aux data pointer */
  18836. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  18837. AuxData *pNextAux; /* Next element in list */
  18838. };
  18839. /*
  18840. ** The "context" argument for an installable function. A pointer to an
  18841. ** instance of this structure is the first argument to the routines used
  18842. ** implement the SQL functions.
  18843. **
  18844. ** There is a typedef for this structure in sqlite.h. So all routines,
  18845. ** even the public interface to SQLite, can use a pointer to this structure.
  18846. ** But this file is the only place where the internal details of this
  18847. ** structure are known.
  18848. **
  18849. ** This structure is defined inside of vdbeInt.h because it uses substructures
  18850. ** (Mem) which are only defined there.
  18851. */
  18852. struct sqlite3_context {
  18853. Mem *pOut; /* The return value is stored here */
  18854. FuncDef *pFunc; /* Pointer to function information */
  18855. Mem *pMem; /* Memory cell used to store aggregate context */
  18856. Vdbe *pVdbe; /* The VM that owns this context */
  18857. int iOp; /* Instruction number of OP_Function */
  18858. int isError; /* Error code returned by the function. */
  18859. u8 skipFlag; /* Skip accumulator loading if true */
  18860. u8 argc; /* Number of arguments */
  18861. sqlite3_value *argv[1]; /* Argument set */
  18862. };
  18863. /* A bitfield type for use inside of structures. Always follow with :N where
  18864. ** N is the number of bits.
  18865. */
  18866. typedef unsigned bft; /* Bit Field Type */
  18867. typedef struct ScanStatus ScanStatus;
  18868. struct ScanStatus {
  18869. int addrExplain; /* OP_Explain for loop */
  18870. int addrLoop; /* Address of "loops" counter */
  18871. int addrVisit; /* Address of "rows visited" counter */
  18872. int iSelectID; /* The "Select-ID" for this loop */
  18873. LogEst nEst; /* Estimated output rows per loop */
  18874. char *zName; /* Name of table or index */
  18875. };
  18876. /*
  18877. ** An instance of the virtual machine. This structure contains the complete
  18878. ** state of the virtual machine.
  18879. **
  18880. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  18881. ** is really a pointer to an instance of this structure.
  18882. */
  18883. struct Vdbe {
  18884. sqlite3 *db; /* The database connection that owns this statement */
  18885. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  18886. Parse *pParse; /* Parsing context used to create this Vdbe */
  18887. ynVar nVar; /* Number of entries in aVar[] */
  18888. u32 magic; /* Magic number for sanity checking */
  18889. int nMem; /* Number of memory locations currently allocated */
  18890. int nCursor; /* Number of slots in apCsr[] */
  18891. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  18892. int pc; /* The program counter */
  18893. int rc; /* Value to return */
  18894. int nChange; /* Number of db changes made since last reset */
  18895. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  18896. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  18897. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  18898. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  18899. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  18900. /* When allocating a new Vdbe object, all of the fields below should be
  18901. ** initialized to zero or NULL */
  18902. Op *aOp; /* Space to hold the virtual machine's program */
  18903. Mem *aMem; /* The memory locations */
  18904. Mem **apArg; /* Arguments to currently executing user function */
  18905. Mem *aColName; /* Column names to return */
  18906. Mem *pResultSet; /* Pointer to an array of results */
  18907. char *zErrMsg; /* Error message written here */
  18908. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  18909. Mem *aVar; /* Values for the OP_Variable opcode. */
  18910. VList *pVList; /* Name of variables */
  18911. #ifndef SQLITE_OMIT_TRACE
  18912. i64 startTime; /* Time when query started - used for profiling */
  18913. #endif
  18914. int nOp; /* Number of instructions in the program */
  18915. #ifdef SQLITE_DEBUG
  18916. int rcApp; /* errcode set by sqlite3_result_error_code() */
  18917. u32 nWrite; /* Number of write operations that have occurred */
  18918. #endif
  18919. u16 nResColumn; /* Number of columns in one row of the result set */
  18920. u8 errorAction; /* Recovery action to do in case of an error */
  18921. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  18922. u8 prepFlags; /* SQLITE_PREPARE_* flags */
  18923. bft expired:1; /* True if the VM needs to be recompiled */
  18924. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  18925. bft explain:2; /* True if EXPLAIN present on SQL command */
  18926. bft changeCntOn:1; /* True to update the change-counter */
  18927. bft runOnlyOnce:1; /* Automatically expire on reset */
  18928. bft usesStmtJournal:1; /* True if uses a statement journal */
  18929. bft readOnly:1; /* True for statements that do not write */
  18930. bft bIsReader:1; /* True for statements that read */
  18931. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  18932. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  18933. u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
  18934. char *zSql; /* Text of the SQL statement that generated this */
  18935. void *pFree; /* Free this when deleting the vdbe */
  18936. VdbeFrame *pFrame; /* Parent frame */
  18937. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  18938. int nFrame; /* Number of frames in pFrame list */
  18939. u32 expmask; /* Binding to these vars invalidates VM */
  18940. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  18941. AuxData *pAuxData; /* Linked list of auxdata allocations */
  18942. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  18943. i64 *anExec; /* Number of times each op has been executed */
  18944. int nScan; /* Entries in aScan[] */
  18945. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  18946. #endif
  18947. };
  18948. /*
  18949. ** The following are allowed values for Vdbe.magic
  18950. */
  18951. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  18952. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  18953. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  18954. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  18955. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  18956. /*
  18957. ** Structure used to store the context required by the
  18958. ** sqlite3_preupdate_*() API functions.
  18959. */
  18960. struct PreUpdate {
  18961. Vdbe *v;
  18962. VdbeCursor *pCsr; /* Cursor to read old values from */
  18963. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  18964. u8 *aRecord; /* old.* database record */
  18965. KeyInfo keyinfo;
  18966. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  18967. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  18968. int iNewReg; /* Register for new.* values */
  18969. i64 iKey1; /* First key value passed to hook */
  18970. i64 iKey2; /* Second key value passed to hook */
  18971. Mem *aNew; /* Array of new.* values */
  18972. Table *pTab; /* Schema object being upated */
  18973. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  18974. };
  18975. /*
  18976. ** Function prototypes
  18977. */
  18978. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  18979. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  18980. void sqliteVdbePopStack(Vdbe*,int);
  18981. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  18982. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  18983. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  18984. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  18985. #endif
  18986. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  18987. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  18988. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  18989. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  18990. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  18991. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  18992. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  18993. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  18994. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  18995. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  18996. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  18997. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  18998. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  18999. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  19000. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  19001. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  19002. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  19003. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  19004. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  19005. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  19006. #ifdef SQLITE_OMIT_FLOATING_POINT
  19007. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  19008. #else
  19009. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  19010. #endif
  19011. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
  19012. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  19013. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  19014. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  19015. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  19016. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  19017. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  19018. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  19019. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  19020. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  19021. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
  19022. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  19023. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  19024. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  19025. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  19026. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  19027. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  19028. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  19029. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  19030. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  19031. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  19032. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  19033. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  19034. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  19035. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  19036. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  19037. #endif
  19038. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  19039. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  19040. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  19041. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  19042. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  19043. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
  19044. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  19045. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  19046. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  19047. #ifdef SQLITE_DEBUG
  19048. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
  19049. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
  19050. #else
  19051. # define sqlite3VdbeIncrWriteCounter(V,C)
  19052. # define sqlite3VdbeAssertAbortable(V)
  19053. #endif
  19054. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  19055. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  19056. #else
  19057. # define sqlite3VdbeEnter(X)
  19058. #endif
  19059. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  19060. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  19061. #else
  19062. # define sqlite3VdbeLeave(X)
  19063. #endif
  19064. #ifdef SQLITE_DEBUG
  19065. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  19066. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  19067. #endif
  19068. #ifndef SQLITE_OMIT_FOREIGN_KEY
  19069. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  19070. #else
  19071. # define sqlite3VdbeCheckFk(p,i) 0
  19072. #endif
  19073. #ifdef SQLITE_DEBUG
  19074. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  19075. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  19076. #endif
  19077. #ifndef SQLITE_OMIT_UTF16
  19078. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  19079. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  19080. #endif
  19081. #ifndef SQLITE_OMIT_INCRBLOB
  19082. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  19083. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  19084. #else
  19085. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  19086. #define ExpandBlob(P) SQLITE_OK
  19087. #endif
  19088. #endif /* !defined(SQLITE_VDBEINT_H) */
  19089. /************** End of vdbeInt.h *********************************************/
  19090. /************** Continuing where we left off in status.c *********************/
  19091. /*
  19092. ** Variables in which to record status information.
  19093. */
  19094. #if SQLITE_PTRSIZE>4
  19095. typedef sqlite3_int64 sqlite3StatValueType;
  19096. #else
  19097. typedef u32 sqlite3StatValueType;
  19098. #endif
  19099. typedef struct sqlite3StatType sqlite3StatType;
  19100. static SQLITE_WSD struct sqlite3StatType {
  19101. sqlite3StatValueType nowValue[10]; /* Current value */
  19102. sqlite3StatValueType mxValue[10]; /* Maximum value */
  19103. } sqlite3Stat = { {0,}, {0,} };
  19104. /*
  19105. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  19106. ** mutex, or by the pcache1 mutex. The following array determines which.
  19107. */
  19108. static const char statMutex[] = {
  19109. 0, /* SQLITE_STATUS_MEMORY_USED */
  19110. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  19111. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  19112. 0, /* SQLITE_STATUS_SCRATCH_USED */
  19113. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  19114. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  19115. 0, /* SQLITE_STATUS_PARSER_STACK */
  19116. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  19117. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  19118. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  19119. };
  19120. /* The "wsdStat" macro will resolve to the status information
  19121. ** state vector. If writable static data is unsupported on the target,
  19122. ** we have to locate the state vector at run-time. In the more common
  19123. ** case where writable static data is supported, wsdStat can refer directly
  19124. ** to the "sqlite3Stat" state vector declared above.
  19125. */
  19126. #ifdef SQLITE_OMIT_WSD
  19127. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  19128. # define wsdStat x[0]
  19129. #else
  19130. # define wsdStatInit
  19131. # define wsdStat sqlite3Stat
  19132. #endif
  19133. /*
  19134. ** Return the current value of a status parameter. The caller must
  19135. ** be holding the appropriate mutex.
  19136. */
  19137. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  19138. wsdStatInit;
  19139. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19140. assert( op>=0 && op<ArraySize(statMutex) );
  19141. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19142. : sqlite3MallocMutex()) );
  19143. return wsdStat.nowValue[op];
  19144. }
  19145. /*
  19146. ** Add N to the value of a status record. The caller must hold the
  19147. ** appropriate mutex. (Locking is checked by assert()).
  19148. **
  19149. ** The StatusUp() routine can accept positive or negative values for N.
  19150. ** The value of N is added to the current status value and the high-water
  19151. ** mark is adjusted if necessary.
  19152. **
  19153. ** The StatusDown() routine lowers the current value by N. The highwater
  19154. ** mark is unchanged. N must be non-negative for StatusDown().
  19155. */
  19156. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  19157. wsdStatInit;
  19158. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19159. assert( op>=0 && op<ArraySize(statMutex) );
  19160. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19161. : sqlite3MallocMutex()) );
  19162. wsdStat.nowValue[op] += N;
  19163. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  19164. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19165. }
  19166. }
  19167. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  19168. wsdStatInit;
  19169. assert( N>=0 );
  19170. assert( op>=0 && op<ArraySize(statMutex) );
  19171. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19172. : sqlite3MallocMutex()) );
  19173. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19174. wsdStat.nowValue[op] -= N;
  19175. }
  19176. /*
  19177. ** Adjust the highwater mark if necessary.
  19178. ** The caller must hold the appropriate mutex.
  19179. */
  19180. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  19181. sqlite3StatValueType newValue;
  19182. wsdStatInit;
  19183. assert( X>=0 );
  19184. newValue = (sqlite3StatValueType)X;
  19185. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19186. assert( op>=0 && op<ArraySize(statMutex) );
  19187. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19188. : sqlite3MallocMutex()) );
  19189. assert( op==SQLITE_STATUS_MALLOC_SIZE
  19190. || op==SQLITE_STATUS_PAGECACHE_SIZE
  19191. || op==SQLITE_STATUS_PARSER_STACK );
  19192. if( newValue>wsdStat.mxValue[op] ){
  19193. wsdStat.mxValue[op] = newValue;
  19194. }
  19195. }
  19196. /*
  19197. ** Query status information.
  19198. */
  19199. SQLITE_API int sqlite3_status64(
  19200. int op,
  19201. sqlite3_int64 *pCurrent,
  19202. sqlite3_int64 *pHighwater,
  19203. int resetFlag
  19204. ){
  19205. sqlite3_mutex *pMutex;
  19206. wsdStatInit;
  19207. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  19208. return SQLITE_MISUSE_BKPT;
  19209. }
  19210. #ifdef SQLITE_ENABLE_API_ARMOR
  19211. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19212. #endif
  19213. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  19214. sqlite3_mutex_enter(pMutex);
  19215. *pCurrent = wsdStat.nowValue[op];
  19216. *pHighwater = wsdStat.mxValue[op];
  19217. if( resetFlag ){
  19218. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19219. }
  19220. sqlite3_mutex_leave(pMutex);
  19221. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  19222. return SQLITE_OK;
  19223. }
  19224. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  19225. sqlite3_int64 iCur = 0, iHwtr = 0;
  19226. int rc;
  19227. #ifdef SQLITE_ENABLE_API_ARMOR
  19228. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19229. #endif
  19230. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  19231. if( rc==0 ){
  19232. *pCurrent = (int)iCur;
  19233. *pHighwater = (int)iHwtr;
  19234. }
  19235. return rc;
  19236. }
  19237. /*
  19238. ** Return the number of LookasideSlot elements on the linked list
  19239. */
  19240. static u32 countLookasideSlots(LookasideSlot *p){
  19241. u32 cnt = 0;
  19242. while( p ){
  19243. p = p->pNext;
  19244. cnt++;
  19245. }
  19246. return cnt;
  19247. }
  19248. /*
  19249. ** Count the number of slots of lookaside memory that are outstanding
  19250. */
  19251. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
  19252. u32 nInit = countLookasideSlots(db->lookaside.pInit);
  19253. u32 nFree = countLookasideSlots(db->lookaside.pFree);
  19254. if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
  19255. return db->lookaside.nSlot - (nInit+nFree);
  19256. }
  19257. /*
  19258. ** Query status information for a single database connection
  19259. */
  19260. SQLITE_API int sqlite3_db_status(
  19261. sqlite3 *db, /* The database connection whose status is desired */
  19262. int op, /* Status verb */
  19263. int *pCurrent, /* Write current value here */
  19264. int *pHighwater, /* Write high-water mark here */
  19265. int resetFlag /* Reset high-water mark if true */
  19266. ){
  19267. int rc = SQLITE_OK; /* Return code */
  19268. #ifdef SQLITE_ENABLE_API_ARMOR
  19269. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  19270. return SQLITE_MISUSE_BKPT;
  19271. }
  19272. #endif
  19273. sqlite3_mutex_enter(db->mutex);
  19274. switch( op ){
  19275. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  19276. *pCurrent = sqlite3LookasideUsed(db, pHighwater);
  19277. if( resetFlag ){
  19278. LookasideSlot *p = db->lookaside.pFree;
  19279. if( p ){
  19280. while( p->pNext ) p = p->pNext;
  19281. p->pNext = db->lookaside.pInit;
  19282. db->lookaside.pInit = db->lookaside.pFree;
  19283. db->lookaside.pFree = 0;
  19284. }
  19285. }
  19286. break;
  19287. }
  19288. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  19289. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  19290. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  19291. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  19292. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  19293. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  19294. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  19295. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  19296. *pCurrent = 0;
  19297. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  19298. if( resetFlag ){
  19299. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  19300. }
  19301. break;
  19302. }
  19303. /*
  19304. ** Return an approximation for the amount of memory currently used
  19305. ** by all pagers associated with the given database connection. The
  19306. ** highwater mark is meaningless and is returned as zero.
  19307. */
  19308. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  19309. case SQLITE_DBSTATUS_CACHE_USED: {
  19310. int totalUsed = 0;
  19311. int i;
  19312. sqlite3BtreeEnterAll(db);
  19313. for(i=0; i<db->nDb; i++){
  19314. Btree *pBt = db->aDb[i].pBt;
  19315. if( pBt ){
  19316. Pager *pPager = sqlite3BtreePager(pBt);
  19317. int nByte = sqlite3PagerMemUsed(pPager);
  19318. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  19319. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  19320. }
  19321. totalUsed += nByte;
  19322. }
  19323. }
  19324. sqlite3BtreeLeaveAll(db);
  19325. *pCurrent = totalUsed;
  19326. *pHighwater = 0;
  19327. break;
  19328. }
  19329. /*
  19330. ** *pCurrent gets an accurate estimate of the amount of memory used
  19331. ** to store the schema for all databases (main, temp, and any ATTACHed
  19332. ** databases. *pHighwater is set to zero.
  19333. */
  19334. case SQLITE_DBSTATUS_SCHEMA_USED: {
  19335. int i; /* Used to iterate through schemas */
  19336. int nByte = 0; /* Used to accumulate return value */
  19337. sqlite3BtreeEnterAll(db);
  19338. db->pnBytesFreed = &nByte;
  19339. for(i=0; i<db->nDb; i++){
  19340. Schema *pSchema = db->aDb[i].pSchema;
  19341. if( ALWAYS(pSchema!=0) ){
  19342. HashElem *p;
  19343. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  19344. pSchema->tblHash.count
  19345. + pSchema->trigHash.count
  19346. + pSchema->idxHash.count
  19347. + pSchema->fkeyHash.count
  19348. );
  19349. nByte += sqlite3_msize(pSchema->tblHash.ht);
  19350. nByte += sqlite3_msize(pSchema->trigHash.ht);
  19351. nByte += sqlite3_msize(pSchema->idxHash.ht);
  19352. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  19353. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  19354. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  19355. }
  19356. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  19357. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  19358. }
  19359. }
  19360. }
  19361. db->pnBytesFreed = 0;
  19362. sqlite3BtreeLeaveAll(db);
  19363. *pHighwater = 0;
  19364. *pCurrent = nByte;
  19365. break;
  19366. }
  19367. /*
  19368. ** *pCurrent gets an accurate estimate of the amount of memory used
  19369. ** to store all prepared statements.
  19370. ** *pHighwater is set to zero.
  19371. */
  19372. case SQLITE_DBSTATUS_STMT_USED: {
  19373. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  19374. int nByte = 0; /* Used to accumulate return value */
  19375. db->pnBytesFreed = &nByte;
  19376. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  19377. sqlite3VdbeClearObject(db, pVdbe);
  19378. sqlite3DbFree(db, pVdbe);
  19379. }
  19380. db->pnBytesFreed = 0;
  19381. *pHighwater = 0; /* IMP: R-64479-57858 */
  19382. *pCurrent = nByte;
  19383. break;
  19384. }
  19385. /*
  19386. ** Set *pCurrent to the total cache hits or misses encountered by all
  19387. ** pagers the database handle is connected to. *pHighwater is always set
  19388. ** to zero.
  19389. */
  19390. case SQLITE_DBSTATUS_CACHE_SPILL:
  19391. op = SQLITE_DBSTATUS_CACHE_WRITE+1;
  19392. /* Fall through into the next case */
  19393. case SQLITE_DBSTATUS_CACHE_HIT:
  19394. case SQLITE_DBSTATUS_CACHE_MISS:
  19395. case SQLITE_DBSTATUS_CACHE_WRITE:{
  19396. int i;
  19397. int nRet = 0;
  19398. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  19399. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  19400. for(i=0; i<db->nDb; i++){
  19401. if( db->aDb[i].pBt ){
  19402. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  19403. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  19404. }
  19405. }
  19406. *pHighwater = 0; /* IMP: R-42420-56072 */
  19407. /* IMP: R-54100-20147 */
  19408. /* IMP: R-29431-39229 */
  19409. *pCurrent = nRet;
  19410. break;
  19411. }
  19412. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  19413. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  19414. ** have been satisfied. The *pHighwater is always set to zero.
  19415. */
  19416. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  19417. *pHighwater = 0; /* IMP: R-11967-56545 */
  19418. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  19419. break;
  19420. }
  19421. default: {
  19422. rc = SQLITE_ERROR;
  19423. }
  19424. }
  19425. sqlite3_mutex_leave(db->mutex);
  19426. return rc;
  19427. }
  19428. /************** End of status.c **********************************************/
  19429. /************** Begin file date.c ********************************************/
  19430. /*
  19431. ** 2003 October 31
  19432. **
  19433. ** The author disclaims copyright to this source code. In place of
  19434. ** a legal notice, here is a blessing:
  19435. **
  19436. ** May you do good and not evil.
  19437. ** May you find forgiveness for yourself and forgive others.
  19438. ** May you share freely, never taking more than you give.
  19439. **
  19440. *************************************************************************
  19441. ** This file contains the C functions that implement date and time
  19442. ** functions for SQLite.
  19443. **
  19444. ** There is only one exported symbol in this file - the function
  19445. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  19446. ** All other code has file scope.
  19447. **
  19448. ** SQLite processes all times and dates as julian day numbers. The
  19449. ** dates and times are stored as the number of days since noon
  19450. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  19451. ** calendar system.
  19452. **
  19453. ** 1970-01-01 00:00:00 is JD 2440587.5
  19454. ** 2000-01-01 00:00:00 is JD 2451544.5
  19455. **
  19456. ** This implementation requires years to be expressed as a 4-digit number
  19457. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  19458. ** be represented, even though julian day numbers allow a much wider
  19459. ** range of dates.
  19460. **
  19461. ** The Gregorian calendar system is used for all dates and times,
  19462. ** even those that predate the Gregorian calendar. Historians usually
  19463. ** use the julian calendar for dates prior to 1582-10-15 and for some
  19464. ** dates afterwards, depending on locale. Beware of this difference.
  19465. **
  19466. ** The conversion algorithms are implemented based on descriptions
  19467. ** in the following text:
  19468. **
  19469. ** Jean Meeus
  19470. ** Astronomical Algorithms, 2nd Edition, 1998
  19471. ** ISBN 0-943396-61-1
  19472. ** Willmann-Bell, Inc
  19473. ** Richmond, Virginia (USA)
  19474. */
  19475. /* #include "sqliteInt.h" */
  19476. /* #include <stdlib.h> */
  19477. /* #include <assert.h> */
  19478. #include <time.h>
  19479. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  19480. /*
  19481. ** The MSVC CRT on Windows CE may not have a localtime() function.
  19482. ** So declare a substitute. The substitute function itself is
  19483. ** defined in "os_win.c".
  19484. */
  19485. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  19486. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  19487. struct tm *__cdecl localtime(const time_t *);
  19488. #endif
  19489. /*
  19490. ** A structure for holding a single date and time.
  19491. */
  19492. typedef struct DateTime DateTime;
  19493. struct DateTime {
  19494. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  19495. int Y, M, D; /* Year, month, and day */
  19496. int h, m; /* Hour and minutes */
  19497. int tz; /* Timezone offset in minutes */
  19498. double s; /* Seconds */
  19499. char validJD; /* True (1) if iJD is valid */
  19500. char rawS; /* Raw numeric value stored in s */
  19501. char validYMD; /* True (1) if Y,M,D are valid */
  19502. char validHMS; /* True (1) if h,m,s are valid */
  19503. char validTZ; /* True (1) if tz is valid */
  19504. char tzSet; /* Timezone was set explicitly */
  19505. char isError; /* An overflow has occurred */
  19506. };
  19507. /*
  19508. ** Convert zDate into one or more integers according to the conversion
  19509. ** specifier zFormat.
  19510. **
  19511. ** zFormat[] contains 4 characters for each integer converted, except for
  19512. ** the last integer which is specified by three characters. The meaning
  19513. ** of a four-character format specifiers ABCD is:
  19514. **
  19515. ** A: number of digits to convert. Always "2" or "4".
  19516. ** B: minimum value. Always "0" or "1".
  19517. ** C: maximum value, decoded as:
  19518. ** a: 12
  19519. ** b: 14
  19520. ** c: 24
  19521. ** d: 31
  19522. ** e: 59
  19523. ** f: 9999
  19524. ** D: the separator character, or \000 to indicate this is the
  19525. ** last number to convert.
  19526. **
  19527. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  19528. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  19529. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  19530. ** the 2-digit day which is the last integer in the set.
  19531. **
  19532. ** The function returns the number of successful conversions.
  19533. */
  19534. static int getDigits(const char *zDate, const char *zFormat, ...){
  19535. /* The aMx[] array translates the 3rd character of each format
  19536. ** spec into a max size: a b c d e f */
  19537. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  19538. va_list ap;
  19539. int cnt = 0;
  19540. char nextC;
  19541. va_start(ap, zFormat);
  19542. do{
  19543. char N = zFormat[0] - '0';
  19544. char min = zFormat[1] - '0';
  19545. int val = 0;
  19546. u16 max;
  19547. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  19548. max = aMx[zFormat[2] - 'a'];
  19549. nextC = zFormat[3];
  19550. val = 0;
  19551. while( N-- ){
  19552. if( !sqlite3Isdigit(*zDate) ){
  19553. goto end_getDigits;
  19554. }
  19555. val = val*10 + *zDate - '0';
  19556. zDate++;
  19557. }
  19558. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  19559. goto end_getDigits;
  19560. }
  19561. *va_arg(ap,int*) = val;
  19562. zDate++;
  19563. cnt++;
  19564. zFormat += 4;
  19565. }while( nextC );
  19566. end_getDigits:
  19567. va_end(ap);
  19568. return cnt;
  19569. }
  19570. /*
  19571. ** Parse a timezone extension on the end of a date-time.
  19572. ** The extension is of the form:
  19573. **
  19574. ** (+/-)HH:MM
  19575. **
  19576. ** Or the "zulu" notation:
  19577. **
  19578. ** Z
  19579. **
  19580. ** If the parse is successful, write the number of minutes
  19581. ** of change in p->tz and return 0. If a parser error occurs,
  19582. ** return non-zero.
  19583. **
  19584. ** A missing specifier is not considered an error.
  19585. */
  19586. static int parseTimezone(const char *zDate, DateTime *p){
  19587. int sgn = 0;
  19588. int nHr, nMn;
  19589. int c;
  19590. while( sqlite3Isspace(*zDate) ){ zDate++; }
  19591. p->tz = 0;
  19592. c = *zDate;
  19593. if( c=='-' ){
  19594. sgn = -1;
  19595. }else if( c=='+' ){
  19596. sgn = +1;
  19597. }else if( c=='Z' || c=='z' ){
  19598. zDate++;
  19599. goto zulu_time;
  19600. }else{
  19601. return c!=0;
  19602. }
  19603. zDate++;
  19604. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  19605. return 1;
  19606. }
  19607. zDate += 5;
  19608. p->tz = sgn*(nMn + nHr*60);
  19609. zulu_time:
  19610. while( sqlite3Isspace(*zDate) ){ zDate++; }
  19611. p->tzSet = 1;
  19612. return *zDate!=0;
  19613. }
  19614. /*
  19615. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  19616. ** The HH, MM, and SS must each be exactly 2 digits. The
  19617. ** fractional seconds FFFF can be one or more digits.
  19618. **
  19619. ** Return 1 if there is a parsing error and 0 on success.
  19620. */
  19621. static int parseHhMmSs(const char *zDate, DateTime *p){
  19622. int h, m, s;
  19623. double ms = 0.0;
  19624. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  19625. return 1;
  19626. }
  19627. zDate += 5;
  19628. if( *zDate==':' ){
  19629. zDate++;
  19630. if( getDigits(zDate, "20e", &s)!=1 ){
  19631. return 1;
  19632. }
  19633. zDate += 2;
  19634. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  19635. double rScale = 1.0;
  19636. zDate++;
  19637. while( sqlite3Isdigit(*zDate) ){
  19638. ms = ms*10.0 + *zDate - '0';
  19639. rScale *= 10.0;
  19640. zDate++;
  19641. }
  19642. ms /= rScale;
  19643. }
  19644. }else{
  19645. s = 0;
  19646. }
  19647. p->validJD = 0;
  19648. p->rawS = 0;
  19649. p->validHMS = 1;
  19650. p->h = h;
  19651. p->m = m;
  19652. p->s = s + ms;
  19653. if( parseTimezone(zDate, p) ) return 1;
  19654. p->validTZ = (p->tz!=0)?1:0;
  19655. return 0;
  19656. }
  19657. /*
  19658. ** Put the DateTime object into its error state.
  19659. */
  19660. static void datetimeError(DateTime *p){
  19661. memset(p, 0, sizeof(*p));
  19662. p->isError = 1;
  19663. }
  19664. /*
  19665. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  19666. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  19667. **
  19668. ** Reference: Meeus page 61
  19669. */
  19670. static void computeJD(DateTime *p){
  19671. int Y, M, D, A, B, X1, X2;
  19672. if( p->validJD ) return;
  19673. if( p->validYMD ){
  19674. Y = p->Y;
  19675. M = p->M;
  19676. D = p->D;
  19677. }else{
  19678. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  19679. M = 1;
  19680. D = 1;
  19681. }
  19682. if( Y<-4713 || Y>9999 || p->rawS ){
  19683. datetimeError(p);
  19684. return;
  19685. }
  19686. if( M<=2 ){
  19687. Y--;
  19688. M += 12;
  19689. }
  19690. A = Y/100;
  19691. B = 2 - A + (A/4);
  19692. X1 = 36525*(Y+4716)/100;
  19693. X2 = 306001*(M+1)/10000;
  19694. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  19695. p->validJD = 1;
  19696. if( p->validHMS ){
  19697. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  19698. if( p->validTZ ){
  19699. p->iJD -= p->tz*60000;
  19700. p->validYMD = 0;
  19701. p->validHMS = 0;
  19702. p->validTZ = 0;
  19703. }
  19704. }
  19705. }
  19706. /*
  19707. ** Parse dates of the form
  19708. **
  19709. ** YYYY-MM-DD HH:MM:SS.FFF
  19710. ** YYYY-MM-DD HH:MM:SS
  19711. ** YYYY-MM-DD HH:MM
  19712. ** YYYY-MM-DD
  19713. **
  19714. ** Write the result into the DateTime structure and return 0
  19715. ** on success and 1 if the input string is not a well-formed
  19716. ** date.
  19717. */
  19718. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  19719. int Y, M, D, neg;
  19720. if( zDate[0]=='-' ){
  19721. zDate++;
  19722. neg = 1;
  19723. }else{
  19724. neg = 0;
  19725. }
  19726. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  19727. return 1;
  19728. }
  19729. zDate += 10;
  19730. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  19731. if( parseHhMmSs(zDate, p)==0 ){
  19732. /* We got the time */
  19733. }else if( *zDate==0 ){
  19734. p->validHMS = 0;
  19735. }else{
  19736. return 1;
  19737. }
  19738. p->validJD = 0;
  19739. p->validYMD = 1;
  19740. p->Y = neg ? -Y : Y;
  19741. p->M = M;
  19742. p->D = D;
  19743. if( p->validTZ ){
  19744. computeJD(p);
  19745. }
  19746. return 0;
  19747. }
  19748. /*
  19749. ** Set the time to the current time reported by the VFS.
  19750. **
  19751. ** Return the number of errors.
  19752. */
  19753. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  19754. p->iJD = sqlite3StmtCurrentTime(context);
  19755. if( p->iJD>0 ){
  19756. p->validJD = 1;
  19757. return 0;
  19758. }else{
  19759. return 1;
  19760. }
  19761. }
  19762. /*
  19763. ** Input "r" is a numeric quantity which might be a julian day number,
  19764. ** or the number of seconds since 1970. If the value if r is within
  19765. ** range of a julian day number, install it as such and set validJD.
  19766. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  19767. */
  19768. static void setRawDateNumber(DateTime *p, double r){
  19769. p->s = r;
  19770. p->rawS = 1;
  19771. if( r>=0.0 && r<5373484.5 ){
  19772. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  19773. p->validJD = 1;
  19774. }
  19775. }
  19776. /*
  19777. ** Attempt to parse the given string into a julian day number. Return
  19778. ** the number of errors.
  19779. **
  19780. ** The following are acceptable forms for the input string:
  19781. **
  19782. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  19783. ** DDDD.DD
  19784. ** now
  19785. **
  19786. ** In the first form, the +/-HH:MM is always optional. The fractional
  19787. ** seconds extension (the ".FFF") is optional. The seconds portion
  19788. ** (":SS.FFF") is option. The year and date can be omitted as long
  19789. ** as there is a time string. The time string can be omitted as long
  19790. ** as there is a year and date.
  19791. */
  19792. static int parseDateOrTime(
  19793. sqlite3_context *context,
  19794. const char *zDate,
  19795. DateTime *p
  19796. ){
  19797. double r;
  19798. if( parseYyyyMmDd(zDate,p)==0 ){
  19799. return 0;
  19800. }else if( parseHhMmSs(zDate, p)==0 ){
  19801. return 0;
  19802. }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
  19803. return setDateTimeToCurrent(context, p);
  19804. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  19805. setRawDateNumber(p, r);
  19806. return 0;
  19807. }
  19808. return 1;
  19809. }
  19810. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  19811. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  19812. ** for DateTime.iJD.
  19813. **
  19814. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  19815. ** such a large integer literal, so we have to encode it.
  19816. */
  19817. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  19818. /*
  19819. ** Return TRUE if the given julian day number is within range.
  19820. **
  19821. ** The input is the JulianDay times 86400000.
  19822. */
  19823. static int validJulianDay(sqlite3_int64 iJD){
  19824. return iJD>=0 && iJD<=INT_464269060799999;
  19825. }
  19826. /*
  19827. ** Compute the Year, Month, and Day from the julian day number.
  19828. */
  19829. static void computeYMD(DateTime *p){
  19830. int Z, A, B, C, D, E, X1;
  19831. if( p->validYMD ) return;
  19832. if( !p->validJD ){
  19833. p->Y = 2000;
  19834. p->M = 1;
  19835. p->D = 1;
  19836. }else if( !validJulianDay(p->iJD) ){
  19837. datetimeError(p);
  19838. return;
  19839. }else{
  19840. Z = (int)((p->iJD + 43200000)/86400000);
  19841. A = (int)((Z - 1867216.25)/36524.25);
  19842. A = Z + 1 + A - (A/4);
  19843. B = A + 1524;
  19844. C = (int)((B - 122.1)/365.25);
  19845. D = (36525*(C&32767))/100;
  19846. E = (int)((B-D)/30.6001);
  19847. X1 = (int)(30.6001*E);
  19848. p->D = B - D - X1;
  19849. p->M = E<14 ? E-1 : E-13;
  19850. p->Y = p->M>2 ? C - 4716 : C - 4715;
  19851. }
  19852. p->validYMD = 1;
  19853. }
  19854. /*
  19855. ** Compute the Hour, Minute, and Seconds from the julian day number.
  19856. */
  19857. static void computeHMS(DateTime *p){
  19858. int s;
  19859. if( p->validHMS ) return;
  19860. computeJD(p);
  19861. s = (int)((p->iJD + 43200000) % 86400000);
  19862. p->s = s/1000.0;
  19863. s = (int)p->s;
  19864. p->s -= s;
  19865. p->h = s/3600;
  19866. s -= p->h*3600;
  19867. p->m = s/60;
  19868. p->s += s - p->m*60;
  19869. p->rawS = 0;
  19870. p->validHMS = 1;
  19871. }
  19872. /*
  19873. ** Compute both YMD and HMS
  19874. */
  19875. static void computeYMD_HMS(DateTime *p){
  19876. computeYMD(p);
  19877. computeHMS(p);
  19878. }
  19879. /*
  19880. ** Clear the YMD and HMS and the TZ
  19881. */
  19882. static void clearYMD_HMS_TZ(DateTime *p){
  19883. p->validYMD = 0;
  19884. p->validHMS = 0;
  19885. p->validTZ = 0;
  19886. }
  19887. #ifndef SQLITE_OMIT_LOCALTIME
  19888. /*
  19889. ** On recent Windows platforms, the localtime_s() function is available
  19890. ** as part of the "Secure CRT". It is essentially equivalent to
  19891. ** localtime_r() available under most POSIX platforms, except that the
  19892. ** order of the parameters is reversed.
  19893. **
  19894. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  19895. **
  19896. ** If the user has not indicated to use localtime_r() or localtime_s()
  19897. ** already, check for an MSVC build environment that provides
  19898. ** localtime_s().
  19899. */
  19900. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  19901. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  19902. #undef HAVE_LOCALTIME_S
  19903. #define HAVE_LOCALTIME_S 1
  19904. #endif
  19905. /*
  19906. ** The following routine implements the rough equivalent of localtime_r()
  19907. ** using whatever operating-system specific localtime facility that
  19908. ** is available. This routine returns 0 on success and
  19909. ** non-zero on any kind of error.
  19910. **
  19911. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  19912. ** routine will always fail.
  19913. **
  19914. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  19915. ** library function localtime_r() is used to assist in the calculation of
  19916. ** local time.
  19917. */
  19918. static int osLocaltime(time_t *t, struct tm *pTm){
  19919. int rc;
  19920. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  19921. struct tm *pX;
  19922. #if SQLITE_THREADSAFE>0
  19923. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  19924. #endif
  19925. sqlite3_mutex_enter(mutex);
  19926. pX = localtime(t);
  19927. #ifndef SQLITE_UNTESTABLE
  19928. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  19929. #endif
  19930. if( pX ) *pTm = *pX;
  19931. sqlite3_mutex_leave(mutex);
  19932. rc = pX==0;
  19933. #else
  19934. #ifndef SQLITE_UNTESTABLE
  19935. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  19936. #endif
  19937. #if HAVE_LOCALTIME_R
  19938. rc = localtime_r(t, pTm)==0;
  19939. #else
  19940. rc = localtime_s(pTm, t);
  19941. #endif /* HAVE_LOCALTIME_R */
  19942. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  19943. return rc;
  19944. }
  19945. #endif /* SQLITE_OMIT_LOCALTIME */
  19946. #ifndef SQLITE_OMIT_LOCALTIME
  19947. /*
  19948. ** Compute the difference (in milliseconds) between localtime and UTC
  19949. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  19950. ** return this value and set *pRc to SQLITE_OK.
  19951. **
  19952. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  19953. ** is undefined in this case.
  19954. */
  19955. static sqlite3_int64 localtimeOffset(
  19956. DateTime *p, /* Date at which to calculate offset */
  19957. sqlite3_context *pCtx, /* Write error here if one occurs */
  19958. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  19959. ){
  19960. DateTime x, y;
  19961. time_t t;
  19962. struct tm sLocal;
  19963. /* Initialize the contents of sLocal to avoid a compiler warning. */
  19964. memset(&sLocal, 0, sizeof(sLocal));
  19965. x = *p;
  19966. computeYMD_HMS(&x);
  19967. if( x.Y<1971 || x.Y>=2038 ){
  19968. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  19969. ** works for years between 1970 and 2037. For dates outside this range,
  19970. ** SQLite attempts to map the year into an equivalent year within this
  19971. ** range, do the calculation, then map the year back.
  19972. */
  19973. x.Y = 2000;
  19974. x.M = 1;
  19975. x.D = 1;
  19976. x.h = 0;
  19977. x.m = 0;
  19978. x.s = 0.0;
  19979. } else {
  19980. int s = (int)(x.s + 0.5);
  19981. x.s = s;
  19982. }
  19983. x.tz = 0;
  19984. x.validJD = 0;
  19985. computeJD(&x);
  19986. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  19987. if( osLocaltime(&t, &sLocal) ){
  19988. sqlite3_result_error(pCtx, "local time unavailable", -1);
  19989. *pRc = SQLITE_ERROR;
  19990. return 0;
  19991. }
  19992. y.Y = sLocal.tm_year + 1900;
  19993. y.M = sLocal.tm_mon + 1;
  19994. y.D = sLocal.tm_mday;
  19995. y.h = sLocal.tm_hour;
  19996. y.m = sLocal.tm_min;
  19997. y.s = sLocal.tm_sec;
  19998. y.validYMD = 1;
  19999. y.validHMS = 1;
  20000. y.validJD = 0;
  20001. y.rawS = 0;
  20002. y.validTZ = 0;
  20003. y.isError = 0;
  20004. computeJD(&y);
  20005. *pRc = SQLITE_OK;
  20006. return y.iJD - x.iJD;
  20007. }
  20008. #endif /* SQLITE_OMIT_LOCALTIME */
  20009. /*
  20010. ** The following table defines various date transformations of the form
  20011. **
  20012. ** 'NNN days'
  20013. **
  20014. ** Where NNN is an arbitrary floating-point number and "days" can be one
  20015. ** of several units of time.
  20016. */
  20017. static const struct {
  20018. u8 eType; /* Transformation type code */
  20019. u8 nName; /* Length of th name */
  20020. char *zName; /* Name of the transformation */
  20021. double rLimit; /* Maximum NNN value for this transform */
  20022. double rXform; /* Constant used for this transform */
  20023. } aXformType[] = {
  20024. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  20025. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  20026. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  20027. { 0, 3, "day", 5373485.0, 86400000.0 },
  20028. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  20029. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  20030. };
  20031. /*
  20032. ** Process a modifier to a date-time stamp. The modifiers are
  20033. ** as follows:
  20034. **
  20035. ** NNN days
  20036. ** NNN hours
  20037. ** NNN minutes
  20038. ** NNN.NNNN seconds
  20039. ** NNN months
  20040. ** NNN years
  20041. ** start of month
  20042. ** start of year
  20043. ** start of week
  20044. ** start of day
  20045. ** weekday N
  20046. ** unixepoch
  20047. ** localtime
  20048. ** utc
  20049. **
  20050. ** Return 0 on success and 1 if there is any kind of error. If the error
  20051. ** is in a system call (i.e. localtime()), then an error message is written
  20052. ** to context pCtx. If the error is an unrecognized modifier, no error is
  20053. ** written to pCtx.
  20054. */
  20055. static int parseModifier(
  20056. sqlite3_context *pCtx, /* Function context */
  20057. const char *z, /* The text of the modifier */
  20058. int n, /* Length of zMod in bytes */
  20059. DateTime *p /* The date/time value to be modified */
  20060. ){
  20061. int rc = 1;
  20062. double r;
  20063. switch(sqlite3UpperToLower[(u8)z[0]] ){
  20064. #ifndef SQLITE_OMIT_LOCALTIME
  20065. case 'l': {
  20066. /* localtime
  20067. **
  20068. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  20069. ** show local time.
  20070. */
  20071. if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
  20072. computeJD(p);
  20073. p->iJD += localtimeOffset(p, pCtx, &rc);
  20074. clearYMD_HMS_TZ(p);
  20075. }
  20076. break;
  20077. }
  20078. #endif
  20079. case 'u': {
  20080. /*
  20081. ** unixepoch
  20082. **
  20083. ** Treat the current value of p->s as the number of
  20084. ** seconds since 1970. Convert to a real julian day number.
  20085. */
  20086. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  20087. r = p->s*1000.0 + 210866760000000.0;
  20088. if( r>=0.0 && r<464269060800000.0 ){
  20089. clearYMD_HMS_TZ(p);
  20090. p->iJD = (sqlite3_int64)r;
  20091. p->validJD = 1;
  20092. p->rawS = 0;
  20093. rc = 0;
  20094. }
  20095. }
  20096. #ifndef SQLITE_OMIT_LOCALTIME
  20097. else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
  20098. if( p->tzSet==0 ){
  20099. sqlite3_int64 c1;
  20100. computeJD(p);
  20101. c1 = localtimeOffset(p, pCtx, &rc);
  20102. if( rc==SQLITE_OK ){
  20103. p->iJD -= c1;
  20104. clearYMD_HMS_TZ(p);
  20105. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  20106. }
  20107. p->tzSet = 1;
  20108. }else{
  20109. rc = SQLITE_OK;
  20110. }
  20111. }
  20112. #endif
  20113. break;
  20114. }
  20115. case 'w': {
  20116. /*
  20117. ** weekday N
  20118. **
  20119. ** Move the date to the same time on the next occurrence of
  20120. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  20121. ** date is already on the appropriate weekday, this is a no-op.
  20122. */
  20123. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  20124. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  20125. && (n=(int)r)==r && n>=0 && r<7 ){
  20126. sqlite3_int64 Z;
  20127. computeYMD_HMS(p);
  20128. p->validTZ = 0;
  20129. p->validJD = 0;
  20130. computeJD(p);
  20131. Z = ((p->iJD + 129600000)/86400000) % 7;
  20132. if( Z>n ) Z -= 7;
  20133. p->iJD += (n - Z)*86400000;
  20134. clearYMD_HMS_TZ(p);
  20135. rc = 0;
  20136. }
  20137. break;
  20138. }
  20139. case 's': {
  20140. /*
  20141. ** start of TTTTT
  20142. **
  20143. ** Move the date backwards to the beginning of the current day,
  20144. ** or month or year.
  20145. */
  20146. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  20147. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  20148. z += 9;
  20149. computeYMD(p);
  20150. p->validHMS = 1;
  20151. p->h = p->m = 0;
  20152. p->s = 0.0;
  20153. p->rawS = 0;
  20154. p->validTZ = 0;
  20155. p->validJD = 0;
  20156. if( sqlite3_stricmp(z,"month")==0 ){
  20157. p->D = 1;
  20158. rc = 0;
  20159. }else if( sqlite3_stricmp(z,"year")==0 ){
  20160. p->M = 1;
  20161. p->D = 1;
  20162. rc = 0;
  20163. }else if( sqlite3_stricmp(z,"day")==0 ){
  20164. rc = 0;
  20165. }
  20166. break;
  20167. }
  20168. case '+':
  20169. case '-':
  20170. case '0':
  20171. case '1':
  20172. case '2':
  20173. case '3':
  20174. case '4':
  20175. case '5':
  20176. case '6':
  20177. case '7':
  20178. case '8':
  20179. case '9': {
  20180. double rRounder;
  20181. int i;
  20182. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  20183. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  20184. rc = 1;
  20185. break;
  20186. }
  20187. if( z[n]==':' ){
  20188. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  20189. ** specified number of hours, minutes, seconds, and fractional seconds
  20190. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  20191. ** omitted.
  20192. */
  20193. const char *z2 = z;
  20194. DateTime tx;
  20195. sqlite3_int64 day;
  20196. if( !sqlite3Isdigit(*z2) ) z2++;
  20197. memset(&tx, 0, sizeof(tx));
  20198. if( parseHhMmSs(z2, &tx) ) break;
  20199. computeJD(&tx);
  20200. tx.iJD -= 43200000;
  20201. day = tx.iJD/86400000;
  20202. tx.iJD -= day*86400000;
  20203. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  20204. computeJD(p);
  20205. clearYMD_HMS_TZ(p);
  20206. p->iJD += tx.iJD;
  20207. rc = 0;
  20208. break;
  20209. }
  20210. /* If control reaches this point, it means the transformation is
  20211. ** one of the forms like "+NNN days". */
  20212. z += n;
  20213. while( sqlite3Isspace(*z) ) z++;
  20214. n = sqlite3Strlen30(z);
  20215. if( n>10 || n<3 ) break;
  20216. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  20217. computeJD(p);
  20218. rc = 1;
  20219. rRounder = r<0 ? -0.5 : +0.5;
  20220. for(i=0; i<ArraySize(aXformType); i++){
  20221. if( aXformType[i].nName==n
  20222. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  20223. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  20224. ){
  20225. switch( aXformType[i].eType ){
  20226. case 1: { /* Special processing to add months */
  20227. int x;
  20228. computeYMD_HMS(p);
  20229. p->M += (int)r;
  20230. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  20231. p->Y += x;
  20232. p->M -= x*12;
  20233. p->validJD = 0;
  20234. r -= (int)r;
  20235. break;
  20236. }
  20237. case 2: { /* Special processing to add years */
  20238. int y = (int)r;
  20239. computeYMD_HMS(p);
  20240. p->Y += y;
  20241. p->validJD = 0;
  20242. r -= (int)r;
  20243. break;
  20244. }
  20245. }
  20246. computeJD(p);
  20247. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  20248. rc = 0;
  20249. break;
  20250. }
  20251. }
  20252. clearYMD_HMS_TZ(p);
  20253. break;
  20254. }
  20255. default: {
  20256. break;
  20257. }
  20258. }
  20259. return rc;
  20260. }
  20261. /*
  20262. ** Process time function arguments. argv[0] is a date-time stamp.
  20263. ** argv[1] and following are modifiers. Parse them all and write
  20264. ** the resulting time into the DateTime structure p. Return 0
  20265. ** on success and 1 if there are any errors.
  20266. **
  20267. ** If there are zero parameters (if even argv[0] is undefined)
  20268. ** then assume a default value of "now" for argv[0].
  20269. */
  20270. static int isDate(
  20271. sqlite3_context *context,
  20272. int argc,
  20273. sqlite3_value **argv,
  20274. DateTime *p
  20275. ){
  20276. int i, n;
  20277. const unsigned char *z;
  20278. int eType;
  20279. memset(p, 0, sizeof(*p));
  20280. if( argc==0 ){
  20281. return setDateTimeToCurrent(context, p);
  20282. }
  20283. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  20284. || eType==SQLITE_INTEGER ){
  20285. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  20286. }else{
  20287. z = sqlite3_value_text(argv[0]);
  20288. if( !z || parseDateOrTime(context, (char*)z, p) ){
  20289. return 1;
  20290. }
  20291. }
  20292. for(i=1; i<argc; i++){
  20293. z = sqlite3_value_text(argv[i]);
  20294. n = sqlite3_value_bytes(argv[i]);
  20295. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  20296. }
  20297. computeJD(p);
  20298. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  20299. return 0;
  20300. }
  20301. /*
  20302. ** The following routines implement the various date and time functions
  20303. ** of SQLite.
  20304. */
  20305. /*
  20306. ** julianday( TIMESTRING, MOD, MOD, ...)
  20307. **
  20308. ** Return the julian day number of the date specified in the arguments
  20309. */
  20310. static void juliandayFunc(
  20311. sqlite3_context *context,
  20312. int argc,
  20313. sqlite3_value **argv
  20314. ){
  20315. DateTime x;
  20316. if( isDate(context, argc, argv, &x)==0 ){
  20317. computeJD(&x);
  20318. sqlite3_result_double(context, x.iJD/86400000.0);
  20319. }
  20320. }
  20321. /*
  20322. ** datetime( TIMESTRING, MOD, MOD, ...)
  20323. **
  20324. ** Return YYYY-MM-DD HH:MM:SS
  20325. */
  20326. static void datetimeFunc(
  20327. sqlite3_context *context,
  20328. int argc,
  20329. sqlite3_value **argv
  20330. ){
  20331. DateTime x;
  20332. if( isDate(context, argc, argv, &x)==0 ){
  20333. char zBuf[100];
  20334. computeYMD_HMS(&x);
  20335. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  20336. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  20337. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20338. }
  20339. }
  20340. /*
  20341. ** time( TIMESTRING, MOD, MOD, ...)
  20342. **
  20343. ** Return HH:MM:SS
  20344. */
  20345. static void timeFunc(
  20346. sqlite3_context *context,
  20347. int argc,
  20348. sqlite3_value **argv
  20349. ){
  20350. DateTime x;
  20351. if( isDate(context, argc, argv, &x)==0 ){
  20352. char zBuf[100];
  20353. computeHMS(&x);
  20354. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  20355. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20356. }
  20357. }
  20358. /*
  20359. ** date( TIMESTRING, MOD, MOD, ...)
  20360. **
  20361. ** Return YYYY-MM-DD
  20362. */
  20363. static void dateFunc(
  20364. sqlite3_context *context,
  20365. int argc,
  20366. sqlite3_value **argv
  20367. ){
  20368. DateTime x;
  20369. if( isDate(context, argc, argv, &x)==0 ){
  20370. char zBuf[100];
  20371. computeYMD(&x);
  20372. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  20373. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20374. }
  20375. }
  20376. /*
  20377. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  20378. **
  20379. ** Return a string described by FORMAT. Conversions as follows:
  20380. **
  20381. ** %d day of month
  20382. ** %f ** fractional seconds SS.SSS
  20383. ** %H hour 00-24
  20384. ** %j day of year 000-366
  20385. ** %J ** julian day number
  20386. ** %m month 01-12
  20387. ** %M minute 00-59
  20388. ** %s seconds since 1970-01-01
  20389. ** %S seconds 00-59
  20390. ** %w day of week 0-6 sunday==0
  20391. ** %W week of year 00-53
  20392. ** %Y year 0000-9999
  20393. ** %% %
  20394. */
  20395. static void strftimeFunc(
  20396. sqlite3_context *context,
  20397. int argc,
  20398. sqlite3_value **argv
  20399. ){
  20400. DateTime x;
  20401. u64 n;
  20402. size_t i,j;
  20403. char *z;
  20404. sqlite3 *db;
  20405. const char *zFmt;
  20406. char zBuf[100];
  20407. if( argc==0 ) return;
  20408. zFmt = (const char*)sqlite3_value_text(argv[0]);
  20409. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  20410. db = sqlite3_context_db_handle(context);
  20411. for(i=0, n=1; zFmt[i]; i++, n++){
  20412. if( zFmt[i]=='%' ){
  20413. switch( zFmt[i+1] ){
  20414. case 'd':
  20415. case 'H':
  20416. case 'm':
  20417. case 'M':
  20418. case 'S':
  20419. case 'W':
  20420. n++;
  20421. /* fall thru */
  20422. case 'w':
  20423. case '%':
  20424. break;
  20425. case 'f':
  20426. n += 8;
  20427. break;
  20428. case 'j':
  20429. n += 3;
  20430. break;
  20431. case 'Y':
  20432. n += 8;
  20433. break;
  20434. case 's':
  20435. case 'J':
  20436. n += 50;
  20437. break;
  20438. default:
  20439. return; /* ERROR. return a NULL */
  20440. }
  20441. i++;
  20442. }
  20443. }
  20444. testcase( n==sizeof(zBuf)-1 );
  20445. testcase( n==sizeof(zBuf) );
  20446. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  20447. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  20448. if( n<sizeof(zBuf) ){
  20449. z = zBuf;
  20450. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  20451. sqlite3_result_error_toobig(context);
  20452. return;
  20453. }else{
  20454. z = sqlite3DbMallocRawNN(db, (int)n);
  20455. if( z==0 ){
  20456. sqlite3_result_error_nomem(context);
  20457. return;
  20458. }
  20459. }
  20460. computeJD(&x);
  20461. computeYMD_HMS(&x);
  20462. for(i=j=0; zFmt[i]; i++){
  20463. if( zFmt[i]!='%' ){
  20464. z[j++] = zFmt[i];
  20465. }else{
  20466. i++;
  20467. switch( zFmt[i] ){
  20468. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  20469. case 'f': {
  20470. double s = x.s;
  20471. if( s>59.999 ) s = 59.999;
  20472. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  20473. j += sqlite3Strlen30(&z[j]);
  20474. break;
  20475. }
  20476. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  20477. case 'W': /* Fall thru */
  20478. case 'j': {
  20479. int nDay; /* Number of days since 1st day of year */
  20480. DateTime y = x;
  20481. y.validJD = 0;
  20482. y.M = 1;
  20483. y.D = 1;
  20484. computeJD(&y);
  20485. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  20486. if( zFmt[i]=='W' ){
  20487. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  20488. wd = (int)(((x.iJD+43200000)/86400000)%7);
  20489. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  20490. j += 2;
  20491. }else{
  20492. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  20493. j += 3;
  20494. }
  20495. break;
  20496. }
  20497. case 'J': {
  20498. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  20499. j+=sqlite3Strlen30(&z[j]);
  20500. break;
  20501. }
  20502. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  20503. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  20504. case 's': {
  20505. sqlite3_snprintf(30,&z[j],"%lld",
  20506. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  20507. j += sqlite3Strlen30(&z[j]);
  20508. break;
  20509. }
  20510. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  20511. case 'w': {
  20512. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  20513. break;
  20514. }
  20515. case 'Y': {
  20516. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  20517. break;
  20518. }
  20519. default: z[j++] = '%'; break;
  20520. }
  20521. }
  20522. }
  20523. z[j] = 0;
  20524. sqlite3_result_text(context, z, -1,
  20525. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  20526. }
  20527. /*
  20528. ** current_time()
  20529. **
  20530. ** This function returns the same value as time('now').
  20531. */
  20532. static void ctimeFunc(
  20533. sqlite3_context *context,
  20534. int NotUsed,
  20535. sqlite3_value **NotUsed2
  20536. ){
  20537. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  20538. timeFunc(context, 0, 0);
  20539. }
  20540. /*
  20541. ** current_date()
  20542. **
  20543. ** This function returns the same value as date('now').
  20544. */
  20545. static void cdateFunc(
  20546. sqlite3_context *context,
  20547. int NotUsed,
  20548. sqlite3_value **NotUsed2
  20549. ){
  20550. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  20551. dateFunc(context, 0, 0);
  20552. }
  20553. /*
  20554. ** current_timestamp()
  20555. **
  20556. ** This function returns the same value as datetime('now').
  20557. */
  20558. static void ctimestampFunc(
  20559. sqlite3_context *context,
  20560. int NotUsed,
  20561. sqlite3_value **NotUsed2
  20562. ){
  20563. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  20564. datetimeFunc(context, 0, 0);
  20565. }
  20566. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  20567. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  20568. /*
  20569. ** If the library is compiled to omit the full-scale date and time
  20570. ** handling (to get a smaller binary), the following minimal version
  20571. ** of the functions current_time(), current_date() and current_timestamp()
  20572. ** are included instead. This is to support column declarations that
  20573. ** include "DEFAULT CURRENT_TIME" etc.
  20574. **
  20575. ** This function uses the C-library functions time(), gmtime()
  20576. ** and strftime(). The format string to pass to strftime() is supplied
  20577. ** as the user-data for the function.
  20578. */
  20579. static void currentTimeFunc(
  20580. sqlite3_context *context,
  20581. int argc,
  20582. sqlite3_value **argv
  20583. ){
  20584. time_t t;
  20585. char *zFormat = (char *)sqlite3_user_data(context);
  20586. sqlite3_int64 iT;
  20587. struct tm *pTm;
  20588. struct tm sNow;
  20589. char zBuf[20];
  20590. UNUSED_PARAMETER(argc);
  20591. UNUSED_PARAMETER(argv);
  20592. iT = sqlite3StmtCurrentTime(context);
  20593. if( iT<=0 ) return;
  20594. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  20595. #if HAVE_GMTIME_R
  20596. pTm = gmtime_r(&t, &sNow);
  20597. #else
  20598. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  20599. pTm = gmtime(&t);
  20600. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  20601. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  20602. #endif
  20603. if( pTm ){
  20604. strftime(zBuf, 20, zFormat, &sNow);
  20605. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20606. }
  20607. }
  20608. #endif
  20609. /*
  20610. ** This function registered all of the above C functions as SQL
  20611. ** functions. This should be the only routine in this file with
  20612. ** external linkage.
  20613. */
  20614. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  20615. static FuncDef aDateTimeFuncs[] = {
  20616. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  20617. PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
  20618. PURE_DATE(date, -1, 0, 0, dateFunc ),
  20619. PURE_DATE(time, -1, 0, 0, timeFunc ),
  20620. PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
  20621. PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
  20622. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  20623. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  20624. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  20625. #else
  20626. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  20627. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  20628. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  20629. #endif
  20630. };
  20631. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  20632. }
  20633. /************** End of date.c ************************************************/
  20634. /************** Begin file os.c **********************************************/
  20635. /*
  20636. ** 2005 November 29
  20637. **
  20638. ** The author disclaims copyright to this source code. In place of
  20639. ** a legal notice, here is a blessing:
  20640. **
  20641. ** May you do good and not evil.
  20642. ** May you find forgiveness for yourself and forgive others.
  20643. ** May you share freely, never taking more than you give.
  20644. **
  20645. ******************************************************************************
  20646. **
  20647. ** This file contains OS interface code that is common to all
  20648. ** architectures.
  20649. */
  20650. /* #include "sqliteInt.h" */
  20651. /*
  20652. ** If we compile with the SQLITE_TEST macro set, then the following block
  20653. ** of code will give us the ability to simulate a disk I/O error. This
  20654. ** is used for testing the I/O recovery logic.
  20655. */
  20656. #if defined(SQLITE_TEST)
  20657. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  20658. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  20659. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  20660. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  20661. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  20662. SQLITE_API int sqlite3_diskfull_pending = 0;
  20663. SQLITE_API int sqlite3_diskfull = 0;
  20664. #endif /* defined(SQLITE_TEST) */
  20665. /*
  20666. ** When testing, also keep a count of the number of open files.
  20667. */
  20668. #if defined(SQLITE_TEST)
  20669. SQLITE_API int sqlite3_open_file_count = 0;
  20670. #endif /* defined(SQLITE_TEST) */
  20671. /*
  20672. ** The default SQLite sqlite3_vfs implementations do not allocate
  20673. ** memory (actually, os_unix.c allocates a small amount of memory
  20674. ** from within OsOpen()), but some third-party implementations may.
  20675. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  20676. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  20677. **
  20678. ** The following functions are instrumented for malloc() failure
  20679. ** testing:
  20680. **
  20681. ** sqlite3OsRead()
  20682. ** sqlite3OsWrite()
  20683. ** sqlite3OsSync()
  20684. ** sqlite3OsFileSize()
  20685. ** sqlite3OsLock()
  20686. ** sqlite3OsCheckReservedLock()
  20687. ** sqlite3OsFileControl()
  20688. ** sqlite3OsShmMap()
  20689. ** sqlite3OsOpen()
  20690. ** sqlite3OsDelete()
  20691. ** sqlite3OsAccess()
  20692. ** sqlite3OsFullPathname()
  20693. **
  20694. */
  20695. #if defined(SQLITE_TEST)
  20696. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  20697. #define DO_OS_MALLOC_TEST(x) \
  20698. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  20699. void *pTstAlloc = sqlite3Malloc(10); \
  20700. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  20701. sqlite3_free(pTstAlloc); \
  20702. }
  20703. #else
  20704. #define DO_OS_MALLOC_TEST(x)
  20705. #endif
  20706. /*
  20707. ** The following routines are convenience wrappers around methods
  20708. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  20709. ** of this would be completely automatic if SQLite were coded using
  20710. ** C++ instead of plain old C.
  20711. */
  20712. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  20713. if( pId->pMethods ){
  20714. pId->pMethods->xClose(pId);
  20715. pId->pMethods = 0;
  20716. }
  20717. }
  20718. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  20719. DO_OS_MALLOC_TEST(id);
  20720. return id->pMethods->xRead(id, pBuf, amt, offset);
  20721. }
  20722. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  20723. DO_OS_MALLOC_TEST(id);
  20724. return id->pMethods->xWrite(id, pBuf, amt, offset);
  20725. }
  20726. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  20727. return id->pMethods->xTruncate(id, size);
  20728. }
  20729. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  20730. DO_OS_MALLOC_TEST(id);
  20731. return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
  20732. }
  20733. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  20734. DO_OS_MALLOC_TEST(id);
  20735. return id->pMethods->xFileSize(id, pSize);
  20736. }
  20737. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  20738. DO_OS_MALLOC_TEST(id);
  20739. return id->pMethods->xLock(id, lockType);
  20740. }
  20741. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  20742. return id->pMethods->xUnlock(id, lockType);
  20743. }
  20744. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  20745. DO_OS_MALLOC_TEST(id);
  20746. return id->pMethods->xCheckReservedLock(id, pResOut);
  20747. }
  20748. /*
  20749. ** Use sqlite3OsFileControl() when we are doing something that might fail
  20750. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  20751. ** when simply tossing information over the wall to the VFS and we do not
  20752. ** really care if the VFS receives and understands the information since it
  20753. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  20754. ** routine has no return value since the return value would be meaningless.
  20755. */
  20756. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  20757. if( id->pMethods==0 ) return SQLITE_NOTFOUND;
  20758. #ifdef SQLITE_TEST
  20759. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
  20760. && op!=SQLITE_FCNTL_LOCK_TIMEOUT
  20761. ){
  20762. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  20763. ** is using a regular VFS, it is called after the corresponding
  20764. ** transaction has been committed. Injecting a fault at this point
  20765. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  20766. ** but the transaction is committed anyway.
  20767. **
  20768. ** The core must call OsFileControl() though, not OsFileControlHint(),
  20769. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  20770. ** means the commit really has failed and an error should be returned
  20771. ** to the user. */
  20772. DO_OS_MALLOC_TEST(id);
  20773. }
  20774. #endif
  20775. return id->pMethods->xFileControl(id, op, pArg);
  20776. }
  20777. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  20778. if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
  20779. }
  20780. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  20781. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  20782. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  20783. }
  20784. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  20785. return id->pMethods->xDeviceCharacteristics(id);
  20786. }
  20787. #ifndef SQLITE_OMIT_WAL
  20788. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  20789. return id->pMethods->xShmLock(id, offset, n, flags);
  20790. }
  20791. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  20792. id->pMethods->xShmBarrier(id);
  20793. }
  20794. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  20795. return id->pMethods->xShmUnmap(id, deleteFlag);
  20796. }
  20797. SQLITE_PRIVATE int sqlite3OsShmMap(
  20798. sqlite3_file *id, /* Database file handle */
  20799. int iPage,
  20800. int pgsz,
  20801. int bExtend, /* True to extend file if necessary */
  20802. void volatile **pp /* OUT: Pointer to mapping */
  20803. ){
  20804. DO_OS_MALLOC_TEST(id);
  20805. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  20806. }
  20807. #endif /* SQLITE_OMIT_WAL */
  20808. #if SQLITE_MAX_MMAP_SIZE>0
  20809. /* The real implementation of xFetch and xUnfetch */
  20810. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  20811. DO_OS_MALLOC_TEST(id);
  20812. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  20813. }
  20814. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  20815. return id->pMethods->xUnfetch(id, iOff, p);
  20816. }
  20817. #else
  20818. /* No-op stubs to use when memory-mapped I/O is disabled */
  20819. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  20820. *pp = 0;
  20821. return SQLITE_OK;
  20822. }
  20823. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  20824. return SQLITE_OK;
  20825. }
  20826. #endif
  20827. /*
  20828. ** The next group of routines are convenience wrappers around the
  20829. ** VFS methods.
  20830. */
  20831. SQLITE_PRIVATE int sqlite3OsOpen(
  20832. sqlite3_vfs *pVfs,
  20833. const char *zPath,
  20834. sqlite3_file *pFile,
  20835. int flags,
  20836. int *pFlagsOut
  20837. ){
  20838. int rc;
  20839. DO_OS_MALLOC_TEST(0);
  20840. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  20841. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  20842. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  20843. ** reaching the VFS. */
  20844. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  20845. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  20846. return rc;
  20847. }
  20848. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  20849. DO_OS_MALLOC_TEST(0);
  20850. assert( dirSync==0 || dirSync==1 );
  20851. return pVfs->xDelete(pVfs, zPath, dirSync);
  20852. }
  20853. SQLITE_PRIVATE int sqlite3OsAccess(
  20854. sqlite3_vfs *pVfs,
  20855. const char *zPath,
  20856. int flags,
  20857. int *pResOut
  20858. ){
  20859. DO_OS_MALLOC_TEST(0);
  20860. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  20861. }
  20862. SQLITE_PRIVATE int sqlite3OsFullPathname(
  20863. sqlite3_vfs *pVfs,
  20864. const char *zPath,
  20865. int nPathOut,
  20866. char *zPathOut
  20867. ){
  20868. DO_OS_MALLOC_TEST(0);
  20869. zPathOut[0] = 0;
  20870. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  20871. }
  20872. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  20873. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  20874. return pVfs->xDlOpen(pVfs, zPath);
  20875. }
  20876. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  20877. pVfs->xDlError(pVfs, nByte, zBufOut);
  20878. }
  20879. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  20880. return pVfs->xDlSym(pVfs, pHdle, zSym);
  20881. }
  20882. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  20883. pVfs->xDlClose(pVfs, pHandle);
  20884. }
  20885. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  20886. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  20887. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  20888. }
  20889. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  20890. return pVfs->xSleep(pVfs, nMicro);
  20891. }
  20892. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  20893. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  20894. }
  20895. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  20896. int rc;
  20897. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  20898. ** method to get the current date and time if that method is available
  20899. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  20900. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  20901. ** unavailable.
  20902. */
  20903. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  20904. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  20905. }else{
  20906. double r;
  20907. rc = pVfs->xCurrentTime(pVfs, &r);
  20908. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  20909. }
  20910. return rc;
  20911. }
  20912. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  20913. sqlite3_vfs *pVfs,
  20914. const char *zFile,
  20915. sqlite3_file **ppFile,
  20916. int flags,
  20917. int *pOutFlags
  20918. ){
  20919. int rc;
  20920. sqlite3_file *pFile;
  20921. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  20922. if( pFile ){
  20923. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  20924. if( rc!=SQLITE_OK ){
  20925. sqlite3_free(pFile);
  20926. }else{
  20927. *ppFile = pFile;
  20928. }
  20929. }else{
  20930. rc = SQLITE_NOMEM_BKPT;
  20931. }
  20932. return rc;
  20933. }
  20934. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  20935. assert( pFile );
  20936. sqlite3OsClose(pFile);
  20937. sqlite3_free(pFile);
  20938. }
  20939. /*
  20940. ** This function is a wrapper around the OS specific implementation of
  20941. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  20942. ** ability to simulate a malloc failure, so that the handling of an
  20943. ** error in sqlite3_os_init() by the upper layers can be tested.
  20944. */
  20945. SQLITE_PRIVATE int sqlite3OsInit(void){
  20946. void *p = sqlite3_malloc(10);
  20947. if( p==0 ) return SQLITE_NOMEM_BKPT;
  20948. sqlite3_free(p);
  20949. return sqlite3_os_init();
  20950. }
  20951. /*
  20952. ** The list of all registered VFS implementations.
  20953. */
  20954. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  20955. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  20956. /*
  20957. ** Locate a VFS by name. If no name is given, simply return the
  20958. ** first VFS on the list.
  20959. */
  20960. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  20961. sqlite3_vfs *pVfs = 0;
  20962. #if SQLITE_THREADSAFE
  20963. sqlite3_mutex *mutex;
  20964. #endif
  20965. #ifndef SQLITE_OMIT_AUTOINIT
  20966. int rc = sqlite3_initialize();
  20967. if( rc ) return 0;
  20968. #endif
  20969. #if SQLITE_THREADSAFE
  20970. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20971. #endif
  20972. sqlite3_mutex_enter(mutex);
  20973. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  20974. if( zVfs==0 ) break;
  20975. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  20976. }
  20977. sqlite3_mutex_leave(mutex);
  20978. return pVfs;
  20979. }
  20980. /*
  20981. ** Unlink a VFS from the linked list
  20982. */
  20983. static void vfsUnlink(sqlite3_vfs *pVfs){
  20984. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  20985. if( pVfs==0 ){
  20986. /* No-op */
  20987. }else if( vfsList==pVfs ){
  20988. vfsList = pVfs->pNext;
  20989. }else if( vfsList ){
  20990. sqlite3_vfs *p = vfsList;
  20991. while( p->pNext && p->pNext!=pVfs ){
  20992. p = p->pNext;
  20993. }
  20994. if( p->pNext==pVfs ){
  20995. p->pNext = pVfs->pNext;
  20996. }
  20997. }
  20998. }
  20999. /*
  21000. ** Register a VFS with the system. It is harmless to register the same
  21001. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  21002. ** true.
  21003. */
  21004. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  21005. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  21006. #ifndef SQLITE_OMIT_AUTOINIT
  21007. int rc = sqlite3_initialize();
  21008. if( rc ) return rc;
  21009. #endif
  21010. #ifdef SQLITE_ENABLE_API_ARMOR
  21011. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  21012. #endif
  21013. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  21014. sqlite3_mutex_enter(mutex);
  21015. vfsUnlink(pVfs);
  21016. if( makeDflt || vfsList==0 ){
  21017. pVfs->pNext = vfsList;
  21018. vfsList = pVfs;
  21019. }else{
  21020. pVfs->pNext = vfsList->pNext;
  21021. vfsList->pNext = pVfs;
  21022. }
  21023. assert(vfsList);
  21024. sqlite3_mutex_leave(mutex);
  21025. return SQLITE_OK;
  21026. }
  21027. /*
  21028. ** Unregister a VFS so that it is no longer accessible.
  21029. */
  21030. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  21031. #if SQLITE_THREADSAFE
  21032. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  21033. #endif
  21034. sqlite3_mutex_enter(mutex);
  21035. vfsUnlink(pVfs);
  21036. sqlite3_mutex_leave(mutex);
  21037. return SQLITE_OK;
  21038. }
  21039. /************** End of os.c **************************************************/
  21040. /************** Begin file fault.c *******************************************/
  21041. /*
  21042. ** 2008 Jan 22
  21043. **
  21044. ** The author disclaims copyright to this source code. In place of
  21045. ** a legal notice, here is a blessing:
  21046. **
  21047. ** May you do good and not evil.
  21048. ** May you find forgiveness for yourself and forgive others.
  21049. ** May you share freely, never taking more than you give.
  21050. **
  21051. *************************************************************************
  21052. **
  21053. ** This file contains code to support the concept of "benign"
  21054. ** malloc failures (when the xMalloc() or xRealloc() method of the
  21055. ** sqlite3_mem_methods structure fails to allocate a block of memory
  21056. ** and returns 0).
  21057. **
  21058. ** Most malloc failures are non-benign. After they occur, SQLite
  21059. ** abandons the current operation and returns an error code (usually
  21060. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  21061. ** fatal. For example, if a malloc fails while resizing a hash table, this
  21062. ** is completely recoverable simply by not carrying out the resize. The
  21063. ** hash table will continue to function normally. So a malloc failure
  21064. ** during a hash table resize is a benign fault.
  21065. */
  21066. /* #include "sqliteInt.h" */
  21067. #ifndef SQLITE_UNTESTABLE
  21068. /*
  21069. ** Global variables.
  21070. */
  21071. typedef struct BenignMallocHooks BenignMallocHooks;
  21072. static SQLITE_WSD struct BenignMallocHooks {
  21073. void (*xBenignBegin)(void);
  21074. void (*xBenignEnd)(void);
  21075. } sqlite3Hooks = { 0, 0 };
  21076. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  21077. ** structure. If writable static data is unsupported on the target,
  21078. ** we have to locate the state vector at run-time. In the more common
  21079. ** case where writable static data is supported, wsdHooks can refer directly
  21080. ** to the "sqlite3Hooks" state vector declared above.
  21081. */
  21082. #ifdef SQLITE_OMIT_WSD
  21083. # define wsdHooksInit \
  21084. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  21085. # define wsdHooks x[0]
  21086. #else
  21087. # define wsdHooksInit
  21088. # define wsdHooks sqlite3Hooks
  21089. #endif
  21090. /*
  21091. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  21092. ** sqlite3EndBenignMalloc() are called, respectively.
  21093. */
  21094. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  21095. void (*xBenignBegin)(void),
  21096. void (*xBenignEnd)(void)
  21097. ){
  21098. wsdHooksInit;
  21099. wsdHooks.xBenignBegin = xBenignBegin;
  21100. wsdHooks.xBenignEnd = xBenignEnd;
  21101. }
  21102. /*
  21103. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  21104. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  21105. ** indicates that subsequent malloc failures are non-benign.
  21106. */
  21107. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  21108. wsdHooksInit;
  21109. if( wsdHooks.xBenignBegin ){
  21110. wsdHooks.xBenignBegin();
  21111. }
  21112. }
  21113. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  21114. wsdHooksInit;
  21115. if( wsdHooks.xBenignEnd ){
  21116. wsdHooks.xBenignEnd();
  21117. }
  21118. }
  21119. #endif /* #ifndef SQLITE_UNTESTABLE */
  21120. /************** End of fault.c ***********************************************/
  21121. /************** Begin file mem0.c ********************************************/
  21122. /*
  21123. ** 2008 October 28
  21124. **
  21125. ** The author disclaims copyright to this source code. In place of
  21126. ** a legal notice, here is a blessing:
  21127. **
  21128. ** May you do good and not evil.
  21129. ** May you find forgiveness for yourself and forgive others.
  21130. ** May you share freely, never taking more than you give.
  21131. **
  21132. *************************************************************************
  21133. **
  21134. ** This file contains a no-op memory allocation drivers for use when
  21135. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  21136. ** here always fail. SQLite will not operate with these drivers. These
  21137. ** are merely placeholders. Real drivers must be substituted using
  21138. ** sqlite3_config() before SQLite will operate.
  21139. */
  21140. /* #include "sqliteInt.h" */
  21141. /*
  21142. ** This version of the memory allocator is the default. It is
  21143. ** used when no other memory allocator is specified using compile-time
  21144. ** macros.
  21145. */
  21146. #ifdef SQLITE_ZERO_MALLOC
  21147. /*
  21148. ** No-op versions of all memory allocation routines
  21149. */
  21150. static void *sqlite3MemMalloc(int nByte){ return 0; }
  21151. static void sqlite3MemFree(void *pPrior){ return; }
  21152. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  21153. static int sqlite3MemSize(void *pPrior){ return 0; }
  21154. static int sqlite3MemRoundup(int n){ return n; }
  21155. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  21156. static void sqlite3MemShutdown(void *NotUsed){ return; }
  21157. /*
  21158. ** This routine is the only routine in this file with external linkage.
  21159. **
  21160. ** Populate the low-level memory allocation function pointers in
  21161. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21162. */
  21163. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21164. static const sqlite3_mem_methods defaultMethods = {
  21165. sqlite3MemMalloc,
  21166. sqlite3MemFree,
  21167. sqlite3MemRealloc,
  21168. sqlite3MemSize,
  21169. sqlite3MemRoundup,
  21170. sqlite3MemInit,
  21171. sqlite3MemShutdown,
  21172. 0
  21173. };
  21174. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21175. }
  21176. #endif /* SQLITE_ZERO_MALLOC */
  21177. /************** End of mem0.c ************************************************/
  21178. /************** Begin file mem1.c ********************************************/
  21179. /*
  21180. ** 2007 August 14
  21181. **
  21182. ** The author disclaims copyright to this source code. In place of
  21183. ** a legal notice, here is a blessing:
  21184. **
  21185. ** May you do good and not evil.
  21186. ** May you find forgiveness for yourself and forgive others.
  21187. ** May you share freely, never taking more than you give.
  21188. **
  21189. *************************************************************************
  21190. **
  21191. ** This file contains low-level memory allocation drivers for when
  21192. ** SQLite will use the standard C-library malloc/realloc/free interface
  21193. ** to obtain the memory it needs.
  21194. **
  21195. ** This file contains implementations of the low-level memory allocation
  21196. ** routines specified in the sqlite3_mem_methods object. The content of
  21197. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  21198. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  21199. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  21200. ** default configuration is to use memory allocation routines in this
  21201. ** file.
  21202. **
  21203. ** C-preprocessor macro summary:
  21204. **
  21205. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  21206. ** the malloc_usable_size() interface exists
  21207. ** on the target platform. Or, this symbol
  21208. ** can be set manually, if desired.
  21209. ** If an equivalent interface exists by
  21210. ** a different name, using a separate -D
  21211. ** option to rename it.
  21212. **
  21213. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  21214. ** memory allocator. Set this symbol to enable
  21215. ** building on older macs.
  21216. **
  21217. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  21218. ** _msize() on windows systems. This might
  21219. ** be necessary when compiling for Delphi,
  21220. ** for example.
  21221. */
  21222. /* #include "sqliteInt.h" */
  21223. /*
  21224. ** This version of the memory allocator is the default. It is
  21225. ** used when no other memory allocator is specified using compile-time
  21226. ** macros.
  21227. */
  21228. #ifdef SQLITE_SYSTEM_MALLOC
  21229. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  21230. /*
  21231. ** Use the zone allocator available on apple products unless the
  21232. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  21233. */
  21234. #include <sys/sysctl.h>
  21235. #include <malloc/malloc.h>
  21236. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  21237. #include <libkern/OSAtomic.h>
  21238. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  21239. static malloc_zone_t* _sqliteZone_;
  21240. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  21241. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  21242. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  21243. #define SQLITE_MALLOCSIZE(x) \
  21244. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  21245. #else /* if not __APPLE__ */
  21246. /*
  21247. ** Use standard C library malloc and free on non-Apple systems.
  21248. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  21249. */
  21250. #define SQLITE_MALLOC(x) malloc(x)
  21251. #define SQLITE_FREE(x) free(x)
  21252. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  21253. /*
  21254. ** The malloc.h header file is needed for malloc_usable_size() function
  21255. ** on some systems (e.g. Linux).
  21256. */
  21257. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  21258. # define SQLITE_USE_MALLOC_H 1
  21259. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  21260. /*
  21261. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  21262. ** use of _msize() is automatic, but can be disabled by compiling with
  21263. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  21264. ** the malloc.h header file.
  21265. */
  21266. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  21267. # define SQLITE_USE_MALLOC_H
  21268. # define SQLITE_USE_MSIZE
  21269. #endif
  21270. /*
  21271. ** Include the malloc.h header file, if necessary. Also set define macro
  21272. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  21273. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  21274. ** The memory size function can always be overridden manually by defining
  21275. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  21276. */
  21277. #if defined(SQLITE_USE_MALLOC_H)
  21278. # include <malloc.h>
  21279. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  21280. # if !defined(SQLITE_MALLOCSIZE)
  21281. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  21282. # endif
  21283. # elif defined(SQLITE_USE_MSIZE)
  21284. # if !defined(SQLITE_MALLOCSIZE)
  21285. # define SQLITE_MALLOCSIZE _msize
  21286. # endif
  21287. # endif
  21288. #endif /* defined(SQLITE_USE_MALLOC_H) */
  21289. #endif /* __APPLE__ or not __APPLE__ */
  21290. /*
  21291. ** Like malloc(), but remember the size of the allocation
  21292. ** so that we can find it later using sqlite3MemSize().
  21293. **
  21294. ** For this low-level routine, we are guaranteed that nByte>0 because
  21295. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  21296. ** routines.
  21297. */
  21298. static void *sqlite3MemMalloc(int nByte){
  21299. #ifdef SQLITE_MALLOCSIZE
  21300. void *p;
  21301. testcase( ROUND8(nByte)==nByte );
  21302. p = SQLITE_MALLOC( nByte );
  21303. if( p==0 ){
  21304. testcase( sqlite3GlobalConfig.xLog!=0 );
  21305. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21306. }
  21307. return p;
  21308. #else
  21309. sqlite3_int64 *p;
  21310. assert( nByte>0 );
  21311. testcase( ROUND8(nByte)!=nByte );
  21312. p = SQLITE_MALLOC( nByte+8 );
  21313. if( p ){
  21314. p[0] = nByte;
  21315. p++;
  21316. }else{
  21317. testcase( sqlite3GlobalConfig.xLog!=0 );
  21318. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21319. }
  21320. return (void *)p;
  21321. #endif
  21322. }
  21323. /*
  21324. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  21325. ** or sqlite3MemRealloc().
  21326. **
  21327. ** For this low-level routine, we already know that pPrior!=0 since
  21328. ** cases where pPrior==0 will have been intecepted and dealt with
  21329. ** by higher-level routines.
  21330. */
  21331. static void sqlite3MemFree(void *pPrior){
  21332. #ifdef SQLITE_MALLOCSIZE
  21333. SQLITE_FREE(pPrior);
  21334. #else
  21335. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  21336. assert( pPrior!=0 );
  21337. p--;
  21338. SQLITE_FREE(p);
  21339. #endif
  21340. }
  21341. /*
  21342. ** Report the allocated size of a prior return from xMalloc()
  21343. ** or xRealloc().
  21344. */
  21345. static int sqlite3MemSize(void *pPrior){
  21346. #ifdef SQLITE_MALLOCSIZE
  21347. assert( pPrior!=0 );
  21348. return (int)SQLITE_MALLOCSIZE(pPrior);
  21349. #else
  21350. sqlite3_int64 *p;
  21351. assert( pPrior!=0 );
  21352. p = (sqlite3_int64*)pPrior;
  21353. p--;
  21354. return (int)p[0];
  21355. #endif
  21356. }
  21357. /*
  21358. ** Like realloc(). Resize an allocation previously obtained from
  21359. ** sqlite3MemMalloc().
  21360. **
  21361. ** For this low-level interface, we know that pPrior!=0. Cases where
  21362. ** pPrior==0 while have been intercepted by higher-level routine and
  21363. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  21364. ** cases where nByte<=0 will have been intercepted by higher-level
  21365. ** routines and redirected to xFree.
  21366. */
  21367. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  21368. #ifdef SQLITE_MALLOCSIZE
  21369. void *p = SQLITE_REALLOC(pPrior, nByte);
  21370. if( p==0 ){
  21371. testcase( sqlite3GlobalConfig.xLog!=0 );
  21372. sqlite3_log(SQLITE_NOMEM,
  21373. "failed memory resize %u to %u bytes",
  21374. SQLITE_MALLOCSIZE(pPrior), nByte);
  21375. }
  21376. return p;
  21377. #else
  21378. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  21379. assert( pPrior!=0 && nByte>0 );
  21380. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  21381. p--;
  21382. p = SQLITE_REALLOC(p, nByte+8 );
  21383. if( p ){
  21384. p[0] = nByte;
  21385. p++;
  21386. }else{
  21387. testcase( sqlite3GlobalConfig.xLog!=0 );
  21388. sqlite3_log(SQLITE_NOMEM,
  21389. "failed memory resize %u to %u bytes",
  21390. sqlite3MemSize(pPrior), nByte);
  21391. }
  21392. return (void*)p;
  21393. #endif
  21394. }
  21395. /*
  21396. ** Round up a request size to the next valid allocation size.
  21397. */
  21398. static int sqlite3MemRoundup(int n){
  21399. return ROUND8(n);
  21400. }
  21401. /*
  21402. ** Initialize this module.
  21403. */
  21404. static int sqlite3MemInit(void *NotUsed){
  21405. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  21406. int cpuCount;
  21407. size_t len;
  21408. if( _sqliteZone_ ){
  21409. return SQLITE_OK;
  21410. }
  21411. len = sizeof(cpuCount);
  21412. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  21413. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  21414. if( cpuCount>1 ){
  21415. /* defer MT decisions to system malloc */
  21416. _sqliteZone_ = malloc_default_zone();
  21417. }else{
  21418. /* only 1 core, use our own zone to contention over global locks,
  21419. ** e.g. we have our own dedicated locks */
  21420. _sqliteZone_ = malloc_create_zone(4096, 0);
  21421. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  21422. }
  21423. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  21424. UNUSED_PARAMETER(NotUsed);
  21425. return SQLITE_OK;
  21426. }
  21427. /*
  21428. ** Deinitialize this module.
  21429. */
  21430. static void sqlite3MemShutdown(void *NotUsed){
  21431. UNUSED_PARAMETER(NotUsed);
  21432. return;
  21433. }
  21434. /*
  21435. ** This routine is the only routine in this file with external linkage.
  21436. **
  21437. ** Populate the low-level memory allocation function pointers in
  21438. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21439. */
  21440. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21441. static const sqlite3_mem_methods defaultMethods = {
  21442. sqlite3MemMalloc,
  21443. sqlite3MemFree,
  21444. sqlite3MemRealloc,
  21445. sqlite3MemSize,
  21446. sqlite3MemRoundup,
  21447. sqlite3MemInit,
  21448. sqlite3MemShutdown,
  21449. 0
  21450. };
  21451. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21452. }
  21453. #endif /* SQLITE_SYSTEM_MALLOC */
  21454. /************** End of mem1.c ************************************************/
  21455. /************** Begin file mem2.c ********************************************/
  21456. /*
  21457. ** 2007 August 15
  21458. **
  21459. ** The author disclaims copyright to this source code. In place of
  21460. ** a legal notice, here is a blessing:
  21461. **
  21462. ** May you do good and not evil.
  21463. ** May you find forgiveness for yourself and forgive others.
  21464. ** May you share freely, never taking more than you give.
  21465. **
  21466. *************************************************************************
  21467. **
  21468. ** This file contains low-level memory allocation drivers for when
  21469. ** SQLite will use the standard C-library malloc/realloc/free interface
  21470. ** to obtain the memory it needs while adding lots of additional debugging
  21471. ** information to each allocation in order to help detect and fix memory
  21472. ** leaks and memory usage errors.
  21473. **
  21474. ** This file contains implementations of the low-level memory allocation
  21475. ** routines specified in the sqlite3_mem_methods object.
  21476. */
  21477. /* #include "sqliteInt.h" */
  21478. /*
  21479. ** This version of the memory allocator is used only if the
  21480. ** SQLITE_MEMDEBUG macro is defined
  21481. */
  21482. #ifdef SQLITE_MEMDEBUG
  21483. /*
  21484. ** The backtrace functionality is only available with GLIBC
  21485. */
  21486. #ifdef __GLIBC__
  21487. extern int backtrace(void**,int);
  21488. extern void backtrace_symbols_fd(void*const*,int,int);
  21489. #else
  21490. # define backtrace(A,B) 1
  21491. # define backtrace_symbols_fd(A,B,C)
  21492. #endif
  21493. /* #include <stdio.h> */
  21494. /*
  21495. ** Each memory allocation looks like this:
  21496. **
  21497. ** ------------------------------------------------------------------------
  21498. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  21499. ** ------------------------------------------------------------------------
  21500. **
  21501. ** The application code sees only a pointer to the allocation. We have
  21502. ** to back up from the allocation pointer to find the MemBlockHdr. The
  21503. ** MemBlockHdr tells us the size of the allocation and the number of
  21504. ** backtrace pointers. There is also a guard word at the end of the
  21505. ** MemBlockHdr.
  21506. */
  21507. struct MemBlockHdr {
  21508. i64 iSize; /* Size of this allocation */
  21509. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  21510. char nBacktrace; /* Number of backtraces on this alloc */
  21511. char nBacktraceSlots; /* Available backtrace slots */
  21512. u8 nTitle; /* Bytes of title; includes '\0' */
  21513. u8 eType; /* Allocation type code */
  21514. int iForeGuard; /* Guard word for sanity */
  21515. };
  21516. /*
  21517. ** Guard words
  21518. */
  21519. #define FOREGUARD 0x80F5E153
  21520. #define REARGUARD 0xE4676B53
  21521. /*
  21522. ** Number of malloc size increments to track.
  21523. */
  21524. #define NCSIZE 1000
  21525. /*
  21526. ** All of the static variables used by this module are collected
  21527. ** into a single structure named "mem". This is to keep the
  21528. ** static variables organized and to reduce namespace pollution
  21529. ** when this module is combined with other in the amalgamation.
  21530. */
  21531. static struct {
  21532. /*
  21533. ** Mutex to control access to the memory allocation subsystem.
  21534. */
  21535. sqlite3_mutex *mutex;
  21536. /*
  21537. ** Head and tail of a linked list of all outstanding allocations
  21538. */
  21539. struct MemBlockHdr *pFirst;
  21540. struct MemBlockHdr *pLast;
  21541. /*
  21542. ** The number of levels of backtrace to save in new allocations.
  21543. */
  21544. int nBacktrace;
  21545. void (*xBacktrace)(int, int, void **);
  21546. /*
  21547. ** Title text to insert in front of each block
  21548. */
  21549. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  21550. char zTitle[100]; /* The title text */
  21551. /*
  21552. ** sqlite3MallocDisallow() increments the following counter.
  21553. ** sqlite3MallocAllow() decrements it.
  21554. */
  21555. int disallow; /* Do not allow memory allocation */
  21556. /*
  21557. ** Gather statistics on the sizes of memory allocations.
  21558. ** nAlloc[i] is the number of allocation attempts of i*8
  21559. ** bytes. i==NCSIZE is the number of allocation attempts for
  21560. ** sizes more than NCSIZE*8 bytes.
  21561. */
  21562. int nAlloc[NCSIZE]; /* Total number of allocations */
  21563. int nCurrent[NCSIZE]; /* Current number of allocations */
  21564. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  21565. } mem;
  21566. /*
  21567. ** Adjust memory usage statistics
  21568. */
  21569. static void adjustStats(int iSize, int increment){
  21570. int i = ROUND8(iSize)/8;
  21571. if( i>NCSIZE-1 ){
  21572. i = NCSIZE - 1;
  21573. }
  21574. if( increment>0 ){
  21575. mem.nAlloc[i]++;
  21576. mem.nCurrent[i]++;
  21577. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  21578. mem.mxCurrent[i] = mem.nCurrent[i];
  21579. }
  21580. }else{
  21581. mem.nCurrent[i]--;
  21582. assert( mem.nCurrent[i]>=0 );
  21583. }
  21584. }
  21585. /*
  21586. ** Given an allocation, find the MemBlockHdr for that allocation.
  21587. **
  21588. ** This routine checks the guards at either end of the allocation and
  21589. ** if they are incorrect it asserts.
  21590. */
  21591. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  21592. struct MemBlockHdr *p;
  21593. int *pInt;
  21594. u8 *pU8;
  21595. int nReserve;
  21596. p = (struct MemBlockHdr*)pAllocation;
  21597. p--;
  21598. assert( p->iForeGuard==(int)FOREGUARD );
  21599. nReserve = ROUND8(p->iSize);
  21600. pInt = (int*)pAllocation;
  21601. pU8 = (u8*)pAllocation;
  21602. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  21603. /* This checks any of the "extra" bytes allocated due
  21604. ** to rounding up to an 8 byte boundary to ensure
  21605. ** they haven't been overwritten.
  21606. */
  21607. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  21608. return p;
  21609. }
  21610. /*
  21611. ** Return the number of bytes currently allocated at address p.
  21612. */
  21613. static int sqlite3MemSize(void *p){
  21614. struct MemBlockHdr *pHdr;
  21615. if( !p ){
  21616. return 0;
  21617. }
  21618. pHdr = sqlite3MemsysGetHeader(p);
  21619. return (int)pHdr->iSize;
  21620. }
  21621. /*
  21622. ** Initialize the memory allocation subsystem.
  21623. */
  21624. static int sqlite3MemInit(void *NotUsed){
  21625. UNUSED_PARAMETER(NotUsed);
  21626. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  21627. if( !sqlite3GlobalConfig.bMemstat ){
  21628. /* If memory status is enabled, then the malloc.c wrapper will already
  21629. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  21630. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  21631. }
  21632. return SQLITE_OK;
  21633. }
  21634. /*
  21635. ** Deinitialize the memory allocation subsystem.
  21636. */
  21637. static void sqlite3MemShutdown(void *NotUsed){
  21638. UNUSED_PARAMETER(NotUsed);
  21639. mem.mutex = 0;
  21640. }
  21641. /*
  21642. ** Round up a request size to the next valid allocation size.
  21643. */
  21644. static int sqlite3MemRoundup(int n){
  21645. return ROUND8(n);
  21646. }
  21647. /*
  21648. ** Fill a buffer with pseudo-random bytes. This is used to preset
  21649. ** the content of a new memory allocation to unpredictable values and
  21650. ** to clear the content of a freed allocation to unpredictable values.
  21651. */
  21652. static void randomFill(char *pBuf, int nByte){
  21653. unsigned int x, y, r;
  21654. x = SQLITE_PTR_TO_INT(pBuf);
  21655. y = nByte | 1;
  21656. while( nByte >= 4 ){
  21657. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  21658. y = y*1103515245 + 12345;
  21659. r = x ^ y;
  21660. *(int*)pBuf = r;
  21661. pBuf += 4;
  21662. nByte -= 4;
  21663. }
  21664. while( nByte-- > 0 ){
  21665. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  21666. y = y*1103515245 + 12345;
  21667. r = x ^ y;
  21668. *(pBuf++) = r & 0xff;
  21669. }
  21670. }
  21671. /*
  21672. ** Allocate nByte bytes of memory.
  21673. */
  21674. static void *sqlite3MemMalloc(int nByte){
  21675. struct MemBlockHdr *pHdr;
  21676. void **pBt;
  21677. char *z;
  21678. int *pInt;
  21679. void *p = 0;
  21680. int totalSize;
  21681. int nReserve;
  21682. sqlite3_mutex_enter(mem.mutex);
  21683. assert( mem.disallow==0 );
  21684. nReserve = ROUND8(nByte);
  21685. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  21686. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  21687. p = malloc(totalSize);
  21688. if( p ){
  21689. z = p;
  21690. pBt = (void**)&z[mem.nTitle];
  21691. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  21692. pHdr->pNext = 0;
  21693. pHdr->pPrev = mem.pLast;
  21694. if( mem.pLast ){
  21695. mem.pLast->pNext = pHdr;
  21696. }else{
  21697. mem.pFirst = pHdr;
  21698. }
  21699. mem.pLast = pHdr;
  21700. pHdr->iForeGuard = FOREGUARD;
  21701. pHdr->eType = MEMTYPE_HEAP;
  21702. pHdr->nBacktraceSlots = mem.nBacktrace;
  21703. pHdr->nTitle = mem.nTitle;
  21704. if( mem.nBacktrace ){
  21705. void *aAddr[40];
  21706. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  21707. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  21708. assert(pBt[0]);
  21709. if( mem.xBacktrace ){
  21710. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  21711. }
  21712. }else{
  21713. pHdr->nBacktrace = 0;
  21714. }
  21715. if( mem.nTitle ){
  21716. memcpy(z, mem.zTitle, mem.nTitle);
  21717. }
  21718. pHdr->iSize = nByte;
  21719. adjustStats(nByte, +1);
  21720. pInt = (int*)&pHdr[1];
  21721. pInt[nReserve/sizeof(int)] = REARGUARD;
  21722. randomFill((char*)pInt, nByte);
  21723. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  21724. p = (void*)pInt;
  21725. }
  21726. sqlite3_mutex_leave(mem.mutex);
  21727. return p;
  21728. }
  21729. /*
  21730. ** Free memory.
  21731. */
  21732. static void sqlite3MemFree(void *pPrior){
  21733. struct MemBlockHdr *pHdr;
  21734. void **pBt;
  21735. char *z;
  21736. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  21737. || mem.mutex!=0 );
  21738. pHdr = sqlite3MemsysGetHeader(pPrior);
  21739. pBt = (void**)pHdr;
  21740. pBt -= pHdr->nBacktraceSlots;
  21741. sqlite3_mutex_enter(mem.mutex);
  21742. if( pHdr->pPrev ){
  21743. assert( pHdr->pPrev->pNext==pHdr );
  21744. pHdr->pPrev->pNext = pHdr->pNext;
  21745. }else{
  21746. assert( mem.pFirst==pHdr );
  21747. mem.pFirst = pHdr->pNext;
  21748. }
  21749. if( pHdr->pNext ){
  21750. assert( pHdr->pNext->pPrev==pHdr );
  21751. pHdr->pNext->pPrev = pHdr->pPrev;
  21752. }else{
  21753. assert( mem.pLast==pHdr );
  21754. mem.pLast = pHdr->pPrev;
  21755. }
  21756. z = (char*)pBt;
  21757. z -= pHdr->nTitle;
  21758. adjustStats((int)pHdr->iSize, -1);
  21759. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  21760. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  21761. free(z);
  21762. sqlite3_mutex_leave(mem.mutex);
  21763. }
  21764. /*
  21765. ** Change the size of an existing memory allocation.
  21766. **
  21767. ** For this debugging implementation, we *always* make a copy of the
  21768. ** allocation into a new place in memory. In this way, if the
  21769. ** higher level code is using pointer to the old allocation, it is
  21770. ** much more likely to break and we are much more liking to find
  21771. ** the error.
  21772. */
  21773. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  21774. struct MemBlockHdr *pOldHdr;
  21775. void *pNew;
  21776. assert( mem.disallow==0 );
  21777. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  21778. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  21779. pNew = sqlite3MemMalloc(nByte);
  21780. if( pNew ){
  21781. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  21782. if( nByte>pOldHdr->iSize ){
  21783. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  21784. }
  21785. sqlite3MemFree(pPrior);
  21786. }
  21787. return pNew;
  21788. }
  21789. /*
  21790. ** Populate the low-level memory allocation function pointers in
  21791. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21792. */
  21793. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21794. static const sqlite3_mem_methods defaultMethods = {
  21795. sqlite3MemMalloc,
  21796. sqlite3MemFree,
  21797. sqlite3MemRealloc,
  21798. sqlite3MemSize,
  21799. sqlite3MemRoundup,
  21800. sqlite3MemInit,
  21801. sqlite3MemShutdown,
  21802. 0
  21803. };
  21804. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21805. }
  21806. /*
  21807. ** Set the "type" of an allocation.
  21808. */
  21809. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  21810. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  21811. struct MemBlockHdr *pHdr;
  21812. pHdr = sqlite3MemsysGetHeader(p);
  21813. assert( pHdr->iForeGuard==FOREGUARD );
  21814. pHdr->eType = eType;
  21815. }
  21816. }
  21817. /*
  21818. ** Return TRUE if the mask of type in eType matches the type of the
  21819. ** allocation p. Also return true if p==NULL.
  21820. **
  21821. ** This routine is designed for use within an assert() statement, to
  21822. ** verify the type of an allocation. For example:
  21823. **
  21824. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21825. */
  21826. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  21827. int rc = 1;
  21828. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  21829. struct MemBlockHdr *pHdr;
  21830. pHdr = sqlite3MemsysGetHeader(p);
  21831. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  21832. if( (pHdr->eType&eType)==0 ){
  21833. rc = 0;
  21834. }
  21835. }
  21836. return rc;
  21837. }
  21838. /*
  21839. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  21840. ** allocation p. Also return true if p==NULL.
  21841. **
  21842. ** This routine is designed for use within an assert() statement, to
  21843. ** verify the type of an allocation. For example:
  21844. **
  21845. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  21846. */
  21847. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  21848. int rc = 1;
  21849. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  21850. struct MemBlockHdr *pHdr;
  21851. pHdr = sqlite3MemsysGetHeader(p);
  21852. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  21853. if( (pHdr->eType&eType)!=0 ){
  21854. rc = 0;
  21855. }
  21856. }
  21857. return rc;
  21858. }
  21859. /*
  21860. ** Set the number of backtrace levels kept for each allocation.
  21861. ** A value of zero turns off backtracing. The number is always rounded
  21862. ** up to a multiple of 2.
  21863. */
  21864. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  21865. if( depth<0 ){ depth = 0; }
  21866. if( depth>20 ){ depth = 20; }
  21867. depth = (depth+1)&0xfe;
  21868. mem.nBacktrace = depth;
  21869. }
  21870. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  21871. mem.xBacktrace = xBacktrace;
  21872. }
  21873. /*
  21874. ** Set the title string for subsequent allocations.
  21875. */
  21876. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  21877. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  21878. sqlite3_mutex_enter(mem.mutex);
  21879. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  21880. memcpy(mem.zTitle, zTitle, n);
  21881. mem.zTitle[n] = 0;
  21882. mem.nTitle = ROUND8(n);
  21883. sqlite3_mutex_leave(mem.mutex);
  21884. }
  21885. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  21886. struct MemBlockHdr *pHdr;
  21887. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  21888. void **pBt = (void**)pHdr;
  21889. pBt -= pHdr->nBacktraceSlots;
  21890. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  21891. }
  21892. }
  21893. /*
  21894. ** Open the file indicated and write a log of all unfreed memory
  21895. ** allocations into that log.
  21896. */
  21897. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  21898. FILE *out;
  21899. struct MemBlockHdr *pHdr;
  21900. void **pBt;
  21901. int i;
  21902. out = fopen(zFilename, "w");
  21903. if( out==0 ){
  21904. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21905. zFilename);
  21906. return;
  21907. }
  21908. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  21909. char *z = (char*)pHdr;
  21910. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  21911. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  21912. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  21913. if( pHdr->nBacktrace ){
  21914. fflush(out);
  21915. pBt = (void**)pHdr;
  21916. pBt -= pHdr->nBacktraceSlots;
  21917. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  21918. fprintf(out, "\n");
  21919. }
  21920. }
  21921. fprintf(out, "COUNTS:\n");
  21922. for(i=0; i<NCSIZE-1; i++){
  21923. if( mem.nAlloc[i] ){
  21924. fprintf(out, " %5d: %10d %10d %10d\n",
  21925. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  21926. }
  21927. }
  21928. if( mem.nAlloc[NCSIZE-1] ){
  21929. fprintf(out, " %5d: %10d %10d %10d\n",
  21930. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  21931. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  21932. }
  21933. fclose(out);
  21934. }
  21935. /*
  21936. ** Return the number of times sqlite3MemMalloc() has been called.
  21937. */
  21938. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  21939. int i;
  21940. int nTotal = 0;
  21941. for(i=0; i<NCSIZE; i++){
  21942. nTotal += mem.nAlloc[i];
  21943. }
  21944. return nTotal;
  21945. }
  21946. #endif /* SQLITE_MEMDEBUG */
  21947. /************** End of mem2.c ************************************************/
  21948. /************** Begin file mem3.c ********************************************/
  21949. /*
  21950. ** 2007 October 14
  21951. **
  21952. ** The author disclaims copyright to this source code. In place of
  21953. ** a legal notice, here is a blessing:
  21954. **
  21955. ** May you do good and not evil.
  21956. ** May you find forgiveness for yourself and forgive others.
  21957. ** May you share freely, never taking more than you give.
  21958. **
  21959. *************************************************************************
  21960. ** This file contains the C functions that implement a memory
  21961. ** allocation subsystem for use by SQLite.
  21962. **
  21963. ** This version of the memory allocation subsystem omits all
  21964. ** use of malloc(). The SQLite user supplies a block of memory
  21965. ** before calling sqlite3_initialize() from which allocations
  21966. ** are made and returned by the xMalloc() and xRealloc()
  21967. ** implementations. Once sqlite3_initialize() has been called,
  21968. ** the amount of memory available to SQLite is fixed and cannot
  21969. ** be changed.
  21970. **
  21971. ** This version of the memory allocation subsystem is included
  21972. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  21973. */
  21974. /* #include "sqliteInt.h" */
  21975. /*
  21976. ** This version of the memory allocator is only built into the library
  21977. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  21978. ** mean that the library will use a memory-pool by default, just that
  21979. ** it is available. The mempool allocator is activated by calling
  21980. ** sqlite3_config().
  21981. */
  21982. #ifdef SQLITE_ENABLE_MEMSYS3
  21983. /*
  21984. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  21985. */
  21986. #define MX_SMALL 10
  21987. /*
  21988. ** Number of freelist hash slots
  21989. */
  21990. #define N_HASH 61
  21991. /*
  21992. ** A memory allocation (also called a "chunk") consists of two or
  21993. ** more blocks where each block is 8 bytes. The first 8 bytes are
  21994. ** a header that is not returned to the user.
  21995. **
  21996. ** A chunk is two or more blocks that is either checked out or
  21997. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  21998. ** size of the allocation in blocks if the allocation is free.
  21999. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  22000. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  22001. ** is true if the previous chunk is checked out and false if the
  22002. ** previous chunk is free. The u.hdr.prevSize field is the size of
  22003. ** the previous chunk in blocks if the previous chunk is on the
  22004. ** freelist. If the previous chunk is checked out, then
  22005. ** u.hdr.prevSize can be part of the data for that chunk and should
  22006. ** not be read or written.
  22007. **
  22008. ** We often identify a chunk by its index in mem3.aPool[]. When
  22009. ** this is done, the chunk index refers to the second block of
  22010. ** the chunk. In this way, the first chunk has an index of 1.
  22011. ** A chunk index of 0 means "no such chunk" and is the equivalent
  22012. ** of a NULL pointer.
  22013. **
  22014. ** The second block of free chunks is of the form u.list. The
  22015. ** two fields form a double-linked list of chunks of related sizes.
  22016. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  22017. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  22018. **
  22019. ** The second block of a chunk is user data if the chunk is checked
  22020. ** out. If a chunk is checked out, the user data may extend into
  22021. ** the u.hdr.prevSize value of the following chunk.
  22022. */
  22023. typedef struct Mem3Block Mem3Block;
  22024. struct Mem3Block {
  22025. union {
  22026. struct {
  22027. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  22028. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  22029. } hdr;
  22030. struct {
  22031. u32 next; /* Index in mem3.aPool[] of next free chunk */
  22032. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  22033. } list;
  22034. } u;
  22035. };
  22036. /*
  22037. ** All of the static variables used by this module are collected
  22038. ** into a single structure named "mem3". This is to keep the
  22039. ** static variables organized and to reduce namespace pollution
  22040. ** when this module is combined with other in the amalgamation.
  22041. */
  22042. static SQLITE_WSD struct Mem3Global {
  22043. /*
  22044. ** Memory available for allocation. nPool is the size of the array
  22045. ** (in Mem3Blocks) pointed to by aPool less 2.
  22046. */
  22047. u32 nPool;
  22048. Mem3Block *aPool;
  22049. /*
  22050. ** True if we are evaluating an out-of-memory callback.
  22051. */
  22052. int alarmBusy;
  22053. /*
  22054. ** Mutex to control access to the memory allocation subsystem.
  22055. */
  22056. sqlite3_mutex *mutex;
  22057. /*
  22058. ** The minimum amount of free space that we have seen.
  22059. */
  22060. u32 mnMaster;
  22061. /*
  22062. ** iMaster is the index of the master chunk. Most new allocations
  22063. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  22064. ** of the current master. iMaster is 0 if there is not master chunk.
  22065. ** The master chunk is not in either the aiHash[] or aiSmall[].
  22066. */
  22067. u32 iMaster;
  22068. u32 szMaster;
  22069. /*
  22070. ** Array of lists of free blocks according to the block size
  22071. ** for smaller chunks, or a hash on the block size for larger
  22072. ** chunks.
  22073. */
  22074. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  22075. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  22076. } mem3 = { 97535575 };
  22077. #define mem3 GLOBAL(struct Mem3Global, mem3)
  22078. /*
  22079. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  22080. ** on. *pRoot is the list that i is a member of.
  22081. */
  22082. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  22083. u32 next = mem3.aPool[i].u.list.next;
  22084. u32 prev = mem3.aPool[i].u.list.prev;
  22085. assert( sqlite3_mutex_held(mem3.mutex) );
  22086. if( prev==0 ){
  22087. *pRoot = next;
  22088. }else{
  22089. mem3.aPool[prev].u.list.next = next;
  22090. }
  22091. if( next ){
  22092. mem3.aPool[next].u.list.prev = prev;
  22093. }
  22094. mem3.aPool[i].u.list.next = 0;
  22095. mem3.aPool[i].u.list.prev = 0;
  22096. }
  22097. /*
  22098. ** Unlink the chunk at index i from
  22099. ** whatever list is currently a member of.
  22100. */
  22101. static void memsys3Unlink(u32 i){
  22102. u32 size, hash;
  22103. assert( sqlite3_mutex_held(mem3.mutex) );
  22104. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22105. assert( i>=1 );
  22106. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22107. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22108. assert( size>=2 );
  22109. if( size <= MX_SMALL ){
  22110. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  22111. }else{
  22112. hash = size % N_HASH;
  22113. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22114. }
  22115. }
  22116. /*
  22117. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  22118. ** at *pRoot.
  22119. */
  22120. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  22121. assert( sqlite3_mutex_held(mem3.mutex) );
  22122. mem3.aPool[i].u.list.next = *pRoot;
  22123. mem3.aPool[i].u.list.prev = 0;
  22124. if( *pRoot ){
  22125. mem3.aPool[*pRoot].u.list.prev = i;
  22126. }
  22127. *pRoot = i;
  22128. }
  22129. /*
  22130. ** Link the chunk at index i into either the appropriate
  22131. ** small chunk list, or into the large chunk hash table.
  22132. */
  22133. static void memsys3Link(u32 i){
  22134. u32 size, hash;
  22135. assert( sqlite3_mutex_held(mem3.mutex) );
  22136. assert( i>=1 );
  22137. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22138. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22139. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22140. assert( size>=2 );
  22141. if( size <= MX_SMALL ){
  22142. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  22143. }else{
  22144. hash = size % N_HASH;
  22145. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  22146. }
  22147. }
  22148. /*
  22149. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  22150. ** will already be held (obtained by code in malloc.c) if
  22151. ** sqlite3GlobalConfig.bMemStat is true.
  22152. */
  22153. static void memsys3Enter(void){
  22154. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  22155. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22156. }
  22157. sqlite3_mutex_enter(mem3.mutex);
  22158. }
  22159. static void memsys3Leave(void){
  22160. sqlite3_mutex_leave(mem3.mutex);
  22161. }
  22162. /*
  22163. ** Called when we are unable to satisfy an allocation of nBytes.
  22164. */
  22165. static void memsys3OutOfMemory(int nByte){
  22166. if( !mem3.alarmBusy ){
  22167. mem3.alarmBusy = 1;
  22168. assert( sqlite3_mutex_held(mem3.mutex) );
  22169. sqlite3_mutex_leave(mem3.mutex);
  22170. sqlite3_release_memory(nByte);
  22171. sqlite3_mutex_enter(mem3.mutex);
  22172. mem3.alarmBusy = 0;
  22173. }
  22174. }
  22175. /*
  22176. ** Chunk i is a free chunk that has been unlinked. Adjust its
  22177. ** size parameters for check-out and return a pointer to the
  22178. ** user portion of the chunk.
  22179. */
  22180. static void *memsys3Checkout(u32 i, u32 nBlock){
  22181. u32 x;
  22182. assert( sqlite3_mutex_held(mem3.mutex) );
  22183. assert( i>=1 );
  22184. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  22185. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  22186. x = mem3.aPool[i-1].u.hdr.size4x;
  22187. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  22188. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  22189. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  22190. return &mem3.aPool[i];
  22191. }
  22192. /*
  22193. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  22194. ** Return a pointer to the new allocation. Or, if the master chunk
  22195. ** is not large enough, return 0.
  22196. */
  22197. static void *memsys3FromMaster(u32 nBlock){
  22198. assert( sqlite3_mutex_held(mem3.mutex) );
  22199. assert( mem3.szMaster>=nBlock );
  22200. if( nBlock>=mem3.szMaster-1 ){
  22201. /* Use the entire master */
  22202. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  22203. mem3.iMaster = 0;
  22204. mem3.szMaster = 0;
  22205. mem3.mnMaster = 0;
  22206. return p;
  22207. }else{
  22208. /* Split the master block. Return the tail. */
  22209. u32 newi, x;
  22210. newi = mem3.iMaster + mem3.szMaster - nBlock;
  22211. assert( newi > mem3.iMaster+1 );
  22212. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  22213. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  22214. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  22215. mem3.szMaster -= nBlock;
  22216. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  22217. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22218. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22219. if( mem3.szMaster < mem3.mnMaster ){
  22220. mem3.mnMaster = mem3.szMaster;
  22221. }
  22222. return (void*)&mem3.aPool[newi];
  22223. }
  22224. }
  22225. /*
  22226. ** *pRoot is the head of a list of free chunks of the same size
  22227. ** or same size hash. In other words, *pRoot is an entry in either
  22228. ** mem3.aiSmall[] or mem3.aiHash[].
  22229. **
  22230. ** This routine examines all entries on the given list and tries
  22231. ** to coalesce each entries with adjacent free chunks.
  22232. **
  22233. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  22234. ** the current mem3.iMaster with the new larger chunk. In order for
  22235. ** this mem3.iMaster replacement to work, the master chunk must be
  22236. ** linked into the hash tables. That is not the normal state of
  22237. ** affairs, of course. The calling routine must link the master
  22238. ** chunk before invoking this routine, then must unlink the (possibly
  22239. ** changed) master chunk once this routine has finished.
  22240. */
  22241. static void memsys3Merge(u32 *pRoot){
  22242. u32 iNext, prev, size, i, x;
  22243. assert( sqlite3_mutex_held(mem3.mutex) );
  22244. for(i=*pRoot; i>0; i=iNext){
  22245. iNext = mem3.aPool[i].u.list.next;
  22246. size = mem3.aPool[i-1].u.hdr.size4x;
  22247. assert( (size&1)==0 );
  22248. if( (size&2)==0 ){
  22249. memsys3UnlinkFromList(i, pRoot);
  22250. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  22251. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  22252. if( prev==iNext ){
  22253. iNext = mem3.aPool[prev].u.list.next;
  22254. }
  22255. memsys3Unlink(prev);
  22256. size = i + size/4 - prev;
  22257. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  22258. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  22259. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  22260. memsys3Link(prev);
  22261. i = prev;
  22262. }else{
  22263. size /= 4;
  22264. }
  22265. if( size>mem3.szMaster ){
  22266. mem3.iMaster = i;
  22267. mem3.szMaster = size;
  22268. }
  22269. }
  22270. }
  22271. /*
  22272. ** Return a block of memory of at least nBytes in size.
  22273. ** Return NULL if unable.
  22274. **
  22275. ** This function assumes that the necessary mutexes, if any, are
  22276. ** already held by the caller. Hence "Unsafe".
  22277. */
  22278. static void *memsys3MallocUnsafe(int nByte){
  22279. u32 i;
  22280. u32 nBlock;
  22281. u32 toFree;
  22282. assert( sqlite3_mutex_held(mem3.mutex) );
  22283. assert( sizeof(Mem3Block)==8 );
  22284. if( nByte<=12 ){
  22285. nBlock = 2;
  22286. }else{
  22287. nBlock = (nByte + 11)/8;
  22288. }
  22289. assert( nBlock>=2 );
  22290. /* STEP 1:
  22291. ** Look for an entry of the correct size in either the small
  22292. ** chunk table or in the large chunk hash table. This is
  22293. ** successful most of the time (about 9 times out of 10).
  22294. */
  22295. if( nBlock <= MX_SMALL ){
  22296. i = mem3.aiSmall[nBlock-2];
  22297. if( i>0 ){
  22298. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  22299. return memsys3Checkout(i, nBlock);
  22300. }
  22301. }else{
  22302. int hash = nBlock % N_HASH;
  22303. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  22304. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  22305. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22306. return memsys3Checkout(i, nBlock);
  22307. }
  22308. }
  22309. }
  22310. /* STEP 2:
  22311. ** Try to satisfy the allocation by carving a piece off of the end
  22312. ** of the master chunk. This step usually works if step 1 fails.
  22313. */
  22314. if( mem3.szMaster>=nBlock ){
  22315. return memsys3FromMaster(nBlock);
  22316. }
  22317. /* STEP 3:
  22318. ** Loop through the entire memory pool. Coalesce adjacent free
  22319. ** chunks. Recompute the master chunk as the largest free chunk.
  22320. ** Then try again to satisfy the allocation by carving a piece off
  22321. ** of the end of the master chunk. This step happens very
  22322. ** rarely (we hope!)
  22323. */
  22324. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  22325. memsys3OutOfMemory(toFree);
  22326. if( mem3.iMaster ){
  22327. memsys3Link(mem3.iMaster);
  22328. mem3.iMaster = 0;
  22329. mem3.szMaster = 0;
  22330. }
  22331. for(i=0; i<N_HASH; i++){
  22332. memsys3Merge(&mem3.aiHash[i]);
  22333. }
  22334. for(i=0; i<MX_SMALL-1; i++){
  22335. memsys3Merge(&mem3.aiSmall[i]);
  22336. }
  22337. if( mem3.szMaster ){
  22338. memsys3Unlink(mem3.iMaster);
  22339. if( mem3.szMaster>=nBlock ){
  22340. return memsys3FromMaster(nBlock);
  22341. }
  22342. }
  22343. }
  22344. /* If none of the above worked, then we fail. */
  22345. return 0;
  22346. }
  22347. /*
  22348. ** Free an outstanding memory allocation.
  22349. **
  22350. ** This function assumes that the necessary mutexes, if any, are
  22351. ** already held by the caller. Hence "Unsafe".
  22352. */
  22353. static void memsys3FreeUnsafe(void *pOld){
  22354. Mem3Block *p = (Mem3Block*)pOld;
  22355. int i;
  22356. u32 size, x;
  22357. assert( sqlite3_mutex_held(mem3.mutex) );
  22358. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  22359. i = p - mem3.aPool;
  22360. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  22361. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22362. assert( i+size<=mem3.nPool+1 );
  22363. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  22364. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  22365. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  22366. memsys3Link(i);
  22367. /* Try to expand the master using the newly freed chunk */
  22368. if( mem3.iMaster ){
  22369. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  22370. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  22371. mem3.iMaster -= size;
  22372. mem3.szMaster += size;
  22373. memsys3Unlink(mem3.iMaster);
  22374. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22375. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22376. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22377. }
  22378. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22379. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  22380. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  22381. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  22382. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22383. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22384. }
  22385. }
  22386. }
  22387. /*
  22388. ** Return the size of an outstanding allocation, in bytes. The
  22389. ** size returned omits the 8-byte header overhead. This only
  22390. ** works for chunks that are currently checked out.
  22391. */
  22392. static int memsys3Size(void *p){
  22393. Mem3Block *pBlock;
  22394. assert( p!=0 );
  22395. pBlock = (Mem3Block*)p;
  22396. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  22397. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  22398. }
  22399. /*
  22400. ** Round up a request size to the next valid allocation size.
  22401. */
  22402. static int memsys3Roundup(int n){
  22403. if( n<=12 ){
  22404. return 12;
  22405. }else{
  22406. return ((n+11)&~7) - 4;
  22407. }
  22408. }
  22409. /*
  22410. ** Allocate nBytes of memory.
  22411. */
  22412. static void *memsys3Malloc(int nBytes){
  22413. sqlite3_int64 *p;
  22414. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  22415. memsys3Enter();
  22416. p = memsys3MallocUnsafe(nBytes);
  22417. memsys3Leave();
  22418. return (void*)p;
  22419. }
  22420. /*
  22421. ** Free memory.
  22422. */
  22423. static void memsys3Free(void *pPrior){
  22424. assert( pPrior );
  22425. memsys3Enter();
  22426. memsys3FreeUnsafe(pPrior);
  22427. memsys3Leave();
  22428. }
  22429. /*
  22430. ** Change the size of an existing memory allocation
  22431. */
  22432. static void *memsys3Realloc(void *pPrior, int nBytes){
  22433. int nOld;
  22434. void *p;
  22435. if( pPrior==0 ){
  22436. return sqlite3_malloc(nBytes);
  22437. }
  22438. if( nBytes<=0 ){
  22439. sqlite3_free(pPrior);
  22440. return 0;
  22441. }
  22442. nOld = memsys3Size(pPrior);
  22443. if( nBytes<=nOld && nBytes>=nOld-128 ){
  22444. return pPrior;
  22445. }
  22446. memsys3Enter();
  22447. p = memsys3MallocUnsafe(nBytes);
  22448. if( p ){
  22449. if( nOld<nBytes ){
  22450. memcpy(p, pPrior, nOld);
  22451. }else{
  22452. memcpy(p, pPrior, nBytes);
  22453. }
  22454. memsys3FreeUnsafe(pPrior);
  22455. }
  22456. memsys3Leave();
  22457. return p;
  22458. }
  22459. /*
  22460. ** Initialize this module.
  22461. */
  22462. static int memsys3Init(void *NotUsed){
  22463. UNUSED_PARAMETER(NotUsed);
  22464. if( !sqlite3GlobalConfig.pHeap ){
  22465. return SQLITE_ERROR;
  22466. }
  22467. /* Store a pointer to the memory block in global structure mem3. */
  22468. assert( sizeof(Mem3Block)==8 );
  22469. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  22470. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  22471. /* Initialize the master block. */
  22472. mem3.szMaster = mem3.nPool;
  22473. mem3.mnMaster = mem3.szMaster;
  22474. mem3.iMaster = 1;
  22475. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  22476. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  22477. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  22478. return SQLITE_OK;
  22479. }
  22480. /*
  22481. ** Deinitialize this module.
  22482. */
  22483. static void memsys3Shutdown(void *NotUsed){
  22484. UNUSED_PARAMETER(NotUsed);
  22485. mem3.mutex = 0;
  22486. return;
  22487. }
  22488. /*
  22489. ** Open the file indicated and write a log of all unfreed memory
  22490. ** allocations into that log.
  22491. */
  22492. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  22493. #ifdef SQLITE_DEBUG
  22494. FILE *out;
  22495. u32 i, j;
  22496. u32 size;
  22497. if( zFilename==0 || zFilename[0]==0 ){
  22498. out = stdout;
  22499. }else{
  22500. out = fopen(zFilename, "w");
  22501. if( out==0 ){
  22502. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22503. zFilename);
  22504. return;
  22505. }
  22506. }
  22507. memsys3Enter();
  22508. fprintf(out, "CHUNKS:\n");
  22509. for(i=1; i<=mem3.nPool; i+=size/4){
  22510. size = mem3.aPool[i-1].u.hdr.size4x;
  22511. if( size/4<=1 ){
  22512. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  22513. assert( 0 );
  22514. break;
  22515. }
  22516. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  22517. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  22518. assert( 0 );
  22519. break;
  22520. }
  22521. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  22522. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  22523. assert( 0 );
  22524. break;
  22525. }
  22526. if( size&1 ){
  22527. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  22528. }else{
  22529. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  22530. i==mem3.iMaster ? " **master**" : "");
  22531. }
  22532. }
  22533. for(i=0; i<MX_SMALL-1; i++){
  22534. if( mem3.aiSmall[i]==0 ) continue;
  22535. fprintf(out, "small(%2d):", i);
  22536. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  22537. fprintf(out, " %p(%d)", &mem3.aPool[j],
  22538. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  22539. }
  22540. fprintf(out, "\n");
  22541. }
  22542. for(i=0; i<N_HASH; i++){
  22543. if( mem3.aiHash[i]==0 ) continue;
  22544. fprintf(out, "hash(%2d):", i);
  22545. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  22546. fprintf(out, " %p(%d)", &mem3.aPool[j],
  22547. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  22548. }
  22549. fprintf(out, "\n");
  22550. }
  22551. fprintf(out, "master=%d\n", mem3.iMaster);
  22552. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  22553. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  22554. sqlite3_mutex_leave(mem3.mutex);
  22555. if( out==stdout ){
  22556. fflush(stdout);
  22557. }else{
  22558. fclose(out);
  22559. }
  22560. #else
  22561. UNUSED_PARAMETER(zFilename);
  22562. #endif
  22563. }
  22564. /*
  22565. ** This routine is the only routine in this file with external
  22566. ** linkage.
  22567. **
  22568. ** Populate the low-level memory allocation function pointers in
  22569. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  22570. ** arguments specify the block of memory to manage.
  22571. **
  22572. ** This routine is only called by sqlite3_config(), and therefore
  22573. ** is not required to be threadsafe (it is not).
  22574. */
  22575. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  22576. static const sqlite3_mem_methods mempoolMethods = {
  22577. memsys3Malloc,
  22578. memsys3Free,
  22579. memsys3Realloc,
  22580. memsys3Size,
  22581. memsys3Roundup,
  22582. memsys3Init,
  22583. memsys3Shutdown,
  22584. 0
  22585. };
  22586. return &mempoolMethods;
  22587. }
  22588. #endif /* SQLITE_ENABLE_MEMSYS3 */
  22589. /************** End of mem3.c ************************************************/
  22590. /************** Begin file mem5.c ********************************************/
  22591. /*
  22592. ** 2007 October 14
  22593. **
  22594. ** The author disclaims copyright to this source code. In place of
  22595. ** a legal notice, here is a blessing:
  22596. **
  22597. ** May you do good and not evil.
  22598. ** May you find forgiveness for yourself and forgive others.
  22599. ** May you share freely, never taking more than you give.
  22600. **
  22601. *************************************************************************
  22602. ** This file contains the C functions that implement a memory
  22603. ** allocation subsystem for use by SQLite.
  22604. **
  22605. ** This version of the memory allocation subsystem omits all
  22606. ** use of malloc(). The application gives SQLite a block of memory
  22607. ** before calling sqlite3_initialize() from which allocations
  22608. ** are made and returned by the xMalloc() and xRealloc()
  22609. ** implementations. Once sqlite3_initialize() has been called,
  22610. ** the amount of memory available to SQLite is fixed and cannot
  22611. ** be changed.
  22612. **
  22613. ** This version of the memory allocation subsystem is included
  22614. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  22615. **
  22616. ** This memory allocator uses the following algorithm:
  22617. **
  22618. ** 1. All memory allocation sizes are rounded up to a power of 2.
  22619. **
  22620. ** 2. If two adjacent free blocks are the halves of a larger block,
  22621. ** then the two blocks are coalesced into the single larger block.
  22622. **
  22623. ** 3. New memory is allocated from the first available free block.
  22624. **
  22625. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  22626. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  22627. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  22628. **
  22629. ** Let n be the size of the largest allocation divided by the minimum
  22630. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  22631. ** be the maximum amount of memory ever outstanding at one time. Let
  22632. ** N be the total amount of memory available for allocation. Robson
  22633. ** proved that this memory allocator will never breakdown due to
  22634. ** fragmentation as long as the following constraint holds:
  22635. **
  22636. ** N >= M*(1 + log2(n)/2) - n + 1
  22637. **
  22638. ** The sqlite3_status() logic tracks the maximum values of n and M so
  22639. ** that an application can, at any time, verify this constraint.
  22640. */
  22641. /* #include "sqliteInt.h" */
  22642. /*
  22643. ** This version of the memory allocator is used only when
  22644. ** SQLITE_ENABLE_MEMSYS5 is defined.
  22645. */
  22646. #ifdef SQLITE_ENABLE_MEMSYS5
  22647. /*
  22648. ** A minimum allocation is an instance of the following structure.
  22649. ** Larger allocations are an array of these structures where the
  22650. ** size of the array is a power of 2.
  22651. **
  22652. ** The size of this object must be a power of two. That fact is
  22653. ** verified in memsys5Init().
  22654. */
  22655. typedef struct Mem5Link Mem5Link;
  22656. struct Mem5Link {
  22657. int next; /* Index of next free chunk */
  22658. int prev; /* Index of previous free chunk */
  22659. };
  22660. /*
  22661. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  22662. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  22663. ** it is not actually possible to reach this limit.
  22664. */
  22665. #define LOGMAX 30
  22666. /*
  22667. ** Masks used for mem5.aCtrl[] elements.
  22668. */
  22669. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  22670. #define CTRL_FREE 0x20 /* True if not checked out */
  22671. /*
  22672. ** All of the static variables used by this module are collected
  22673. ** into a single structure named "mem5". This is to keep the
  22674. ** static variables organized and to reduce namespace pollution
  22675. ** when this module is combined with other in the amalgamation.
  22676. */
  22677. static SQLITE_WSD struct Mem5Global {
  22678. /*
  22679. ** Memory available for allocation
  22680. */
  22681. int szAtom; /* Smallest possible allocation in bytes */
  22682. int nBlock; /* Number of szAtom sized blocks in zPool */
  22683. u8 *zPool; /* Memory available to be allocated */
  22684. /*
  22685. ** Mutex to control access to the memory allocation subsystem.
  22686. */
  22687. sqlite3_mutex *mutex;
  22688. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22689. /*
  22690. ** Performance statistics
  22691. */
  22692. u64 nAlloc; /* Total number of calls to malloc */
  22693. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  22694. u64 totalExcess; /* Total internal fragmentation */
  22695. u32 currentOut; /* Current checkout, including internal fragmentation */
  22696. u32 currentCount; /* Current number of distinct checkouts */
  22697. u32 maxOut; /* Maximum instantaneous currentOut */
  22698. u32 maxCount; /* Maximum instantaneous currentCount */
  22699. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  22700. #endif
  22701. /*
  22702. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  22703. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  22704. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  22705. */
  22706. int aiFreelist[LOGMAX+1];
  22707. /*
  22708. ** Space for tracking which blocks are checked out and the size
  22709. ** of each block. One byte per block.
  22710. */
  22711. u8 *aCtrl;
  22712. } mem5;
  22713. /*
  22714. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  22715. */
  22716. #define mem5 GLOBAL(struct Mem5Global, mem5)
  22717. /*
  22718. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  22719. ** structures, return a pointer to the idx-th such link.
  22720. */
  22721. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  22722. /*
  22723. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  22724. ** on. It should be found on mem5.aiFreelist[iLogsize].
  22725. */
  22726. static void memsys5Unlink(int i, int iLogsize){
  22727. int next, prev;
  22728. assert( i>=0 && i<mem5.nBlock );
  22729. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  22730. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  22731. next = MEM5LINK(i)->next;
  22732. prev = MEM5LINK(i)->prev;
  22733. if( prev<0 ){
  22734. mem5.aiFreelist[iLogsize] = next;
  22735. }else{
  22736. MEM5LINK(prev)->next = next;
  22737. }
  22738. if( next>=0 ){
  22739. MEM5LINK(next)->prev = prev;
  22740. }
  22741. }
  22742. /*
  22743. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  22744. ** free list.
  22745. */
  22746. static void memsys5Link(int i, int iLogsize){
  22747. int x;
  22748. assert( sqlite3_mutex_held(mem5.mutex) );
  22749. assert( i>=0 && i<mem5.nBlock );
  22750. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  22751. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  22752. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  22753. MEM5LINK(i)->prev = -1;
  22754. if( x>=0 ){
  22755. assert( x<mem5.nBlock );
  22756. MEM5LINK(x)->prev = i;
  22757. }
  22758. mem5.aiFreelist[iLogsize] = i;
  22759. }
  22760. /*
  22761. ** Obtain or release the mutex needed to access global data structures.
  22762. */
  22763. static void memsys5Enter(void){
  22764. sqlite3_mutex_enter(mem5.mutex);
  22765. }
  22766. static void memsys5Leave(void){
  22767. sqlite3_mutex_leave(mem5.mutex);
  22768. }
  22769. /*
  22770. ** Return the size of an outstanding allocation, in bytes.
  22771. ** This only works for chunks that are currently checked out.
  22772. */
  22773. static int memsys5Size(void *p){
  22774. int iSize, i;
  22775. assert( p!=0 );
  22776. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  22777. assert( i>=0 && i<mem5.nBlock );
  22778. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  22779. return iSize;
  22780. }
  22781. /*
  22782. ** Return a block of memory of at least nBytes in size.
  22783. ** Return NULL if unable. Return NULL if nBytes==0.
  22784. **
  22785. ** The caller guarantees that nByte is positive.
  22786. **
  22787. ** The caller has obtained a mutex prior to invoking this
  22788. ** routine so there is never any chance that two or more
  22789. ** threads can be in this routine at the same time.
  22790. */
  22791. static void *memsys5MallocUnsafe(int nByte){
  22792. int i; /* Index of a mem5.aPool[] slot */
  22793. int iBin; /* Index into mem5.aiFreelist[] */
  22794. int iFullSz; /* Size of allocation rounded up to power of 2 */
  22795. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  22796. /* nByte must be a positive */
  22797. assert( nByte>0 );
  22798. /* No more than 1GiB per allocation */
  22799. if( nByte > 0x40000000 ) return 0;
  22800. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22801. /* Keep track of the maximum allocation request. Even unfulfilled
  22802. ** requests are counted */
  22803. if( (u32)nByte>mem5.maxRequest ){
  22804. mem5.maxRequest = nByte;
  22805. }
  22806. #endif
  22807. /* Round nByte up to the next valid power of two */
  22808. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  22809. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  22810. ** block. If not, then split a block of the next larger power of
  22811. ** two in order to create a new free block of size iLogsize.
  22812. */
  22813. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  22814. if( iBin>LOGMAX ){
  22815. testcase( sqlite3GlobalConfig.xLog!=0 );
  22816. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  22817. return 0;
  22818. }
  22819. i = mem5.aiFreelist[iBin];
  22820. memsys5Unlink(i, iBin);
  22821. while( iBin>iLogsize ){
  22822. int newSize;
  22823. iBin--;
  22824. newSize = 1 << iBin;
  22825. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  22826. memsys5Link(i+newSize, iBin);
  22827. }
  22828. mem5.aCtrl[i] = iLogsize;
  22829. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22830. /* Update allocator performance statistics. */
  22831. mem5.nAlloc++;
  22832. mem5.totalAlloc += iFullSz;
  22833. mem5.totalExcess += iFullSz - nByte;
  22834. mem5.currentCount++;
  22835. mem5.currentOut += iFullSz;
  22836. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  22837. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  22838. #endif
  22839. #ifdef SQLITE_DEBUG
  22840. /* Make sure the allocated memory does not assume that it is set to zero
  22841. ** or retains a value from a previous allocation */
  22842. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  22843. #endif
  22844. /* Return a pointer to the allocated memory. */
  22845. return (void*)&mem5.zPool[i*mem5.szAtom];
  22846. }
  22847. /*
  22848. ** Free an outstanding memory allocation.
  22849. */
  22850. static void memsys5FreeUnsafe(void *pOld){
  22851. u32 size, iLogsize;
  22852. int iBlock;
  22853. /* Set iBlock to the index of the block pointed to by pOld in
  22854. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  22855. */
  22856. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  22857. /* Check that the pointer pOld points to a valid, non-free block. */
  22858. assert( iBlock>=0 && iBlock<mem5.nBlock );
  22859. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  22860. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  22861. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  22862. size = 1<<iLogsize;
  22863. assert( iBlock+size-1<(u32)mem5.nBlock );
  22864. mem5.aCtrl[iBlock] |= CTRL_FREE;
  22865. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  22866. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22867. assert( mem5.currentCount>0 );
  22868. assert( mem5.currentOut>=(size*mem5.szAtom) );
  22869. mem5.currentCount--;
  22870. mem5.currentOut -= size*mem5.szAtom;
  22871. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  22872. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  22873. #endif
  22874. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  22875. while( ALWAYS(iLogsize<LOGMAX) ){
  22876. int iBuddy;
  22877. if( (iBlock>>iLogsize) & 1 ){
  22878. iBuddy = iBlock - size;
  22879. assert( iBuddy>=0 );
  22880. }else{
  22881. iBuddy = iBlock + size;
  22882. if( iBuddy>=mem5.nBlock ) break;
  22883. }
  22884. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  22885. memsys5Unlink(iBuddy, iLogsize);
  22886. iLogsize++;
  22887. if( iBuddy<iBlock ){
  22888. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  22889. mem5.aCtrl[iBlock] = 0;
  22890. iBlock = iBuddy;
  22891. }else{
  22892. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  22893. mem5.aCtrl[iBuddy] = 0;
  22894. }
  22895. size *= 2;
  22896. }
  22897. #ifdef SQLITE_DEBUG
  22898. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  22899. ** not used after being freed */
  22900. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  22901. #endif
  22902. memsys5Link(iBlock, iLogsize);
  22903. }
  22904. /*
  22905. ** Allocate nBytes of memory.
  22906. */
  22907. static void *memsys5Malloc(int nBytes){
  22908. sqlite3_int64 *p = 0;
  22909. if( nBytes>0 ){
  22910. memsys5Enter();
  22911. p = memsys5MallocUnsafe(nBytes);
  22912. memsys5Leave();
  22913. }
  22914. return (void*)p;
  22915. }
  22916. /*
  22917. ** Free memory.
  22918. **
  22919. ** The outer layer memory allocator prevents this routine from
  22920. ** being called with pPrior==0.
  22921. */
  22922. static void memsys5Free(void *pPrior){
  22923. assert( pPrior!=0 );
  22924. memsys5Enter();
  22925. memsys5FreeUnsafe(pPrior);
  22926. memsys5Leave();
  22927. }
  22928. /*
  22929. ** Change the size of an existing memory allocation.
  22930. **
  22931. ** The outer layer memory allocator prevents this routine from
  22932. ** being called with pPrior==0.
  22933. **
  22934. ** nBytes is always a value obtained from a prior call to
  22935. ** memsys5Round(). Hence nBytes is always a non-negative power
  22936. ** of two. If nBytes==0 that means that an oversize allocation
  22937. ** (an allocation larger than 0x40000000) was requested and this
  22938. ** routine should return 0 without freeing pPrior.
  22939. */
  22940. static void *memsys5Realloc(void *pPrior, int nBytes){
  22941. int nOld;
  22942. void *p;
  22943. assert( pPrior!=0 );
  22944. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  22945. assert( nBytes>=0 );
  22946. if( nBytes==0 ){
  22947. return 0;
  22948. }
  22949. nOld = memsys5Size(pPrior);
  22950. if( nBytes<=nOld ){
  22951. return pPrior;
  22952. }
  22953. p = memsys5Malloc(nBytes);
  22954. if( p ){
  22955. memcpy(p, pPrior, nOld);
  22956. memsys5Free(pPrior);
  22957. }
  22958. return p;
  22959. }
  22960. /*
  22961. ** Round up a request size to the next valid allocation size. If
  22962. ** the allocation is too large to be handled by this allocation system,
  22963. ** return 0.
  22964. **
  22965. ** All allocations must be a power of two and must be expressed by a
  22966. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  22967. ** or 1073741824 bytes.
  22968. */
  22969. static int memsys5Roundup(int n){
  22970. int iFullSz;
  22971. if( n > 0x40000000 ) return 0;
  22972. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  22973. return iFullSz;
  22974. }
  22975. /*
  22976. ** Return the ceiling of the logarithm base 2 of iValue.
  22977. **
  22978. ** Examples: memsys5Log(1) -> 0
  22979. ** memsys5Log(2) -> 1
  22980. ** memsys5Log(4) -> 2
  22981. ** memsys5Log(5) -> 3
  22982. ** memsys5Log(8) -> 3
  22983. ** memsys5Log(9) -> 4
  22984. */
  22985. static int memsys5Log(int iValue){
  22986. int iLog;
  22987. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  22988. return iLog;
  22989. }
  22990. /*
  22991. ** Initialize the memory allocator.
  22992. **
  22993. ** This routine is not threadsafe. The caller must be holding a mutex
  22994. ** to prevent multiple threads from entering at the same time.
  22995. */
  22996. static int memsys5Init(void *NotUsed){
  22997. int ii; /* Loop counter */
  22998. int nByte; /* Number of bytes of memory available to this allocator */
  22999. u8 *zByte; /* Memory usable by this allocator */
  23000. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  23001. int iOffset; /* An offset into mem5.aCtrl[] */
  23002. UNUSED_PARAMETER(NotUsed);
  23003. /* For the purposes of this routine, disable the mutex */
  23004. mem5.mutex = 0;
  23005. /* The size of a Mem5Link object must be a power of two. Verify that
  23006. ** this is case.
  23007. */
  23008. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  23009. nByte = sqlite3GlobalConfig.nHeap;
  23010. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  23011. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  23012. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  23013. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  23014. mem5.szAtom = (1<<nMinLog);
  23015. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  23016. mem5.szAtom = mem5.szAtom << 1;
  23017. }
  23018. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  23019. mem5.zPool = zByte;
  23020. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  23021. for(ii=0; ii<=LOGMAX; ii++){
  23022. mem5.aiFreelist[ii] = -1;
  23023. }
  23024. iOffset = 0;
  23025. for(ii=LOGMAX; ii>=0; ii--){
  23026. int nAlloc = (1<<ii);
  23027. if( (iOffset+nAlloc)<=mem5.nBlock ){
  23028. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  23029. memsys5Link(iOffset, ii);
  23030. iOffset += nAlloc;
  23031. }
  23032. assert((iOffset+nAlloc)>mem5.nBlock);
  23033. }
  23034. /* If a mutex is required for normal operation, allocate one */
  23035. if( sqlite3GlobalConfig.bMemstat==0 ){
  23036. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23037. }
  23038. return SQLITE_OK;
  23039. }
  23040. /*
  23041. ** Deinitialize this module.
  23042. */
  23043. static void memsys5Shutdown(void *NotUsed){
  23044. UNUSED_PARAMETER(NotUsed);
  23045. mem5.mutex = 0;
  23046. return;
  23047. }
  23048. #ifdef SQLITE_TEST
  23049. /*
  23050. ** Open the file indicated and write a log of all unfreed memory
  23051. ** allocations into that log.
  23052. */
  23053. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  23054. FILE *out;
  23055. int i, j, n;
  23056. int nMinLog;
  23057. if( zFilename==0 || zFilename[0]==0 ){
  23058. out = stdout;
  23059. }else{
  23060. out = fopen(zFilename, "w");
  23061. if( out==0 ){
  23062. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23063. zFilename);
  23064. return;
  23065. }
  23066. }
  23067. memsys5Enter();
  23068. nMinLog = memsys5Log(mem5.szAtom);
  23069. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  23070. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  23071. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  23072. }
  23073. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  23074. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  23075. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  23076. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  23077. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  23078. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  23079. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  23080. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  23081. memsys5Leave();
  23082. if( out==stdout ){
  23083. fflush(stdout);
  23084. }else{
  23085. fclose(out);
  23086. }
  23087. }
  23088. #endif
  23089. /*
  23090. ** This routine is the only routine in this file with external
  23091. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  23092. ** struct populated with the memsys5 methods.
  23093. */
  23094. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  23095. static const sqlite3_mem_methods memsys5Methods = {
  23096. memsys5Malloc,
  23097. memsys5Free,
  23098. memsys5Realloc,
  23099. memsys5Size,
  23100. memsys5Roundup,
  23101. memsys5Init,
  23102. memsys5Shutdown,
  23103. 0
  23104. };
  23105. return &memsys5Methods;
  23106. }
  23107. #endif /* SQLITE_ENABLE_MEMSYS5 */
  23108. /************** End of mem5.c ************************************************/
  23109. /************** Begin file mutex.c *******************************************/
  23110. /*
  23111. ** 2007 August 14
  23112. **
  23113. ** The author disclaims copyright to this source code. In place of
  23114. ** a legal notice, here is a blessing:
  23115. **
  23116. ** May you do good and not evil.
  23117. ** May you find forgiveness for yourself and forgive others.
  23118. ** May you share freely, never taking more than you give.
  23119. **
  23120. *************************************************************************
  23121. ** This file contains the C functions that implement mutexes.
  23122. **
  23123. ** This file contains code that is common across all mutex implementations.
  23124. */
  23125. /* #include "sqliteInt.h" */
  23126. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  23127. /*
  23128. ** For debugging purposes, record when the mutex subsystem is initialized
  23129. ** and uninitialized so that we can assert() if there is an attempt to
  23130. ** allocate a mutex while the system is uninitialized.
  23131. */
  23132. static SQLITE_WSD int mutexIsInit = 0;
  23133. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  23134. #ifndef SQLITE_MUTEX_OMIT
  23135. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23136. /*
  23137. ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
  23138. ** the implementation of a wrapper around the system default mutex
  23139. ** implementation (sqlite3DefaultMutex()).
  23140. **
  23141. ** Most calls are passed directly through to the underlying default
  23142. ** mutex implementation. Except, if a mutex is configured by calling
  23143. ** sqlite3MutexWarnOnContention() on it, then if contention is ever
  23144. ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
  23145. **
  23146. ** This type of mutex is used as the database handle mutex when testing
  23147. ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
  23148. */
  23149. /*
  23150. ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
  23151. ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
  23152. ** allocated by the system mutex implementation. Variable iType is usually set
  23153. ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
  23154. ** or one of the static mutex identifiers. Or, if this is a recursive mutex
  23155. ** that has been configured using sqlite3MutexWarnOnContention(), it is
  23156. ** set to SQLITE_MUTEX_WARNONCONTENTION.
  23157. */
  23158. typedef struct CheckMutex CheckMutex;
  23159. struct CheckMutex {
  23160. int iType;
  23161. sqlite3_mutex *mutex;
  23162. };
  23163. #define SQLITE_MUTEX_WARNONCONTENTION (-1)
  23164. /*
  23165. ** Pointer to real mutex methods object used by the CheckMutex
  23166. ** implementation. Set by checkMutexInit().
  23167. */
  23168. static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
  23169. #ifdef SQLITE_DEBUG
  23170. static int checkMutexHeld(sqlite3_mutex *p){
  23171. return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
  23172. }
  23173. static int checkMutexNotheld(sqlite3_mutex *p){
  23174. return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
  23175. }
  23176. #endif
  23177. /*
  23178. ** Initialize and deinitialize the mutex subsystem.
  23179. */
  23180. static int checkMutexInit(void){
  23181. pGlobalMutexMethods = sqlite3DefaultMutex();
  23182. return SQLITE_OK;
  23183. }
  23184. static int checkMutexEnd(void){
  23185. pGlobalMutexMethods = 0;
  23186. return SQLITE_OK;
  23187. }
  23188. /*
  23189. ** Allocate a mutex.
  23190. */
  23191. static sqlite3_mutex *checkMutexAlloc(int iType){
  23192. static CheckMutex staticMutexes[] = {
  23193. {2, 0}, {3, 0}, {4, 0}, {5, 0},
  23194. {6, 0}, {7, 0}, {8, 0}, {9, 0},
  23195. {10, 0}, {11, 0}, {12, 0}, {13, 0}
  23196. };
  23197. CheckMutex *p = 0;
  23198. assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
  23199. if( iType<2 ){
  23200. p = sqlite3MallocZero(sizeof(CheckMutex));
  23201. if( p==0 ) return 0;
  23202. p->iType = iType;
  23203. }else{
  23204. #ifdef SQLITE_ENABLE_API_ARMOR
  23205. if( iType-2>=ArraySize(staticMutexes) ){
  23206. (void)SQLITE_MISUSE_BKPT;
  23207. return 0;
  23208. }
  23209. #endif
  23210. p = &staticMutexes[iType-2];
  23211. }
  23212. if( p->mutex==0 ){
  23213. p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
  23214. if( p->mutex==0 ){
  23215. if( iType<2 ){
  23216. sqlite3_free(p);
  23217. }
  23218. p = 0;
  23219. }
  23220. }
  23221. return (sqlite3_mutex*)p;
  23222. }
  23223. /*
  23224. ** Free a mutex.
  23225. */
  23226. static void checkMutexFree(sqlite3_mutex *p){
  23227. assert( SQLITE_MUTEX_RECURSIVE<2 );
  23228. assert( SQLITE_MUTEX_FAST<2 );
  23229. assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
  23230. #if SQLITE_ENABLE_API_ARMOR
  23231. if( ((CheckMutex*)p)->iType<2 )
  23232. #endif
  23233. {
  23234. CheckMutex *pCheck = (CheckMutex*)p;
  23235. pGlobalMutexMethods->xMutexFree(pCheck->mutex);
  23236. sqlite3_free(pCheck);
  23237. }
  23238. #ifdef SQLITE_ENABLE_API_ARMOR
  23239. else{
  23240. (void)SQLITE_MISUSE_BKPT;
  23241. }
  23242. #endif
  23243. }
  23244. /*
  23245. ** Enter the mutex.
  23246. */
  23247. static void checkMutexEnter(sqlite3_mutex *p){
  23248. CheckMutex *pCheck = (CheckMutex*)p;
  23249. if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
  23250. if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
  23251. return;
  23252. }
  23253. sqlite3_log(SQLITE_MISUSE,
  23254. "illegal multi-threaded access to database connection"
  23255. );
  23256. }
  23257. pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
  23258. }
  23259. /*
  23260. ** Enter the mutex (do not block).
  23261. */
  23262. static int checkMutexTry(sqlite3_mutex *p){
  23263. CheckMutex *pCheck = (CheckMutex*)p;
  23264. return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
  23265. }
  23266. /*
  23267. ** Leave the mutex.
  23268. */
  23269. static void checkMutexLeave(sqlite3_mutex *p){
  23270. CheckMutex *pCheck = (CheckMutex*)p;
  23271. pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
  23272. }
  23273. sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
  23274. static const sqlite3_mutex_methods sMutex = {
  23275. checkMutexInit,
  23276. checkMutexEnd,
  23277. checkMutexAlloc,
  23278. checkMutexFree,
  23279. checkMutexEnter,
  23280. checkMutexTry,
  23281. checkMutexLeave,
  23282. #ifdef SQLITE_DEBUG
  23283. checkMutexHeld,
  23284. checkMutexNotheld
  23285. #else
  23286. 0,
  23287. 0
  23288. #endif
  23289. };
  23290. return &sMutex;
  23291. }
  23292. /*
  23293. ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
  23294. ** one on which there should be no contention.
  23295. */
  23296. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
  23297. if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
  23298. CheckMutex *pCheck = (CheckMutex*)p;
  23299. assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
  23300. pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
  23301. }
  23302. }
  23303. #endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
  23304. /*
  23305. ** Initialize the mutex system.
  23306. */
  23307. SQLITE_PRIVATE int sqlite3MutexInit(void){
  23308. int rc = SQLITE_OK;
  23309. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  23310. /* If the xMutexAlloc method has not been set, then the user did not
  23311. ** install a mutex implementation via sqlite3_config() prior to
  23312. ** sqlite3_initialize() being called. This block copies pointers to
  23313. ** the default implementation into the sqlite3GlobalConfig structure.
  23314. */
  23315. sqlite3_mutex_methods const *pFrom;
  23316. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  23317. if( sqlite3GlobalConfig.bCoreMutex ){
  23318. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23319. pFrom = multiThreadedCheckMutex();
  23320. #else
  23321. pFrom = sqlite3DefaultMutex();
  23322. #endif
  23323. }else{
  23324. pFrom = sqlite3NoopMutex();
  23325. }
  23326. pTo->xMutexInit = pFrom->xMutexInit;
  23327. pTo->xMutexEnd = pFrom->xMutexEnd;
  23328. pTo->xMutexFree = pFrom->xMutexFree;
  23329. pTo->xMutexEnter = pFrom->xMutexEnter;
  23330. pTo->xMutexTry = pFrom->xMutexTry;
  23331. pTo->xMutexLeave = pFrom->xMutexLeave;
  23332. pTo->xMutexHeld = pFrom->xMutexHeld;
  23333. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  23334. sqlite3MemoryBarrier();
  23335. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  23336. }
  23337. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  23338. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  23339. #ifdef SQLITE_DEBUG
  23340. GLOBAL(int, mutexIsInit) = 1;
  23341. #endif
  23342. return rc;
  23343. }
  23344. /*
  23345. ** Shutdown the mutex system. This call frees resources allocated by
  23346. ** sqlite3MutexInit().
  23347. */
  23348. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  23349. int rc = SQLITE_OK;
  23350. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  23351. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  23352. }
  23353. #ifdef SQLITE_DEBUG
  23354. GLOBAL(int, mutexIsInit) = 0;
  23355. #endif
  23356. return rc;
  23357. }
  23358. /*
  23359. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  23360. */
  23361. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  23362. #ifndef SQLITE_OMIT_AUTOINIT
  23363. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  23364. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  23365. #endif
  23366. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23367. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23368. }
  23369. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  23370. if( !sqlite3GlobalConfig.bCoreMutex ){
  23371. return 0;
  23372. }
  23373. assert( GLOBAL(int, mutexIsInit) );
  23374. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23375. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23376. }
  23377. /*
  23378. ** Free a dynamic mutex.
  23379. */
  23380. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  23381. if( p ){
  23382. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  23383. sqlite3GlobalConfig.mutex.xMutexFree(p);
  23384. }
  23385. }
  23386. /*
  23387. ** Obtain the mutex p. If some other thread already has the mutex, block
  23388. ** until it can be obtained.
  23389. */
  23390. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  23391. if( p ){
  23392. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  23393. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  23394. }
  23395. }
  23396. /*
  23397. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  23398. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  23399. */
  23400. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  23401. int rc = SQLITE_OK;
  23402. if( p ){
  23403. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  23404. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  23405. }
  23406. return rc;
  23407. }
  23408. /*
  23409. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  23410. ** entered by the same thread. The behavior is undefined if the mutex
  23411. ** is not currently entered. If a NULL pointer is passed as an argument
  23412. ** this function is a no-op.
  23413. */
  23414. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  23415. if( p ){
  23416. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  23417. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  23418. }
  23419. }
  23420. #ifndef NDEBUG
  23421. /*
  23422. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23423. ** intended for use inside assert() statements.
  23424. */
  23425. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  23426. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  23427. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  23428. }
  23429. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  23430. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  23431. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  23432. }
  23433. #endif
  23434. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  23435. /************** End of mutex.c ***********************************************/
  23436. /************** Begin file mutex_noop.c **************************************/
  23437. /*
  23438. ** 2008 October 07
  23439. **
  23440. ** The author disclaims copyright to this source code. In place of
  23441. ** a legal notice, here is a blessing:
  23442. **
  23443. ** May you do good and not evil.
  23444. ** May you find forgiveness for yourself and forgive others.
  23445. ** May you share freely, never taking more than you give.
  23446. **
  23447. *************************************************************************
  23448. ** This file contains the C functions that implement mutexes.
  23449. **
  23450. ** This implementation in this file does not provide any mutual
  23451. ** exclusion and is thus suitable for use only in applications
  23452. ** that use SQLite in a single thread. The routines defined
  23453. ** here are place-holders. Applications can substitute working
  23454. ** mutex routines at start-time using the
  23455. **
  23456. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  23457. **
  23458. ** interface.
  23459. **
  23460. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  23461. ** that does error checking on mutexes to make sure they are being
  23462. ** called correctly.
  23463. */
  23464. /* #include "sqliteInt.h" */
  23465. #ifndef SQLITE_MUTEX_OMIT
  23466. #ifndef SQLITE_DEBUG
  23467. /*
  23468. ** Stub routines for all mutex methods.
  23469. **
  23470. ** This routines provide no mutual exclusion or error checking.
  23471. */
  23472. static int noopMutexInit(void){ return SQLITE_OK; }
  23473. static int noopMutexEnd(void){ return SQLITE_OK; }
  23474. static sqlite3_mutex *noopMutexAlloc(int id){
  23475. UNUSED_PARAMETER(id);
  23476. return (sqlite3_mutex*)8;
  23477. }
  23478. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23479. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23480. static int noopMutexTry(sqlite3_mutex *p){
  23481. UNUSED_PARAMETER(p);
  23482. return SQLITE_OK;
  23483. }
  23484. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23485. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  23486. static const sqlite3_mutex_methods sMutex = {
  23487. noopMutexInit,
  23488. noopMutexEnd,
  23489. noopMutexAlloc,
  23490. noopMutexFree,
  23491. noopMutexEnter,
  23492. noopMutexTry,
  23493. noopMutexLeave,
  23494. 0,
  23495. 0,
  23496. };
  23497. return &sMutex;
  23498. }
  23499. #endif /* !SQLITE_DEBUG */
  23500. #ifdef SQLITE_DEBUG
  23501. /*
  23502. ** In this implementation, error checking is provided for testing
  23503. ** and debugging purposes. The mutexes still do not provide any
  23504. ** mutual exclusion.
  23505. */
  23506. /*
  23507. ** The mutex object
  23508. */
  23509. typedef struct sqlite3_debug_mutex {
  23510. int id; /* The mutex type */
  23511. int cnt; /* Number of entries without a matching leave */
  23512. } sqlite3_debug_mutex;
  23513. /*
  23514. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23515. ** intended for use inside assert() statements.
  23516. */
  23517. static int debugMutexHeld(sqlite3_mutex *pX){
  23518. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23519. return p==0 || p->cnt>0;
  23520. }
  23521. static int debugMutexNotheld(sqlite3_mutex *pX){
  23522. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23523. return p==0 || p->cnt==0;
  23524. }
  23525. /*
  23526. ** Initialize and deinitialize the mutex subsystem.
  23527. */
  23528. static int debugMutexInit(void){ return SQLITE_OK; }
  23529. static int debugMutexEnd(void){ return SQLITE_OK; }
  23530. /*
  23531. ** The sqlite3_mutex_alloc() routine allocates a new
  23532. ** mutex and returns a pointer to it. If it returns NULL
  23533. ** that means that a mutex could not be allocated.
  23534. */
  23535. static sqlite3_mutex *debugMutexAlloc(int id){
  23536. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  23537. sqlite3_debug_mutex *pNew = 0;
  23538. switch( id ){
  23539. case SQLITE_MUTEX_FAST:
  23540. case SQLITE_MUTEX_RECURSIVE: {
  23541. pNew = sqlite3Malloc(sizeof(*pNew));
  23542. if( pNew ){
  23543. pNew->id = id;
  23544. pNew->cnt = 0;
  23545. }
  23546. break;
  23547. }
  23548. default: {
  23549. #ifdef SQLITE_ENABLE_API_ARMOR
  23550. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  23551. (void)SQLITE_MISUSE_BKPT;
  23552. return 0;
  23553. }
  23554. #endif
  23555. pNew = &aStatic[id-2];
  23556. pNew->id = id;
  23557. break;
  23558. }
  23559. }
  23560. return (sqlite3_mutex*)pNew;
  23561. }
  23562. /*
  23563. ** This routine deallocates a previously allocated mutex.
  23564. */
  23565. static void debugMutexFree(sqlite3_mutex *pX){
  23566. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23567. assert( p->cnt==0 );
  23568. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  23569. sqlite3_free(p);
  23570. }else{
  23571. #ifdef SQLITE_ENABLE_API_ARMOR
  23572. (void)SQLITE_MISUSE_BKPT;
  23573. #endif
  23574. }
  23575. }
  23576. /*
  23577. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  23578. ** to enter a mutex. If another thread is already within the mutex,
  23579. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  23580. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  23581. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  23582. ** be entered multiple times by the same thread. In such cases the,
  23583. ** mutex must be exited an equal number of times before another thread
  23584. ** can enter. If the same thread tries to enter any other kind of mutex
  23585. ** more than once, the behavior is undefined.
  23586. */
  23587. static void debugMutexEnter(sqlite3_mutex *pX){
  23588. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23589. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  23590. p->cnt++;
  23591. }
  23592. static int debugMutexTry(sqlite3_mutex *pX){
  23593. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23594. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  23595. p->cnt++;
  23596. return SQLITE_OK;
  23597. }
  23598. /*
  23599. ** The sqlite3_mutex_leave() routine exits a mutex that was
  23600. ** previously entered by the same thread. The behavior
  23601. ** is undefined if the mutex is not currently entered or
  23602. ** is not currently allocated. SQLite will never do either.
  23603. */
  23604. static void debugMutexLeave(sqlite3_mutex *pX){
  23605. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23606. assert( debugMutexHeld(pX) );
  23607. p->cnt--;
  23608. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  23609. }
  23610. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  23611. static const sqlite3_mutex_methods sMutex = {
  23612. debugMutexInit,
  23613. debugMutexEnd,
  23614. debugMutexAlloc,
  23615. debugMutexFree,
  23616. debugMutexEnter,
  23617. debugMutexTry,
  23618. debugMutexLeave,
  23619. debugMutexHeld,
  23620. debugMutexNotheld
  23621. };
  23622. return &sMutex;
  23623. }
  23624. #endif /* SQLITE_DEBUG */
  23625. /*
  23626. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  23627. ** is used regardless of the run-time threadsafety setting.
  23628. */
  23629. #ifdef SQLITE_MUTEX_NOOP
  23630. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  23631. return sqlite3NoopMutex();
  23632. }
  23633. #endif /* defined(SQLITE_MUTEX_NOOP) */
  23634. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  23635. /************** End of mutex_noop.c ******************************************/
  23636. /************** Begin file mutex_unix.c **************************************/
  23637. /*
  23638. ** 2007 August 28
  23639. **
  23640. ** The author disclaims copyright to this source code. In place of
  23641. ** a legal notice, here is a blessing:
  23642. **
  23643. ** May you do good and not evil.
  23644. ** May you find forgiveness for yourself and forgive others.
  23645. ** May you share freely, never taking more than you give.
  23646. **
  23647. *************************************************************************
  23648. ** This file contains the C functions that implement mutexes for pthreads
  23649. */
  23650. /* #include "sqliteInt.h" */
  23651. /*
  23652. ** The code in this file is only used if we are compiling threadsafe
  23653. ** under unix with pthreads.
  23654. **
  23655. ** Note that this implementation requires a version of pthreads that
  23656. ** supports recursive mutexes.
  23657. */
  23658. #ifdef SQLITE_MUTEX_PTHREADS
  23659. #include <pthread.h>
  23660. /*
  23661. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  23662. ** are necessary under two condidtions: (1) Debug builds and (2) using
  23663. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  23664. */
  23665. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  23666. # define SQLITE_MUTEX_NREF 1
  23667. #else
  23668. # define SQLITE_MUTEX_NREF 0
  23669. #endif
  23670. /*
  23671. ** Each recursive mutex is an instance of the following structure.
  23672. */
  23673. struct sqlite3_mutex {
  23674. pthread_mutex_t mutex; /* Mutex controlling the lock */
  23675. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23676. int id; /* Mutex type */
  23677. #endif
  23678. #if SQLITE_MUTEX_NREF
  23679. volatile int nRef; /* Number of entrances */
  23680. volatile pthread_t owner; /* Thread that is within this mutex */
  23681. int trace; /* True to trace changes */
  23682. #endif
  23683. };
  23684. #if SQLITE_MUTEX_NREF
  23685. # define SQLITE3_MUTEX_INITIALIZER(id) \
  23686. {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
  23687. #elif defined(SQLITE_ENABLE_API_ARMOR)
  23688. # define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
  23689. #else
  23690. #define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
  23691. #endif
  23692. /*
  23693. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23694. ** intended for use only inside assert() statements. On some platforms,
  23695. ** there might be race conditions that can cause these routines to
  23696. ** deliver incorrect results. In particular, if pthread_equal() is
  23697. ** not an atomic operation, then these routines might delivery
  23698. ** incorrect results. On most platforms, pthread_equal() is a
  23699. ** comparison of two integers and is therefore atomic. But we are
  23700. ** told that HPUX is not such a platform. If so, then these routines
  23701. ** will not always work correctly on HPUX.
  23702. **
  23703. ** On those platforms where pthread_equal() is not atomic, SQLite
  23704. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  23705. ** make sure no assert() statements are evaluated and hence these
  23706. ** routines are never called.
  23707. */
  23708. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  23709. static int pthreadMutexHeld(sqlite3_mutex *p){
  23710. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  23711. }
  23712. static int pthreadMutexNotheld(sqlite3_mutex *p){
  23713. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  23714. }
  23715. #endif
  23716. /*
  23717. ** Try to provide a memory barrier operation, needed for initialization
  23718. ** and also for the implementation of xShmBarrier in the VFS in cases
  23719. ** where SQLite is compiled without mutexes.
  23720. */
  23721. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  23722. #if defined(SQLITE_MEMORY_BARRIER)
  23723. SQLITE_MEMORY_BARRIER;
  23724. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  23725. __sync_synchronize();
  23726. #endif
  23727. }
  23728. /*
  23729. ** Initialize and deinitialize the mutex subsystem.
  23730. */
  23731. static int pthreadMutexInit(void){ return SQLITE_OK; }
  23732. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  23733. /*
  23734. ** The sqlite3_mutex_alloc() routine allocates a new
  23735. ** mutex and returns a pointer to it. If it returns NULL
  23736. ** that means that a mutex could not be allocated. SQLite
  23737. ** will unwind its stack and return an error. The argument
  23738. ** to sqlite3_mutex_alloc() is one of these integer constants:
  23739. **
  23740. ** <ul>
  23741. ** <li> SQLITE_MUTEX_FAST
  23742. ** <li> SQLITE_MUTEX_RECURSIVE
  23743. ** <li> SQLITE_MUTEX_STATIC_MASTER
  23744. ** <li> SQLITE_MUTEX_STATIC_MEM
  23745. ** <li> SQLITE_MUTEX_STATIC_OPEN
  23746. ** <li> SQLITE_MUTEX_STATIC_PRNG
  23747. ** <li> SQLITE_MUTEX_STATIC_LRU
  23748. ** <li> SQLITE_MUTEX_STATIC_PMEM
  23749. ** <li> SQLITE_MUTEX_STATIC_APP1
  23750. ** <li> SQLITE_MUTEX_STATIC_APP2
  23751. ** <li> SQLITE_MUTEX_STATIC_APP3
  23752. ** <li> SQLITE_MUTEX_STATIC_VFS1
  23753. ** <li> SQLITE_MUTEX_STATIC_VFS2
  23754. ** <li> SQLITE_MUTEX_STATIC_VFS3
  23755. ** </ul>
  23756. **
  23757. ** The first two constants cause sqlite3_mutex_alloc() to create
  23758. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  23759. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  23760. ** The mutex implementation does not need to make a distinction
  23761. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  23762. ** not want to. But SQLite will only request a recursive mutex in
  23763. ** cases where it really needs one. If a faster non-recursive mutex
  23764. ** implementation is available on the host platform, the mutex subsystem
  23765. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  23766. **
  23767. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  23768. ** a pointer to a static preexisting mutex. Six static mutexes are
  23769. ** used by the current version of SQLite. Future versions of SQLite
  23770. ** may add additional static mutexes. Static mutexes are for internal
  23771. ** use by SQLite only. Applications that use SQLite mutexes should
  23772. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  23773. ** SQLITE_MUTEX_RECURSIVE.
  23774. **
  23775. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  23776. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  23777. ** returns a different mutex on every call. But for the static
  23778. ** mutex types, the same mutex is returned on every call that has
  23779. ** the same type number.
  23780. */
  23781. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  23782. static sqlite3_mutex staticMutexes[] = {
  23783. SQLITE3_MUTEX_INITIALIZER(2),
  23784. SQLITE3_MUTEX_INITIALIZER(3),
  23785. SQLITE3_MUTEX_INITIALIZER(4),
  23786. SQLITE3_MUTEX_INITIALIZER(5),
  23787. SQLITE3_MUTEX_INITIALIZER(6),
  23788. SQLITE3_MUTEX_INITIALIZER(7),
  23789. SQLITE3_MUTEX_INITIALIZER(8),
  23790. SQLITE3_MUTEX_INITIALIZER(9),
  23791. SQLITE3_MUTEX_INITIALIZER(10),
  23792. SQLITE3_MUTEX_INITIALIZER(11),
  23793. SQLITE3_MUTEX_INITIALIZER(12),
  23794. SQLITE3_MUTEX_INITIALIZER(13)
  23795. };
  23796. sqlite3_mutex *p;
  23797. switch( iType ){
  23798. case SQLITE_MUTEX_RECURSIVE: {
  23799. p = sqlite3MallocZero( sizeof(*p) );
  23800. if( p ){
  23801. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23802. /* If recursive mutexes are not available, we will have to
  23803. ** build our own. See below. */
  23804. pthread_mutex_init(&p->mutex, 0);
  23805. #else
  23806. /* Use a recursive mutex if it is available */
  23807. pthread_mutexattr_t recursiveAttr;
  23808. pthread_mutexattr_init(&recursiveAttr);
  23809. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  23810. pthread_mutex_init(&p->mutex, &recursiveAttr);
  23811. pthread_mutexattr_destroy(&recursiveAttr);
  23812. #endif
  23813. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23814. p->id = SQLITE_MUTEX_RECURSIVE;
  23815. #endif
  23816. }
  23817. break;
  23818. }
  23819. case SQLITE_MUTEX_FAST: {
  23820. p = sqlite3MallocZero( sizeof(*p) );
  23821. if( p ){
  23822. pthread_mutex_init(&p->mutex, 0);
  23823. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23824. p->id = SQLITE_MUTEX_FAST;
  23825. #endif
  23826. }
  23827. break;
  23828. }
  23829. default: {
  23830. #ifdef SQLITE_ENABLE_API_ARMOR
  23831. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  23832. (void)SQLITE_MISUSE_BKPT;
  23833. return 0;
  23834. }
  23835. #endif
  23836. p = &staticMutexes[iType-2];
  23837. break;
  23838. }
  23839. }
  23840. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23841. assert( p==0 || p->id==iType );
  23842. #endif
  23843. return p;
  23844. }
  23845. /*
  23846. ** This routine deallocates a previously
  23847. ** allocated mutex. SQLite is careful to deallocate every
  23848. ** mutex that it allocates.
  23849. */
  23850. static void pthreadMutexFree(sqlite3_mutex *p){
  23851. assert( p->nRef==0 );
  23852. #if SQLITE_ENABLE_API_ARMOR
  23853. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  23854. #endif
  23855. {
  23856. pthread_mutex_destroy(&p->mutex);
  23857. sqlite3_free(p);
  23858. }
  23859. #ifdef SQLITE_ENABLE_API_ARMOR
  23860. else{
  23861. (void)SQLITE_MISUSE_BKPT;
  23862. }
  23863. #endif
  23864. }
  23865. /*
  23866. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  23867. ** to enter a mutex. If another thread is already within the mutex,
  23868. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  23869. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  23870. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  23871. ** be entered multiple times by the same thread. In such cases the,
  23872. ** mutex must be exited an equal number of times before another thread
  23873. ** can enter. If the same thread tries to enter any other kind of mutex
  23874. ** more than once, the behavior is undefined.
  23875. */
  23876. static void pthreadMutexEnter(sqlite3_mutex *p){
  23877. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  23878. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23879. /* If recursive mutexes are not available, then we have to grow
  23880. ** our own. This implementation assumes that pthread_equal()
  23881. ** is atomic - that it cannot be deceived into thinking self
  23882. ** and p->owner are equal if p->owner changes between two values
  23883. ** that are not equal to self while the comparison is taking place.
  23884. ** This implementation also assumes a coherent cache - that
  23885. ** separate processes cannot read different values from the same
  23886. ** address at the same time. If either of these two conditions
  23887. ** are not met, then the mutexes will fail and problems will result.
  23888. */
  23889. {
  23890. pthread_t self = pthread_self();
  23891. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  23892. p->nRef++;
  23893. }else{
  23894. pthread_mutex_lock(&p->mutex);
  23895. assert( p->nRef==0 );
  23896. p->owner = self;
  23897. p->nRef = 1;
  23898. }
  23899. }
  23900. #else
  23901. /* Use the built-in recursive mutexes if they are available.
  23902. */
  23903. pthread_mutex_lock(&p->mutex);
  23904. #if SQLITE_MUTEX_NREF
  23905. assert( p->nRef>0 || p->owner==0 );
  23906. p->owner = pthread_self();
  23907. p->nRef++;
  23908. #endif
  23909. #endif
  23910. #ifdef SQLITE_DEBUG
  23911. if( p->trace ){
  23912. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  23913. }
  23914. #endif
  23915. }
  23916. static int pthreadMutexTry(sqlite3_mutex *p){
  23917. int rc;
  23918. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  23919. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23920. /* If recursive mutexes are not available, then we have to grow
  23921. ** our own. This implementation assumes that pthread_equal()
  23922. ** is atomic - that it cannot be deceived into thinking self
  23923. ** and p->owner are equal if p->owner changes between two values
  23924. ** that are not equal to self while the comparison is taking place.
  23925. ** This implementation also assumes a coherent cache - that
  23926. ** separate processes cannot read different values from the same
  23927. ** address at the same time. If either of these two conditions
  23928. ** are not met, then the mutexes will fail and problems will result.
  23929. */
  23930. {
  23931. pthread_t self = pthread_self();
  23932. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  23933. p->nRef++;
  23934. rc = SQLITE_OK;
  23935. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  23936. assert( p->nRef==0 );
  23937. p->owner = self;
  23938. p->nRef = 1;
  23939. rc = SQLITE_OK;
  23940. }else{
  23941. rc = SQLITE_BUSY;
  23942. }
  23943. }
  23944. #else
  23945. /* Use the built-in recursive mutexes if they are available.
  23946. */
  23947. if( pthread_mutex_trylock(&p->mutex)==0 ){
  23948. #if SQLITE_MUTEX_NREF
  23949. p->owner = pthread_self();
  23950. p->nRef++;
  23951. #endif
  23952. rc = SQLITE_OK;
  23953. }else{
  23954. rc = SQLITE_BUSY;
  23955. }
  23956. #endif
  23957. #ifdef SQLITE_DEBUG
  23958. if( rc==SQLITE_OK && p->trace ){
  23959. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  23960. }
  23961. #endif
  23962. return rc;
  23963. }
  23964. /*
  23965. ** The sqlite3_mutex_leave() routine exits a mutex that was
  23966. ** previously entered by the same thread. The behavior
  23967. ** is undefined if the mutex is not currently entered or
  23968. ** is not currently allocated. SQLite will never do either.
  23969. */
  23970. static void pthreadMutexLeave(sqlite3_mutex *p){
  23971. assert( pthreadMutexHeld(p) );
  23972. #if SQLITE_MUTEX_NREF
  23973. p->nRef--;
  23974. if( p->nRef==0 ) p->owner = 0;
  23975. #endif
  23976. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  23977. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23978. if( p->nRef==0 ){
  23979. pthread_mutex_unlock(&p->mutex);
  23980. }
  23981. #else
  23982. pthread_mutex_unlock(&p->mutex);
  23983. #endif
  23984. #ifdef SQLITE_DEBUG
  23985. if( p->trace ){
  23986. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  23987. }
  23988. #endif
  23989. }
  23990. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  23991. static const sqlite3_mutex_methods sMutex = {
  23992. pthreadMutexInit,
  23993. pthreadMutexEnd,
  23994. pthreadMutexAlloc,
  23995. pthreadMutexFree,
  23996. pthreadMutexEnter,
  23997. pthreadMutexTry,
  23998. pthreadMutexLeave,
  23999. #ifdef SQLITE_DEBUG
  24000. pthreadMutexHeld,
  24001. pthreadMutexNotheld
  24002. #else
  24003. 0,
  24004. 0
  24005. #endif
  24006. };
  24007. return &sMutex;
  24008. }
  24009. #endif /* SQLITE_MUTEX_PTHREADS */
  24010. /************** End of mutex_unix.c ******************************************/
  24011. /************** Begin file mutex_w32.c ***************************************/
  24012. /*
  24013. ** 2007 August 14
  24014. **
  24015. ** The author disclaims copyright to this source code. In place of
  24016. ** a legal notice, here is a blessing:
  24017. **
  24018. ** May you do good and not evil.
  24019. ** May you find forgiveness for yourself and forgive others.
  24020. ** May you share freely, never taking more than you give.
  24021. **
  24022. *************************************************************************
  24023. ** This file contains the C functions that implement mutexes for Win32.
  24024. */
  24025. /* #include "sqliteInt.h" */
  24026. #if SQLITE_OS_WIN
  24027. /*
  24028. ** Include code that is common to all os_*.c files
  24029. */
  24030. /************** Include os_common.h in the middle of mutex_w32.c *************/
  24031. /************** Begin file os_common.h ***************************************/
  24032. /*
  24033. ** 2004 May 22
  24034. **
  24035. ** The author disclaims copyright to this source code. In place of
  24036. ** a legal notice, here is a blessing:
  24037. **
  24038. ** May you do good and not evil.
  24039. ** May you find forgiveness for yourself and forgive others.
  24040. ** May you share freely, never taking more than you give.
  24041. **
  24042. ******************************************************************************
  24043. **
  24044. ** This file contains macros and a little bit of code that is common to
  24045. ** all of the platform-specific files (os_*.c) and is #included into those
  24046. ** files.
  24047. **
  24048. ** This file should be #included by the os_*.c files only. It is not a
  24049. ** general purpose header file.
  24050. */
  24051. #ifndef _OS_COMMON_H_
  24052. #define _OS_COMMON_H_
  24053. /*
  24054. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  24055. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  24056. ** switch. The following code should catch this problem at compile-time.
  24057. */
  24058. #ifdef MEMORY_DEBUG
  24059. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  24060. #endif
  24061. /*
  24062. ** Macros for performance tracing. Normally turned off. Only works
  24063. ** on i486 hardware.
  24064. */
  24065. #ifdef SQLITE_PERFORMANCE_TRACE
  24066. /*
  24067. ** hwtime.h contains inline assembler code for implementing
  24068. ** high-performance timing routines.
  24069. */
  24070. /************** Include hwtime.h in the middle of os_common.h ****************/
  24071. /************** Begin file hwtime.h ******************************************/
  24072. /*
  24073. ** 2008 May 27
  24074. **
  24075. ** The author disclaims copyright to this source code. In place of
  24076. ** a legal notice, here is a blessing:
  24077. **
  24078. ** May you do good and not evil.
  24079. ** May you find forgiveness for yourself and forgive others.
  24080. ** May you share freely, never taking more than you give.
  24081. **
  24082. ******************************************************************************
  24083. **
  24084. ** This file contains inline asm code for retrieving "high-performance"
  24085. ** counters for x86 class CPUs.
  24086. */
  24087. #ifndef SQLITE_HWTIME_H
  24088. #define SQLITE_HWTIME_H
  24089. /*
  24090. ** The following routine only works on pentium-class (or newer) processors.
  24091. ** It uses the RDTSC opcode to read the cycle count value out of the
  24092. ** processor and returns that value. This can be used for high-res
  24093. ** profiling.
  24094. */
  24095. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  24096. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  24097. #if defined(__GNUC__)
  24098. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24099. unsigned int lo, hi;
  24100. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  24101. return (sqlite_uint64)hi << 32 | lo;
  24102. }
  24103. #elif defined(_MSC_VER)
  24104. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  24105. __asm {
  24106. rdtsc
  24107. ret ; return value at EDX:EAX
  24108. }
  24109. }
  24110. #endif
  24111. #elif (defined(__GNUC__) && defined(__x86_64__))
  24112. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24113. unsigned long val;
  24114. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  24115. return val;
  24116. }
  24117. #elif (defined(__GNUC__) && defined(__ppc__))
  24118. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24119. unsigned long long retval;
  24120. unsigned long junk;
  24121. __asm__ __volatile__ ("\n\
  24122. 1: mftbu %1\n\
  24123. mftb %L0\n\
  24124. mftbu %0\n\
  24125. cmpw %0,%1\n\
  24126. bne 1b"
  24127. : "=r" (retval), "=r" (junk));
  24128. return retval;
  24129. }
  24130. #else
  24131. #error Need implementation of sqlite3Hwtime() for your platform.
  24132. /*
  24133. ** To compile without implementing sqlite3Hwtime() for your platform,
  24134. ** you can remove the above #error and use the following
  24135. ** stub function. You will lose timing support for many
  24136. ** of the debugging and testing utilities, but it should at
  24137. ** least compile and run.
  24138. */
  24139. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  24140. #endif
  24141. #endif /* !defined(SQLITE_HWTIME_H) */
  24142. /************** End of hwtime.h **********************************************/
  24143. /************** Continuing where we left off in os_common.h ******************/
  24144. static sqlite_uint64 g_start;
  24145. static sqlite_uint64 g_elapsed;
  24146. #define TIMER_START g_start=sqlite3Hwtime()
  24147. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  24148. #define TIMER_ELAPSED g_elapsed
  24149. #else
  24150. #define TIMER_START
  24151. #define TIMER_END
  24152. #define TIMER_ELAPSED ((sqlite_uint64)0)
  24153. #endif
  24154. /*
  24155. ** If we compile with the SQLITE_TEST macro set, then the following block
  24156. ** of code will give us the ability to simulate a disk I/O error. This
  24157. ** is used for testing the I/O recovery logic.
  24158. */
  24159. #if defined(SQLITE_TEST)
  24160. SQLITE_API extern int sqlite3_io_error_hit;
  24161. SQLITE_API extern int sqlite3_io_error_hardhit;
  24162. SQLITE_API extern int sqlite3_io_error_pending;
  24163. SQLITE_API extern int sqlite3_io_error_persist;
  24164. SQLITE_API extern int sqlite3_io_error_benign;
  24165. SQLITE_API extern int sqlite3_diskfull_pending;
  24166. SQLITE_API extern int sqlite3_diskfull;
  24167. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  24168. #define SimulateIOError(CODE) \
  24169. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  24170. || sqlite3_io_error_pending-- == 1 ) \
  24171. { local_ioerr(); CODE; }
  24172. static void local_ioerr(){
  24173. IOTRACE(("IOERR\n"));
  24174. sqlite3_io_error_hit++;
  24175. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  24176. }
  24177. #define SimulateDiskfullError(CODE) \
  24178. if( sqlite3_diskfull_pending ){ \
  24179. if( sqlite3_diskfull_pending == 1 ){ \
  24180. local_ioerr(); \
  24181. sqlite3_diskfull = 1; \
  24182. sqlite3_io_error_hit = 1; \
  24183. CODE; \
  24184. }else{ \
  24185. sqlite3_diskfull_pending--; \
  24186. } \
  24187. }
  24188. #else
  24189. #define SimulateIOErrorBenign(X)
  24190. #define SimulateIOError(A)
  24191. #define SimulateDiskfullError(A)
  24192. #endif /* defined(SQLITE_TEST) */
  24193. /*
  24194. ** When testing, keep a count of the number of open files.
  24195. */
  24196. #if defined(SQLITE_TEST)
  24197. SQLITE_API extern int sqlite3_open_file_count;
  24198. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  24199. #else
  24200. #define OpenCounter(X)
  24201. #endif /* defined(SQLITE_TEST) */
  24202. #endif /* !defined(_OS_COMMON_H_) */
  24203. /************** End of os_common.h *******************************************/
  24204. /************** Continuing where we left off in mutex_w32.c ******************/
  24205. /*
  24206. ** Include the header file for the Windows VFS.
  24207. */
  24208. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  24209. /************** Begin file os_win.h ******************************************/
  24210. /*
  24211. ** 2013 November 25
  24212. **
  24213. ** The author disclaims copyright to this source code. In place of
  24214. ** a legal notice, here is a blessing:
  24215. **
  24216. ** May you do good and not evil.
  24217. ** May you find forgiveness for yourself and forgive others.
  24218. ** May you share freely, never taking more than you give.
  24219. **
  24220. ******************************************************************************
  24221. **
  24222. ** This file contains code that is specific to Windows.
  24223. */
  24224. #ifndef SQLITE_OS_WIN_H
  24225. #define SQLITE_OS_WIN_H
  24226. /*
  24227. ** Include the primary Windows SDK header file.
  24228. */
  24229. #include "windows.h"
  24230. #ifdef __CYGWIN__
  24231. # include <sys/cygwin.h>
  24232. # include <errno.h> /* amalgamator: dontcache */
  24233. #endif
  24234. /*
  24235. ** Determine if we are dealing with Windows NT.
  24236. **
  24237. ** We ought to be able to determine if we are compiling for Windows 9x or
  24238. ** Windows NT using the _WIN32_WINNT macro as follows:
  24239. **
  24240. ** #if defined(_WIN32_WINNT)
  24241. ** # define SQLITE_OS_WINNT 1
  24242. ** #else
  24243. ** # define SQLITE_OS_WINNT 0
  24244. ** #endif
  24245. **
  24246. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  24247. ** it ought to, so the above test does not work. We'll just assume that
  24248. ** everything is Windows NT unless the programmer explicitly says otherwise
  24249. ** by setting SQLITE_OS_WINNT to 0.
  24250. */
  24251. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  24252. # define SQLITE_OS_WINNT 1
  24253. #endif
  24254. /*
  24255. ** Determine if we are dealing with Windows CE - which has a much reduced
  24256. ** API.
  24257. */
  24258. #if defined(_WIN32_WCE)
  24259. # define SQLITE_OS_WINCE 1
  24260. #else
  24261. # define SQLITE_OS_WINCE 0
  24262. #endif
  24263. /*
  24264. ** Determine if we are dealing with WinRT, which provides only a subset of
  24265. ** the full Win32 API.
  24266. */
  24267. #if !defined(SQLITE_OS_WINRT)
  24268. # define SQLITE_OS_WINRT 0
  24269. #endif
  24270. /*
  24271. ** For WinCE, some API function parameters do not appear to be declared as
  24272. ** volatile.
  24273. */
  24274. #if SQLITE_OS_WINCE
  24275. # define SQLITE_WIN32_VOLATILE
  24276. #else
  24277. # define SQLITE_WIN32_VOLATILE volatile
  24278. #endif
  24279. /*
  24280. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  24281. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  24282. */
  24283. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  24284. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  24285. # define SQLITE_OS_WIN_THREADS 1
  24286. #else
  24287. # define SQLITE_OS_WIN_THREADS 0
  24288. #endif
  24289. #endif /* SQLITE_OS_WIN_H */
  24290. /************** End of os_win.h **********************************************/
  24291. /************** Continuing where we left off in mutex_w32.c ******************/
  24292. #endif
  24293. /*
  24294. ** The code in this file is only used if we are compiling multithreaded
  24295. ** on a Win32 system.
  24296. */
  24297. #ifdef SQLITE_MUTEX_W32
  24298. /*
  24299. ** Each recursive mutex is an instance of the following structure.
  24300. */
  24301. struct sqlite3_mutex {
  24302. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  24303. int id; /* Mutex type */
  24304. #ifdef SQLITE_DEBUG
  24305. volatile int nRef; /* Number of enterances */
  24306. volatile DWORD owner; /* Thread holding this mutex */
  24307. volatile LONG trace; /* True to trace changes */
  24308. #endif
  24309. };
  24310. /*
  24311. ** These are the initializer values used when declaring a "static" mutex
  24312. ** on Win32. It should be noted that all mutexes require initialization
  24313. ** on the Win32 platform.
  24314. */
  24315. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  24316. #ifdef SQLITE_DEBUG
  24317. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
  24318. 0L, (DWORD)0, 0 }
  24319. #else
  24320. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
  24321. #endif
  24322. #ifdef SQLITE_DEBUG
  24323. /*
  24324. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24325. ** intended for use only inside assert() statements.
  24326. */
  24327. static int winMutexHeld(sqlite3_mutex *p){
  24328. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  24329. }
  24330. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  24331. return p->nRef==0 || p->owner!=tid;
  24332. }
  24333. static int winMutexNotheld(sqlite3_mutex *p){
  24334. DWORD tid = GetCurrentThreadId();
  24335. return winMutexNotheld2(p, tid);
  24336. }
  24337. #endif
  24338. /*
  24339. ** Try to provide a memory barrier operation, needed for initialization
  24340. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  24341. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  24342. */
  24343. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  24344. #if defined(SQLITE_MEMORY_BARRIER)
  24345. SQLITE_MEMORY_BARRIER;
  24346. #elif defined(__GNUC__)
  24347. __sync_synchronize();
  24348. #elif MSVC_VERSION>=1300
  24349. _ReadWriteBarrier();
  24350. #elif defined(MemoryBarrier)
  24351. MemoryBarrier();
  24352. #endif
  24353. }
  24354. /*
  24355. ** Initialize and deinitialize the mutex subsystem.
  24356. */
  24357. static sqlite3_mutex winMutex_staticMutexes[] = {
  24358. SQLITE3_MUTEX_INITIALIZER(2),
  24359. SQLITE3_MUTEX_INITIALIZER(3),
  24360. SQLITE3_MUTEX_INITIALIZER(4),
  24361. SQLITE3_MUTEX_INITIALIZER(5),
  24362. SQLITE3_MUTEX_INITIALIZER(6),
  24363. SQLITE3_MUTEX_INITIALIZER(7),
  24364. SQLITE3_MUTEX_INITIALIZER(8),
  24365. SQLITE3_MUTEX_INITIALIZER(9),
  24366. SQLITE3_MUTEX_INITIALIZER(10),
  24367. SQLITE3_MUTEX_INITIALIZER(11),
  24368. SQLITE3_MUTEX_INITIALIZER(12),
  24369. SQLITE3_MUTEX_INITIALIZER(13)
  24370. };
  24371. static int winMutex_isInit = 0;
  24372. static int winMutex_isNt = -1; /* <0 means "need to query" */
  24373. /* As the winMutexInit() and winMutexEnd() functions are called as part
  24374. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  24375. ** "interlocked" magic used here is probably not strictly necessary.
  24376. */
  24377. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  24378. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  24379. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  24380. static int winMutexInit(void){
  24381. /* The first to increment to 1 does actual initialization */
  24382. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  24383. int i;
  24384. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  24385. #if SQLITE_OS_WINRT
  24386. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  24387. #else
  24388. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  24389. #endif
  24390. }
  24391. winMutex_isInit = 1;
  24392. }else{
  24393. /* Another thread is (in the process of) initializing the static
  24394. ** mutexes */
  24395. while( !winMutex_isInit ){
  24396. sqlite3_win32_sleep(1);
  24397. }
  24398. }
  24399. return SQLITE_OK;
  24400. }
  24401. static int winMutexEnd(void){
  24402. /* The first to decrement to 0 does actual shutdown
  24403. ** (which should be the last to shutdown.) */
  24404. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  24405. if( winMutex_isInit==1 ){
  24406. int i;
  24407. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  24408. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  24409. }
  24410. winMutex_isInit = 0;
  24411. }
  24412. }
  24413. return SQLITE_OK;
  24414. }
  24415. /*
  24416. ** The sqlite3_mutex_alloc() routine allocates a new
  24417. ** mutex and returns a pointer to it. If it returns NULL
  24418. ** that means that a mutex could not be allocated. SQLite
  24419. ** will unwind its stack and return an error. The argument
  24420. ** to sqlite3_mutex_alloc() is one of these integer constants:
  24421. **
  24422. ** <ul>
  24423. ** <li> SQLITE_MUTEX_FAST
  24424. ** <li> SQLITE_MUTEX_RECURSIVE
  24425. ** <li> SQLITE_MUTEX_STATIC_MASTER
  24426. ** <li> SQLITE_MUTEX_STATIC_MEM
  24427. ** <li> SQLITE_MUTEX_STATIC_OPEN
  24428. ** <li> SQLITE_MUTEX_STATIC_PRNG
  24429. ** <li> SQLITE_MUTEX_STATIC_LRU
  24430. ** <li> SQLITE_MUTEX_STATIC_PMEM
  24431. ** <li> SQLITE_MUTEX_STATIC_APP1
  24432. ** <li> SQLITE_MUTEX_STATIC_APP2
  24433. ** <li> SQLITE_MUTEX_STATIC_APP3
  24434. ** <li> SQLITE_MUTEX_STATIC_VFS1
  24435. ** <li> SQLITE_MUTEX_STATIC_VFS2
  24436. ** <li> SQLITE_MUTEX_STATIC_VFS3
  24437. ** </ul>
  24438. **
  24439. ** The first two constants cause sqlite3_mutex_alloc() to create
  24440. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  24441. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  24442. ** The mutex implementation does not need to make a distinction
  24443. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  24444. ** not want to. But SQLite will only request a recursive mutex in
  24445. ** cases where it really needs one. If a faster non-recursive mutex
  24446. ** implementation is available on the host platform, the mutex subsystem
  24447. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  24448. **
  24449. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  24450. ** a pointer to a static preexisting mutex. Six static mutexes are
  24451. ** used by the current version of SQLite. Future versions of SQLite
  24452. ** may add additional static mutexes. Static mutexes are for internal
  24453. ** use by SQLite only. Applications that use SQLite mutexes should
  24454. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  24455. ** SQLITE_MUTEX_RECURSIVE.
  24456. **
  24457. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  24458. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  24459. ** returns a different mutex on every call. But for the static
  24460. ** mutex types, the same mutex is returned on every call that has
  24461. ** the same type number.
  24462. */
  24463. static sqlite3_mutex *winMutexAlloc(int iType){
  24464. sqlite3_mutex *p;
  24465. switch( iType ){
  24466. case SQLITE_MUTEX_FAST:
  24467. case SQLITE_MUTEX_RECURSIVE: {
  24468. p = sqlite3MallocZero( sizeof(*p) );
  24469. if( p ){
  24470. p->id = iType;
  24471. #ifdef SQLITE_DEBUG
  24472. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  24473. p->trace = 1;
  24474. #endif
  24475. #endif
  24476. #if SQLITE_OS_WINRT
  24477. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  24478. #else
  24479. InitializeCriticalSection(&p->mutex);
  24480. #endif
  24481. }
  24482. break;
  24483. }
  24484. default: {
  24485. #ifdef SQLITE_ENABLE_API_ARMOR
  24486. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  24487. (void)SQLITE_MISUSE_BKPT;
  24488. return 0;
  24489. }
  24490. #endif
  24491. p = &winMutex_staticMutexes[iType-2];
  24492. #ifdef SQLITE_DEBUG
  24493. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  24494. InterlockedCompareExchange(&p->trace, 1, 0);
  24495. #endif
  24496. #endif
  24497. break;
  24498. }
  24499. }
  24500. assert( p==0 || p->id==iType );
  24501. return p;
  24502. }
  24503. /*
  24504. ** This routine deallocates a previously
  24505. ** allocated mutex. SQLite is careful to deallocate every
  24506. ** mutex that it allocates.
  24507. */
  24508. static void winMutexFree(sqlite3_mutex *p){
  24509. assert( p );
  24510. assert( p->nRef==0 && p->owner==0 );
  24511. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  24512. DeleteCriticalSection(&p->mutex);
  24513. sqlite3_free(p);
  24514. }else{
  24515. #ifdef SQLITE_ENABLE_API_ARMOR
  24516. (void)SQLITE_MISUSE_BKPT;
  24517. #endif
  24518. }
  24519. }
  24520. /*
  24521. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24522. ** to enter a mutex. If another thread is already within the mutex,
  24523. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24524. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24525. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24526. ** be entered multiple times by the same thread. In such cases the,
  24527. ** mutex must be exited an equal number of times before another thread
  24528. ** can enter. If the same thread tries to enter any other kind of mutex
  24529. ** more than once, the behavior is undefined.
  24530. */
  24531. static void winMutexEnter(sqlite3_mutex *p){
  24532. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24533. DWORD tid = GetCurrentThreadId();
  24534. #endif
  24535. #ifdef SQLITE_DEBUG
  24536. assert( p );
  24537. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  24538. #else
  24539. assert( p );
  24540. #endif
  24541. assert( winMutex_isInit==1 );
  24542. EnterCriticalSection(&p->mutex);
  24543. #ifdef SQLITE_DEBUG
  24544. assert( p->nRef>0 || p->owner==0 );
  24545. p->owner = tid;
  24546. p->nRef++;
  24547. if( p->trace ){
  24548. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  24549. tid, p->id, p, p->trace, p->nRef));
  24550. }
  24551. #endif
  24552. }
  24553. static int winMutexTry(sqlite3_mutex *p){
  24554. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24555. DWORD tid = GetCurrentThreadId();
  24556. #endif
  24557. int rc = SQLITE_BUSY;
  24558. assert( p );
  24559. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  24560. /*
  24561. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  24562. ** is used it is merely an optimization. So it is OK for it to always
  24563. ** fail.
  24564. **
  24565. ** The TryEnterCriticalSection() interface is only available on WinNT.
  24566. ** And some windows compilers complain if you try to use it without
  24567. ** first doing some #defines that prevent SQLite from building on Win98.
  24568. ** For that reason, we will omit this optimization for now. See
  24569. ** ticket #2685.
  24570. */
  24571. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  24572. assert( winMutex_isInit==1 );
  24573. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  24574. if( winMutex_isNt<0 ){
  24575. winMutex_isNt = sqlite3_win32_is_nt();
  24576. }
  24577. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  24578. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  24579. #ifdef SQLITE_DEBUG
  24580. p->owner = tid;
  24581. p->nRef++;
  24582. #endif
  24583. rc = SQLITE_OK;
  24584. }
  24585. #else
  24586. UNUSED_PARAMETER(p);
  24587. #endif
  24588. #ifdef SQLITE_DEBUG
  24589. if( p->trace ){
  24590. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  24591. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  24592. }
  24593. #endif
  24594. return rc;
  24595. }
  24596. /*
  24597. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24598. ** previously entered by the same thread. The behavior
  24599. ** is undefined if the mutex is not currently entered or
  24600. ** is not currently allocated. SQLite will never do either.
  24601. */
  24602. static void winMutexLeave(sqlite3_mutex *p){
  24603. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24604. DWORD tid = GetCurrentThreadId();
  24605. #endif
  24606. assert( p );
  24607. #ifdef SQLITE_DEBUG
  24608. assert( p->nRef>0 );
  24609. assert( p->owner==tid );
  24610. p->nRef--;
  24611. if( p->nRef==0 ) p->owner = 0;
  24612. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  24613. #endif
  24614. assert( winMutex_isInit==1 );
  24615. LeaveCriticalSection(&p->mutex);
  24616. #ifdef SQLITE_DEBUG
  24617. if( p->trace ){
  24618. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  24619. tid, p->id, p, p->trace, p->nRef));
  24620. }
  24621. #endif
  24622. }
  24623. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24624. static const sqlite3_mutex_methods sMutex = {
  24625. winMutexInit,
  24626. winMutexEnd,
  24627. winMutexAlloc,
  24628. winMutexFree,
  24629. winMutexEnter,
  24630. winMutexTry,
  24631. winMutexLeave,
  24632. #ifdef SQLITE_DEBUG
  24633. winMutexHeld,
  24634. winMutexNotheld
  24635. #else
  24636. 0,
  24637. 0
  24638. #endif
  24639. };
  24640. return &sMutex;
  24641. }
  24642. #endif /* SQLITE_MUTEX_W32 */
  24643. /************** End of mutex_w32.c *******************************************/
  24644. /************** Begin file malloc.c ******************************************/
  24645. /*
  24646. ** 2001 September 15
  24647. **
  24648. ** The author disclaims copyright to this source code. In place of
  24649. ** a legal notice, here is a blessing:
  24650. **
  24651. ** May you do good and not evil.
  24652. ** May you find forgiveness for yourself and forgive others.
  24653. ** May you share freely, never taking more than you give.
  24654. **
  24655. *************************************************************************
  24656. **
  24657. ** Memory allocation functions used throughout sqlite.
  24658. */
  24659. /* #include "sqliteInt.h" */
  24660. /* #include <stdarg.h> */
  24661. /*
  24662. ** Attempt to release up to n bytes of non-essential memory currently
  24663. ** held by SQLite. An example of non-essential memory is memory used to
  24664. ** cache database pages that are not currently in use.
  24665. */
  24666. SQLITE_API int sqlite3_release_memory(int n){
  24667. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  24668. return sqlite3PcacheReleaseMemory(n);
  24669. #else
  24670. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  24671. ** is a no-op returning zero if SQLite is not compiled with
  24672. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  24673. UNUSED_PARAMETER(n);
  24674. return 0;
  24675. #endif
  24676. }
  24677. /*
  24678. ** State information local to the memory allocation subsystem.
  24679. */
  24680. static SQLITE_WSD struct Mem0Global {
  24681. sqlite3_mutex *mutex; /* Mutex to serialize access */
  24682. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  24683. /*
  24684. ** True if heap is nearly "full" where "full" is defined by the
  24685. ** sqlite3_soft_heap_limit() setting.
  24686. */
  24687. int nearlyFull;
  24688. } mem0 = { 0, 0, 0 };
  24689. #define mem0 GLOBAL(struct Mem0Global, mem0)
  24690. /*
  24691. ** Return the memory allocator mutex. sqlite3_status() needs it.
  24692. */
  24693. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  24694. return mem0.mutex;
  24695. }
  24696. #ifndef SQLITE_OMIT_DEPRECATED
  24697. /*
  24698. ** Deprecated external interface. It used to set an alarm callback
  24699. ** that was invoked when memory usage grew too large. Now it is a
  24700. ** no-op.
  24701. */
  24702. SQLITE_API int sqlite3_memory_alarm(
  24703. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  24704. void *pArg,
  24705. sqlite3_int64 iThreshold
  24706. ){
  24707. (void)xCallback;
  24708. (void)pArg;
  24709. (void)iThreshold;
  24710. return SQLITE_OK;
  24711. }
  24712. #endif
  24713. /*
  24714. ** Set the soft heap-size limit for the library. Passing a zero or
  24715. ** negative value indicates no limit.
  24716. */
  24717. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  24718. sqlite3_int64 priorLimit;
  24719. sqlite3_int64 excess;
  24720. sqlite3_int64 nUsed;
  24721. #ifndef SQLITE_OMIT_AUTOINIT
  24722. int rc = sqlite3_initialize();
  24723. if( rc ) return -1;
  24724. #endif
  24725. sqlite3_mutex_enter(mem0.mutex);
  24726. priorLimit = mem0.alarmThreshold;
  24727. if( n<0 ){
  24728. sqlite3_mutex_leave(mem0.mutex);
  24729. return priorLimit;
  24730. }
  24731. mem0.alarmThreshold = n;
  24732. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  24733. mem0.nearlyFull = (n>0 && n<=nUsed);
  24734. sqlite3_mutex_leave(mem0.mutex);
  24735. excess = sqlite3_memory_used() - n;
  24736. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  24737. return priorLimit;
  24738. }
  24739. SQLITE_API void sqlite3_soft_heap_limit(int n){
  24740. if( n<0 ) n = 0;
  24741. sqlite3_soft_heap_limit64(n);
  24742. }
  24743. /*
  24744. ** Initialize the memory allocation subsystem.
  24745. */
  24746. SQLITE_PRIVATE int sqlite3MallocInit(void){
  24747. int rc;
  24748. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  24749. sqlite3MemSetDefault();
  24750. }
  24751. memset(&mem0, 0, sizeof(mem0));
  24752. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  24753. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  24754. || sqlite3GlobalConfig.nPage<=0 ){
  24755. sqlite3GlobalConfig.pPage = 0;
  24756. sqlite3GlobalConfig.szPage = 0;
  24757. }
  24758. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  24759. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  24760. return rc;
  24761. }
  24762. /*
  24763. ** Return true if the heap is currently under memory pressure - in other
  24764. ** words if the amount of heap used is close to the limit set by
  24765. ** sqlite3_soft_heap_limit().
  24766. */
  24767. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  24768. return mem0.nearlyFull;
  24769. }
  24770. /*
  24771. ** Deinitialize the memory allocation subsystem.
  24772. */
  24773. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  24774. if( sqlite3GlobalConfig.m.xShutdown ){
  24775. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  24776. }
  24777. memset(&mem0, 0, sizeof(mem0));
  24778. }
  24779. /*
  24780. ** Return the amount of memory currently checked out.
  24781. */
  24782. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  24783. sqlite3_int64 res, mx;
  24784. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  24785. return res;
  24786. }
  24787. /*
  24788. ** Return the maximum amount of memory that has ever been
  24789. ** checked out since either the beginning of this process
  24790. ** or since the most recent reset.
  24791. */
  24792. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  24793. sqlite3_int64 res, mx;
  24794. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  24795. return mx;
  24796. }
  24797. /*
  24798. ** Trigger the alarm
  24799. */
  24800. static void sqlite3MallocAlarm(int nByte){
  24801. if( mem0.alarmThreshold<=0 ) return;
  24802. sqlite3_mutex_leave(mem0.mutex);
  24803. sqlite3_release_memory(nByte);
  24804. sqlite3_mutex_enter(mem0.mutex);
  24805. }
  24806. /*
  24807. ** Do a memory allocation with statistics and alarms. Assume the
  24808. ** lock is already held.
  24809. */
  24810. static void mallocWithAlarm(int n, void **pp){
  24811. void *p;
  24812. int nFull;
  24813. assert( sqlite3_mutex_held(mem0.mutex) );
  24814. assert( n>0 );
  24815. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  24816. ** implementation of malloc_good_size(), which must be called in debug
  24817. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  24818. ** or else a crash results. Hence, do not attempt to optimize out the
  24819. ** following xRoundup() call. */
  24820. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  24821. #ifdef SQLITE_MAX_MEMORY
  24822. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  24823. *pp = 0;
  24824. return;
  24825. }
  24826. #endif
  24827. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  24828. if( mem0.alarmThreshold>0 ){
  24829. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  24830. if( nUsed >= mem0.alarmThreshold - nFull ){
  24831. mem0.nearlyFull = 1;
  24832. sqlite3MallocAlarm(nFull);
  24833. }else{
  24834. mem0.nearlyFull = 0;
  24835. }
  24836. }
  24837. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  24838. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  24839. if( p==0 && mem0.alarmThreshold>0 ){
  24840. sqlite3MallocAlarm(nFull);
  24841. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  24842. }
  24843. #endif
  24844. if( p ){
  24845. nFull = sqlite3MallocSize(p);
  24846. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  24847. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  24848. }
  24849. *pp = p;
  24850. }
  24851. /*
  24852. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  24853. ** assumes the memory subsystem has already been initialized.
  24854. */
  24855. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  24856. void *p;
  24857. if( n==0 || n>=0x7fffff00 ){
  24858. /* A memory allocation of a number of bytes which is near the maximum
  24859. ** signed integer value might cause an integer overflow inside of the
  24860. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  24861. ** 255 bytes of overhead. SQLite itself will never use anything near
  24862. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  24863. p = 0;
  24864. }else if( sqlite3GlobalConfig.bMemstat ){
  24865. sqlite3_mutex_enter(mem0.mutex);
  24866. mallocWithAlarm((int)n, &p);
  24867. sqlite3_mutex_leave(mem0.mutex);
  24868. }else{
  24869. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  24870. }
  24871. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  24872. return p;
  24873. }
  24874. /*
  24875. ** This version of the memory allocation is for use by the application.
  24876. ** First make sure the memory subsystem is initialized, then do the
  24877. ** allocation.
  24878. */
  24879. SQLITE_API void *sqlite3_malloc(int n){
  24880. #ifndef SQLITE_OMIT_AUTOINIT
  24881. if( sqlite3_initialize() ) return 0;
  24882. #endif
  24883. return n<=0 ? 0 : sqlite3Malloc(n);
  24884. }
  24885. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  24886. #ifndef SQLITE_OMIT_AUTOINIT
  24887. if( sqlite3_initialize() ) return 0;
  24888. #endif
  24889. return sqlite3Malloc(n);
  24890. }
  24891. /*
  24892. ** TRUE if p is a lookaside memory allocation from db
  24893. */
  24894. #ifndef SQLITE_OMIT_LOOKASIDE
  24895. static int isLookaside(sqlite3 *db, void *p){
  24896. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  24897. }
  24898. #else
  24899. #define isLookaside(A,B) 0
  24900. #endif
  24901. /*
  24902. ** Return the size of a memory allocation previously obtained from
  24903. ** sqlite3Malloc() or sqlite3_malloc().
  24904. */
  24905. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  24906. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24907. return sqlite3GlobalConfig.m.xSize(p);
  24908. }
  24909. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  24910. assert( p!=0 );
  24911. if( db==0 || !isLookaside(db,p) ){
  24912. #ifdef SQLITE_DEBUG
  24913. if( db==0 ){
  24914. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  24915. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24916. }else{
  24917. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24918. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24919. }
  24920. #endif
  24921. return sqlite3GlobalConfig.m.xSize(p);
  24922. }else{
  24923. assert( sqlite3_mutex_held(db->mutex) );
  24924. return db->lookaside.sz;
  24925. }
  24926. }
  24927. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  24928. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  24929. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24930. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  24931. }
  24932. /*
  24933. ** Free memory previously obtained from sqlite3Malloc().
  24934. */
  24935. SQLITE_API void sqlite3_free(void *p){
  24936. if( p==0 ) return; /* IMP: R-49053-54554 */
  24937. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24938. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  24939. if( sqlite3GlobalConfig.bMemstat ){
  24940. sqlite3_mutex_enter(mem0.mutex);
  24941. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  24942. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  24943. sqlite3GlobalConfig.m.xFree(p);
  24944. sqlite3_mutex_leave(mem0.mutex);
  24945. }else{
  24946. sqlite3GlobalConfig.m.xFree(p);
  24947. }
  24948. }
  24949. /*
  24950. ** Add the size of memory allocation "p" to the count in
  24951. ** *db->pnBytesFreed.
  24952. */
  24953. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  24954. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  24955. }
  24956. /*
  24957. ** Free memory that might be associated with a particular database
  24958. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  24959. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  24960. */
  24961. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  24962. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  24963. assert( p!=0 );
  24964. if( db ){
  24965. if( db->pnBytesFreed ){
  24966. measureAllocationSize(db, p);
  24967. return;
  24968. }
  24969. if( isLookaside(db, p) ){
  24970. LookasideSlot *pBuf = (LookasideSlot*)p;
  24971. #ifdef SQLITE_DEBUG
  24972. /* Trash all content in the buffer being freed */
  24973. memset(p, 0xaa, db->lookaside.sz);
  24974. #endif
  24975. pBuf->pNext = db->lookaside.pFree;
  24976. db->lookaside.pFree = pBuf;
  24977. return;
  24978. }
  24979. }
  24980. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24981. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24982. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  24983. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  24984. sqlite3_free(p);
  24985. }
  24986. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  24987. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  24988. if( p ) sqlite3DbFreeNN(db, p);
  24989. }
  24990. /*
  24991. ** Change the size of an existing memory allocation
  24992. */
  24993. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  24994. int nOld, nNew, nDiff;
  24995. void *pNew;
  24996. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  24997. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  24998. if( pOld==0 ){
  24999. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  25000. }
  25001. if( nBytes==0 ){
  25002. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  25003. return 0;
  25004. }
  25005. if( nBytes>=0x7fffff00 ){
  25006. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  25007. return 0;
  25008. }
  25009. nOld = sqlite3MallocSize(pOld);
  25010. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  25011. ** argument to xRealloc is always a value returned by a prior call to
  25012. ** xRoundup. */
  25013. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  25014. if( nOld==nNew ){
  25015. pNew = pOld;
  25016. }else if( sqlite3GlobalConfig.bMemstat ){
  25017. sqlite3_mutex_enter(mem0.mutex);
  25018. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  25019. nDiff = nNew - nOld;
  25020. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  25021. mem0.alarmThreshold-nDiff ){
  25022. sqlite3MallocAlarm(nDiff);
  25023. }
  25024. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25025. if( pNew==0 && mem0.alarmThreshold>0 ){
  25026. sqlite3MallocAlarm((int)nBytes);
  25027. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25028. }
  25029. if( pNew ){
  25030. nNew = sqlite3MallocSize(pNew);
  25031. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  25032. }
  25033. sqlite3_mutex_leave(mem0.mutex);
  25034. }else{
  25035. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25036. }
  25037. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  25038. return pNew;
  25039. }
  25040. /*
  25041. ** The public interface to sqlite3Realloc. Make sure that the memory
  25042. ** subsystem is initialized prior to invoking sqliteRealloc.
  25043. */
  25044. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  25045. #ifndef SQLITE_OMIT_AUTOINIT
  25046. if( sqlite3_initialize() ) return 0;
  25047. #endif
  25048. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  25049. return sqlite3Realloc(pOld, n);
  25050. }
  25051. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  25052. #ifndef SQLITE_OMIT_AUTOINIT
  25053. if( sqlite3_initialize() ) return 0;
  25054. #endif
  25055. return sqlite3Realloc(pOld, n);
  25056. }
  25057. /*
  25058. ** Allocate and zero memory.
  25059. */
  25060. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  25061. void *p = sqlite3Malloc(n);
  25062. if( p ){
  25063. memset(p, 0, (size_t)n);
  25064. }
  25065. return p;
  25066. }
  25067. /*
  25068. ** Allocate and zero memory. If the allocation fails, make
  25069. ** the mallocFailed flag in the connection pointer.
  25070. */
  25071. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  25072. void *p;
  25073. testcase( db==0 );
  25074. p = sqlite3DbMallocRaw(db, n);
  25075. if( p ) memset(p, 0, (size_t)n);
  25076. return p;
  25077. }
  25078. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  25079. ** slower case when the allocation cannot be fulfilled using lookaside.
  25080. */
  25081. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  25082. void *p;
  25083. assert( db!=0 );
  25084. p = sqlite3Malloc(n);
  25085. if( !p ) sqlite3OomFault(db);
  25086. sqlite3MemdebugSetType(p,
  25087. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  25088. return p;
  25089. }
  25090. /*
  25091. ** Allocate memory, either lookaside (if possible) or heap.
  25092. ** If the allocation fails, set the mallocFailed flag in
  25093. ** the connection pointer.
  25094. **
  25095. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  25096. ** failure on the same database connection) then always return 0.
  25097. ** Hence for a particular database connection, once malloc starts
  25098. ** failing, it fails consistently until mallocFailed is reset.
  25099. ** This is an important assumption. There are many places in the
  25100. ** code that do things like this:
  25101. **
  25102. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  25103. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  25104. ** if( b ) a[10] = 9;
  25105. **
  25106. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  25107. ** that all prior mallocs (ex: "a") worked too.
  25108. **
  25109. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  25110. ** not a NULL pointer.
  25111. */
  25112. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  25113. void *p;
  25114. if( db ) return sqlite3DbMallocRawNN(db, n);
  25115. p = sqlite3Malloc(n);
  25116. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25117. return p;
  25118. }
  25119. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  25120. #ifndef SQLITE_OMIT_LOOKASIDE
  25121. LookasideSlot *pBuf;
  25122. assert( db!=0 );
  25123. assert( sqlite3_mutex_held(db->mutex) );
  25124. assert( db->pnBytesFreed==0 );
  25125. if( db->lookaside.bDisable==0 ){
  25126. assert( db->mallocFailed==0 );
  25127. if( n>db->lookaside.sz ){
  25128. db->lookaside.anStat[1]++;
  25129. }else if( (pBuf = db->lookaside.pFree)!=0 ){
  25130. db->lookaside.pFree = pBuf->pNext;
  25131. db->lookaside.anStat[0]++;
  25132. return (void*)pBuf;
  25133. }else if( (pBuf = db->lookaside.pInit)!=0 ){
  25134. db->lookaside.pInit = pBuf->pNext;
  25135. db->lookaside.anStat[0]++;
  25136. return (void*)pBuf;
  25137. }else{
  25138. db->lookaside.anStat[2]++;
  25139. }
  25140. }else if( db->mallocFailed ){
  25141. return 0;
  25142. }
  25143. #else
  25144. assert( db!=0 );
  25145. assert( sqlite3_mutex_held(db->mutex) );
  25146. assert( db->pnBytesFreed==0 );
  25147. if( db->mallocFailed ){
  25148. return 0;
  25149. }
  25150. #endif
  25151. return dbMallocRawFinish(db, n);
  25152. }
  25153. /* Forward declaration */
  25154. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  25155. /*
  25156. ** Resize the block of memory pointed to by p to n bytes. If the
  25157. ** resize fails, set the mallocFailed flag in the connection object.
  25158. */
  25159. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  25160. assert( db!=0 );
  25161. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  25162. assert( sqlite3_mutex_held(db->mutex) );
  25163. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  25164. return dbReallocFinish(db, p, n);
  25165. }
  25166. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  25167. void *pNew = 0;
  25168. assert( db!=0 );
  25169. assert( p!=0 );
  25170. if( db->mallocFailed==0 ){
  25171. if( isLookaside(db, p) ){
  25172. pNew = sqlite3DbMallocRawNN(db, n);
  25173. if( pNew ){
  25174. memcpy(pNew, p, db->lookaside.sz);
  25175. sqlite3DbFree(db, p);
  25176. }
  25177. }else{
  25178. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25179. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25180. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25181. pNew = sqlite3_realloc64(p, n);
  25182. if( !pNew ){
  25183. sqlite3OomFault(db);
  25184. }
  25185. sqlite3MemdebugSetType(pNew,
  25186. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  25187. }
  25188. }
  25189. return pNew;
  25190. }
  25191. /*
  25192. ** Attempt to reallocate p. If the reallocation fails, then free p
  25193. ** and set the mallocFailed flag in the database connection.
  25194. */
  25195. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  25196. void *pNew;
  25197. pNew = sqlite3DbRealloc(db, p, n);
  25198. if( !pNew ){
  25199. sqlite3DbFree(db, p);
  25200. }
  25201. return pNew;
  25202. }
  25203. /*
  25204. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  25205. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  25206. ** is because when memory debugging is turned on, these two functions are
  25207. ** called via macros that record the current file and line number in the
  25208. ** ThreadData structure.
  25209. */
  25210. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  25211. char *zNew;
  25212. size_t n;
  25213. if( z==0 ){
  25214. return 0;
  25215. }
  25216. n = strlen(z) + 1;
  25217. zNew = sqlite3DbMallocRaw(db, n);
  25218. if( zNew ){
  25219. memcpy(zNew, z, n);
  25220. }
  25221. return zNew;
  25222. }
  25223. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  25224. char *zNew;
  25225. assert( db!=0 );
  25226. if( z==0 ){
  25227. return 0;
  25228. }
  25229. assert( (n&0x7fffffff)==n );
  25230. zNew = sqlite3DbMallocRawNN(db, n+1);
  25231. if( zNew ){
  25232. memcpy(zNew, z, (size_t)n);
  25233. zNew[n] = 0;
  25234. }
  25235. return zNew;
  25236. }
  25237. /*
  25238. ** The text between zStart and zEnd represents a phrase within a larger
  25239. ** SQL statement. Make a copy of this phrase in space obtained form
  25240. ** sqlite3DbMalloc(). Omit leading and trailing whitespace.
  25241. */
  25242. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  25243. int n;
  25244. while( sqlite3Isspace(zStart[0]) ) zStart++;
  25245. n = (int)(zEnd - zStart);
  25246. while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
  25247. return sqlite3DbStrNDup(db, zStart, n);
  25248. }
  25249. /*
  25250. ** Free any prior content in *pz and replace it with a copy of zNew.
  25251. */
  25252. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  25253. sqlite3DbFree(db, *pz);
  25254. *pz = sqlite3DbStrDup(db, zNew);
  25255. }
  25256. /*
  25257. ** Call this routine to record the fact that an OOM (out-of-memory) error
  25258. ** has happened. This routine will set db->mallocFailed, and also
  25259. ** temporarily disable the lookaside memory allocator and interrupt
  25260. ** any running VDBEs.
  25261. */
  25262. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  25263. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  25264. db->mallocFailed = 1;
  25265. if( db->nVdbeExec>0 ){
  25266. db->u1.isInterrupted = 1;
  25267. }
  25268. db->lookaside.bDisable++;
  25269. }
  25270. }
  25271. /*
  25272. ** This routine reactivates the memory allocator and clears the
  25273. ** db->mallocFailed flag as necessary.
  25274. **
  25275. ** The memory allocator is not restarted if there are running
  25276. ** VDBEs.
  25277. */
  25278. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  25279. if( db->mallocFailed && db->nVdbeExec==0 ){
  25280. db->mallocFailed = 0;
  25281. db->u1.isInterrupted = 0;
  25282. assert( db->lookaside.bDisable>0 );
  25283. db->lookaside.bDisable--;
  25284. }
  25285. }
  25286. /*
  25287. ** Take actions at the end of an API call to indicate an OOM error
  25288. */
  25289. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  25290. sqlite3OomClear(db);
  25291. sqlite3Error(db, SQLITE_NOMEM);
  25292. return SQLITE_NOMEM_BKPT;
  25293. }
  25294. /*
  25295. ** This function must be called before exiting any API function (i.e.
  25296. ** returning control to the user) that has called sqlite3_malloc or
  25297. ** sqlite3_realloc.
  25298. **
  25299. ** The returned value is normally a copy of the second argument to this
  25300. ** function. However, if a malloc() failure has occurred since the previous
  25301. ** invocation SQLITE_NOMEM is returned instead.
  25302. **
  25303. ** If an OOM as occurred, then the connection error-code (the value
  25304. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  25305. */
  25306. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  25307. /* If the db handle must hold the connection handle mutex here.
  25308. ** Otherwise the read (and possible write) of db->mallocFailed
  25309. ** is unsafe, as is the call to sqlite3Error().
  25310. */
  25311. assert( db!=0 );
  25312. assert( sqlite3_mutex_held(db->mutex) );
  25313. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  25314. return apiOomError(db);
  25315. }
  25316. return rc & db->errMask;
  25317. }
  25318. /************** End of malloc.c **********************************************/
  25319. /************** Begin file printf.c ******************************************/
  25320. /*
  25321. ** The "printf" code that follows dates from the 1980's. It is in
  25322. ** the public domain.
  25323. **
  25324. **************************************************************************
  25325. **
  25326. ** This file contains code for a set of "printf"-like routines. These
  25327. ** routines format strings much like the printf() from the standard C
  25328. ** library, though the implementation here has enhancements to support
  25329. ** SQLite.
  25330. */
  25331. /* #include "sqliteInt.h" */
  25332. /*
  25333. ** Conversion types fall into various categories as defined by the
  25334. ** following enumeration.
  25335. */
  25336. #define etRADIX 0 /* non-decimal integer types. %x %o */
  25337. #define etFLOAT 1 /* Floating point. %f */
  25338. #define etEXP 2 /* Exponentional notation. %e and %E */
  25339. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  25340. #define etSIZE 4 /* Return number of characters processed so far. %n */
  25341. #define etSTRING 5 /* Strings. %s */
  25342. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  25343. #define etPERCENT 7 /* Percent symbol. %% */
  25344. #define etCHARX 8 /* Characters. %c */
  25345. /* The rest are extensions, not normally found in printf() */
  25346. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  25347. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  25348. NULL pointers replaced by SQL NULL. %Q */
  25349. #define etTOKEN 11 /* a pointer to a Token structure */
  25350. #define etSRCLIST 12 /* a pointer to a SrcList */
  25351. #define etPOINTER 13 /* The %p conversion */
  25352. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  25353. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  25354. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  25355. #define etINVALID 17 /* Any unrecognized conversion type */
  25356. /*
  25357. ** An "etByte" is an 8-bit unsigned value.
  25358. */
  25359. typedef unsigned char etByte;
  25360. /*
  25361. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  25362. ** by an instance of the following structure
  25363. */
  25364. typedef struct et_info { /* Information about each format field */
  25365. char fmttype; /* The format field code letter */
  25366. etByte base; /* The base for radix conversion */
  25367. etByte flags; /* One or more of FLAG_ constants below */
  25368. etByte type; /* Conversion paradigm */
  25369. etByte charset; /* Offset into aDigits[] of the digits string */
  25370. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  25371. } et_info;
  25372. /*
  25373. ** Allowed values for et_info.flags
  25374. */
  25375. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  25376. #define FLAG_STRING 4 /* Allow infinite precision */
  25377. /*
  25378. ** The following table is searched linearly, so it is good to put the
  25379. ** most frequently used conversion types first.
  25380. */
  25381. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  25382. static const char aPrefix[] = "-x0\000X0";
  25383. static const et_info fmtinfo[] = {
  25384. { 'd', 10, 1, etDECIMAL, 0, 0 },
  25385. { 's', 0, 4, etSTRING, 0, 0 },
  25386. { 'g', 0, 1, etGENERIC, 30, 0 },
  25387. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  25388. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  25389. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  25390. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  25391. { 'c', 0, 0, etCHARX, 0, 0 },
  25392. { 'o', 8, 0, etRADIX, 0, 2 },
  25393. { 'u', 10, 0, etDECIMAL, 0, 0 },
  25394. { 'x', 16, 0, etRADIX, 16, 1 },
  25395. { 'X', 16, 0, etRADIX, 0, 4 },
  25396. #ifndef SQLITE_OMIT_FLOATING_POINT
  25397. { 'f', 0, 1, etFLOAT, 0, 0 },
  25398. { 'e', 0, 1, etEXP, 30, 0 },
  25399. { 'E', 0, 1, etEXP, 14, 0 },
  25400. { 'G', 0, 1, etGENERIC, 14, 0 },
  25401. #endif
  25402. { 'i', 10, 1, etDECIMAL, 0, 0 },
  25403. { 'n', 0, 0, etSIZE, 0, 0 },
  25404. { '%', 0, 0, etPERCENT, 0, 0 },
  25405. { 'p', 16, 0, etPOINTER, 0, 1 },
  25406. /* All the rest are undocumented and are for internal use only */
  25407. { 'T', 0, 0, etTOKEN, 0, 0 },
  25408. { 'S', 0, 0, etSRCLIST, 0, 0 },
  25409. { 'r', 10, 1, etORDINAL, 0, 0 },
  25410. };
  25411. /*
  25412. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  25413. ** conversions will work.
  25414. */
  25415. #ifndef SQLITE_OMIT_FLOATING_POINT
  25416. /*
  25417. ** "*val" is a double such that 0.1 <= *val < 10.0
  25418. ** Return the ascii code for the leading digit of *val, then
  25419. ** multiply "*val" by 10.0 to renormalize.
  25420. **
  25421. ** Example:
  25422. ** input: *val = 3.14159
  25423. ** output: *val = 1.4159 function return = '3'
  25424. **
  25425. ** The counter *cnt is incremented each time. After counter exceeds
  25426. ** 16 (the number of significant digits in a 64-bit float) '0' is
  25427. ** always returned.
  25428. */
  25429. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  25430. int digit;
  25431. LONGDOUBLE_TYPE d;
  25432. if( (*cnt)<=0 ) return '0';
  25433. (*cnt)--;
  25434. digit = (int)*val;
  25435. d = digit;
  25436. digit += '0';
  25437. *val = (*val - d)*10.0;
  25438. return (char)digit;
  25439. }
  25440. #endif /* SQLITE_OMIT_FLOATING_POINT */
  25441. /*
  25442. ** Set the StrAccum object to an error mode.
  25443. */
  25444. static void setStrAccumError(StrAccum *p, u8 eError){
  25445. assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
  25446. p->accError = eError;
  25447. p->nAlloc = 0;
  25448. }
  25449. /*
  25450. ** Extra argument values from a PrintfArguments object
  25451. */
  25452. static sqlite3_int64 getIntArg(PrintfArguments *p){
  25453. if( p->nArg<=p->nUsed ) return 0;
  25454. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  25455. }
  25456. static double getDoubleArg(PrintfArguments *p){
  25457. if( p->nArg<=p->nUsed ) return 0.0;
  25458. return sqlite3_value_double(p->apArg[p->nUsed++]);
  25459. }
  25460. static char *getTextArg(PrintfArguments *p){
  25461. if( p->nArg<=p->nUsed ) return 0;
  25462. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  25463. }
  25464. /*
  25465. ** On machines with a small stack size, you can redefine the
  25466. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  25467. */
  25468. #ifndef SQLITE_PRINT_BUF_SIZE
  25469. # define SQLITE_PRINT_BUF_SIZE 70
  25470. #endif
  25471. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  25472. /*
  25473. ** Render a string given by "fmt" into the StrAccum object.
  25474. */
  25475. SQLITE_API void sqlite3_str_vappendf(
  25476. sqlite3_str *pAccum, /* Accumulate results here */
  25477. const char *fmt, /* Format string */
  25478. va_list ap /* arguments */
  25479. ){
  25480. int c; /* Next character in the format string */
  25481. char *bufpt; /* Pointer to the conversion buffer */
  25482. int precision; /* Precision of the current field */
  25483. int length; /* Length of the field */
  25484. int idx; /* A general purpose loop counter */
  25485. int width; /* Width of the current field */
  25486. etByte flag_leftjustify; /* True if "-" flag is present */
  25487. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  25488. etByte flag_alternateform; /* True if "#" flag is present */
  25489. etByte flag_altform2; /* True if "!" flag is present */
  25490. etByte flag_zeropad; /* True if field width constant starts with zero */
  25491. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  25492. etByte done; /* Loop termination flag */
  25493. etByte cThousand; /* Thousands separator for %d and %u */
  25494. etByte xtype = etINVALID; /* Conversion paradigm */
  25495. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  25496. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  25497. sqlite_uint64 longvalue; /* Value for integer types */
  25498. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  25499. const et_info *infop; /* Pointer to the appropriate info structure */
  25500. char *zOut; /* Rendering buffer */
  25501. int nOut; /* Size of the rendering buffer */
  25502. char *zExtra = 0; /* Malloced memory used by some conversion */
  25503. #ifndef SQLITE_OMIT_FLOATING_POINT
  25504. int exp, e2; /* exponent of real numbers */
  25505. int nsd; /* Number of significant digits returned */
  25506. double rounder; /* Used for rounding floating point values */
  25507. etByte flag_dp; /* True if decimal point should be shown */
  25508. etByte flag_rtz; /* True if trailing zeros should be removed */
  25509. #endif
  25510. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  25511. char buf[etBUFSIZE]; /* Conversion buffer */
  25512. /* pAccum never starts out with an empty buffer that was obtained from
  25513. ** malloc(). This precondition is required by the mprintf("%z...")
  25514. ** optimization. */
  25515. assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  25516. bufpt = 0;
  25517. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  25518. pArgList = va_arg(ap, PrintfArguments*);
  25519. bArgList = 1;
  25520. }else{
  25521. bArgList = 0;
  25522. }
  25523. for(; (c=(*fmt))!=0; ++fmt){
  25524. if( c!='%' ){
  25525. bufpt = (char *)fmt;
  25526. #if HAVE_STRCHRNUL
  25527. fmt = strchrnul(fmt, '%');
  25528. #else
  25529. do{ fmt++; }while( *fmt && *fmt != '%' );
  25530. #endif
  25531. sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
  25532. if( *fmt==0 ) break;
  25533. }
  25534. if( (c=(*++fmt))==0 ){
  25535. sqlite3_str_append(pAccum, "%", 1);
  25536. break;
  25537. }
  25538. /* Find out what flags are present */
  25539. flag_leftjustify = flag_prefix = cThousand =
  25540. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  25541. done = 0;
  25542. do{
  25543. switch( c ){
  25544. case '-': flag_leftjustify = 1; break;
  25545. case '+': flag_prefix = '+'; break;
  25546. case ' ': flag_prefix = ' '; break;
  25547. case '#': flag_alternateform = 1; break;
  25548. case '!': flag_altform2 = 1; break;
  25549. case '0': flag_zeropad = 1; break;
  25550. case ',': cThousand = ','; break;
  25551. default: done = 1; break;
  25552. }
  25553. }while( !done && (c=(*++fmt))!=0 );
  25554. /* Get the field width */
  25555. if( c=='*' ){
  25556. if( bArgList ){
  25557. width = (int)getIntArg(pArgList);
  25558. }else{
  25559. width = va_arg(ap,int);
  25560. }
  25561. if( width<0 ){
  25562. flag_leftjustify = 1;
  25563. width = width >= -2147483647 ? -width : 0;
  25564. }
  25565. c = *++fmt;
  25566. }else{
  25567. unsigned wx = 0;
  25568. while( c>='0' && c<='9' ){
  25569. wx = wx*10 + c - '0';
  25570. c = *++fmt;
  25571. }
  25572. testcase( wx>0x7fffffff );
  25573. width = wx & 0x7fffffff;
  25574. }
  25575. assert( width>=0 );
  25576. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  25577. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  25578. width = SQLITE_PRINTF_PRECISION_LIMIT;
  25579. }
  25580. #endif
  25581. /* Get the precision */
  25582. if( c=='.' ){
  25583. c = *++fmt;
  25584. if( c=='*' ){
  25585. if( bArgList ){
  25586. precision = (int)getIntArg(pArgList);
  25587. }else{
  25588. precision = va_arg(ap,int);
  25589. }
  25590. c = *++fmt;
  25591. if( precision<0 ){
  25592. precision = precision >= -2147483647 ? -precision : -1;
  25593. }
  25594. }else{
  25595. unsigned px = 0;
  25596. while( c>='0' && c<='9' ){
  25597. px = px*10 + c - '0';
  25598. c = *++fmt;
  25599. }
  25600. testcase( px>0x7fffffff );
  25601. precision = px & 0x7fffffff;
  25602. }
  25603. }else{
  25604. precision = -1;
  25605. }
  25606. assert( precision>=(-1) );
  25607. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  25608. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  25609. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  25610. }
  25611. #endif
  25612. /* Get the conversion type modifier */
  25613. if( c=='l' ){
  25614. flag_long = 1;
  25615. c = *++fmt;
  25616. if( c=='l' ){
  25617. flag_long = 2;
  25618. c = *++fmt;
  25619. }
  25620. }else{
  25621. flag_long = 0;
  25622. }
  25623. /* Fetch the info entry for the field */
  25624. infop = &fmtinfo[0];
  25625. xtype = etINVALID;
  25626. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  25627. if( c==fmtinfo[idx].fmttype ){
  25628. infop = &fmtinfo[idx];
  25629. xtype = infop->type;
  25630. break;
  25631. }
  25632. }
  25633. /*
  25634. ** At this point, variables are initialized as follows:
  25635. **
  25636. ** flag_alternateform TRUE if a '#' is present.
  25637. ** flag_altform2 TRUE if a '!' is present.
  25638. ** flag_prefix '+' or ' ' or zero
  25639. ** flag_leftjustify TRUE if a '-' is present or if the
  25640. ** field width was negative.
  25641. ** flag_zeropad TRUE if the width began with 0.
  25642. ** flag_long 1 for "l", 2 for "ll"
  25643. ** width The specified field width. This is
  25644. ** always non-negative. Zero is the default.
  25645. ** precision The specified precision. The default
  25646. ** is -1.
  25647. ** xtype The class of the conversion.
  25648. ** infop Pointer to the appropriate info struct.
  25649. */
  25650. switch( xtype ){
  25651. case etPOINTER:
  25652. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  25653. sizeof(char*)==sizeof(long int) ? 1 : 0;
  25654. /* Fall through into the next case */
  25655. case etORDINAL:
  25656. case etRADIX:
  25657. cThousand = 0;
  25658. /* Fall through into the next case */
  25659. case etDECIMAL:
  25660. if( infop->flags & FLAG_SIGNED ){
  25661. i64 v;
  25662. if( bArgList ){
  25663. v = getIntArg(pArgList);
  25664. }else if( flag_long ){
  25665. if( flag_long==2 ){
  25666. v = va_arg(ap,i64) ;
  25667. }else{
  25668. v = va_arg(ap,long int);
  25669. }
  25670. }else{
  25671. v = va_arg(ap,int);
  25672. }
  25673. if( v<0 ){
  25674. if( v==SMALLEST_INT64 ){
  25675. longvalue = ((u64)1)<<63;
  25676. }else{
  25677. longvalue = -v;
  25678. }
  25679. prefix = '-';
  25680. }else{
  25681. longvalue = v;
  25682. prefix = flag_prefix;
  25683. }
  25684. }else{
  25685. if( bArgList ){
  25686. longvalue = (u64)getIntArg(pArgList);
  25687. }else if( flag_long ){
  25688. if( flag_long==2 ){
  25689. longvalue = va_arg(ap,u64);
  25690. }else{
  25691. longvalue = va_arg(ap,unsigned long int);
  25692. }
  25693. }else{
  25694. longvalue = va_arg(ap,unsigned int);
  25695. }
  25696. prefix = 0;
  25697. }
  25698. if( longvalue==0 ) flag_alternateform = 0;
  25699. if( flag_zeropad && precision<width-(prefix!=0) ){
  25700. precision = width-(prefix!=0);
  25701. }
  25702. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  25703. nOut = etBUFSIZE;
  25704. zOut = buf;
  25705. }else{
  25706. u64 n = (u64)precision + 10 + precision/3;
  25707. zOut = zExtra = sqlite3Malloc( n );
  25708. if( zOut==0 ){
  25709. setStrAccumError(pAccum, SQLITE_NOMEM);
  25710. return;
  25711. }
  25712. nOut = (int)n;
  25713. }
  25714. bufpt = &zOut[nOut-1];
  25715. if( xtype==etORDINAL ){
  25716. static const char zOrd[] = "thstndrd";
  25717. int x = (int)(longvalue % 10);
  25718. if( x>=4 || (longvalue/10)%10==1 ){
  25719. x = 0;
  25720. }
  25721. *(--bufpt) = zOrd[x*2+1];
  25722. *(--bufpt) = zOrd[x*2];
  25723. }
  25724. {
  25725. const char *cset = &aDigits[infop->charset];
  25726. u8 base = infop->base;
  25727. do{ /* Convert to ascii */
  25728. *(--bufpt) = cset[longvalue%base];
  25729. longvalue = longvalue/base;
  25730. }while( longvalue>0 );
  25731. }
  25732. length = (int)(&zOut[nOut-1]-bufpt);
  25733. while( precision>length ){
  25734. *(--bufpt) = '0'; /* Zero pad */
  25735. length++;
  25736. }
  25737. if( cThousand ){
  25738. int nn = (length - 1)/3; /* Number of "," to insert */
  25739. int ix = (length - 1)%3 + 1;
  25740. bufpt -= nn;
  25741. for(idx=0; nn>0; idx++){
  25742. bufpt[idx] = bufpt[idx+nn];
  25743. ix--;
  25744. if( ix==0 ){
  25745. bufpt[++idx] = cThousand;
  25746. nn--;
  25747. ix = 3;
  25748. }
  25749. }
  25750. }
  25751. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  25752. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  25753. const char *pre;
  25754. char x;
  25755. pre = &aPrefix[infop->prefix];
  25756. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  25757. }
  25758. length = (int)(&zOut[nOut-1]-bufpt);
  25759. break;
  25760. case etFLOAT:
  25761. case etEXP:
  25762. case etGENERIC:
  25763. if( bArgList ){
  25764. realvalue = getDoubleArg(pArgList);
  25765. }else{
  25766. realvalue = va_arg(ap,double);
  25767. }
  25768. #ifdef SQLITE_OMIT_FLOATING_POINT
  25769. length = 0;
  25770. #else
  25771. if( precision<0 ) precision = 6; /* Set default precision */
  25772. if( realvalue<0.0 ){
  25773. realvalue = -realvalue;
  25774. prefix = '-';
  25775. }else{
  25776. prefix = flag_prefix;
  25777. }
  25778. if( xtype==etGENERIC && precision>0 ) precision--;
  25779. testcase( precision>0xfff );
  25780. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  25781. if( xtype==etFLOAT ) realvalue += rounder;
  25782. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  25783. exp = 0;
  25784. if( sqlite3IsNaN((double)realvalue) ){
  25785. bufpt = "NaN";
  25786. length = 3;
  25787. break;
  25788. }
  25789. if( realvalue>0.0 ){
  25790. LONGDOUBLE_TYPE scale = 1.0;
  25791. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  25792. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  25793. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  25794. realvalue /= scale;
  25795. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  25796. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  25797. if( exp>350 ){
  25798. bufpt = buf;
  25799. buf[0] = prefix;
  25800. memcpy(buf+(prefix!=0),"Inf",4);
  25801. length = 3+(prefix!=0);
  25802. break;
  25803. }
  25804. }
  25805. bufpt = buf;
  25806. /*
  25807. ** If the field type is etGENERIC, then convert to either etEXP
  25808. ** or etFLOAT, as appropriate.
  25809. */
  25810. if( xtype!=etFLOAT ){
  25811. realvalue += rounder;
  25812. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  25813. }
  25814. if( xtype==etGENERIC ){
  25815. flag_rtz = !flag_alternateform;
  25816. if( exp<-4 || exp>precision ){
  25817. xtype = etEXP;
  25818. }else{
  25819. precision = precision - exp;
  25820. xtype = etFLOAT;
  25821. }
  25822. }else{
  25823. flag_rtz = flag_altform2;
  25824. }
  25825. if( xtype==etEXP ){
  25826. e2 = 0;
  25827. }else{
  25828. e2 = exp;
  25829. }
  25830. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  25831. bufpt = zExtra
  25832. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  25833. if( bufpt==0 ){
  25834. setStrAccumError(pAccum, SQLITE_NOMEM);
  25835. return;
  25836. }
  25837. }
  25838. zOut = bufpt;
  25839. nsd = 16 + flag_altform2*10;
  25840. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  25841. /* The sign in front of the number */
  25842. if( prefix ){
  25843. *(bufpt++) = prefix;
  25844. }
  25845. /* Digits prior to the decimal point */
  25846. if( e2<0 ){
  25847. *(bufpt++) = '0';
  25848. }else{
  25849. for(; e2>=0; e2--){
  25850. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  25851. }
  25852. }
  25853. /* The decimal point */
  25854. if( flag_dp ){
  25855. *(bufpt++) = '.';
  25856. }
  25857. /* "0" digits after the decimal point but before the first
  25858. ** significant digit of the number */
  25859. for(e2++; e2<0; precision--, e2++){
  25860. assert( precision>0 );
  25861. *(bufpt++) = '0';
  25862. }
  25863. /* Significant digits after the decimal point */
  25864. while( (precision--)>0 ){
  25865. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  25866. }
  25867. /* Remove trailing zeros and the "." if no digits follow the "." */
  25868. if( flag_rtz && flag_dp ){
  25869. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  25870. assert( bufpt>zOut );
  25871. if( bufpt[-1]=='.' ){
  25872. if( flag_altform2 ){
  25873. *(bufpt++) = '0';
  25874. }else{
  25875. *(--bufpt) = 0;
  25876. }
  25877. }
  25878. }
  25879. /* Add the "eNNN" suffix */
  25880. if( xtype==etEXP ){
  25881. *(bufpt++) = aDigits[infop->charset];
  25882. if( exp<0 ){
  25883. *(bufpt++) = '-'; exp = -exp;
  25884. }else{
  25885. *(bufpt++) = '+';
  25886. }
  25887. if( exp>=100 ){
  25888. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  25889. exp %= 100;
  25890. }
  25891. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  25892. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  25893. }
  25894. *bufpt = 0;
  25895. /* The converted number is in buf[] and zero terminated. Output it.
  25896. ** Note that the number is in the usual order, not reversed as with
  25897. ** integer conversions. */
  25898. length = (int)(bufpt-zOut);
  25899. bufpt = zOut;
  25900. /* Special case: Add leading zeros if the flag_zeropad flag is
  25901. ** set and we are not left justified */
  25902. if( flag_zeropad && !flag_leftjustify && length < width){
  25903. int i;
  25904. int nPad = width - length;
  25905. for(i=width; i>=nPad; i--){
  25906. bufpt[i] = bufpt[i-nPad];
  25907. }
  25908. i = prefix!=0;
  25909. while( nPad-- ) bufpt[i++] = '0';
  25910. length = width;
  25911. }
  25912. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  25913. break;
  25914. case etSIZE:
  25915. if( !bArgList ){
  25916. *(va_arg(ap,int*)) = pAccum->nChar;
  25917. }
  25918. length = width = 0;
  25919. break;
  25920. case etPERCENT:
  25921. buf[0] = '%';
  25922. bufpt = buf;
  25923. length = 1;
  25924. break;
  25925. case etCHARX:
  25926. if( bArgList ){
  25927. bufpt = getTextArg(pArgList);
  25928. length = 1;
  25929. if( bufpt ){
  25930. buf[0] = c = *(bufpt++);
  25931. if( (c&0xc0)==0xc0 ){
  25932. while( length<4 && (bufpt[0]&0xc0)==0x80 ){
  25933. buf[length++] = *(bufpt++);
  25934. }
  25935. }
  25936. }else{
  25937. buf[0] = 0;
  25938. }
  25939. }else{
  25940. unsigned int ch = va_arg(ap,unsigned int);
  25941. if( ch<0x00080 ){
  25942. buf[0] = ch & 0xff;
  25943. length = 1;
  25944. }else if( ch<0x00800 ){
  25945. buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
  25946. buf[1] = 0x80 + (u8)(ch & 0x3f);
  25947. length = 2;
  25948. }else if( ch<0x10000 ){
  25949. buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
  25950. buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
  25951. buf[2] = 0x80 + (u8)(ch & 0x3f);
  25952. length = 3;
  25953. }else{
  25954. buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
  25955. buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
  25956. buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
  25957. buf[3] = 0x80 + (u8)(ch & 0x3f);
  25958. length = 4;
  25959. }
  25960. }
  25961. if( precision>1 ){
  25962. width -= precision-1;
  25963. if( width>1 && !flag_leftjustify ){
  25964. sqlite3_str_appendchar(pAccum, width-1, ' ');
  25965. width = 0;
  25966. }
  25967. while( precision-- > 1 ){
  25968. sqlite3_str_append(pAccum, buf, length);
  25969. }
  25970. }
  25971. bufpt = buf;
  25972. flag_altform2 = 1;
  25973. goto adjust_width_for_utf8;
  25974. case etSTRING:
  25975. case etDYNSTRING:
  25976. if( bArgList ){
  25977. bufpt = getTextArg(pArgList);
  25978. xtype = etSTRING;
  25979. }else{
  25980. bufpt = va_arg(ap,char*);
  25981. }
  25982. if( bufpt==0 ){
  25983. bufpt = "";
  25984. }else if( xtype==etDYNSTRING ){
  25985. if( pAccum->nChar==0 && pAccum->mxAlloc && width==0 && precision<0 ){
  25986. /* Special optimization for sqlite3_mprintf("%z..."):
  25987. ** Extend an existing memory allocation rather than creating
  25988. ** a new one. */
  25989. assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  25990. pAccum->zText = bufpt;
  25991. pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
  25992. pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
  25993. pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
  25994. length = 0;
  25995. break;
  25996. }
  25997. zExtra = bufpt;
  25998. }
  25999. if( precision>=0 ){
  26000. if( flag_altform2 ){
  26001. /* Set length to the number of bytes needed in order to display
  26002. ** precision characters */
  26003. unsigned char *z = (unsigned char*)bufpt;
  26004. while( precision-- > 0 && z[0] ){
  26005. SQLITE_SKIP_UTF8(z);
  26006. }
  26007. length = (int)(z - (unsigned char*)bufpt);
  26008. }else{
  26009. for(length=0; length<precision && bufpt[length]; length++){}
  26010. }
  26011. }else{
  26012. length = 0x7fffffff & (int)strlen(bufpt);
  26013. }
  26014. adjust_width_for_utf8:
  26015. if( flag_altform2 && width>0 ){
  26016. /* Adjust width to account for extra bytes in UTF-8 characters */
  26017. int ii = length - 1;
  26018. while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
  26019. }
  26020. break;
  26021. case etSQLESCAPE: /* %q: Escape ' characters */
  26022. case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
  26023. case etSQLESCAPE3: { /* %w: Escape " characters */
  26024. int i, j, k, n, isnull;
  26025. int needQuote;
  26026. char ch;
  26027. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  26028. char *escarg;
  26029. if( bArgList ){
  26030. escarg = getTextArg(pArgList);
  26031. }else{
  26032. escarg = va_arg(ap,char*);
  26033. }
  26034. isnull = escarg==0;
  26035. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  26036. /* For %q, %Q, and %w, the precision is the number of byte (or
  26037. ** characters if the ! flags is present) to use from the input.
  26038. ** Because of the extra quoting characters inserted, the number
  26039. ** of output characters may be larger than the precision.
  26040. */
  26041. k = precision;
  26042. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  26043. if( ch==q ) n++;
  26044. if( flag_altform2 && (ch&0xc0)==0xc0 ){
  26045. while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
  26046. }
  26047. }
  26048. needQuote = !isnull && xtype==etSQLESCAPE2;
  26049. n += i + 3;
  26050. if( n>etBUFSIZE ){
  26051. bufpt = zExtra = sqlite3Malloc( n );
  26052. if( bufpt==0 ){
  26053. setStrAccumError(pAccum, SQLITE_NOMEM);
  26054. return;
  26055. }
  26056. }else{
  26057. bufpt = buf;
  26058. }
  26059. j = 0;
  26060. if( needQuote ) bufpt[j++] = q;
  26061. k = i;
  26062. for(i=0; i<k; i++){
  26063. bufpt[j++] = ch = escarg[i];
  26064. if( ch==q ) bufpt[j++] = ch;
  26065. }
  26066. if( needQuote ) bufpt[j++] = q;
  26067. bufpt[j] = 0;
  26068. length = j;
  26069. goto adjust_width_for_utf8;
  26070. }
  26071. case etTOKEN: {
  26072. Token *pToken;
  26073. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26074. pToken = va_arg(ap, Token*);
  26075. assert( bArgList==0 );
  26076. if( pToken && pToken->n ){
  26077. sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
  26078. }
  26079. length = width = 0;
  26080. break;
  26081. }
  26082. case etSRCLIST: {
  26083. SrcList *pSrc;
  26084. int k;
  26085. struct SrcList_item *pItem;
  26086. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26087. pSrc = va_arg(ap, SrcList*);
  26088. k = va_arg(ap, int);
  26089. pItem = &pSrc->a[k];
  26090. assert( bArgList==0 );
  26091. assert( k>=0 && k<pSrc->nSrc );
  26092. if( pItem->zDatabase ){
  26093. sqlite3_str_appendall(pAccum, pItem->zDatabase);
  26094. sqlite3_str_append(pAccum, ".", 1);
  26095. }
  26096. sqlite3_str_appendall(pAccum, pItem->zName);
  26097. length = width = 0;
  26098. break;
  26099. }
  26100. default: {
  26101. assert( xtype==etINVALID );
  26102. return;
  26103. }
  26104. }/* End switch over the format type */
  26105. /*
  26106. ** The text of the conversion is pointed to by "bufpt" and is
  26107. ** "length" characters long. The field width is "width". Do
  26108. ** the output. Both length and width are in bytes, not characters,
  26109. ** at this point. If the "!" flag was present on string conversions
  26110. ** indicating that width and precision should be expressed in characters,
  26111. ** then the values have been translated prior to reaching this point.
  26112. */
  26113. width -= length;
  26114. if( width>0 ){
  26115. if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26116. sqlite3_str_append(pAccum, bufpt, length);
  26117. if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26118. }else{
  26119. sqlite3_str_append(pAccum, bufpt, length);
  26120. }
  26121. if( zExtra ){
  26122. sqlite3DbFree(pAccum->db, zExtra);
  26123. zExtra = 0;
  26124. }
  26125. }/* End for loop over the format string */
  26126. } /* End of function */
  26127. /*
  26128. ** Enlarge the memory allocation on a StrAccum object so that it is
  26129. ** able to accept at least N more bytes of text.
  26130. **
  26131. ** Return the number of bytes of text that StrAccum is able to accept
  26132. ** after the attempted enlargement. The value returned might be zero.
  26133. */
  26134. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  26135. char *zNew;
  26136. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  26137. if( p->accError ){
  26138. testcase(p->accError==SQLITE_TOOBIG);
  26139. testcase(p->accError==SQLITE_NOMEM);
  26140. return 0;
  26141. }
  26142. if( p->mxAlloc==0 ){
  26143. N = p->nAlloc - p->nChar - 1;
  26144. setStrAccumError(p, SQLITE_TOOBIG);
  26145. return N;
  26146. }else{
  26147. char *zOld = isMalloced(p) ? p->zText : 0;
  26148. i64 szNew = p->nChar;
  26149. szNew += N + 1;
  26150. if( szNew+p->nChar<=p->mxAlloc ){
  26151. /* Force exponential buffer size growth as long as it does not overflow,
  26152. ** to avoid having to call this routine too often */
  26153. szNew += p->nChar;
  26154. }
  26155. if( szNew > p->mxAlloc ){
  26156. sqlite3_str_reset(p);
  26157. setStrAccumError(p, SQLITE_TOOBIG);
  26158. return 0;
  26159. }else{
  26160. p->nAlloc = (int)szNew;
  26161. }
  26162. if( p->db ){
  26163. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  26164. }else{
  26165. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  26166. }
  26167. if( zNew ){
  26168. assert( p->zText!=0 || p->nChar==0 );
  26169. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  26170. p->zText = zNew;
  26171. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  26172. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26173. }else{
  26174. sqlite3_str_reset(p);
  26175. setStrAccumError(p, SQLITE_NOMEM);
  26176. return 0;
  26177. }
  26178. }
  26179. return N;
  26180. }
  26181. /*
  26182. ** Append N copies of character c to the given string buffer.
  26183. */
  26184. SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
  26185. testcase( p->nChar + (i64)N > 0x7fffffff );
  26186. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  26187. return;
  26188. }
  26189. while( (N--)>0 ) p->zText[p->nChar++] = c;
  26190. }
  26191. /*
  26192. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  26193. ** So enlarge if first, then do the append.
  26194. **
  26195. ** This is a helper routine to sqlite3_str_append() that does special-case
  26196. ** work (enlarging the buffer) using tail recursion, so that the
  26197. ** sqlite3_str_append() routine can use fast calling semantics.
  26198. */
  26199. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  26200. N = sqlite3StrAccumEnlarge(p, N);
  26201. if( N>0 ){
  26202. memcpy(&p->zText[p->nChar], z, N);
  26203. p->nChar += N;
  26204. }
  26205. }
  26206. /*
  26207. ** Append N bytes of text from z to the StrAccum object. Increase the
  26208. ** size of the memory allocation for StrAccum if necessary.
  26209. */
  26210. SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
  26211. assert( z!=0 || N==0 );
  26212. assert( p->zText!=0 || p->nChar==0 || p->accError );
  26213. assert( N>=0 );
  26214. assert( p->accError==0 || p->nAlloc==0 );
  26215. if( p->nChar+N >= p->nAlloc ){
  26216. enlargeAndAppend(p,z,N);
  26217. }else if( N ){
  26218. assert( p->zText );
  26219. p->nChar += N;
  26220. memcpy(&p->zText[p->nChar-N], z, N);
  26221. }
  26222. }
  26223. /*
  26224. ** Append the complete text of zero-terminated string z[] to the p string.
  26225. */
  26226. SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
  26227. sqlite3_str_append(p, z, sqlite3Strlen30(z));
  26228. }
  26229. /*
  26230. ** Finish off a string by making sure it is zero-terminated.
  26231. ** Return a pointer to the resulting string. Return a NULL
  26232. ** pointer if any kind of error was encountered.
  26233. */
  26234. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  26235. char *zText;
  26236. assert( p->mxAlloc>0 && !isMalloced(p) );
  26237. zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  26238. if( zText ){
  26239. memcpy(zText, p->zText, p->nChar+1);
  26240. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26241. }else{
  26242. setStrAccumError(p, SQLITE_NOMEM);
  26243. }
  26244. p->zText = zText;
  26245. return zText;
  26246. }
  26247. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  26248. if( p->zText ){
  26249. p->zText[p->nChar] = 0;
  26250. if( p->mxAlloc>0 && !isMalloced(p) ){
  26251. return strAccumFinishRealloc(p);
  26252. }
  26253. }
  26254. return p->zText;
  26255. }
  26256. /*
  26257. ** This singleton is an sqlite3_str object that is returned if
  26258. ** sqlite3_malloc() fails to provide space for a real one. This
  26259. ** sqlite3_str object accepts no new text and always returns
  26260. ** an SQLITE_NOMEM error.
  26261. */
  26262. static sqlite3_str sqlite3OomStr = {
  26263. 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
  26264. };
  26265. /* Finalize a string created using sqlite3_str_new().
  26266. */
  26267. SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
  26268. char *z;
  26269. if( p!=0 && p!=&sqlite3OomStr ){
  26270. z = sqlite3StrAccumFinish(p);
  26271. sqlite3_free(p);
  26272. }else{
  26273. z = 0;
  26274. }
  26275. return z;
  26276. }
  26277. /* Return any error code associated with p */
  26278. SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
  26279. return p ? p->accError : SQLITE_NOMEM;
  26280. }
  26281. /* Return the current length of p in bytes */
  26282. SQLITE_API int sqlite3_str_length(sqlite3_str *p){
  26283. return p ? p->nChar : 0;
  26284. }
  26285. /* Return the current value for p */
  26286. SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
  26287. if( p==0 || p->nChar==0 ) return 0;
  26288. p->zText[p->nChar] = 0;
  26289. return p->zText;
  26290. }
  26291. /*
  26292. ** Reset an StrAccum string. Reclaim all malloced memory.
  26293. */
  26294. SQLITE_API void sqlite3_str_reset(StrAccum *p){
  26295. if( isMalloced(p) ){
  26296. sqlite3DbFree(p->db, p->zText);
  26297. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  26298. }
  26299. p->nAlloc = 0;
  26300. p->nChar = 0;
  26301. p->zText = 0;
  26302. }
  26303. /*
  26304. ** Initialize a string accumulator.
  26305. **
  26306. ** p: The accumulator to be initialized.
  26307. ** db: Pointer to a database connection. May be NULL. Lookaside
  26308. ** memory is used if not NULL. db->mallocFailed is set appropriately
  26309. ** when not NULL.
  26310. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  26311. ** is malloced.
  26312. ** n: Size of zBase in bytes. If total space requirements never exceed
  26313. ** n then no memory allocations ever occur.
  26314. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  26315. ** allocations will ever occur.
  26316. */
  26317. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  26318. p->zText = zBase;
  26319. p->db = db;
  26320. p->nAlloc = n;
  26321. p->mxAlloc = mx;
  26322. p->nChar = 0;
  26323. p->accError = 0;
  26324. p->printfFlags = 0;
  26325. }
  26326. /* Allocate and initialize a new dynamic string object */
  26327. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
  26328. sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
  26329. if( p ){
  26330. sqlite3StrAccumInit(p, 0, 0, 0,
  26331. db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
  26332. }else{
  26333. p = &sqlite3OomStr;
  26334. }
  26335. return p;
  26336. }
  26337. /*
  26338. ** Print into memory obtained from sqliteMalloc(). Use the internal
  26339. ** %-conversion extensions.
  26340. */
  26341. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  26342. char *z;
  26343. char zBase[SQLITE_PRINT_BUF_SIZE];
  26344. StrAccum acc;
  26345. assert( db!=0 );
  26346. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  26347. db->aLimit[SQLITE_LIMIT_LENGTH]);
  26348. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  26349. sqlite3_str_vappendf(&acc, zFormat, ap);
  26350. z = sqlite3StrAccumFinish(&acc);
  26351. if( acc.accError==SQLITE_NOMEM ){
  26352. sqlite3OomFault(db);
  26353. }
  26354. return z;
  26355. }
  26356. /*
  26357. ** Print into memory obtained from sqliteMalloc(). Use the internal
  26358. ** %-conversion extensions.
  26359. */
  26360. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  26361. va_list ap;
  26362. char *z;
  26363. va_start(ap, zFormat);
  26364. z = sqlite3VMPrintf(db, zFormat, ap);
  26365. va_end(ap);
  26366. return z;
  26367. }
  26368. /*
  26369. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  26370. ** %-conversion extensions.
  26371. */
  26372. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  26373. char *z;
  26374. char zBase[SQLITE_PRINT_BUF_SIZE];
  26375. StrAccum acc;
  26376. #ifdef SQLITE_ENABLE_API_ARMOR
  26377. if( zFormat==0 ){
  26378. (void)SQLITE_MISUSE_BKPT;
  26379. return 0;
  26380. }
  26381. #endif
  26382. #ifndef SQLITE_OMIT_AUTOINIT
  26383. if( sqlite3_initialize() ) return 0;
  26384. #endif
  26385. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  26386. sqlite3_str_vappendf(&acc, zFormat, ap);
  26387. z = sqlite3StrAccumFinish(&acc);
  26388. return z;
  26389. }
  26390. /*
  26391. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  26392. ** %-conversion extensions.
  26393. */
  26394. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  26395. va_list ap;
  26396. char *z;
  26397. #ifndef SQLITE_OMIT_AUTOINIT
  26398. if( sqlite3_initialize() ) return 0;
  26399. #endif
  26400. va_start(ap, zFormat);
  26401. z = sqlite3_vmprintf(zFormat, ap);
  26402. va_end(ap);
  26403. return z;
  26404. }
  26405. /*
  26406. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  26407. ** current locale settings. This is important for SQLite because we
  26408. ** are not able to use a "," as the decimal point in place of "." as
  26409. ** specified by some locales.
  26410. **
  26411. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  26412. ** from the snprintf() standard. Unfortunately, it is too late to change
  26413. ** this without breaking compatibility, so we just have to live with the
  26414. ** mistake.
  26415. **
  26416. ** sqlite3_vsnprintf() is the varargs version.
  26417. */
  26418. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  26419. StrAccum acc;
  26420. if( n<=0 ) return zBuf;
  26421. #ifdef SQLITE_ENABLE_API_ARMOR
  26422. if( zBuf==0 || zFormat==0 ) {
  26423. (void)SQLITE_MISUSE_BKPT;
  26424. if( zBuf ) zBuf[0] = 0;
  26425. return zBuf;
  26426. }
  26427. #endif
  26428. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  26429. sqlite3_str_vappendf(&acc, zFormat, ap);
  26430. zBuf[acc.nChar] = 0;
  26431. return zBuf;
  26432. }
  26433. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  26434. char *z;
  26435. va_list ap;
  26436. va_start(ap,zFormat);
  26437. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  26438. va_end(ap);
  26439. return z;
  26440. }
  26441. /*
  26442. ** This is the routine that actually formats the sqlite3_log() message.
  26443. ** We house it in a separate routine from sqlite3_log() to avoid using
  26444. ** stack space on small-stack systems when logging is disabled.
  26445. **
  26446. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  26447. ** allocate memory because it might be called while the memory allocator
  26448. ** mutex is held.
  26449. **
  26450. ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
  26451. ** certain format characters (%q) or for very large precisions or widths.
  26452. ** Care must be taken that any sqlite3_log() calls that occur while the
  26453. ** memory mutex is held do not use these mechanisms.
  26454. */
  26455. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  26456. StrAccum acc; /* String accumulator */
  26457. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  26458. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  26459. sqlite3_str_vappendf(&acc, zFormat, ap);
  26460. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  26461. sqlite3StrAccumFinish(&acc));
  26462. }
  26463. /*
  26464. ** Format and write a message to the log if logging is enabled.
  26465. */
  26466. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  26467. va_list ap; /* Vararg list */
  26468. if( sqlite3GlobalConfig.xLog ){
  26469. va_start(ap, zFormat);
  26470. renderLogMsg(iErrCode, zFormat, ap);
  26471. va_end(ap);
  26472. }
  26473. }
  26474. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  26475. /*
  26476. ** A version of printf() that understands %lld. Used for debugging.
  26477. ** The printf() built into some versions of windows does not understand %lld
  26478. ** and segfaults if you give it a long long int.
  26479. */
  26480. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  26481. va_list ap;
  26482. StrAccum acc;
  26483. char zBuf[500];
  26484. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  26485. va_start(ap,zFormat);
  26486. sqlite3_str_vappendf(&acc, zFormat, ap);
  26487. va_end(ap);
  26488. sqlite3StrAccumFinish(&acc);
  26489. #ifdef SQLITE_OS_TRACE_PROC
  26490. {
  26491. extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
  26492. SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
  26493. }
  26494. #else
  26495. fprintf(stdout,"%s", zBuf);
  26496. fflush(stdout);
  26497. #endif
  26498. }
  26499. #endif
  26500. /*
  26501. ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
  26502. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  26503. */
  26504. SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
  26505. va_list ap;
  26506. va_start(ap,zFormat);
  26507. sqlite3_str_vappendf(p, zFormat, ap);
  26508. va_end(ap);
  26509. }
  26510. /************** End of printf.c **********************************************/
  26511. /************** Begin file treeview.c ****************************************/
  26512. /*
  26513. ** 2015-06-08
  26514. **
  26515. ** The author disclaims copyright to this source code. In place of
  26516. ** a legal notice, here is a blessing:
  26517. **
  26518. ** May you do good and not evil.
  26519. ** May you find forgiveness for yourself and forgive others.
  26520. ** May you share freely, never taking more than you give.
  26521. **
  26522. *************************************************************************
  26523. **
  26524. ** This file contains C code to implement the TreeView debugging routines.
  26525. ** These routines print a parse tree to standard output for debugging and
  26526. ** analysis.
  26527. **
  26528. ** The interfaces in this file is only available when compiling
  26529. ** with SQLITE_DEBUG.
  26530. */
  26531. /* #include "sqliteInt.h" */
  26532. #ifdef SQLITE_DEBUG
  26533. /*
  26534. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  26535. ** is not the last item in the tree.
  26536. */
  26537. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  26538. if( p==0 ){
  26539. p = sqlite3_malloc64( sizeof(*p) );
  26540. if( p==0 ) return 0;
  26541. memset(p, 0, sizeof(*p));
  26542. }else{
  26543. p->iLevel++;
  26544. }
  26545. assert( moreToFollow==0 || moreToFollow==1 );
  26546. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  26547. return p;
  26548. }
  26549. /*
  26550. ** Finished with one layer of the tree
  26551. */
  26552. static void sqlite3TreeViewPop(TreeView *p){
  26553. if( p==0 ) return;
  26554. p->iLevel--;
  26555. if( p->iLevel<0 ) sqlite3_free(p);
  26556. }
  26557. /*
  26558. ** Generate a single line of output for the tree, with a prefix that contains
  26559. ** all the appropriate tree lines
  26560. */
  26561. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  26562. va_list ap;
  26563. int i;
  26564. StrAccum acc;
  26565. char zBuf[500];
  26566. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  26567. if( p ){
  26568. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  26569. sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
  26570. }
  26571. sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  26572. }
  26573. if( zFormat!=0 ){
  26574. va_start(ap, zFormat);
  26575. sqlite3_str_vappendf(&acc, zFormat, ap);
  26576. va_end(ap);
  26577. assert( acc.nChar>0 );
  26578. sqlite3_str_append(&acc, "\n", 1);
  26579. }
  26580. sqlite3StrAccumFinish(&acc);
  26581. fprintf(stdout,"%s", zBuf);
  26582. fflush(stdout);
  26583. }
  26584. /*
  26585. ** Shorthand for starting a new tree item that consists of a single label
  26586. */
  26587. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  26588. p = sqlite3TreeViewPush(p, moreFollows);
  26589. sqlite3TreeViewLine(p, "%s", zLabel);
  26590. }
  26591. /*
  26592. ** Generate a human-readable description of a WITH clause.
  26593. */
  26594. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  26595. int i;
  26596. if( pWith==0 ) return;
  26597. if( pWith->nCte==0 ) return;
  26598. if( pWith->pOuter ){
  26599. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  26600. }else{
  26601. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  26602. }
  26603. if( pWith->nCte>0 ){
  26604. pView = sqlite3TreeViewPush(pView, 1);
  26605. for(i=0; i<pWith->nCte; i++){
  26606. StrAccum x;
  26607. char zLine[1000];
  26608. const struct Cte *pCte = &pWith->a[i];
  26609. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  26610. sqlite3_str_appendf(&x, "%s", pCte->zName);
  26611. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  26612. char cSep = '(';
  26613. int j;
  26614. for(j=0; j<pCte->pCols->nExpr; j++){
  26615. sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  26616. cSep = ',';
  26617. }
  26618. sqlite3_str_appendf(&x, ")");
  26619. }
  26620. sqlite3_str_appendf(&x, " AS");
  26621. sqlite3StrAccumFinish(&x);
  26622. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  26623. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  26624. sqlite3TreeViewPop(pView);
  26625. }
  26626. sqlite3TreeViewPop(pView);
  26627. }
  26628. }
  26629. /*
  26630. ** Generate a human-readable description of a Select object.
  26631. */
  26632. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  26633. int n = 0;
  26634. int cnt = 0;
  26635. if( p==0 ){
  26636. sqlite3TreeViewLine(pView, "nil-SELECT");
  26637. return;
  26638. }
  26639. pView = sqlite3TreeViewPush(pView, moreToFollow);
  26640. if( p->pWith ){
  26641. sqlite3TreeViewWith(pView, p->pWith, 1);
  26642. cnt = 1;
  26643. sqlite3TreeViewPush(pView, 1);
  26644. }
  26645. do{
  26646. #if SELECTTRACE_ENABLED
  26647. sqlite3TreeViewLine(pView,
  26648. "SELECT%s%s (%s/%p) selFlags=0x%x nSelectRow=%d",
  26649. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  26650. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
  26651. p->zSelName, p, p->selFlags,
  26652. (int)p->nSelectRow
  26653. );
  26654. #else
  26655. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
  26656. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  26657. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
  26658. (int)p->nSelectRow
  26659. );
  26660. #endif
  26661. if( cnt++ ) sqlite3TreeViewPop(pView);
  26662. if( p->pPrior ){
  26663. n = 1000;
  26664. }else{
  26665. n = 0;
  26666. if( p->pSrc && p->pSrc->nSrc ) n++;
  26667. if( p->pWhere ) n++;
  26668. if( p->pGroupBy ) n++;
  26669. if( p->pHaving ) n++;
  26670. if( p->pOrderBy ) n++;
  26671. if( p->pLimit ) n++;
  26672. }
  26673. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  26674. if( p->pSrc && p->pSrc->nSrc ){
  26675. int i;
  26676. pView = sqlite3TreeViewPush(pView, (n--)>0);
  26677. sqlite3TreeViewLine(pView, "FROM");
  26678. for(i=0; i<p->pSrc->nSrc; i++){
  26679. struct SrcList_item *pItem = &p->pSrc->a[i];
  26680. StrAccum x;
  26681. char zLine[100];
  26682. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  26683. sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
  26684. if( pItem->zDatabase ){
  26685. sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  26686. }else if( pItem->zName ){
  26687. sqlite3_str_appendf(&x, " %s", pItem->zName);
  26688. }
  26689. if( pItem->pTab ){
  26690. sqlite3_str_appendf(&x, " tabname=%Q", pItem->pTab->zName);
  26691. }
  26692. if( pItem->zAlias ){
  26693. sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
  26694. }
  26695. if( pItem->fg.jointype & JT_LEFT ){
  26696. sqlite3_str_appendf(&x, " LEFT-JOIN");
  26697. }
  26698. sqlite3StrAccumFinish(&x);
  26699. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  26700. if( pItem->pSelect ){
  26701. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  26702. }
  26703. if( pItem->fg.isTabFunc ){
  26704. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  26705. }
  26706. sqlite3TreeViewPop(pView);
  26707. }
  26708. sqlite3TreeViewPop(pView);
  26709. }
  26710. if( p->pWhere ){
  26711. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  26712. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  26713. sqlite3TreeViewPop(pView);
  26714. }
  26715. if( p->pGroupBy ){
  26716. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  26717. }
  26718. if( p->pHaving ){
  26719. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  26720. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  26721. sqlite3TreeViewPop(pView);
  26722. }
  26723. if( p->pOrderBy ){
  26724. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  26725. }
  26726. if( p->pLimit ){
  26727. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  26728. sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
  26729. if( p->pLimit->pRight ){
  26730. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  26731. sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
  26732. sqlite3TreeViewPop(pView);
  26733. }
  26734. sqlite3TreeViewPop(pView);
  26735. }
  26736. if( p->pPrior ){
  26737. const char *zOp = "UNION";
  26738. switch( p->op ){
  26739. case TK_ALL: zOp = "UNION ALL"; break;
  26740. case TK_INTERSECT: zOp = "INTERSECT"; break;
  26741. case TK_EXCEPT: zOp = "EXCEPT"; break;
  26742. }
  26743. sqlite3TreeViewItem(pView, zOp, 1);
  26744. }
  26745. p = p->pPrior;
  26746. }while( p!=0 );
  26747. sqlite3TreeViewPop(pView);
  26748. }
  26749. /*
  26750. ** Generate a human-readable explanation of an expression tree.
  26751. */
  26752. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  26753. const char *zBinOp = 0; /* Binary operator */
  26754. const char *zUniOp = 0; /* Unary operator */
  26755. char zFlgs[60];
  26756. pView = sqlite3TreeViewPush(pView, moreToFollow);
  26757. if( pExpr==0 ){
  26758. sqlite3TreeViewLine(pView, "nil");
  26759. sqlite3TreeViewPop(pView);
  26760. return;
  26761. }
  26762. if( pExpr->flags ){
  26763. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  26764. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  26765. pExpr->flags, pExpr->iRightJoinTable);
  26766. }else{
  26767. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  26768. }
  26769. }else{
  26770. zFlgs[0] = 0;
  26771. }
  26772. switch( pExpr->op ){
  26773. case TK_AGG_COLUMN: {
  26774. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  26775. pExpr->iTable, pExpr->iColumn, zFlgs);
  26776. break;
  26777. }
  26778. case TK_COLUMN: {
  26779. if( pExpr->iTable<0 ){
  26780. /* This only happens when coding check constraints */
  26781. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  26782. }else{
  26783. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  26784. pExpr->iTable, pExpr->iColumn, zFlgs);
  26785. }
  26786. break;
  26787. }
  26788. case TK_INTEGER: {
  26789. if( pExpr->flags & EP_IntValue ){
  26790. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  26791. }else{
  26792. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  26793. }
  26794. break;
  26795. }
  26796. #ifndef SQLITE_OMIT_FLOATING_POINT
  26797. case TK_FLOAT: {
  26798. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  26799. break;
  26800. }
  26801. #endif
  26802. case TK_STRING: {
  26803. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  26804. break;
  26805. }
  26806. case TK_NULL: {
  26807. sqlite3TreeViewLine(pView,"NULL");
  26808. break;
  26809. }
  26810. case TK_TRUEFALSE: {
  26811. sqlite3TreeViewLine(pView,
  26812. sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
  26813. break;
  26814. }
  26815. #ifndef SQLITE_OMIT_BLOB_LITERAL
  26816. case TK_BLOB: {
  26817. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  26818. break;
  26819. }
  26820. #endif
  26821. case TK_VARIABLE: {
  26822. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  26823. pExpr->u.zToken, pExpr->iColumn);
  26824. break;
  26825. }
  26826. case TK_REGISTER: {
  26827. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  26828. break;
  26829. }
  26830. case TK_ID: {
  26831. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  26832. break;
  26833. }
  26834. #ifndef SQLITE_OMIT_CAST
  26835. case TK_CAST: {
  26836. /* Expressions of the form: CAST(pLeft AS token) */
  26837. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  26838. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26839. break;
  26840. }
  26841. #endif /* SQLITE_OMIT_CAST */
  26842. case TK_LT: zBinOp = "LT"; break;
  26843. case TK_LE: zBinOp = "LE"; break;
  26844. case TK_GT: zBinOp = "GT"; break;
  26845. case TK_GE: zBinOp = "GE"; break;
  26846. case TK_NE: zBinOp = "NE"; break;
  26847. case TK_EQ: zBinOp = "EQ"; break;
  26848. case TK_IS: zBinOp = "IS"; break;
  26849. case TK_ISNOT: zBinOp = "ISNOT"; break;
  26850. case TK_AND: zBinOp = "AND"; break;
  26851. case TK_OR: zBinOp = "OR"; break;
  26852. case TK_PLUS: zBinOp = "ADD"; break;
  26853. case TK_STAR: zBinOp = "MUL"; break;
  26854. case TK_MINUS: zBinOp = "SUB"; break;
  26855. case TK_REM: zBinOp = "REM"; break;
  26856. case TK_BITAND: zBinOp = "BITAND"; break;
  26857. case TK_BITOR: zBinOp = "BITOR"; break;
  26858. case TK_SLASH: zBinOp = "DIV"; break;
  26859. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  26860. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  26861. case TK_CONCAT: zBinOp = "CONCAT"; break;
  26862. case TK_DOT: zBinOp = "DOT"; break;
  26863. case TK_UMINUS: zUniOp = "UMINUS"; break;
  26864. case TK_UPLUS: zUniOp = "UPLUS"; break;
  26865. case TK_BITNOT: zUniOp = "BITNOT"; break;
  26866. case TK_NOT: zUniOp = "NOT"; break;
  26867. case TK_ISNULL: zUniOp = "ISNULL"; break;
  26868. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  26869. case TK_TRUTH: {
  26870. int x;
  26871. const char *azOp[] = {
  26872. "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
  26873. };
  26874. assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
  26875. assert( pExpr->pRight );
  26876. assert( pExpr->pRight->op==TK_TRUEFALSE );
  26877. x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
  26878. zUniOp = azOp[x];
  26879. break;
  26880. }
  26881. case TK_SPAN: {
  26882. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  26883. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26884. break;
  26885. }
  26886. case TK_COLLATE: {
  26887. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  26888. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26889. break;
  26890. }
  26891. case TK_AGG_FUNCTION:
  26892. case TK_FUNCTION: {
  26893. ExprList *pFarg; /* List of function arguments */
  26894. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  26895. pFarg = 0;
  26896. }else{
  26897. pFarg = pExpr->x.pList;
  26898. }
  26899. if( pExpr->op==TK_AGG_FUNCTION ){
  26900. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  26901. pExpr->op2, pExpr->u.zToken);
  26902. }else{
  26903. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  26904. }
  26905. if( pFarg ){
  26906. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  26907. }
  26908. break;
  26909. }
  26910. #ifndef SQLITE_OMIT_SUBQUERY
  26911. case TK_EXISTS: {
  26912. sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
  26913. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  26914. break;
  26915. }
  26916. case TK_SELECT: {
  26917. sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
  26918. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  26919. break;
  26920. }
  26921. case TK_IN: {
  26922. sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
  26923. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  26924. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  26925. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  26926. }else{
  26927. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  26928. }
  26929. break;
  26930. }
  26931. #endif /* SQLITE_OMIT_SUBQUERY */
  26932. /*
  26933. ** x BETWEEN y AND z
  26934. **
  26935. ** This is equivalent to
  26936. **
  26937. ** x>=y AND x<=z
  26938. **
  26939. ** X is stored in pExpr->pLeft.
  26940. ** Y is stored in pExpr->pList->a[0].pExpr.
  26941. ** Z is stored in pExpr->pList->a[1].pExpr.
  26942. */
  26943. case TK_BETWEEN: {
  26944. Expr *pX = pExpr->pLeft;
  26945. Expr *pY = pExpr->x.pList->a[0].pExpr;
  26946. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  26947. sqlite3TreeViewLine(pView, "BETWEEN");
  26948. sqlite3TreeViewExpr(pView, pX, 1);
  26949. sqlite3TreeViewExpr(pView, pY, 1);
  26950. sqlite3TreeViewExpr(pView, pZ, 0);
  26951. break;
  26952. }
  26953. case TK_TRIGGER: {
  26954. /* If the opcode is TK_TRIGGER, then the expression is a reference
  26955. ** to a column in the new.* or old.* pseudo-tables available to
  26956. ** trigger programs. In this case Expr.iTable is set to 1 for the
  26957. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  26958. ** is set to the column of the pseudo-table to read, or to -1 to
  26959. ** read the rowid field.
  26960. */
  26961. sqlite3TreeViewLine(pView, "%s(%d)",
  26962. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  26963. break;
  26964. }
  26965. case TK_CASE: {
  26966. sqlite3TreeViewLine(pView, "CASE");
  26967. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  26968. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  26969. break;
  26970. }
  26971. #ifndef SQLITE_OMIT_TRIGGER
  26972. case TK_RAISE: {
  26973. const char *zType = "unk";
  26974. switch( pExpr->affinity ){
  26975. case OE_Rollback: zType = "rollback"; break;
  26976. case OE_Abort: zType = "abort"; break;
  26977. case OE_Fail: zType = "fail"; break;
  26978. case OE_Ignore: zType = "ignore"; break;
  26979. }
  26980. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  26981. break;
  26982. }
  26983. #endif
  26984. case TK_MATCH: {
  26985. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  26986. pExpr->iTable, pExpr->iColumn, zFlgs);
  26987. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  26988. break;
  26989. }
  26990. case TK_VECTOR: {
  26991. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  26992. break;
  26993. }
  26994. case TK_SELECT_COLUMN: {
  26995. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  26996. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  26997. break;
  26998. }
  26999. case TK_IF_NULL_ROW: {
  27000. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  27001. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27002. break;
  27003. }
  27004. default: {
  27005. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  27006. break;
  27007. }
  27008. }
  27009. if( zBinOp ){
  27010. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  27011. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27012. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  27013. }else if( zUniOp ){
  27014. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  27015. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27016. }
  27017. sqlite3TreeViewPop(pView);
  27018. }
  27019. /*
  27020. ** Generate a human-readable explanation of an expression list.
  27021. */
  27022. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  27023. TreeView *pView,
  27024. const ExprList *pList,
  27025. const char *zLabel
  27026. ){
  27027. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  27028. if( pList==0 ){
  27029. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  27030. }else{
  27031. int i;
  27032. sqlite3TreeViewLine(pView, "%s", zLabel);
  27033. for(i=0; i<pList->nExpr; i++){
  27034. int j = pList->a[i].u.x.iOrderByCol;
  27035. char *zName = pList->a[i].zName;
  27036. int moreToFollow = i<pList->nExpr - 1;
  27037. if( j || zName ){
  27038. sqlite3TreeViewPush(pView, moreToFollow);
  27039. moreToFollow = 0;
  27040. sqlite3TreeViewLine(pView, 0);
  27041. if( zName ){
  27042. fprintf(stdout, "AS %s ", zName);
  27043. }
  27044. if( j ){
  27045. fprintf(stdout, "iOrderByCol=%d", j);
  27046. }
  27047. fprintf(stdout, "\n");
  27048. fflush(stdout);
  27049. }
  27050. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
  27051. if( j || zName ){
  27052. sqlite3TreeViewPop(pView);
  27053. }
  27054. }
  27055. }
  27056. }
  27057. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  27058. TreeView *pView,
  27059. const ExprList *pList,
  27060. u8 moreToFollow,
  27061. const char *zLabel
  27062. ){
  27063. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27064. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  27065. sqlite3TreeViewPop(pView);
  27066. }
  27067. #endif /* SQLITE_DEBUG */
  27068. /************** End of treeview.c ********************************************/
  27069. /************** Begin file random.c ******************************************/
  27070. /*
  27071. ** 2001 September 15
  27072. **
  27073. ** The author disclaims copyright to this source code. In place of
  27074. ** a legal notice, here is a blessing:
  27075. **
  27076. ** May you do good and not evil.
  27077. ** May you find forgiveness for yourself and forgive others.
  27078. ** May you share freely, never taking more than you give.
  27079. **
  27080. *************************************************************************
  27081. ** This file contains code to implement a pseudo-random number
  27082. ** generator (PRNG) for SQLite.
  27083. **
  27084. ** Random numbers are used by some of the database backends in order
  27085. ** to generate random integer keys for tables or random filenames.
  27086. */
  27087. /* #include "sqliteInt.h" */
  27088. /* All threads share a single random number generator.
  27089. ** This structure is the current state of the generator.
  27090. */
  27091. static SQLITE_WSD struct sqlite3PrngType {
  27092. unsigned char isInit; /* True if initialized */
  27093. unsigned char i, j; /* State variables */
  27094. unsigned char s[256]; /* State variables */
  27095. } sqlite3Prng;
  27096. /*
  27097. ** Return N random bytes.
  27098. */
  27099. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  27100. unsigned char t;
  27101. unsigned char *zBuf = pBuf;
  27102. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  27103. ** state vector. If writable static data is unsupported on the target,
  27104. ** we have to locate the state vector at run-time. In the more common
  27105. ** case where writable static data is supported, wsdPrng can refer directly
  27106. ** to the "sqlite3Prng" state vector declared above.
  27107. */
  27108. #ifdef SQLITE_OMIT_WSD
  27109. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  27110. # define wsdPrng p[0]
  27111. #else
  27112. # define wsdPrng sqlite3Prng
  27113. #endif
  27114. #if SQLITE_THREADSAFE
  27115. sqlite3_mutex *mutex;
  27116. #endif
  27117. #ifndef SQLITE_OMIT_AUTOINIT
  27118. if( sqlite3_initialize() ) return;
  27119. #endif
  27120. #if SQLITE_THREADSAFE
  27121. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  27122. #endif
  27123. sqlite3_mutex_enter(mutex);
  27124. if( N<=0 || pBuf==0 ){
  27125. wsdPrng.isInit = 0;
  27126. sqlite3_mutex_leave(mutex);
  27127. return;
  27128. }
  27129. /* Initialize the state of the random number generator once,
  27130. ** the first time this routine is called. The seed value does
  27131. ** not need to contain a lot of randomness since we are not
  27132. ** trying to do secure encryption or anything like that...
  27133. **
  27134. ** Nothing in this file or anywhere else in SQLite does any kind of
  27135. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  27136. ** number generator) not as an encryption device.
  27137. */
  27138. if( !wsdPrng.isInit ){
  27139. int i;
  27140. char k[256];
  27141. wsdPrng.j = 0;
  27142. wsdPrng.i = 0;
  27143. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  27144. for(i=0; i<256; i++){
  27145. wsdPrng.s[i] = (u8)i;
  27146. }
  27147. for(i=0; i<256; i++){
  27148. wsdPrng.j += wsdPrng.s[i] + k[i];
  27149. t = wsdPrng.s[wsdPrng.j];
  27150. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  27151. wsdPrng.s[i] = t;
  27152. }
  27153. wsdPrng.isInit = 1;
  27154. }
  27155. assert( N>0 );
  27156. do{
  27157. wsdPrng.i++;
  27158. t = wsdPrng.s[wsdPrng.i];
  27159. wsdPrng.j += t;
  27160. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  27161. wsdPrng.s[wsdPrng.j] = t;
  27162. t += wsdPrng.s[wsdPrng.i];
  27163. *(zBuf++) = wsdPrng.s[t];
  27164. }while( --N );
  27165. sqlite3_mutex_leave(mutex);
  27166. }
  27167. #ifndef SQLITE_UNTESTABLE
  27168. /*
  27169. ** For testing purposes, we sometimes want to preserve the state of
  27170. ** PRNG and restore the PRNG to its saved state at a later time, or
  27171. ** to reset the PRNG to its initial state. These routines accomplish
  27172. ** those tasks.
  27173. **
  27174. ** The sqlite3_test_control() interface calls these routines to
  27175. ** control the PRNG.
  27176. */
  27177. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  27178. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  27179. memcpy(
  27180. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  27181. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  27182. sizeof(sqlite3Prng)
  27183. );
  27184. }
  27185. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  27186. memcpy(
  27187. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  27188. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  27189. sizeof(sqlite3Prng)
  27190. );
  27191. }
  27192. #endif /* SQLITE_UNTESTABLE */
  27193. /************** End of random.c **********************************************/
  27194. /************** Begin file threads.c *****************************************/
  27195. /*
  27196. ** 2012 July 21
  27197. **
  27198. ** The author disclaims copyright to this source code. In place of
  27199. ** a legal notice, here is a blessing:
  27200. **
  27201. ** May you do good and not evil.
  27202. ** May you find forgiveness for yourself and forgive others.
  27203. ** May you share freely, never taking more than you give.
  27204. **
  27205. ******************************************************************************
  27206. **
  27207. ** This file presents a simple cross-platform threading interface for
  27208. ** use internally by SQLite.
  27209. **
  27210. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  27211. ** runs independently of its creator until it is joined using
  27212. ** sqlite3ThreadJoin(), at which point it terminates.
  27213. **
  27214. ** Threads do not have to be real. It could be that the work of the
  27215. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  27216. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  27217. ** single threaded systems. Nothing in SQLite requires multiple threads.
  27218. ** This interface exists so that applications that want to take advantage
  27219. ** of multiple cores can do so, while also allowing applications to stay
  27220. ** single-threaded if desired.
  27221. */
  27222. /* #include "sqliteInt.h" */
  27223. #if SQLITE_OS_WIN
  27224. /* # include "os_win.h" */
  27225. #endif
  27226. #if SQLITE_MAX_WORKER_THREADS>0
  27227. /********************************* Unix Pthreads ****************************/
  27228. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  27229. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  27230. /* #include <pthread.h> */
  27231. /* A running thread */
  27232. struct SQLiteThread {
  27233. pthread_t tid; /* Thread ID */
  27234. int done; /* Set to true when thread finishes */
  27235. void *pOut; /* Result returned by the thread */
  27236. void *(*xTask)(void*); /* The thread routine */
  27237. void *pIn; /* Argument to the thread */
  27238. };
  27239. /* Create a new thread */
  27240. SQLITE_PRIVATE int sqlite3ThreadCreate(
  27241. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  27242. void *(*xTask)(void*), /* Routine to run in a separate thread */
  27243. void *pIn /* Argument passed into xTask() */
  27244. ){
  27245. SQLiteThread *p;
  27246. int rc;
  27247. assert( ppThread!=0 );
  27248. assert( xTask!=0 );
  27249. /* This routine is never used in single-threaded mode */
  27250. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  27251. *ppThread = 0;
  27252. p = sqlite3Malloc(sizeof(*p));
  27253. if( p==0 ) return SQLITE_NOMEM_BKPT;
  27254. memset(p, 0, sizeof(*p));
  27255. p->xTask = xTask;
  27256. p->pIn = pIn;
  27257. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  27258. ** function that returns SQLITE_ERROR when passed the argument 200, that
  27259. ** forces worker threads to run sequentially and deterministically
  27260. ** for testing purposes. */
  27261. if( sqlite3FaultSim(200) ){
  27262. rc = 1;
  27263. }else{
  27264. rc = pthread_create(&p->tid, 0, xTask, pIn);
  27265. }
  27266. if( rc ){
  27267. p->done = 1;
  27268. p->pOut = xTask(pIn);
  27269. }
  27270. *ppThread = p;
  27271. return SQLITE_OK;
  27272. }
  27273. /* Get the results of the thread */
  27274. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  27275. int rc;
  27276. assert( ppOut!=0 );
  27277. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  27278. if( p->done ){
  27279. *ppOut = p->pOut;
  27280. rc = SQLITE_OK;
  27281. }else{
  27282. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  27283. }
  27284. sqlite3_free(p);
  27285. return rc;
  27286. }
  27287. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  27288. /******************************** End Unix Pthreads *************************/
  27289. /********************************* Win32 Threads ****************************/
  27290. #if SQLITE_OS_WIN_THREADS
  27291. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  27292. #include <process.h>
  27293. /* A running thread */
  27294. struct SQLiteThread {
  27295. void *tid; /* The thread handle */
  27296. unsigned id; /* The thread identifier */
  27297. void *(*xTask)(void*); /* The routine to run as a thread */
  27298. void *pIn; /* Argument to xTask */
  27299. void *pResult; /* Result of xTask */
  27300. };
  27301. /* Thread procedure Win32 compatibility shim */
  27302. static unsigned __stdcall sqlite3ThreadProc(
  27303. void *pArg /* IN: Pointer to the SQLiteThread structure */
  27304. ){
  27305. SQLiteThread *p = (SQLiteThread *)pArg;
  27306. assert( p!=0 );
  27307. #if 0
  27308. /*
  27309. ** This assert appears to trigger spuriously on certain
  27310. ** versions of Windows, possibly due to _beginthreadex()
  27311. ** and/or CreateThread() not fully setting their thread
  27312. ** ID parameter before starting the thread.
  27313. */
  27314. assert( p->id==GetCurrentThreadId() );
  27315. #endif
  27316. assert( p->xTask!=0 );
  27317. p->pResult = p->xTask(p->pIn);
  27318. _endthreadex(0);
  27319. return 0; /* NOT REACHED */
  27320. }
  27321. /* Create a new thread */
  27322. SQLITE_PRIVATE int sqlite3ThreadCreate(
  27323. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  27324. void *(*xTask)(void*), /* Routine to run in a separate thread */
  27325. void *pIn /* Argument passed into xTask() */
  27326. ){
  27327. SQLiteThread *p;
  27328. assert( ppThread!=0 );
  27329. assert( xTask!=0 );
  27330. *ppThread = 0;
  27331. p = sqlite3Malloc(sizeof(*p));
  27332. if( p==0 ) return SQLITE_NOMEM_BKPT;
  27333. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  27334. ** function that returns SQLITE_ERROR when passed the argument 200, that
  27335. ** forces worker threads to run sequentially and deterministically
  27336. ** (via the sqlite3FaultSim() term of the conditional) for testing
  27337. ** purposes. */
  27338. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  27339. memset(p, 0, sizeof(*p));
  27340. }else{
  27341. p->xTask = xTask;
  27342. p->pIn = pIn;
  27343. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  27344. if( p->tid==0 ){
  27345. memset(p, 0, sizeof(*p));
  27346. }
  27347. }
  27348. if( p->xTask==0 ){
  27349. p->id = GetCurrentThreadId();
  27350. p->pResult = xTask(pIn);
  27351. }
  27352. *ppThread = p;
  27353. return SQLITE_OK;
  27354. }
  27355. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  27356. /* Get the results of the thread */
  27357. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  27358. DWORD rc;
  27359. BOOL bRc;
  27360. assert( ppOut!=0 );
  27361. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  27362. if( p->xTask==0 ){
  27363. /* assert( p->id==GetCurrentThreadId() ); */
  27364. rc = WAIT_OBJECT_0;
  27365. assert( p->tid==0 );
  27366. }else{
  27367. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  27368. rc = sqlite3Win32Wait((HANDLE)p->tid);
  27369. assert( rc!=WAIT_IO_COMPLETION );
  27370. bRc = CloseHandle((HANDLE)p->tid);
  27371. assert( bRc );
  27372. }
  27373. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  27374. sqlite3_free(p);
  27375. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  27376. }
  27377. #endif /* SQLITE_OS_WIN_THREADS */
  27378. /******************************** End Win32 Threads *************************/
  27379. /********************************* Single-Threaded **************************/
  27380. #ifndef SQLITE_THREADS_IMPLEMENTED
  27381. /*
  27382. ** This implementation does not actually create a new thread. It does the
  27383. ** work of the thread in the main thread, when either the thread is created
  27384. ** or when it is joined
  27385. */
  27386. /* A running thread */
  27387. struct SQLiteThread {
  27388. void *(*xTask)(void*); /* The routine to run as a thread */
  27389. void *pIn; /* Argument to xTask */
  27390. void *pResult; /* Result of xTask */
  27391. };
  27392. /* Create a new thread */
  27393. SQLITE_PRIVATE int sqlite3ThreadCreate(
  27394. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  27395. void *(*xTask)(void*), /* Routine to run in a separate thread */
  27396. void *pIn /* Argument passed into xTask() */
  27397. ){
  27398. SQLiteThread *p;
  27399. assert( ppThread!=0 );
  27400. assert( xTask!=0 );
  27401. *ppThread = 0;
  27402. p = sqlite3Malloc(sizeof(*p));
  27403. if( p==0 ) return SQLITE_NOMEM_BKPT;
  27404. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  27405. p->xTask = xTask;
  27406. p->pIn = pIn;
  27407. }else{
  27408. p->xTask = 0;
  27409. p->pResult = xTask(pIn);
  27410. }
  27411. *ppThread = p;
  27412. return SQLITE_OK;
  27413. }
  27414. /* Get the results of the thread */
  27415. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  27416. assert( ppOut!=0 );
  27417. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  27418. if( p->xTask ){
  27419. *ppOut = p->xTask(p->pIn);
  27420. }else{
  27421. *ppOut = p->pResult;
  27422. }
  27423. sqlite3_free(p);
  27424. #if defined(SQLITE_TEST)
  27425. {
  27426. void *pTstAlloc = sqlite3Malloc(10);
  27427. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  27428. sqlite3_free(pTstAlloc);
  27429. }
  27430. #endif
  27431. return SQLITE_OK;
  27432. }
  27433. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  27434. /****************************** End Single-Threaded *************************/
  27435. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  27436. /************** End of threads.c *********************************************/
  27437. /************** Begin file utf.c *********************************************/
  27438. /*
  27439. ** 2004 April 13
  27440. **
  27441. ** The author disclaims copyright to this source code. In place of
  27442. ** a legal notice, here is a blessing:
  27443. **
  27444. ** May you do good and not evil.
  27445. ** May you find forgiveness for yourself and forgive others.
  27446. ** May you share freely, never taking more than you give.
  27447. **
  27448. *************************************************************************
  27449. ** This file contains routines used to translate between UTF-8,
  27450. ** UTF-16, UTF-16BE, and UTF-16LE.
  27451. **
  27452. ** Notes on UTF-8:
  27453. **
  27454. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  27455. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  27456. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  27457. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  27458. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  27459. **
  27460. **
  27461. ** Notes on UTF-16: (with wwww+1==uuuuu)
  27462. **
  27463. ** Word-0 Word-1 Value
  27464. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  27465. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  27466. **
  27467. **
  27468. ** BOM or Byte Order Mark:
  27469. ** 0xff 0xfe little-endian utf-16 follows
  27470. ** 0xfe 0xff big-endian utf-16 follows
  27471. **
  27472. */
  27473. /* #include "sqliteInt.h" */
  27474. /* #include <assert.h> */
  27475. /* #include "vdbeInt.h" */
  27476. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  27477. /*
  27478. ** The following constant value is used by the SQLITE_BIGENDIAN and
  27479. ** SQLITE_LITTLEENDIAN macros.
  27480. */
  27481. SQLITE_PRIVATE const int sqlite3one = 1;
  27482. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  27483. /*
  27484. ** This lookup table is used to help decode the first byte of
  27485. ** a multi-byte UTF8 character.
  27486. */
  27487. static const unsigned char sqlite3Utf8Trans1[] = {
  27488. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  27489. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  27490. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  27491. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  27492. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  27493. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  27494. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  27495. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  27496. };
  27497. #define WRITE_UTF8(zOut, c) { \
  27498. if( c<0x00080 ){ \
  27499. *zOut++ = (u8)(c&0xFF); \
  27500. } \
  27501. else if( c<0x00800 ){ \
  27502. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  27503. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  27504. } \
  27505. else if( c<0x10000 ){ \
  27506. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  27507. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  27508. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  27509. }else{ \
  27510. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  27511. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  27512. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  27513. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  27514. } \
  27515. }
  27516. #define WRITE_UTF16LE(zOut, c) { \
  27517. if( c<=0xFFFF ){ \
  27518. *zOut++ = (u8)(c&0x00FF); \
  27519. *zOut++ = (u8)((c>>8)&0x00FF); \
  27520. }else{ \
  27521. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  27522. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  27523. *zOut++ = (u8)(c&0x00FF); \
  27524. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  27525. } \
  27526. }
  27527. #define WRITE_UTF16BE(zOut, c) { \
  27528. if( c<=0xFFFF ){ \
  27529. *zOut++ = (u8)((c>>8)&0x00FF); \
  27530. *zOut++ = (u8)(c&0x00FF); \
  27531. }else{ \
  27532. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  27533. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  27534. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  27535. *zOut++ = (u8)(c&0x00FF); \
  27536. } \
  27537. }
  27538. #define READ_UTF16LE(zIn, TERM, c){ \
  27539. c = (*zIn++); \
  27540. c += ((*zIn++)<<8); \
  27541. if( c>=0xD800 && c<0xE000 && TERM ){ \
  27542. int c2 = (*zIn++); \
  27543. c2 += ((*zIn++)<<8); \
  27544. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  27545. } \
  27546. }
  27547. #define READ_UTF16BE(zIn, TERM, c){ \
  27548. c = ((*zIn++)<<8); \
  27549. c += (*zIn++); \
  27550. if( c>=0xD800 && c<0xE000 && TERM ){ \
  27551. int c2 = ((*zIn++)<<8); \
  27552. c2 += (*zIn++); \
  27553. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  27554. } \
  27555. }
  27556. /*
  27557. ** Translate a single UTF-8 character. Return the unicode value.
  27558. **
  27559. ** During translation, assume that the byte that zTerm points
  27560. ** is a 0x00.
  27561. **
  27562. ** Write a pointer to the next unread byte back into *pzNext.
  27563. **
  27564. ** Notes On Invalid UTF-8:
  27565. **
  27566. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  27567. ** be encoded as a multi-byte character. Any multi-byte character that
  27568. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  27569. **
  27570. ** * This routine never allows a UTF16 surrogate value to be encoded.
  27571. ** If a multi-byte character attempts to encode a value between
  27572. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  27573. **
  27574. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  27575. ** byte of a character are interpreted as single-byte characters
  27576. ** and rendered as themselves even though they are technically
  27577. ** invalid characters.
  27578. **
  27579. ** * This routine accepts over-length UTF8 encodings
  27580. ** for unicode values 0x80 and greater. It does not change over-length
  27581. ** encodings to 0xfffd as some systems recommend.
  27582. */
  27583. #define READ_UTF8(zIn, zTerm, c) \
  27584. c = *(zIn++); \
  27585. if( c>=0xc0 ){ \
  27586. c = sqlite3Utf8Trans1[c-0xc0]; \
  27587. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  27588. c = (c<<6) + (0x3f & *(zIn++)); \
  27589. } \
  27590. if( c<0x80 \
  27591. || (c&0xFFFFF800)==0xD800 \
  27592. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  27593. }
  27594. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  27595. const unsigned char **pz /* Pointer to string from which to read char */
  27596. ){
  27597. unsigned int c;
  27598. /* Same as READ_UTF8() above but without the zTerm parameter.
  27599. ** For this routine, we assume the UTF8 string is always zero-terminated.
  27600. */
  27601. c = *((*pz)++);
  27602. if( c>=0xc0 ){
  27603. c = sqlite3Utf8Trans1[c-0xc0];
  27604. while( (*(*pz) & 0xc0)==0x80 ){
  27605. c = (c<<6) + (0x3f & *((*pz)++));
  27606. }
  27607. if( c<0x80
  27608. || (c&0xFFFFF800)==0xD800
  27609. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  27610. }
  27611. return c;
  27612. }
  27613. /*
  27614. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  27615. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  27616. */
  27617. /* #define TRANSLATE_TRACE 1 */
  27618. #ifndef SQLITE_OMIT_UTF16
  27619. /*
  27620. ** This routine transforms the internal text encoding used by pMem to
  27621. ** desiredEnc. It is an error if the string is already of the desired
  27622. ** encoding, or if *pMem does not contain a string value.
  27623. */
  27624. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  27625. int len; /* Maximum length of output string in bytes */
  27626. unsigned char *zOut; /* Output buffer */
  27627. unsigned char *zIn; /* Input iterator */
  27628. unsigned char *zTerm; /* End of input */
  27629. unsigned char *z; /* Output iterator */
  27630. unsigned int c;
  27631. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  27632. assert( pMem->flags&MEM_Str );
  27633. assert( pMem->enc!=desiredEnc );
  27634. assert( pMem->enc!=0 );
  27635. assert( pMem->n>=0 );
  27636. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  27637. {
  27638. char zBuf[100];
  27639. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  27640. fprintf(stderr, "INPUT: %s\n", zBuf);
  27641. }
  27642. #endif
  27643. /* If the translation is between UTF-16 little and big endian, then
  27644. ** all that is required is to swap the byte order. This case is handled
  27645. ** differently from the others.
  27646. */
  27647. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  27648. u8 temp;
  27649. int rc;
  27650. rc = sqlite3VdbeMemMakeWriteable(pMem);
  27651. if( rc!=SQLITE_OK ){
  27652. assert( rc==SQLITE_NOMEM );
  27653. return SQLITE_NOMEM_BKPT;
  27654. }
  27655. zIn = (u8*)pMem->z;
  27656. zTerm = &zIn[pMem->n&~1];
  27657. while( zIn<zTerm ){
  27658. temp = *zIn;
  27659. *zIn = *(zIn+1);
  27660. zIn++;
  27661. *zIn++ = temp;
  27662. }
  27663. pMem->enc = desiredEnc;
  27664. goto translate_out;
  27665. }
  27666. /* Set len to the maximum number of bytes required in the output buffer. */
  27667. if( desiredEnc==SQLITE_UTF8 ){
  27668. /* When converting from UTF-16, the maximum growth results from
  27669. ** translating a 2-byte character to a 4-byte UTF-8 character.
  27670. ** A single byte is required for the output string
  27671. ** nul-terminator.
  27672. */
  27673. pMem->n &= ~1;
  27674. len = pMem->n * 2 + 1;
  27675. }else{
  27676. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  27677. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  27678. ** character. Two bytes are required in the output buffer for the
  27679. ** nul-terminator.
  27680. */
  27681. len = pMem->n * 2 + 2;
  27682. }
  27683. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  27684. ** byte past the end.
  27685. **
  27686. ** Variable zOut is set to point at the output buffer, space obtained
  27687. ** from sqlite3_malloc().
  27688. */
  27689. zIn = (u8*)pMem->z;
  27690. zTerm = &zIn[pMem->n];
  27691. zOut = sqlite3DbMallocRaw(pMem->db, len);
  27692. if( !zOut ){
  27693. return SQLITE_NOMEM_BKPT;
  27694. }
  27695. z = zOut;
  27696. if( pMem->enc==SQLITE_UTF8 ){
  27697. if( desiredEnc==SQLITE_UTF16LE ){
  27698. /* UTF-8 -> UTF-16 Little-endian */
  27699. while( zIn<zTerm ){
  27700. READ_UTF8(zIn, zTerm, c);
  27701. WRITE_UTF16LE(z, c);
  27702. }
  27703. }else{
  27704. assert( desiredEnc==SQLITE_UTF16BE );
  27705. /* UTF-8 -> UTF-16 Big-endian */
  27706. while( zIn<zTerm ){
  27707. READ_UTF8(zIn, zTerm, c);
  27708. WRITE_UTF16BE(z, c);
  27709. }
  27710. }
  27711. pMem->n = (int)(z - zOut);
  27712. *z++ = 0;
  27713. }else{
  27714. assert( desiredEnc==SQLITE_UTF8 );
  27715. if( pMem->enc==SQLITE_UTF16LE ){
  27716. /* UTF-16 Little-endian -> UTF-8 */
  27717. while( zIn<zTerm ){
  27718. READ_UTF16LE(zIn, zIn<zTerm, c);
  27719. WRITE_UTF8(z, c);
  27720. }
  27721. }else{
  27722. /* UTF-16 Big-endian -> UTF-8 */
  27723. while( zIn<zTerm ){
  27724. READ_UTF16BE(zIn, zIn<zTerm, c);
  27725. WRITE_UTF8(z, c);
  27726. }
  27727. }
  27728. pMem->n = (int)(z - zOut);
  27729. }
  27730. *z = 0;
  27731. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  27732. c = pMem->flags;
  27733. sqlite3VdbeMemRelease(pMem);
  27734. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  27735. pMem->enc = desiredEnc;
  27736. pMem->z = (char*)zOut;
  27737. pMem->zMalloc = pMem->z;
  27738. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  27739. translate_out:
  27740. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  27741. {
  27742. char zBuf[100];
  27743. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  27744. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  27745. }
  27746. #endif
  27747. return SQLITE_OK;
  27748. }
  27749. #endif /* SQLITE_OMIT_UTF16 */
  27750. #ifndef SQLITE_OMIT_UTF16
  27751. /*
  27752. ** This routine checks for a byte-order mark at the beginning of the
  27753. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  27754. ** the encoding of the Mem adjusted. This routine does not do any
  27755. ** byte-swapping, it just sets Mem.enc appropriately.
  27756. **
  27757. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  27758. ** changed by this function.
  27759. */
  27760. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  27761. int rc = SQLITE_OK;
  27762. u8 bom = 0;
  27763. assert( pMem->n>=0 );
  27764. if( pMem->n>1 ){
  27765. u8 b1 = *(u8 *)pMem->z;
  27766. u8 b2 = *(((u8 *)pMem->z) + 1);
  27767. if( b1==0xFE && b2==0xFF ){
  27768. bom = SQLITE_UTF16BE;
  27769. }
  27770. if( b1==0xFF && b2==0xFE ){
  27771. bom = SQLITE_UTF16LE;
  27772. }
  27773. }
  27774. if( bom ){
  27775. rc = sqlite3VdbeMemMakeWriteable(pMem);
  27776. if( rc==SQLITE_OK ){
  27777. pMem->n -= 2;
  27778. memmove(pMem->z, &pMem->z[2], pMem->n);
  27779. pMem->z[pMem->n] = '\0';
  27780. pMem->z[pMem->n+1] = '\0';
  27781. pMem->flags |= MEM_Term;
  27782. pMem->enc = bom;
  27783. }
  27784. }
  27785. return rc;
  27786. }
  27787. #endif /* SQLITE_OMIT_UTF16 */
  27788. /*
  27789. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  27790. ** return the number of unicode characters in pZ up to (but not including)
  27791. ** the first 0x00 byte. If nByte is not less than zero, return the
  27792. ** number of unicode characters in the first nByte of pZ (or up to
  27793. ** the first 0x00, whichever comes first).
  27794. */
  27795. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  27796. int r = 0;
  27797. const u8 *z = (const u8*)zIn;
  27798. const u8 *zTerm;
  27799. if( nByte>=0 ){
  27800. zTerm = &z[nByte];
  27801. }else{
  27802. zTerm = (const u8*)(-1);
  27803. }
  27804. assert( z<=zTerm );
  27805. while( *z!=0 && z<zTerm ){
  27806. SQLITE_SKIP_UTF8(z);
  27807. r++;
  27808. }
  27809. return r;
  27810. }
  27811. /* This test function is not currently used by the automated test-suite.
  27812. ** Hence it is only available in debug builds.
  27813. */
  27814. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  27815. /*
  27816. ** Translate UTF-8 to UTF-8.
  27817. **
  27818. ** This has the effect of making sure that the string is well-formed
  27819. ** UTF-8. Miscoded characters are removed.
  27820. **
  27821. ** The translation is done in-place and aborted if the output
  27822. ** overruns the input.
  27823. */
  27824. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  27825. unsigned char *zOut = zIn;
  27826. unsigned char *zStart = zIn;
  27827. u32 c;
  27828. while( zIn[0] && zOut<=zIn ){
  27829. c = sqlite3Utf8Read((const u8**)&zIn);
  27830. if( c!=0xfffd ){
  27831. WRITE_UTF8(zOut, c);
  27832. }
  27833. }
  27834. *zOut = 0;
  27835. return (int)(zOut - zStart);
  27836. }
  27837. #endif
  27838. #ifndef SQLITE_OMIT_UTF16
  27839. /*
  27840. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  27841. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  27842. ** be freed by the calling function.
  27843. **
  27844. ** NULL is returned if there is an allocation error.
  27845. */
  27846. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  27847. Mem m;
  27848. memset(&m, 0, sizeof(m));
  27849. m.db = db;
  27850. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  27851. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  27852. if( db->mallocFailed ){
  27853. sqlite3VdbeMemRelease(&m);
  27854. m.z = 0;
  27855. }
  27856. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  27857. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  27858. assert( m.z || db->mallocFailed );
  27859. return m.z;
  27860. }
  27861. /*
  27862. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  27863. ** Return the number of bytes in the first nChar unicode characters
  27864. ** in pZ. nChar must be non-negative.
  27865. */
  27866. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  27867. int c;
  27868. unsigned char const *z = zIn;
  27869. int n = 0;
  27870. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  27871. while( n<nChar ){
  27872. READ_UTF16BE(z, 1, c);
  27873. n++;
  27874. }
  27875. }else{
  27876. while( n<nChar ){
  27877. READ_UTF16LE(z, 1, c);
  27878. n++;
  27879. }
  27880. }
  27881. return (int)(z-(unsigned char const *)zIn);
  27882. }
  27883. #if defined(SQLITE_TEST)
  27884. /*
  27885. ** This routine is called from the TCL test function "translate_selftest".
  27886. ** It checks that the primitives for serializing and deserializing
  27887. ** characters in each encoding are inverses of each other.
  27888. */
  27889. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  27890. unsigned int i, t;
  27891. unsigned char zBuf[20];
  27892. unsigned char *z;
  27893. int n;
  27894. unsigned int c;
  27895. for(i=0; i<0x00110000; i++){
  27896. z = zBuf;
  27897. WRITE_UTF8(z, i);
  27898. n = (int)(z-zBuf);
  27899. assert( n>0 && n<=4 );
  27900. z[0] = 0;
  27901. z = zBuf;
  27902. c = sqlite3Utf8Read((const u8**)&z);
  27903. t = i;
  27904. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  27905. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  27906. assert( c==t );
  27907. assert( (z-zBuf)==n );
  27908. }
  27909. for(i=0; i<0x00110000; i++){
  27910. if( i>=0xD800 && i<0xE000 ) continue;
  27911. z = zBuf;
  27912. WRITE_UTF16LE(z, i);
  27913. n = (int)(z-zBuf);
  27914. assert( n>0 && n<=4 );
  27915. z[0] = 0;
  27916. z = zBuf;
  27917. READ_UTF16LE(z, 1, c);
  27918. assert( c==i );
  27919. assert( (z-zBuf)==n );
  27920. }
  27921. for(i=0; i<0x00110000; i++){
  27922. if( i>=0xD800 && i<0xE000 ) continue;
  27923. z = zBuf;
  27924. WRITE_UTF16BE(z, i);
  27925. n = (int)(z-zBuf);
  27926. assert( n>0 && n<=4 );
  27927. z[0] = 0;
  27928. z = zBuf;
  27929. READ_UTF16BE(z, 1, c);
  27930. assert( c==i );
  27931. assert( (z-zBuf)==n );
  27932. }
  27933. }
  27934. #endif /* SQLITE_TEST */
  27935. #endif /* SQLITE_OMIT_UTF16 */
  27936. /************** End of utf.c *************************************************/
  27937. /************** Begin file util.c ********************************************/
  27938. /*
  27939. ** 2001 September 15
  27940. **
  27941. ** The author disclaims copyright to this source code. In place of
  27942. ** a legal notice, here is a blessing:
  27943. **
  27944. ** May you do good and not evil.
  27945. ** May you find forgiveness for yourself and forgive others.
  27946. ** May you share freely, never taking more than you give.
  27947. **
  27948. *************************************************************************
  27949. ** Utility functions used throughout sqlite.
  27950. **
  27951. ** This file contains functions for allocating memory, comparing
  27952. ** strings, and stuff like that.
  27953. **
  27954. */
  27955. /* #include "sqliteInt.h" */
  27956. /* #include <stdarg.h> */
  27957. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  27958. # include <math.h>
  27959. #endif
  27960. /*
  27961. ** Routine needed to support the testcase() macro.
  27962. */
  27963. #ifdef SQLITE_COVERAGE_TEST
  27964. SQLITE_PRIVATE void sqlite3Coverage(int x){
  27965. static unsigned dummy = 0;
  27966. dummy += (unsigned)x;
  27967. }
  27968. #endif
  27969. /*
  27970. ** Give a callback to the test harness that can be used to simulate faults
  27971. ** in places where it is difficult or expensive to do so purely by means
  27972. ** of inputs.
  27973. **
  27974. ** The intent of the integer argument is to let the fault simulator know
  27975. ** which of multiple sqlite3FaultSim() calls has been hit.
  27976. **
  27977. ** Return whatever integer value the test callback returns, or return
  27978. ** SQLITE_OK if no test callback is installed.
  27979. */
  27980. #ifndef SQLITE_UNTESTABLE
  27981. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  27982. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  27983. return xCallback ? xCallback(iTest) : SQLITE_OK;
  27984. }
  27985. #endif
  27986. #ifndef SQLITE_OMIT_FLOATING_POINT
  27987. /*
  27988. ** Return true if the floating point value is Not a Number (NaN).
  27989. **
  27990. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  27991. ** Otherwise, we have our own implementation that works on most systems.
  27992. */
  27993. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  27994. int rc; /* The value return */
  27995. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  27996. /*
  27997. ** Systems that support the isnan() library function should probably
  27998. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  27999. ** found that many systems do not have a working isnan() function so
  28000. ** this implementation is provided as an alternative.
  28001. **
  28002. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  28003. ** On the other hand, the use of -ffast-math comes with the following
  28004. ** warning:
  28005. **
  28006. ** This option [-ffast-math] should never be turned on by any
  28007. ** -O option since it can result in incorrect output for programs
  28008. ** which depend on an exact implementation of IEEE or ISO
  28009. ** rules/specifications for math functions.
  28010. **
  28011. ** Under MSVC, this NaN test may fail if compiled with a floating-
  28012. ** point precision mode other than /fp:precise. From the MSDN
  28013. ** documentation:
  28014. **
  28015. ** The compiler [with /fp:precise] will properly handle comparisons
  28016. ** involving NaN. For example, x != x evaluates to true if x is NaN
  28017. ** ...
  28018. */
  28019. #ifdef __FAST_MATH__
  28020. # error SQLite will not work correctly with the -ffast-math option of GCC.
  28021. #endif
  28022. volatile double y = x;
  28023. volatile double z = y;
  28024. rc = (y!=z);
  28025. #else /* if HAVE_ISNAN */
  28026. rc = isnan(x);
  28027. #endif /* HAVE_ISNAN */
  28028. testcase( rc );
  28029. return rc;
  28030. }
  28031. #endif /* SQLITE_OMIT_FLOATING_POINT */
  28032. /*
  28033. ** Compute a string length that is limited to what can be stored in
  28034. ** lower 30 bits of a 32-bit signed integer.
  28035. **
  28036. ** The value returned will never be negative. Nor will it ever be greater
  28037. ** than the actual length of the string. For very long strings (greater
  28038. ** than 1GiB) the value returned might be less than the true string length.
  28039. */
  28040. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  28041. if( z==0 ) return 0;
  28042. return 0x3fffffff & (int)strlen(z);
  28043. }
  28044. /*
  28045. ** Return the declared type of a column. Or return zDflt if the column
  28046. ** has no declared type.
  28047. **
  28048. ** The column type is an extra string stored after the zero-terminator on
  28049. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  28050. */
  28051. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  28052. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  28053. return pCol->zName + strlen(pCol->zName) + 1;
  28054. }
  28055. /*
  28056. ** Helper function for sqlite3Error() - called rarely. Broken out into
  28057. ** a separate routine to avoid unnecessary register saves on entry to
  28058. ** sqlite3Error().
  28059. */
  28060. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  28061. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  28062. sqlite3SystemError(db, err_code);
  28063. }
  28064. /*
  28065. ** Set the current error code to err_code and clear any prior error message.
  28066. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  28067. ** that would be appropriate.
  28068. */
  28069. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  28070. assert( db!=0 );
  28071. db->errCode = err_code;
  28072. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  28073. }
  28074. /*
  28075. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  28076. ** to do based on the SQLite error code in rc.
  28077. */
  28078. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  28079. if( rc==SQLITE_IOERR_NOMEM ) return;
  28080. rc &= 0xff;
  28081. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  28082. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  28083. }
  28084. }
  28085. /*
  28086. ** Set the most recent error code and error string for the sqlite
  28087. ** handle "db". The error code is set to "err_code".
  28088. **
  28089. ** If it is not NULL, string zFormat specifies the format of the
  28090. ** error string in the style of the printf functions: The following
  28091. ** format characters are allowed:
  28092. **
  28093. ** %s Insert a string
  28094. ** %z A string that should be freed after use
  28095. ** %d Insert an integer
  28096. ** %T Insert a token
  28097. ** %S Insert the first element of a SrcList
  28098. **
  28099. ** zFormat and any string tokens that follow it are assumed to be
  28100. ** encoded in UTF-8.
  28101. **
  28102. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  28103. ** should be called with err_code set to SQLITE_OK and zFormat set
  28104. ** to NULL.
  28105. */
  28106. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  28107. assert( db!=0 );
  28108. db->errCode = err_code;
  28109. sqlite3SystemError(db, err_code);
  28110. if( zFormat==0 ){
  28111. sqlite3Error(db, err_code);
  28112. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  28113. char *z;
  28114. va_list ap;
  28115. va_start(ap, zFormat);
  28116. z = sqlite3VMPrintf(db, zFormat, ap);
  28117. va_end(ap);
  28118. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  28119. }
  28120. }
  28121. /*
  28122. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  28123. ** The following formatting characters are allowed:
  28124. **
  28125. ** %s Insert a string
  28126. ** %z A string that should be freed after use
  28127. ** %d Insert an integer
  28128. ** %T Insert a token
  28129. ** %S Insert the first element of a SrcList
  28130. **
  28131. ** This function should be used to report any error that occurs while
  28132. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  28133. ** last thing the sqlite3_prepare() function does is copy the error
  28134. ** stored by this function into the database handle using sqlite3Error().
  28135. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  28136. ** during statement execution (sqlite3_step() etc.).
  28137. */
  28138. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  28139. char *zMsg;
  28140. va_list ap;
  28141. sqlite3 *db = pParse->db;
  28142. va_start(ap, zFormat);
  28143. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  28144. va_end(ap);
  28145. if( db->suppressErr ){
  28146. sqlite3DbFree(db, zMsg);
  28147. }else{
  28148. pParse->nErr++;
  28149. sqlite3DbFree(db, pParse->zErrMsg);
  28150. pParse->zErrMsg = zMsg;
  28151. pParse->rc = SQLITE_ERROR;
  28152. }
  28153. }
  28154. /*
  28155. ** Convert an SQL-style quoted string into a normal string by removing
  28156. ** the quote characters. The conversion is done in-place. If the
  28157. ** input does not begin with a quote character, then this routine
  28158. ** is a no-op.
  28159. **
  28160. ** The input string must be zero-terminated. A new zero-terminator
  28161. ** is added to the dequoted string.
  28162. **
  28163. ** The return value is -1 if no dequoting occurs or the length of the
  28164. ** dequoted string, exclusive of the zero terminator, if dequoting does
  28165. ** occur.
  28166. **
  28167. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  28168. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  28169. ** "a-b-c".
  28170. */
  28171. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  28172. char quote;
  28173. int i, j;
  28174. if( z==0 ) return;
  28175. quote = z[0];
  28176. if( !sqlite3Isquote(quote) ) return;
  28177. if( quote=='[' ) quote = ']';
  28178. for(i=1, j=0;; i++){
  28179. assert( z[i] );
  28180. if( z[i]==quote ){
  28181. if( z[i+1]==quote ){
  28182. z[j++] = quote;
  28183. i++;
  28184. }else{
  28185. break;
  28186. }
  28187. }else{
  28188. z[j++] = z[i];
  28189. }
  28190. }
  28191. z[j] = 0;
  28192. }
  28193. /*
  28194. ** Generate a Token object from a string
  28195. */
  28196. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  28197. p->z = z;
  28198. p->n = sqlite3Strlen30(z);
  28199. }
  28200. /* Convenient short-hand */
  28201. #define UpperToLower sqlite3UpperToLower
  28202. /*
  28203. ** Some systems have stricmp(). Others have strcasecmp(). Because
  28204. ** there is no consistency, we will define our own.
  28205. **
  28206. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  28207. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  28208. ** the contents of two buffers containing UTF-8 strings in a
  28209. ** case-independent fashion, using the same definition of "case
  28210. ** independence" that SQLite uses internally when comparing identifiers.
  28211. */
  28212. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  28213. if( zLeft==0 ){
  28214. return zRight ? -1 : 0;
  28215. }else if( zRight==0 ){
  28216. return 1;
  28217. }
  28218. return sqlite3StrICmp(zLeft, zRight);
  28219. }
  28220. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  28221. unsigned char *a, *b;
  28222. int c;
  28223. a = (unsigned char *)zLeft;
  28224. b = (unsigned char *)zRight;
  28225. for(;;){
  28226. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  28227. if( c || *a==0 ) break;
  28228. a++;
  28229. b++;
  28230. }
  28231. return c;
  28232. }
  28233. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  28234. register unsigned char *a, *b;
  28235. if( zLeft==0 ){
  28236. return zRight ? -1 : 0;
  28237. }else if( zRight==0 ){
  28238. return 1;
  28239. }
  28240. a = (unsigned char *)zLeft;
  28241. b = (unsigned char *)zRight;
  28242. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  28243. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  28244. }
  28245. /*
  28246. ** Compute 10 to the E-th power. Examples: E==1 results in 10.
  28247. ** E==2 results in 100. E==50 results in 1.0e50.
  28248. **
  28249. ** This routine only works for values of E between 1 and 341.
  28250. */
  28251. static LONGDOUBLE_TYPE sqlite3Pow10(int E){
  28252. #if defined(_MSC_VER)
  28253. static const LONGDOUBLE_TYPE x[] = {
  28254. 1.0e+001,
  28255. 1.0e+002,
  28256. 1.0e+004,
  28257. 1.0e+008,
  28258. 1.0e+016,
  28259. 1.0e+032,
  28260. 1.0e+064,
  28261. 1.0e+128,
  28262. 1.0e+256
  28263. };
  28264. LONGDOUBLE_TYPE r = 1.0;
  28265. int i;
  28266. assert( E>=0 && E<=307 );
  28267. for(i=0; E!=0; i++, E >>=1){
  28268. if( E & 1 ) r *= x[i];
  28269. }
  28270. return r;
  28271. #else
  28272. LONGDOUBLE_TYPE x = 10.0;
  28273. LONGDOUBLE_TYPE r = 1.0;
  28274. while(1){
  28275. if( E & 1 ) r *= x;
  28276. E >>= 1;
  28277. if( E==0 ) break;
  28278. x *= x;
  28279. }
  28280. return r;
  28281. #endif
  28282. }
  28283. /*
  28284. ** The string z[] is an text representation of a real number.
  28285. ** Convert this string to a double and write it into *pResult.
  28286. **
  28287. ** The string z[] is length bytes in length (bytes, not characters) and
  28288. ** uses the encoding enc. The string is not necessarily zero-terminated.
  28289. **
  28290. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  28291. ** if the string is empty or contains extraneous text. Valid numbers
  28292. ** are in one of these formats:
  28293. **
  28294. ** [+-]digits[E[+-]digits]
  28295. ** [+-]digits.[digits][E[+-]digits]
  28296. ** [+-].digits[E[+-]digits]
  28297. **
  28298. ** Leading and trailing whitespace is ignored for the purpose of determining
  28299. ** validity.
  28300. **
  28301. ** If some prefix of the input string is a valid number, this routine
  28302. ** returns FALSE but it still converts the prefix and writes the result
  28303. ** into *pResult.
  28304. */
  28305. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  28306. #ifndef SQLITE_OMIT_FLOATING_POINT
  28307. int incr;
  28308. const char *zEnd = z + length;
  28309. /* sign * significand * (10 ^ (esign * exponent)) */
  28310. int sign = 1; /* sign of significand */
  28311. i64 s = 0; /* significand */
  28312. int d = 0; /* adjust exponent for shifting decimal point */
  28313. int esign = 1; /* sign of exponent */
  28314. int e = 0; /* exponent */
  28315. int eValid = 1; /* True exponent is either not used or is well-formed */
  28316. double result;
  28317. int nDigits = 0;
  28318. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  28319. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  28320. *pResult = 0.0; /* Default return value, in case of an error */
  28321. if( enc==SQLITE_UTF8 ){
  28322. incr = 1;
  28323. }else{
  28324. int i;
  28325. incr = 2;
  28326. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  28327. for(i=3-enc; i<length && z[i]==0; i+=2){}
  28328. nonNum = i<length;
  28329. zEnd = &z[i^1];
  28330. z += (enc&1);
  28331. }
  28332. /* skip leading spaces */
  28333. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  28334. if( z>=zEnd ) return 0;
  28335. /* get sign of significand */
  28336. if( *z=='-' ){
  28337. sign = -1;
  28338. z+=incr;
  28339. }else if( *z=='+' ){
  28340. z+=incr;
  28341. }
  28342. /* copy max significant digits to significand */
  28343. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  28344. s = s*10 + (*z - '0');
  28345. z+=incr; nDigits++;
  28346. }
  28347. /* skip non-significant significand digits
  28348. ** (increase exponent by d to shift decimal left) */
  28349. while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
  28350. if( z>=zEnd ) goto do_atof_calc;
  28351. /* if decimal point is present */
  28352. if( *z=='.' ){
  28353. z+=incr;
  28354. /* copy digits from after decimal to significand
  28355. ** (decrease exponent by d to shift decimal right) */
  28356. while( z<zEnd && sqlite3Isdigit(*z) ){
  28357. if( s<((LARGEST_INT64-9)/10) ){
  28358. s = s*10 + (*z - '0');
  28359. d--;
  28360. }
  28361. z+=incr; nDigits++;
  28362. }
  28363. }
  28364. if( z>=zEnd ) goto do_atof_calc;
  28365. /* if exponent is present */
  28366. if( *z=='e' || *z=='E' ){
  28367. z+=incr;
  28368. eValid = 0;
  28369. /* This branch is needed to avoid a (harmless) buffer overread. The
  28370. ** special comment alerts the mutation tester that the correct answer
  28371. ** is obtained even if the branch is omitted */
  28372. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  28373. /* get sign of exponent */
  28374. if( *z=='-' ){
  28375. esign = -1;
  28376. z+=incr;
  28377. }else if( *z=='+' ){
  28378. z+=incr;
  28379. }
  28380. /* copy digits to exponent */
  28381. while( z<zEnd && sqlite3Isdigit(*z) ){
  28382. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  28383. z+=incr;
  28384. eValid = 1;
  28385. }
  28386. }
  28387. /* skip trailing spaces */
  28388. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  28389. do_atof_calc:
  28390. /* adjust exponent by d, and update sign */
  28391. e = (e*esign) + d;
  28392. if( e<0 ) {
  28393. esign = -1;
  28394. e *= -1;
  28395. } else {
  28396. esign = 1;
  28397. }
  28398. if( s==0 ) {
  28399. /* In the IEEE 754 standard, zero is signed. */
  28400. result = sign<0 ? -(double)0 : (double)0;
  28401. } else {
  28402. /* Attempt to reduce exponent.
  28403. **
  28404. ** Branches that are not required for the correct answer but which only
  28405. ** help to obtain the correct answer faster are marked with special
  28406. ** comments, as a hint to the mutation tester.
  28407. */
  28408. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  28409. if( esign>0 ){
  28410. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  28411. s *= 10;
  28412. }else{
  28413. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  28414. s /= 10;
  28415. }
  28416. e--;
  28417. }
  28418. /* adjust the sign of significand */
  28419. s = sign<0 ? -s : s;
  28420. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  28421. result = (double)s;
  28422. }else{
  28423. /* attempt to handle extremely small/large numbers better */
  28424. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  28425. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  28426. LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
  28427. if( esign<0 ){
  28428. result = s / scale;
  28429. result /= 1.0e+308;
  28430. }else{
  28431. result = s * scale;
  28432. result *= 1.0e+308;
  28433. }
  28434. }else{ assert( e>=342 );
  28435. if( esign<0 ){
  28436. result = 0.0*s;
  28437. }else{
  28438. #ifdef INFINITY
  28439. result = INFINITY*s;
  28440. #else
  28441. result = 1e308*1e308*s; /* Infinity */
  28442. #endif
  28443. }
  28444. }
  28445. }else{
  28446. LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
  28447. if( esign<0 ){
  28448. result = s / scale;
  28449. }else{
  28450. result = s * scale;
  28451. }
  28452. }
  28453. }
  28454. }
  28455. /* store the result */
  28456. *pResult = result;
  28457. /* return true if number and no extra non-whitespace chracters after */
  28458. return z==zEnd && nDigits>0 && eValid && nonNum==0;
  28459. #else
  28460. return !sqlite3Atoi64(z, pResult, length, enc);
  28461. #endif /* SQLITE_OMIT_FLOATING_POINT */
  28462. }
  28463. /*
  28464. ** Compare the 19-character string zNum against the text representation
  28465. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  28466. ** if zNum is less than, equal to, or greater than the string.
  28467. ** Note that zNum must contain exactly 19 characters.
  28468. **
  28469. ** Unlike memcmp() this routine is guaranteed to return the difference
  28470. ** in the values of the last digit if the only difference is in the
  28471. ** last digit. So, for example,
  28472. **
  28473. ** compare2pow63("9223372036854775800", 1)
  28474. **
  28475. ** will return -8.
  28476. */
  28477. static int compare2pow63(const char *zNum, int incr){
  28478. int c = 0;
  28479. int i;
  28480. /* 012345678901234567 */
  28481. const char *pow63 = "922337203685477580";
  28482. for(i=0; c==0 && i<18; i++){
  28483. c = (zNum[i*incr]-pow63[i])*10;
  28484. }
  28485. if( c==0 ){
  28486. c = zNum[18*incr] - '8';
  28487. testcase( c==(-1) );
  28488. testcase( c==0 );
  28489. testcase( c==(+1) );
  28490. }
  28491. return c;
  28492. }
  28493. /*
  28494. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  28495. ** routine does *not* accept hexadecimal notation.
  28496. **
  28497. ** Returns:
  28498. **
  28499. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  28500. ** 1 Excess non-space text after the integer value
  28501. ** 2 Integer too large for a 64-bit signed integer or is malformed
  28502. ** 3 Special case of 9223372036854775808
  28503. **
  28504. ** length is the number of bytes in the string (bytes, not characters).
  28505. ** The string is not necessarily zero-terminated. The encoding is
  28506. ** given by enc.
  28507. */
  28508. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  28509. int incr;
  28510. u64 u = 0;
  28511. int neg = 0; /* assume positive */
  28512. int i;
  28513. int c = 0;
  28514. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  28515. int rc; /* Baseline return code */
  28516. const char *zStart;
  28517. const char *zEnd = zNum + length;
  28518. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  28519. if( enc==SQLITE_UTF8 ){
  28520. incr = 1;
  28521. }else{
  28522. incr = 2;
  28523. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  28524. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  28525. nonNum = i<length;
  28526. zEnd = &zNum[i^1];
  28527. zNum += (enc&1);
  28528. }
  28529. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  28530. if( zNum<zEnd ){
  28531. if( *zNum=='-' ){
  28532. neg = 1;
  28533. zNum+=incr;
  28534. }else if( *zNum=='+' ){
  28535. zNum+=incr;
  28536. }
  28537. }
  28538. zStart = zNum;
  28539. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  28540. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  28541. u = u*10 + c - '0';
  28542. }
  28543. testcase( i==18*incr );
  28544. testcase( i==19*incr );
  28545. testcase( i==20*incr );
  28546. if( u>LARGEST_INT64 ){
  28547. /* This test and assignment is needed only to suppress UB warnings
  28548. ** from clang and -fsanitize=undefined. This test and assignment make
  28549. ** the code a little larger and slower, and no harm comes from omitting
  28550. ** them, but we must appaise the undefined-behavior pharisees. */
  28551. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  28552. }else if( neg ){
  28553. *pNum = -(i64)u;
  28554. }else{
  28555. *pNum = (i64)u;
  28556. }
  28557. rc = 0;
  28558. if( (i==0 && zStart==zNum) /* No digits */
  28559. || nonNum /* UTF16 with high-order bytes non-zero */
  28560. ){
  28561. rc = 1;
  28562. }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
  28563. int jj = i;
  28564. do{
  28565. if( !sqlite3Isspace(zNum[jj]) ){
  28566. rc = 1; /* Extra non-space text after the integer */
  28567. break;
  28568. }
  28569. jj += incr;
  28570. }while( &zNum[jj]<zEnd );
  28571. }
  28572. if( i<19*incr ){
  28573. /* Less than 19 digits, so we know that it fits in 64 bits */
  28574. assert( u<=LARGEST_INT64 );
  28575. return rc;
  28576. }else{
  28577. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  28578. c = i>19*incr ? 1 : compare2pow63(zNum, incr);
  28579. if( c<0 ){
  28580. /* zNum is less than 9223372036854775808 so it fits */
  28581. assert( u<=LARGEST_INT64 );
  28582. return rc;
  28583. }else{
  28584. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  28585. if( c>0 ){
  28586. /* zNum is greater than 9223372036854775808 so it overflows */
  28587. return 2;
  28588. }else{
  28589. /* zNum is exactly 9223372036854775808. Fits if negative. The
  28590. ** special case 2 overflow if positive */
  28591. assert( u-1==LARGEST_INT64 );
  28592. return neg ? rc : 3;
  28593. }
  28594. }
  28595. }
  28596. }
  28597. /*
  28598. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  28599. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  28600. ** whereas sqlite3Atoi64() does not.
  28601. **
  28602. ** Returns:
  28603. **
  28604. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  28605. ** 1 Excess text after the integer value
  28606. ** 2 Integer too large for a 64-bit signed integer or is malformed
  28607. ** 3 Special case of 9223372036854775808
  28608. */
  28609. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  28610. #ifndef SQLITE_OMIT_HEX_INTEGER
  28611. if( z[0]=='0'
  28612. && (z[1]=='x' || z[1]=='X')
  28613. ){
  28614. u64 u = 0;
  28615. int i, k;
  28616. for(i=2; z[i]=='0'; i++){}
  28617. for(k=i; sqlite3Isxdigit(z[k]); k++){
  28618. u = u*16 + sqlite3HexToInt(z[k]);
  28619. }
  28620. memcpy(pOut, &u, 8);
  28621. return (z[k]==0 && k-i<=16) ? 0 : 2;
  28622. }else
  28623. #endif /* SQLITE_OMIT_HEX_INTEGER */
  28624. {
  28625. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  28626. }
  28627. }
  28628. /*
  28629. ** If zNum represents an integer that will fit in 32-bits, then set
  28630. ** *pValue to that integer and return true. Otherwise return false.
  28631. **
  28632. ** This routine accepts both decimal and hexadecimal notation for integers.
  28633. **
  28634. ** Any non-numeric characters that following zNum are ignored.
  28635. ** This is different from sqlite3Atoi64() which requires the
  28636. ** input number to be zero-terminated.
  28637. */
  28638. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  28639. sqlite_int64 v = 0;
  28640. int i, c;
  28641. int neg = 0;
  28642. if( zNum[0]=='-' ){
  28643. neg = 1;
  28644. zNum++;
  28645. }else if( zNum[0]=='+' ){
  28646. zNum++;
  28647. }
  28648. #ifndef SQLITE_OMIT_HEX_INTEGER
  28649. else if( zNum[0]=='0'
  28650. && (zNum[1]=='x' || zNum[1]=='X')
  28651. && sqlite3Isxdigit(zNum[2])
  28652. ){
  28653. u32 u = 0;
  28654. zNum += 2;
  28655. while( zNum[0]=='0' ) zNum++;
  28656. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  28657. u = u*16 + sqlite3HexToInt(zNum[i]);
  28658. }
  28659. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  28660. memcpy(pValue, &u, 4);
  28661. return 1;
  28662. }else{
  28663. return 0;
  28664. }
  28665. }
  28666. #endif
  28667. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  28668. while( zNum[0]=='0' ) zNum++;
  28669. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  28670. v = v*10 + c;
  28671. }
  28672. /* The longest decimal representation of a 32 bit integer is 10 digits:
  28673. **
  28674. ** 1234567890
  28675. ** 2^31 -> 2147483648
  28676. */
  28677. testcase( i==10 );
  28678. if( i>10 ){
  28679. return 0;
  28680. }
  28681. testcase( v-neg==2147483647 );
  28682. if( v-neg>2147483647 ){
  28683. return 0;
  28684. }
  28685. if( neg ){
  28686. v = -v;
  28687. }
  28688. *pValue = (int)v;
  28689. return 1;
  28690. }
  28691. /*
  28692. ** Return a 32-bit integer value extracted from a string. If the
  28693. ** string is not an integer, just return 0.
  28694. */
  28695. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  28696. int x = 0;
  28697. if( z ) sqlite3GetInt32(z, &x);
  28698. return x;
  28699. }
  28700. /*
  28701. ** The variable-length integer encoding is as follows:
  28702. **
  28703. ** KEY:
  28704. ** A = 0xxxxxxx 7 bits of data and one flag bit
  28705. ** B = 1xxxxxxx 7 bits of data and one flag bit
  28706. ** C = xxxxxxxx 8 bits of data
  28707. **
  28708. ** 7 bits - A
  28709. ** 14 bits - BA
  28710. ** 21 bits - BBA
  28711. ** 28 bits - BBBA
  28712. ** 35 bits - BBBBA
  28713. ** 42 bits - BBBBBA
  28714. ** 49 bits - BBBBBBA
  28715. ** 56 bits - BBBBBBBA
  28716. ** 64 bits - BBBBBBBBC
  28717. */
  28718. /*
  28719. ** Write a 64-bit variable-length integer to memory starting at p[0].
  28720. ** The length of data write will be between 1 and 9 bytes. The number
  28721. ** of bytes written is returned.
  28722. **
  28723. ** A variable-length integer consists of the lower 7 bits of each byte
  28724. ** for all bytes that have the 8th bit set and one byte with the 8th
  28725. ** bit clear. Except, if we get to the 9th byte, it stores the full
  28726. ** 8 bits and is the last byte.
  28727. */
  28728. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  28729. int i, j, n;
  28730. u8 buf[10];
  28731. if( v & (((u64)0xff000000)<<32) ){
  28732. p[8] = (u8)v;
  28733. v >>= 8;
  28734. for(i=7; i>=0; i--){
  28735. p[i] = (u8)((v & 0x7f) | 0x80);
  28736. v >>= 7;
  28737. }
  28738. return 9;
  28739. }
  28740. n = 0;
  28741. do{
  28742. buf[n++] = (u8)((v & 0x7f) | 0x80);
  28743. v >>= 7;
  28744. }while( v!=0 );
  28745. buf[0] &= 0x7f;
  28746. assert( n<=9 );
  28747. for(i=0, j=n-1; j>=0; j--, i++){
  28748. p[i] = buf[j];
  28749. }
  28750. return n;
  28751. }
  28752. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  28753. if( v<=0x7f ){
  28754. p[0] = v&0x7f;
  28755. return 1;
  28756. }
  28757. if( v<=0x3fff ){
  28758. p[0] = ((v>>7)&0x7f)|0x80;
  28759. p[1] = v&0x7f;
  28760. return 2;
  28761. }
  28762. return putVarint64(p,v);
  28763. }
  28764. /*
  28765. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  28766. ** are defined here rather than simply putting the constant expressions
  28767. ** inline in order to work around bugs in the RVT compiler.
  28768. **
  28769. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  28770. **
  28771. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  28772. */
  28773. #define SLOT_2_0 0x001fc07f
  28774. #define SLOT_4_2_0 0xf01fc07f
  28775. /*
  28776. ** Read a 64-bit variable-length integer from memory starting at p[0].
  28777. ** Return the number of bytes read. The value is stored in *v.
  28778. */
  28779. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  28780. u32 a,b,s;
  28781. a = *p;
  28782. /* a: p0 (unmasked) */
  28783. if (!(a&0x80))
  28784. {
  28785. *v = a;
  28786. return 1;
  28787. }
  28788. p++;
  28789. b = *p;
  28790. /* b: p1 (unmasked) */
  28791. if (!(b&0x80))
  28792. {
  28793. a &= 0x7f;
  28794. a = a<<7;
  28795. a |= b;
  28796. *v = a;
  28797. return 2;
  28798. }
  28799. /* Verify that constants are precomputed correctly */
  28800. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  28801. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  28802. p++;
  28803. a = a<<14;
  28804. a |= *p;
  28805. /* a: p0<<14 | p2 (unmasked) */
  28806. if (!(a&0x80))
  28807. {
  28808. a &= SLOT_2_0;
  28809. b &= 0x7f;
  28810. b = b<<7;
  28811. a |= b;
  28812. *v = a;
  28813. return 3;
  28814. }
  28815. /* CSE1 from below */
  28816. a &= SLOT_2_0;
  28817. p++;
  28818. b = b<<14;
  28819. b |= *p;
  28820. /* b: p1<<14 | p3 (unmasked) */
  28821. if (!(b&0x80))
  28822. {
  28823. b &= SLOT_2_0;
  28824. /* moved CSE1 up */
  28825. /* a &= (0x7f<<14)|(0x7f); */
  28826. a = a<<7;
  28827. a |= b;
  28828. *v = a;
  28829. return 4;
  28830. }
  28831. /* a: p0<<14 | p2 (masked) */
  28832. /* b: p1<<14 | p3 (unmasked) */
  28833. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  28834. /* moved CSE1 up */
  28835. /* a &= (0x7f<<14)|(0x7f); */
  28836. b &= SLOT_2_0;
  28837. s = a;
  28838. /* s: p0<<14 | p2 (masked) */
  28839. p++;
  28840. a = a<<14;
  28841. a |= *p;
  28842. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  28843. if (!(a&0x80))
  28844. {
  28845. /* we can skip these cause they were (effectively) done above
  28846. ** while calculating s */
  28847. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  28848. /* b &= (0x7f<<14)|(0x7f); */
  28849. b = b<<7;
  28850. a |= b;
  28851. s = s>>18;
  28852. *v = ((u64)s)<<32 | a;
  28853. return 5;
  28854. }
  28855. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  28856. s = s<<7;
  28857. s |= b;
  28858. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  28859. p++;
  28860. b = b<<14;
  28861. b |= *p;
  28862. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  28863. if (!(b&0x80))
  28864. {
  28865. /* we can skip this cause it was (effectively) done above in calc'ing s */
  28866. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  28867. a &= SLOT_2_0;
  28868. a = a<<7;
  28869. a |= b;
  28870. s = s>>18;
  28871. *v = ((u64)s)<<32 | a;
  28872. return 6;
  28873. }
  28874. p++;
  28875. a = a<<14;
  28876. a |= *p;
  28877. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  28878. if (!(a&0x80))
  28879. {
  28880. a &= SLOT_4_2_0;
  28881. b &= SLOT_2_0;
  28882. b = b<<7;
  28883. a |= b;
  28884. s = s>>11;
  28885. *v = ((u64)s)<<32 | a;
  28886. return 7;
  28887. }
  28888. /* CSE2 from below */
  28889. a &= SLOT_2_0;
  28890. p++;
  28891. b = b<<14;
  28892. b |= *p;
  28893. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  28894. if (!(b&0x80))
  28895. {
  28896. b &= SLOT_4_2_0;
  28897. /* moved CSE2 up */
  28898. /* a &= (0x7f<<14)|(0x7f); */
  28899. a = a<<7;
  28900. a |= b;
  28901. s = s>>4;
  28902. *v = ((u64)s)<<32 | a;
  28903. return 8;
  28904. }
  28905. p++;
  28906. a = a<<15;
  28907. a |= *p;
  28908. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  28909. /* moved CSE2 up */
  28910. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  28911. b &= SLOT_2_0;
  28912. b = b<<8;
  28913. a |= b;
  28914. s = s<<4;
  28915. b = p[-4];
  28916. b &= 0x7f;
  28917. b = b>>3;
  28918. s |= b;
  28919. *v = ((u64)s)<<32 | a;
  28920. return 9;
  28921. }
  28922. /*
  28923. ** Read a 32-bit variable-length integer from memory starting at p[0].
  28924. ** Return the number of bytes read. The value is stored in *v.
  28925. **
  28926. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  28927. ** integer, then set *v to 0xffffffff.
  28928. **
  28929. ** A MACRO version, getVarint32, is provided which inlines the
  28930. ** single-byte case. All code should use the MACRO version as
  28931. ** this function assumes the single-byte case has already been handled.
  28932. */
  28933. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  28934. u32 a,b;
  28935. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  28936. ** by the getVarin32() macro */
  28937. a = *p;
  28938. /* a: p0 (unmasked) */
  28939. #ifndef getVarint32
  28940. if (!(a&0x80))
  28941. {
  28942. /* Values between 0 and 127 */
  28943. *v = a;
  28944. return 1;
  28945. }
  28946. #endif
  28947. /* The 2-byte case */
  28948. p++;
  28949. b = *p;
  28950. /* b: p1 (unmasked) */
  28951. if (!(b&0x80))
  28952. {
  28953. /* Values between 128 and 16383 */
  28954. a &= 0x7f;
  28955. a = a<<7;
  28956. *v = a | b;
  28957. return 2;
  28958. }
  28959. /* The 3-byte case */
  28960. p++;
  28961. a = a<<14;
  28962. a |= *p;
  28963. /* a: p0<<14 | p2 (unmasked) */
  28964. if (!(a&0x80))
  28965. {
  28966. /* Values between 16384 and 2097151 */
  28967. a &= (0x7f<<14)|(0x7f);
  28968. b &= 0x7f;
  28969. b = b<<7;
  28970. *v = a | b;
  28971. return 3;
  28972. }
  28973. /* A 32-bit varint is used to store size information in btrees.
  28974. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  28975. ** A 3-byte varint is sufficient, for example, to record the size
  28976. ** of a 1048569-byte BLOB or string.
  28977. **
  28978. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  28979. ** rare larger cases can be handled by the slower 64-bit varint
  28980. ** routine.
  28981. */
  28982. #if 1
  28983. {
  28984. u64 v64;
  28985. u8 n;
  28986. p -= 2;
  28987. n = sqlite3GetVarint(p, &v64);
  28988. assert( n>3 && n<=9 );
  28989. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  28990. *v = 0xffffffff;
  28991. }else{
  28992. *v = (u32)v64;
  28993. }
  28994. return n;
  28995. }
  28996. #else
  28997. /* For following code (kept for historical record only) shows an
  28998. ** unrolling for the 3- and 4-byte varint cases. This code is
  28999. ** slightly faster, but it is also larger and much harder to test.
  29000. */
  29001. p++;
  29002. b = b<<14;
  29003. b |= *p;
  29004. /* b: p1<<14 | p3 (unmasked) */
  29005. if (!(b&0x80))
  29006. {
  29007. /* Values between 2097152 and 268435455 */
  29008. b &= (0x7f<<14)|(0x7f);
  29009. a &= (0x7f<<14)|(0x7f);
  29010. a = a<<7;
  29011. *v = a | b;
  29012. return 4;
  29013. }
  29014. p++;
  29015. a = a<<14;
  29016. a |= *p;
  29017. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  29018. if (!(a&0x80))
  29019. {
  29020. /* Values between 268435456 and 34359738367 */
  29021. a &= SLOT_4_2_0;
  29022. b &= SLOT_4_2_0;
  29023. b = b<<7;
  29024. *v = a | b;
  29025. return 5;
  29026. }
  29027. /* We can only reach this point when reading a corrupt database
  29028. ** file. In that case we are not in any hurry. Use the (relatively
  29029. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  29030. ** value. */
  29031. {
  29032. u64 v64;
  29033. u8 n;
  29034. p -= 4;
  29035. n = sqlite3GetVarint(p, &v64);
  29036. assert( n>5 && n<=9 );
  29037. *v = (u32)v64;
  29038. return n;
  29039. }
  29040. #endif
  29041. }
  29042. /*
  29043. ** Return the number of bytes that will be needed to store the given
  29044. ** 64-bit integer.
  29045. */
  29046. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  29047. int i;
  29048. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  29049. return i;
  29050. }
  29051. /*
  29052. ** Read or write a four-byte big-endian integer value.
  29053. */
  29054. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  29055. #if SQLITE_BYTEORDER==4321
  29056. u32 x;
  29057. memcpy(&x,p,4);
  29058. return x;
  29059. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29060. u32 x;
  29061. memcpy(&x,p,4);
  29062. return __builtin_bswap32(x);
  29063. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29064. u32 x;
  29065. memcpy(&x,p,4);
  29066. return _byteswap_ulong(x);
  29067. #else
  29068. testcase( p[0]&0x80 );
  29069. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  29070. #endif
  29071. }
  29072. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  29073. #if SQLITE_BYTEORDER==4321
  29074. memcpy(p,&v,4);
  29075. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29076. u32 x = __builtin_bswap32(v);
  29077. memcpy(p,&x,4);
  29078. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29079. u32 x = _byteswap_ulong(v);
  29080. memcpy(p,&x,4);
  29081. #else
  29082. p[0] = (u8)(v>>24);
  29083. p[1] = (u8)(v>>16);
  29084. p[2] = (u8)(v>>8);
  29085. p[3] = (u8)v;
  29086. #endif
  29087. }
  29088. /*
  29089. ** Translate a single byte of Hex into an integer.
  29090. ** This routine only works if h really is a valid hexadecimal
  29091. ** character: 0..9a..fA..F
  29092. */
  29093. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  29094. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  29095. #ifdef SQLITE_ASCII
  29096. h += 9*(1&(h>>6));
  29097. #endif
  29098. #ifdef SQLITE_EBCDIC
  29099. h += 9*(1&~(h>>4));
  29100. #endif
  29101. return (u8)(h & 0xf);
  29102. }
  29103. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  29104. /*
  29105. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  29106. ** value. Return a pointer to its binary value. Space to hold the
  29107. ** binary value has been obtained from malloc and must be freed by
  29108. ** the calling routine.
  29109. */
  29110. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  29111. char *zBlob;
  29112. int i;
  29113. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  29114. n--;
  29115. if( zBlob ){
  29116. for(i=0; i<n; i+=2){
  29117. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  29118. }
  29119. zBlob[i/2] = 0;
  29120. }
  29121. return zBlob;
  29122. }
  29123. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  29124. /*
  29125. ** Log an error that is an API call on a connection pointer that should
  29126. ** not have been used. The "type" of connection pointer is given as the
  29127. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  29128. */
  29129. static void logBadConnection(const char *zType){
  29130. sqlite3_log(SQLITE_MISUSE,
  29131. "API call with %s database connection pointer",
  29132. zType
  29133. );
  29134. }
  29135. /*
  29136. ** Check to make sure we have a valid db pointer. This test is not
  29137. ** foolproof but it does provide some measure of protection against
  29138. ** misuse of the interface such as passing in db pointers that are
  29139. ** NULL or which have been previously closed. If this routine returns
  29140. ** 1 it means that the db pointer is valid and 0 if it should not be
  29141. ** dereferenced for any reason. The calling function should invoke
  29142. ** SQLITE_MISUSE immediately.
  29143. **
  29144. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  29145. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  29146. ** open properly and is not fit for general use but which can be
  29147. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  29148. */
  29149. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  29150. u32 magic;
  29151. if( db==0 ){
  29152. logBadConnection("NULL");
  29153. return 0;
  29154. }
  29155. magic = db->magic;
  29156. if( magic!=SQLITE_MAGIC_OPEN ){
  29157. if( sqlite3SafetyCheckSickOrOk(db) ){
  29158. testcase( sqlite3GlobalConfig.xLog!=0 );
  29159. logBadConnection("unopened");
  29160. }
  29161. return 0;
  29162. }else{
  29163. return 1;
  29164. }
  29165. }
  29166. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  29167. u32 magic;
  29168. magic = db->magic;
  29169. if( magic!=SQLITE_MAGIC_SICK &&
  29170. magic!=SQLITE_MAGIC_OPEN &&
  29171. magic!=SQLITE_MAGIC_BUSY ){
  29172. testcase( sqlite3GlobalConfig.xLog!=0 );
  29173. logBadConnection("invalid");
  29174. return 0;
  29175. }else{
  29176. return 1;
  29177. }
  29178. }
  29179. /*
  29180. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  29181. ** the other 64-bit signed integer at *pA and store the result in *pA.
  29182. ** Return 0 on success. Or if the operation would have resulted in an
  29183. ** overflow, leave *pA unchanged and return 1.
  29184. */
  29185. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  29186. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  29187. return __builtin_add_overflow(*pA, iB, pA);
  29188. #else
  29189. i64 iA = *pA;
  29190. testcase( iA==0 ); testcase( iA==1 );
  29191. testcase( iB==-1 ); testcase( iB==0 );
  29192. if( iB>=0 ){
  29193. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  29194. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  29195. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  29196. }else{
  29197. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  29198. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  29199. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  29200. }
  29201. *pA += iB;
  29202. return 0;
  29203. #endif
  29204. }
  29205. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  29206. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  29207. return __builtin_sub_overflow(*pA, iB, pA);
  29208. #else
  29209. testcase( iB==SMALLEST_INT64+1 );
  29210. if( iB==SMALLEST_INT64 ){
  29211. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  29212. if( (*pA)>=0 ) return 1;
  29213. *pA -= iB;
  29214. return 0;
  29215. }else{
  29216. return sqlite3AddInt64(pA, -iB);
  29217. }
  29218. #endif
  29219. }
  29220. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  29221. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  29222. return __builtin_mul_overflow(*pA, iB, pA);
  29223. #else
  29224. i64 iA = *pA;
  29225. if( iB>0 ){
  29226. if( iA>LARGEST_INT64/iB ) return 1;
  29227. if( iA<SMALLEST_INT64/iB ) return 1;
  29228. }else if( iB<0 ){
  29229. if( iA>0 ){
  29230. if( iB<SMALLEST_INT64/iA ) return 1;
  29231. }else if( iA<0 ){
  29232. if( iB==SMALLEST_INT64 ) return 1;
  29233. if( iA==SMALLEST_INT64 ) return 1;
  29234. if( -iA>LARGEST_INT64/-iB ) return 1;
  29235. }
  29236. }
  29237. *pA = iA*iB;
  29238. return 0;
  29239. #endif
  29240. }
  29241. /*
  29242. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  29243. ** if the integer has a value of -2147483648, return +2147483647
  29244. */
  29245. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  29246. if( x>=0 ) return x;
  29247. if( x==(int)0x80000000 ) return 0x7fffffff;
  29248. return -x;
  29249. }
  29250. #ifdef SQLITE_ENABLE_8_3_NAMES
  29251. /*
  29252. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  29253. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  29254. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  29255. ** three characters, then shorten the suffix on z[] to be the last three
  29256. ** characters of the original suffix.
  29257. **
  29258. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  29259. ** do the suffix shortening regardless of URI parameter.
  29260. **
  29261. ** Examples:
  29262. **
  29263. ** test.db-journal => test.nal
  29264. ** test.db-wal => test.wal
  29265. ** test.db-shm => test.shm
  29266. ** test.db-mj7f3319fa => test.9fa
  29267. */
  29268. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  29269. #if SQLITE_ENABLE_8_3_NAMES<2
  29270. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  29271. #endif
  29272. {
  29273. int i, sz;
  29274. sz = sqlite3Strlen30(z);
  29275. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  29276. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  29277. }
  29278. }
  29279. #endif
  29280. /*
  29281. ** Find (an approximate) sum of two LogEst values. This computation is
  29282. ** not a simple "+" operator because LogEst is stored as a logarithmic
  29283. ** value.
  29284. **
  29285. */
  29286. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  29287. static const unsigned char x[] = {
  29288. 10, 10, /* 0,1 */
  29289. 9, 9, /* 2,3 */
  29290. 8, 8, /* 4,5 */
  29291. 7, 7, 7, /* 6,7,8 */
  29292. 6, 6, 6, /* 9,10,11 */
  29293. 5, 5, 5, /* 12-14 */
  29294. 4, 4, 4, 4, /* 15-18 */
  29295. 3, 3, 3, 3, 3, 3, /* 19-24 */
  29296. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  29297. };
  29298. if( a>=b ){
  29299. if( a>b+49 ) return a;
  29300. if( a>b+31 ) return a+1;
  29301. return a+x[a-b];
  29302. }else{
  29303. if( b>a+49 ) return b;
  29304. if( b>a+31 ) return b+1;
  29305. return b+x[b-a];
  29306. }
  29307. }
  29308. /*
  29309. ** Convert an integer into a LogEst. In other words, compute an
  29310. ** approximation for 10*log2(x).
  29311. */
  29312. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  29313. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  29314. LogEst y = 40;
  29315. if( x<8 ){
  29316. if( x<2 ) return 0;
  29317. while( x<8 ){ y -= 10; x <<= 1; }
  29318. }else{
  29319. #if GCC_VERSION>=5004000
  29320. int i = 60 - __builtin_clzll(x);
  29321. y += i*10;
  29322. x >>= i;
  29323. #else
  29324. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  29325. while( x>15 ){ y += 10; x >>= 1; }
  29326. #endif
  29327. }
  29328. return a[x&7] + y - 10;
  29329. }
  29330. #ifndef SQLITE_OMIT_VIRTUALTABLE
  29331. /*
  29332. ** Convert a double into a LogEst
  29333. ** In other words, compute an approximation for 10*log2(x).
  29334. */
  29335. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  29336. u64 a;
  29337. LogEst e;
  29338. assert( sizeof(x)==8 && sizeof(a)==8 );
  29339. if( x<=1 ) return 0;
  29340. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  29341. memcpy(&a, &x, 8);
  29342. e = (a>>52) - 1022;
  29343. return e*10;
  29344. }
  29345. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  29346. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  29347. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  29348. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  29349. /*
  29350. ** Convert a LogEst into an integer.
  29351. **
  29352. ** Note that this routine is only used when one or more of various
  29353. ** non-standard compile-time options is enabled.
  29354. */
  29355. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  29356. u64 n;
  29357. n = x%10;
  29358. x /= 10;
  29359. if( n>=5 ) n -= 2;
  29360. else if( n>=1 ) n -= 1;
  29361. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  29362. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  29363. if( x>60 ) return (u64)LARGEST_INT64;
  29364. #else
  29365. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  29366. ** possible to this routine is 310, resulting in a maximum x of 31 */
  29367. assert( x<=60 );
  29368. #endif
  29369. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  29370. }
  29371. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  29372. /*
  29373. ** Add a new name/number pair to a VList. This might require that the
  29374. ** VList object be reallocated, so return the new VList. If an OOM
  29375. ** error occurs, the original VList returned and the
  29376. ** db->mallocFailed flag is set.
  29377. **
  29378. ** A VList is really just an array of integers. To destroy a VList,
  29379. ** simply pass it to sqlite3DbFree().
  29380. **
  29381. ** The first integer is the number of integers allocated for the whole
  29382. ** VList. The second integer is the number of integers actually used.
  29383. ** Each name/number pair is encoded by subsequent groups of 3 or more
  29384. ** integers.
  29385. **
  29386. ** Each name/number pair starts with two integers which are the numeric
  29387. ** value for the pair and the size of the name/number pair, respectively.
  29388. ** The text name overlays one or more following integers. The text name
  29389. ** is always zero-terminated.
  29390. **
  29391. ** Conceptually:
  29392. **
  29393. ** struct VList {
  29394. ** int nAlloc; // Number of allocated slots
  29395. ** int nUsed; // Number of used slots
  29396. ** struct VListEntry {
  29397. ** int iValue; // Value for this entry
  29398. ** int nSlot; // Slots used by this entry
  29399. ** // ... variable name goes here
  29400. ** } a[0];
  29401. ** }
  29402. **
  29403. ** During code generation, pointers to the variable names within the
  29404. ** VList are taken. When that happens, nAlloc is set to zero as an
  29405. ** indication that the VList may never again be enlarged, since the
  29406. ** accompanying realloc() would invalidate the pointers.
  29407. */
  29408. SQLITE_PRIVATE VList *sqlite3VListAdd(
  29409. sqlite3 *db, /* The database connection used for malloc() */
  29410. VList *pIn, /* The input VList. Might be NULL */
  29411. const char *zName, /* Name of symbol to add */
  29412. int nName, /* Bytes of text in zName */
  29413. int iVal /* Value to associate with zName */
  29414. ){
  29415. int nInt; /* number of sizeof(int) objects needed for zName */
  29416. char *z; /* Pointer to where zName will be stored */
  29417. int i; /* Index in pIn[] where zName is stored */
  29418. nInt = nName/4 + 3;
  29419. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  29420. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  29421. /* Enlarge the allocation */
  29422. int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
  29423. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  29424. if( pOut==0 ) return pIn;
  29425. if( pIn==0 ) pOut[1] = 2;
  29426. pIn = pOut;
  29427. pIn[0] = nAlloc;
  29428. }
  29429. i = pIn[1];
  29430. pIn[i] = iVal;
  29431. pIn[i+1] = nInt;
  29432. z = (char*)&pIn[i+2];
  29433. pIn[1] = i+nInt;
  29434. assert( pIn[1]<=pIn[0] );
  29435. memcpy(z, zName, nName);
  29436. z[nName] = 0;
  29437. return pIn;
  29438. }
  29439. /*
  29440. ** Return a pointer to the name of a variable in the given VList that
  29441. ** has the value iVal. Or return a NULL if there is no such variable in
  29442. ** the list
  29443. */
  29444. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  29445. int i, mx;
  29446. if( pIn==0 ) return 0;
  29447. mx = pIn[1];
  29448. i = 2;
  29449. do{
  29450. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  29451. i += pIn[i+1];
  29452. }while( i<mx );
  29453. return 0;
  29454. }
  29455. /*
  29456. ** Return the number of the variable named zName, if it is in VList.
  29457. ** or return 0 if there is no such variable.
  29458. */
  29459. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  29460. int i, mx;
  29461. if( pIn==0 ) return 0;
  29462. mx = pIn[1];
  29463. i = 2;
  29464. do{
  29465. const char *z = (const char*)&pIn[i+2];
  29466. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  29467. i += pIn[i+1];
  29468. }while( i<mx );
  29469. return 0;
  29470. }
  29471. /************** End of util.c ************************************************/
  29472. /************** Begin file hash.c ********************************************/
  29473. /*
  29474. ** 2001 September 22
  29475. **
  29476. ** The author disclaims copyright to this source code. In place of
  29477. ** a legal notice, here is a blessing:
  29478. **
  29479. ** May you do good and not evil.
  29480. ** May you find forgiveness for yourself and forgive others.
  29481. ** May you share freely, never taking more than you give.
  29482. **
  29483. *************************************************************************
  29484. ** This is the implementation of generic hash-tables
  29485. ** used in SQLite.
  29486. */
  29487. /* #include "sqliteInt.h" */
  29488. /* #include <assert.h> */
  29489. /* Turn bulk memory into a hash table object by initializing the
  29490. ** fields of the Hash structure.
  29491. **
  29492. ** "pNew" is a pointer to the hash table that is to be initialized.
  29493. */
  29494. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  29495. assert( pNew!=0 );
  29496. pNew->first = 0;
  29497. pNew->count = 0;
  29498. pNew->htsize = 0;
  29499. pNew->ht = 0;
  29500. }
  29501. /* Remove all entries from a hash table. Reclaim all memory.
  29502. ** Call this routine to delete a hash table or to reset a hash table
  29503. ** to the empty state.
  29504. */
  29505. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  29506. HashElem *elem; /* For looping over all elements of the table */
  29507. assert( pH!=0 );
  29508. elem = pH->first;
  29509. pH->first = 0;
  29510. sqlite3_free(pH->ht);
  29511. pH->ht = 0;
  29512. pH->htsize = 0;
  29513. while( elem ){
  29514. HashElem *next_elem = elem->next;
  29515. sqlite3_free(elem);
  29516. elem = next_elem;
  29517. }
  29518. pH->count = 0;
  29519. }
  29520. /*
  29521. ** The hashing function.
  29522. */
  29523. static unsigned int strHash(const char *z){
  29524. unsigned int h = 0;
  29525. unsigned char c;
  29526. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  29527. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  29528. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  29529. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  29530. h += sqlite3UpperToLower[c];
  29531. h *= 0x9e3779b1;
  29532. }
  29533. return h;
  29534. }
  29535. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  29536. ** insert pNew into the pEntry hash bucket.
  29537. */
  29538. static void insertElement(
  29539. Hash *pH, /* The complete hash table */
  29540. struct _ht *pEntry, /* The entry into which pNew is inserted */
  29541. HashElem *pNew /* The element to be inserted */
  29542. ){
  29543. HashElem *pHead; /* First element already in pEntry */
  29544. if( pEntry ){
  29545. pHead = pEntry->count ? pEntry->chain : 0;
  29546. pEntry->count++;
  29547. pEntry->chain = pNew;
  29548. }else{
  29549. pHead = 0;
  29550. }
  29551. if( pHead ){
  29552. pNew->next = pHead;
  29553. pNew->prev = pHead->prev;
  29554. if( pHead->prev ){ pHead->prev->next = pNew; }
  29555. else { pH->first = pNew; }
  29556. pHead->prev = pNew;
  29557. }else{
  29558. pNew->next = pH->first;
  29559. if( pH->first ){ pH->first->prev = pNew; }
  29560. pNew->prev = 0;
  29561. pH->first = pNew;
  29562. }
  29563. }
  29564. /* Resize the hash table so that it cantains "new_size" buckets.
  29565. **
  29566. ** The hash table might fail to resize if sqlite3_malloc() fails or
  29567. ** if the new size is the same as the prior size.
  29568. ** Return TRUE if the resize occurs and false if not.
  29569. */
  29570. static int rehash(Hash *pH, unsigned int new_size){
  29571. struct _ht *new_ht; /* The new hash table */
  29572. HashElem *elem, *next_elem; /* For looping over existing elements */
  29573. #if SQLITE_MALLOC_SOFT_LIMIT>0
  29574. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  29575. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  29576. }
  29577. if( new_size==pH->htsize ) return 0;
  29578. #endif
  29579. /* The inability to allocates space for a larger hash table is
  29580. ** a performance hit but it is not a fatal error. So mark the
  29581. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  29582. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  29583. ** only zeroes the requested number of bytes whereas this module will
  29584. ** use the actual amount of space allocated for the hash table (which
  29585. ** may be larger than the requested amount).
  29586. */
  29587. sqlite3BeginBenignMalloc();
  29588. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  29589. sqlite3EndBenignMalloc();
  29590. if( new_ht==0 ) return 0;
  29591. sqlite3_free(pH->ht);
  29592. pH->ht = new_ht;
  29593. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  29594. memset(new_ht, 0, new_size*sizeof(struct _ht));
  29595. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  29596. unsigned int h = strHash(elem->pKey) % new_size;
  29597. next_elem = elem->next;
  29598. insertElement(pH, &new_ht[h], elem);
  29599. }
  29600. return 1;
  29601. }
  29602. /* This function (for internal use only) locates an element in an
  29603. ** hash table that matches the given key. If no element is found,
  29604. ** a pointer to a static null element with HashElem.data==0 is returned.
  29605. ** If pH is not NULL, then the hash for this key is written to *pH.
  29606. */
  29607. static HashElem *findElementWithHash(
  29608. const Hash *pH, /* The pH to be searched */
  29609. const char *pKey, /* The key we are searching for */
  29610. unsigned int *pHash /* Write the hash value here */
  29611. ){
  29612. HashElem *elem; /* Used to loop thru the element list */
  29613. int count; /* Number of elements left to test */
  29614. unsigned int h; /* The computed hash */
  29615. static HashElem nullElement = { 0, 0, 0, 0 };
  29616. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  29617. struct _ht *pEntry;
  29618. h = strHash(pKey) % pH->htsize;
  29619. pEntry = &pH->ht[h];
  29620. elem = pEntry->chain;
  29621. count = pEntry->count;
  29622. }else{
  29623. h = 0;
  29624. elem = pH->first;
  29625. count = pH->count;
  29626. }
  29627. if( pHash ) *pHash = h;
  29628. while( count-- ){
  29629. assert( elem!=0 );
  29630. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  29631. return elem;
  29632. }
  29633. elem = elem->next;
  29634. }
  29635. return &nullElement;
  29636. }
  29637. /* Remove a single entry from the hash table given a pointer to that
  29638. ** element and a hash on the element's key.
  29639. */
  29640. static void removeElementGivenHash(
  29641. Hash *pH, /* The pH containing "elem" */
  29642. HashElem* elem, /* The element to be removed from the pH */
  29643. unsigned int h /* Hash value for the element */
  29644. ){
  29645. struct _ht *pEntry;
  29646. if( elem->prev ){
  29647. elem->prev->next = elem->next;
  29648. }else{
  29649. pH->first = elem->next;
  29650. }
  29651. if( elem->next ){
  29652. elem->next->prev = elem->prev;
  29653. }
  29654. if( pH->ht ){
  29655. pEntry = &pH->ht[h];
  29656. if( pEntry->chain==elem ){
  29657. pEntry->chain = elem->next;
  29658. }
  29659. pEntry->count--;
  29660. assert( pEntry->count>=0 );
  29661. }
  29662. sqlite3_free( elem );
  29663. pH->count--;
  29664. if( pH->count==0 ){
  29665. assert( pH->first==0 );
  29666. assert( pH->count==0 );
  29667. sqlite3HashClear(pH);
  29668. }
  29669. }
  29670. /* Attempt to locate an element of the hash table pH with a key
  29671. ** that matches pKey. Return the data for this element if it is
  29672. ** found, or NULL if there is no match.
  29673. */
  29674. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  29675. assert( pH!=0 );
  29676. assert( pKey!=0 );
  29677. return findElementWithHash(pH, pKey, 0)->data;
  29678. }
  29679. /* Insert an element into the hash table pH. The key is pKey
  29680. ** and the data is "data".
  29681. **
  29682. ** If no element exists with a matching key, then a new
  29683. ** element is created and NULL is returned.
  29684. **
  29685. ** If another element already exists with the same key, then the
  29686. ** new data replaces the old data and the old data is returned.
  29687. ** The key is not copied in this instance. If a malloc fails, then
  29688. ** the new data is returned and the hash table is unchanged.
  29689. **
  29690. ** If the "data" parameter to this function is NULL, then the
  29691. ** element corresponding to "key" is removed from the hash table.
  29692. */
  29693. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  29694. unsigned int h; /* the hash of the key modulo hash table size */
  29695. HashElem *elem; /* Used to loop thru the element list */
  29696. HashElem *new_elem; /* New element added to the pH */
  29697. assert( pH!=0 );
  29698. assert( pKey!=0 );
  29699. elem = findElementWithHash(pH,pKey,&h);
  29700. if( elem->data ){
  29701. void *old_data = elem->data;
  29702. if( data==0 ){
  29703. removeElementGivenHash(pH,elem,h);
  29704. }else{
  29705. elem->data = data;
  29706. elem->pKey = pKey;
  29707. }
  29708. return old_data;
  29709. }
  29710. if( data==0 ) return 0;
  29711. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  29712. if( new_elem==0 ) return data;
  29713. new_elem->pKey = pKey;
  29714. new_elem->data = data;
  29715. pH->count++;
  29716. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  29717. if( rehash(pH, pH->count*2) ){
  29718. assert( pH->htsize>0 );
  29719. h = strHash(pKey) % pH->htsize;
  29720. }
  29721. }
  29722. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  29723. return 0;
  29724. }
  29725. /************** End of hash.c ************************************************/
  29726. /************** Begin file opcodes.c *****************************************/
  29727. /* Automatically generated. Do not edit */
  29728. /* See the tool/mkopcodec.tcl script for details. */
  29729. #if !defined(SQLITE_OMIT_EXPLAIN) \
  29730. || defined(VDBE_PROFILE) \
  29731. || defined(SQLITE_DEBUG)
  29732. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  29733. # define OpHelp(X) "\0" X
  29734. #else
  29735. # define OpHelp(X)
  29736. #endif
  29737. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  29738. static const char *const azName[] = {
  29739. /* 0 */ "Savepoint" OpHelp(""),
  29740. /* 1 */ "AutoCommit" OpHelp(""),
  29741. /* 2 */ "Transaction" OpHelp(""),
  29742. /* 3 */ "SorterNext" OpHelp(""),
  29743. /* 4 */ "PrevIfOpen" OpHelp(""),
  29744. /* 5 */ "NextIfOpen" OpHelp(""),
  29745. /* 6 */ "Prev" OpHelp(""),
  29746. /* 7 */ "Next" OpHelp(""),
  29747. /* 8 */ "Checkpoint" OpHelp(""),
  29748. /* 9 */ "JournalMode" OpHelp(""),
  29749. /* 10 */ "Vacuum" OpHelp(""),
  29750. /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  29751. /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  29752. /* 13 */ "Goto" OpHelp(""),
  29753. /* 14 */ "Gosub" OpHelp(""),
  29754. /* 15 */ "InitCoroutine" OpHelp(""),
  29755. /* 16 */ "Yield" OpHelp(""),
  29756. /* 17 */ "MustBeInt" OpHelp(""),
  29757. /* 18 */ "Jump" OpHelp(""),
  29758. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  29759. /* 20 */ "Once" OpHelp(""),
  29760. /* 21 */ "If" OpHelp(""),
  29761. /* 22 */ "IfNot" OpHelp(""),
  29762. /* 23 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  29763. /* 24 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  29764. /* 25 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  29765. /* 26 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  29766. /* 27 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  29767. /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  29768. /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
  29769. /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
  29770. /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  29771. /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
  29772. /* 33 */ "Last" OpHelp(""),
  29773. /* 34 */ "IfSmaller" OpHelp(""),
  29774. /* 35 */ "SorterSort" OpHelp(""),
  29775. /* 36 */ "Sort" OpHelp(""),
  29776. /* 37 */ "Rewind" OpHelp(""),
  29777. /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  29778. /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  29779. /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  29780. /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  29781. /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  29782. /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  29783. /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  29784. /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  29785. /* 46 */ "Program" OpHelp(""),
  29786. /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  29787. /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  29788. /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  29789. /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  29790. /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  29791. /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  29792. /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  29793. /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  29794. /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  29795. /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  29796. /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  29797. /* 58 */ "ElseNotEq" OpHelp(""),
  29798. /* 59 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  29799. /* 60 */ "IncrVacuum" OpHelp(""),
  29800. /* 61 */ "VNext" OpHelp(""),
  29801. /* 62 */ "Init" OpHelp("Start at P2"),
  29802. /* 63 */ "Return" OpHelp(""),
  29803. /* 64 */ "EndCoroutine" OpHelp(""),
  29804. /* 65 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  29805. /* 66 */ "Halt" OpHelp(""),
  29806. /* 67 */ "Integer" OpHelp("r[P2]=P1"),
  29807. /* 68 */ "Int64" OpHelp("r[P2]=P4"),
  29808. /* 69 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  29809. /* 70 */ "Null" OpHelp("r[P2..P3]=NULL"),
  29810. /* 71 */ "SoftNull" OpHelp("r[P1]=NULL"),
  29811. /* 72 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  29812. /* 73 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  29813. /* 74 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  29814. /* 75 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  29815. /* 76 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  29816. /* 77 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  29817. /* 78 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  29818. /* 79 */ "CollSeq" OpHelp(""),
  29819. /* 80 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  29820. /* 81 */ "RealAffinity" OpHelp(""),
  29821. /* 82 */ "Cast" OpHelp("affinity(r[P1])"),
  29822. /* 83 */ "Permutation" OpHelp(""),
  29823. /* 84 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  29824. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  29825. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  29826. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  29827. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  29828. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  29829. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  29830. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  29831. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  29832. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  29833. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  29834. /* 95 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
  29835. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  29836. /* 97 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
  29837. /* 98 */ "Column" OpHelp("r[P3]=PX"),
  29838. /* 99 */ "String8" OpHelp("r[P2]='P4'"),
  29839. /* 100 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  29840. /* 101 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  29841. /* 102 */ "Count" OpHelp("r[P2]=count()"),
  29842. /* 103 */ "ReadCookie" OpHelp(""),
  29843. /* 104 */ "SetCookie" OpHelp(""),
  29844. /* 105 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  29845. /* 106 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  29846. /* 107 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  29847. /* 108 */ "OpenDup" OpHelp(""),
  29848. /* 109 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  29849. /* 110 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  29850. /* 111 */ "SorterOpen" OpHelp(""),
  29851. /* 112 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  29852. /* 113 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  29853. /* 114 */ "Close" OpHelp(""),
  29854. /* 115 */ "ColumnsUsed" OpHelp(""),
  29855. /* 116 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  29856. /* 117 */ "NewRowid" OpHelp("r[P2]=rowid"),
  29857. /* 118 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  29858. /* 119 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  29859. /* 120 */ "Delete" OpHelp(""),
  29860. /* 121 */ "ResetCount" OpHelp(""),
  29861. /* 122 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  29862. /* 123 */ "SorterData" OpHelp("r[P2]=data"),
  29863. /* 124 */ "RowData" OpHelp("r[P2]=data"),
  29864. /* 125 */ "Rowid" OpHelp("r[P2]=rowid"),
  29865. /* 126 */ "NullRow" OpHelp(""),
  29866. /* 127 */ "SeekEnd" OpHelp(""),
  29867. /* 128 */ "SorterInsert" OpHelp("key=r[P2]"),
  29868. /* 129 */ "IdxInsert" OpHelp("key=r[P2]"),
  29869. /* 130 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  29870. /* 131 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
  29871. /* 132 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  29872. /* 133 */ "Destroy" OpHelp(""),
  29873. /* 134 */ "Real" OpHelp("r[P2]=P4"),
  29874. /* 135 */ "Clear" OpHelp(""),
  29875. /* 136 */ "ResetSorter" OpHelp(""),
  29876. /* 137 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
  29877. /* 138 */ "SqlExec" OpHelp(""),
  29878. /* 139 */ "ParseSchema" OpHelp(""),
  29879. /* 140 */ "LoadAnalysis" OpHelp(""),
  29880. /* 141 */ "DropTable" OpHelp(""),
  29881. /* 142 */ "DropIndex" OpHelp(""),
  29882. /* 143 */ "DropTrigger" OpHelp(""),
  29883. /* 144 */ "IntegrityCk" OpHelp(""),
  29884. /* 145 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  29885. /* 146 */ "Param" OpHelp(""),
  29886. /* 147 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  29887. /* 148 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  29888. /* 149 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  29889. /* 150 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  29890. /* 151 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  29891. /* 152 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  29892. /* 153 */ "Expire" OpHelp(""),
  29893. /* 154 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  29894. /* 155 */ "VBegin" OpHelp(""),
  29895. /* 156 */ "VCreate" OpHelp(""),
  29896. /* 157 */ "VDestroy" OpHelp(""),
  29897. /* 158 */ "VOpen" OpHelp(""),
  29898. /* 159 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  29899. /* 160 */ "VRename" OpHelp(""),
  29900. /* 161 */ "Pagecount" OpHelp(""),
  29901. /* 162 */ "MaxPgcnt" OpHelp(""),
  29902. /* 163 */ "PureFunc0" OpHelp(""),
  29903. /* 164 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  29904. /* 165 */ "PureFunc" OpHelp(""),
  29905. /* 166 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  29906. /* 167 */ "Trace" OpHelp(""),
  29907. /* 168 */ "CursorHint" OpHelp(""),
  29908. /* 169 */ "Noop" OpHelp(""),
  29909. /* 170 */ "Explain" OpHelp(""),
  29910. /* 171 */ "Abortable" OpHelp(""),
  29911. };
  29912. return azName[i];
  29913. }
  29914. #endif
  29915. /************** End of opcodes.c *********************************************/
  29916. /************** Begin file os_unix.c *****************************************/
  29917. /*
  29918. ** 2004 May 22
  29919. **
  29920. ** The author disclaims copyright to this source code. In place of
  29921. ** a legal notice, here is a blessing:
  29922. **
  29923. ** May you do good and not evil.
  29924. ** May you find forgiveness for yourself and forgive others.
  29925. ** May you share freely, never taking more than you give.
  29926. **
  29927. ******************************************************************************
  29928. **
  29929. ** This file contains the VFS implementation for unix-like operating systems
  29930. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  29931. **
  29932. ** There are actually several different VFS implementations in this file.
  29933. ** The differences are in the way that file locking is done. The default
  29934. ** implementation uses Posix Advisory Locks. Alternative implementations
  29935. ** use flock(), dot-files, various proprietary locking schemas, or simply
  29936. ** skip locking all together.
  29937. **
  29938. ** This source file is organized into divisions where the logic for various
  29939. ** subfunctions is contained within the appropriate division. PLEASE
  29940. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  29941. ** in the correct division and should be clearly labeled.
  29942. **
  29943. ** The layout of divisions is as follows:
  29944. **
  29945. ** * General-purpose declarations and utility functions.
  29946. ** * Unique file ID logic used by VxWorks.
  29947. ** * Various locking primitive implementations (all except proxy locking):
  29948. ** + for Posix Advisory Locks
  29949. ** + for no-op locks
  29950. ** + for dot-file locks
  29951. ** + for flock() locking
  29952. ** + for named semaphore locks (VxWorks only)
  29953. ** + for AFP filesystem locks (MacOSX only)
  29954. ** * sqlite3_file methods not associated with locking.
  29955. ** * Definitions of sqlite3_io_methods objects for all locking
  29956. ** methods plus "finder" functions for each locking method.
  29957. ** * sqlite3_vfs method implementations.
  29958. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  29959. ** * Definitions of sqlite3_vfs objects for all locking methods
  29960. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  29961. */
  29962. /* #include "sqliteInt.h" */
  29963. #if SQLITE_OS_UNIX /* This file is used on unix only */
  29964. /*
  29965. ** There are various methods for file locking used for concurrency
  29966. ** control:
  29967. **
  29968. ** 1. POSIX locking (the default),
  29969. ** 2. No locking,
  29970. ** 3. Dot-file locking,
  29971. ** 4. flock() locking,
  29972. ** 5. AFP locking (OSX only),
  29973. ** 6. Named POSIX semaphores (VXWorks only),
  29974. ** 7. proxy locking. (OSX only)
  29975. **
  29976. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  29977. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  29978. ** selection of the appropriate locking style based on the filesystem
  29979. ** where the database is located.
  29980. */
  29981. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  29982. # if defined(__APPLE__)
  29983. # define SQLITE_ENABLE_LOCKING_STYLE 1
  29984. # else
  29985. # define SQLITE_ENABLE_LOCKING_STYLE 0
  29986. # endif
  29987. #endif
  29988. /* Use pread() and pwrite() if they are available */
  29989. #if defined(__APPLE__)
  29990. # define HAVE_PREAD 1
  29991. # define HAVE_PWRITE 1
  29992. #endif
  29993. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  29994. # undef USE_PREAD
  29995. # define USE_PREAD64 1
  29996. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  29997. # undef USE_PREAD64
  29998. # define USE_PREAD 1
  29999. #endif
  30000. /*
  30001. ** standard include files.
  30002. */
  30003. #include <sys/types.h>
  30004. #include <sys/stat.h>
  30005. #include <fcntl.h>
  30006. #include <sys/ioctl.h>
  30007. #include <unistd.h>
  30008. /* #include <time.h> */
  30009. #include <sys/time.h>
  30010. #include <errno.h>
  30011. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30012. # include <sys/mman.h>
  30013. #endif
  30014. #if SQLITE_ENABLE_LOCKING_STYLE
  30015. /* # include <sys/ioctl.h> */
  30016. # include <sys/file.h>
  30017. # include <sys/param.h>
  30018. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  30019. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  30020. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  30021. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  30022. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  30023. # define HAVE_GETHOSTUUID 1
  30024. # else
  30025. # warning "gethostuuid() is disabled."
  30026. # endif
  30027. #endif
  30028. #if OS_VXWORKS
  30029. /* # include <sys/ioctl.h> */
  30030. # include <semaphore.h>
  30031. # include <limits.h>
  30032. #endif /* OS_VXWORKS */
  30033. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30034. # include <sys/mount.h>
  30035. #endif
  30036. #ifdef HAVE_UTIME
  30037. # include <utime.h>
  30038. #endif
  30039. /*
  30040. ** Allowed values of unixFile.fsFlags
  30041. */
  30042. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  30043. /*
  30044. ** If we are to be thread-safe, include the pthreads header and define
  30045. ** the SQLITE_UNIX_THREADS macro.
  30046. */
  30047. #if SQLITE_THREADSAFE
  30048. /* # include <pthread.h> */
  30049. # define SQLITE_UNIX_THREADS 1
  30050. #endif
  30051. /*
  30052. ** Default permissions when creating a new file
  30053. */
  30054. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  30055. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  30056. #endif
  30057. /*
  30058. ** Default permissions when creating auto proxy dir
  30059. */
  30060. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  30061. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  30062. #endif
  30063. /*
  30064. ** Maximum supported path-length.
  30065. */
  30066. #define MAX_PATHNAME 512
  30067. /*
  30068. ** Maximum supported symbolic links
  30069. */
  30070. #define SQLITE_MAX_SYMLINKS 100
  30071. /* Always cast the getpid() return type for compatibility with
  30072. ** kernel modules in VxWorks. */
  30073. #define osGetpid(X) (pid_t)getpid()
  30074. /*
  30075. ** Only set the lastErrno if the error code is a real error and not
  30076. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  30077. */
  30078. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  30079. /* Forward references */
  30080. typedef struct unixShm unixShm; /* Connection shared memory */
  30081. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  30082. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  30083. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  30084. /*
  30085. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  30086. ** cannot be closed immediately. In these cases, instances of the following
  30087. ** structure are used to store the file descriptor while waiting for an
  30088. ** opportunity to either close or reuse it.
  30089. */
  30090. struct UnixUnusedFd {
  30091. int fd; /* File descriptor to close */
  30092. int flags; /* Flags this file descriptor was opened with */
  30093. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  30094. };
  30095. /*
  30096. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  30097. ** VFS implementations.
  30098. */
  30099. typedef struct unixFile unixFile;
  30100. struct unixFile {
  30101. sqlite3_io_methods const *pMethod; /* Always the first entry */
  30102. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  30103. unixInodeInfo *pInode; /* Info about locks on this inode */
  30104. int h; /* The file descriptor */
  30105. unsigned char eFileLock; /* The type of lock held on this fd */
  30106. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  30107. int lastErrno; /* The unix errno from last I/O error */
  30108. void *lockingContext; /* Locking style specific state */
  30109. UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
  30110. const char *zPath; /* Name of the file */
  30111. unixShm *pShm; /* Shared memory segment information */
  30112. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  30113. #if SQLITE_MAX_MMAP_SIZE>0
  30114. int nFetchOut; /* Number of outstanding xFetch refs */
  30115. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  30116. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  30117. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  30118. void *pMapRegion; /* Memory mapped region */
  30119. #endif
  30120. int sectorSize; /* Device sector size */
  30121. int deviceCharacteristics; /* Precomputed device characteristics */
  30122. #if SQLITE_ENABLE_LOCKING_STYLE
  30123. int openFlags; /* The flags specified at open() */
  30124. #endif
  30125. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  30126. unsigned fsFlags; /* cached details from statfs() */
  30127. #endif
  30128. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  30129. unsigned iBusyTimeout; /* Wait this many millisec on locks */
  30130. #endif
  30131. #if OS_VXWORKS
  30132. struct vxworksFileId *pId; /* Unique file ID */
  30133. #endif
  30134. #ifdef SQLITE_DEBUG
  30135. /* The next group of variables are used to track whether or not the
  30136. ** transaction counter in bytes 24-27 of database files are updated
  30137. ** whenever any part of the database changes. An assertion fault will
  30138. ** occur if a file is updated without also updating the transaction
  30139. ** counter. This test is made to avoid new problems similar to the
  30140. ** one described by ticket #3584.
  30141. */
  30142. unsigned char transCntrChng; /* True if the transaction counter changed */
  30143. unsigned char dbUpdate; /* True if any part of database file changed */
  30144. unsigned char inNormalWrite; /* True if in a normal write operation */
  30145. #endif
  30146. #ifdef SQLITE_TEST
  30147. /* In test mode, increase the size of this structure a bit so that
  30148. ** it is larger than the struct CrashFile defined in test6.c.
  30149. */
  30150. char aPadding[32];
  30151. #endif
  30152. };
  30153. /* This variable holds the process id (pid) from when the xRandomness()
  30154. ** method was called. If xOpen() is called from a different process id,
  30155. ** indicating that a fork() has occurred, the PRNG will be reset.
  30156. */
  30157. static pid_t randomnessPid = 0;
  30158. /*
  30159. ** Allowed values for the unixFile.ctrlFlags bitmask:
  30160. */
  30161. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  30162. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  30163. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  30164. #ifndef SQLITE_DISABLE_DIRSYNC
  30165. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  30166. #else
  30167. # define UNIXFILE_DIRSYNC 0x00
  30168. #endif
  30169. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  30170. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  30171. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  30172. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  30173. /*
  30174. ** Include code that is common to all os_*.c files
  30175. */
  30176. /************** Include os_common.h in the middle of os_unix.c ***************/
  30177. /************** Begin file os_common.h ***************************************/
  30178. /*
  30179. ** 2004 May 22
  30180. **
  30181. ** The author disclaims copyright to this source code. In place of
  30182. ** a legal notice, here is a blessing:
  30183. **
  30184. ** May you do good and not evil.
  30185. ** May you find forgiveness for yourself and forgive others.
  30186. ** May you share freely, never taking more than you give.
  30187. **
  30188. ******************************************************************************
  30189. **
  30190. ** This file contains macros and a little bit of code that is common to
  30191. ** all of the platform-specific files (os_*.c) and is #included into those
  30192. ** files.
  30193. **
  30194. ** This file should be #included by the os_*.c files only. It is not a
  30195. ** general purpose header file.
  30196. */
  30197. #ifndef _OS_COMMON_H_
  30198. #define _OS_COMMON_H_
  30199. /*
  30200. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  30201. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  30202. ** switch. The following code should catch this problem at compile-time.
  30203. */
  30204. #ifdef MEMORY_DEBUG
  30205. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  30206. #endif
  30207. /*
  30208. ** Macros for performance tracing. Normally turned off. Only works
  30209. ** on i486 hardware.
  30210. */
  30211. #ifdef SQLITE_PERFORMANCE_TRACE
  30212. /*
  30213. ** hwtime.h contains inline assembler code for implementing
  30214. ** high-performance timing routines.
  30215. */
  30216. /************** Include hwtime.h in the middle of os_common.h ****************/
  30217. /************** Begin file hwtime.h ******************************************/
  30218. /*
  30219. ** 2008 May 27
  30220. **
  30221. ** The author disclaims copyright to this source code. In place of
  30222. ** a legal notice, here is a blessing:
  30223. **
  30224. ** May you do good and not evil.
  30225. ** May you find forgiveness for yourself and forgive others.
  30226. ** May you share freely, never taking more than you give.
  30227. **
  30228. ******************************************************************************
  30229. **
  30230. ** This file contains inline asm code for retrieving "high-performance"
  30231. ** counters for x86 class CPUs.
  30232. */
  30233. #ifndef SQLITE_HWTIME_H
  30234. #define SQLITE_HWTIME_H
  30235. /*
  30236. ** The following routine only works on pentium-class (or newer) processors.
  30237. ** It uses the RDTSC opcode to read the cycle count value out of the
  30238. ** processor and returns that value. This can be used for high-res
  30239. ** profiling.
  30240. */
  30241. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  30242. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  30243. #if defined(__GNUC__)
  30244. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30245. unsigned int lo, hi;
  30246. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  30247. return (sqlite_uint64)hi << 32 | lo;
  30248. }
  30249. #elif defined(_MSC_VER)
  30250. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  30251. __asm {
  30252. rdtsc
  30253. ret ; return value at EDX:EAX
  30254. }
  30255. }
  30256. #endif
  30257. #elif (defined(__GNUC__) && defined(__x86_64__))
  30258. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30259. unsigned long val;
  30260. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  30261. return val;
  30262. }
  30263. #elif (defined(__GNUC__) && defined(__ppc__))
  30264. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30265. unsigned long long retval;
  30266. unsigned long junk;
  30267. __asm__ __volatile__ ("\n\
  30268. 1: mftbu %1\n\
  30269. mftb %L0\n\
  30270. mftbu %0\n\
  30271. cmpw %0,%1\n\
  30272. bne 1b"
  30273. : "=r" (retval), "=r" (junk));
  30274. return retval;
  30275. }
  30276. #else
  30277. #error Need implementation of sqlite3Hwtime() for your platform.
  30278. /*
  30279. ** To compile without implementing sqlite3Hwtime() for your platform,
  30280. ** you can remove the above #error and use the following
  30281. ** stub function. You will lose timing support for many
  30282. ** of the debugging and testing utilities, but it should at
  30283. ** least compile and run.
  30284. */
  30285. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  30286. #endif
  30287. #endif /* !defined(SQLITE_HWTIME_H) */
  30288. /************** End of hwtime.h **********************************************/
  30289. /************** Continuing where we left off in os_common.h ******************/
  30290. static sqlite_uint64 g_start;
  30291. static sqlite_uint64 g_elapsed;
  30292. #define TIMER_START g_start=sqlite3Hwtime()
  30293. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  30294. #define TIMER_ELAPSED g_elapsed
  30295. #else
  30296. #define TIMER_START
  30297. #define TIMER_END
  30298. #define TIMER_ELAPSED ((sqlite_uint64)0)
  30299. #endif
  30300. /*
  30301. ** If we compile with the SQLITE_TEST macro set, then the following block
  30302. ** of code will give us the ability to simulate a disk I/O error. This
  30303. ** is used for testing the I/O recovery logic.
  30304. */
  30305. #if defined(SQLITE_TEST)
  30306. SQLITE_API extern int sqlite3_io_error_hit;
  30307. SQLITE_API extern int sqlite3_io_error_hardhit;
  30308. SQLITE_API extern int sqlite3_io_error_pending;
  30309. SQLITE_API extern int sqlite3_io_error_persist;
  30310. SQLITE_API extern int sqlite3_io_error_benign;
  30311. SQLITE_API extern int sqlite3_diskfull_pending;
  30312. SQLITE_API extern int sqlite3_diskfull;
  30313. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  30314. #define SimulateIOError(CODE) \
  30315. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  30316. || sqlite3_io_error_pending-- == 1 ) \
  30317. { local_ioerr(); CODE; }
  30318. static void local_ioerr(){
  30319. IOTRACE(("IOERR\n"));
  30320. sqlite3_io_error_hit++;
  30321. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  30322. }
  30323. #define SimulateDiskfullError(CODE) \
  30324. if( sqlite3_diskfull_pending ){ \
  30325. if( sqlite3_diskfull_pending == 1 ){ \
  30326. local_ioerr(); \
  30327. sqlite3_diskfull = 1; \
  30328. sqlite3_io_error_hit = 1; \
  30329. CODE; \
  30330. }else{ \
  30331. sqlite3_diskfull_pending--; \
  30332. } \
  30333. }
  30334. #else
  30335. #define SimulateIOErrorBenign(X)
  30336. #define SimulateIOError(A)
  30337. #define SimulateDiskfullError(A)
  30338. #endif /* defined(SQLITE_TEST) */
  30339. /*
  30340. ** When testing, keep a count of the number of open files.
  30341. */
  30342. #if defined(SQLITE_TEST)
  30343. SQLITE_API extern int sqlite3_open_file_count;
  30344. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  30345. #else
  30346. #define OpenCounter(X)
  30347. #endif /* defined(SQLITE_TEST) */
  30348. #endif /* !defined(_OS_COMMON_H_) */
  30349. /************** End of os_common.h *******************************************/
  30350. /************** Continuing where we left off in os_unix.c ********************/
  30351. /*
  30352. ** Define various macros that are missing from some systems.
  30353. */
  30354. #ifndef O_LARGEFILE
  30355. # define O_LARGEFILE 0
  30356. #endif
  30357. #ifdef SQLITE_DISABLE_LFS
  30358. # undef O_LARGEFILE
  30359. # define O_LARGEFILE 0
  30360. #endif
  30361. #ifndef O_NOFOLLOW
  30362. # define O_NOFOLLOW 0
  30363. #endif
  30364. #ifndef O_BINARY
  30365. # define O_BINARY 0
  30366. #endif
  30367. /*
  30368. ** The threadid macro resolves to the thread-id or to 0. Used for
  30369. ** testing and debugging only.
  30370. */
  30371. #if SQLITE_THREADSAFE
  30372. #define threadid pthread_self()
  30373. #else
  30374. #define threadid 0
  30375. #endif
  30376. /*
  30377. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  30378. */
  30379. #if !defined(HAVE_MREMAP)
  30380. # if defined(__linux__) && defined(_GNU_SOURCE)
  30381. # define HAVE_MREMAP 1
  30382. # else
  30383. # define HAVE_MREMAP 0
  30384. # endif
  30385. #endif
  30386. /*
  30387. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  30388. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  30389. */
  30390. #ifdef __ANDROID__
  30391. # define lseek lseek64
  30392. #endif
  30393. #ifdef __linux__
  30394. /*
  30395. ** Linux-specific IOCTL magic numbers used for controlling F2FS
  30396. */
  30397. #define F2FS_IOCTL_MAGIC 0xf5
  30398. #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
  30399. #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
  30400. #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
  30401. #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
  30402. #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
  30403. #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
  30404. #endif /* __linux__ */
  30405. /*
  30406. ** Different Unix systems declare open() in different ways. Same use
  30407. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  30408. ** The difference is important when using a pointer to the function.
  30409. **
  30410. ** The safest way to deal with the problem is to always use this wrapper
  30411. ** which always has the same well-defined interface.
  30412. */
  30413. static int posixOpen(const char *zFile, int flags, int mode){
  30414. return open(zFile, flags, mode);
  30415. }
  30416. /* Forward reference */
  30417. static int openDirectory(const char*, int*);
  30418. static int unixGetpagesize(void);
  30419. /*
  30420. ** Many system calls are accessed through pointer-to-functions so that
  30421. ** they may be overridden at runtime to facilitate fault injection during
  30422. ** testing and sandboxing. The following array holds the names and pointers
  30423. ** to all overrideable system calls.
  30424. */
  30425. static struct unix_syscall {
  30426. const char *zName; /* Name of the system call */
  30427. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  30428. sqlite3_syscall_ptr pDefault; /* Default value */
  30429. } aSyscall[] = {
  30430. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  30431. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  30432. { "close", (sqlite3_syscall_ptr)close, 0 },
  30433. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  30434. { "access", (sqlite3_syscall_ptr)access, 0 },
  30435. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  30436. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  30437. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  30438. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  30439. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  30440. /*
  30441. ** The DJGPP compiler environment looks mostly like Unix, but it
  30442. ** lacks the fcntl() system call. So redefine fcntl() to be something
  30443. ** that always succeeds. This means that locking does not occur under
  30444. ** DJGPP. But it is DOS - what did you expect?
  30445. */
  30446. #ifdef __DJGPP__
  30447. { "fstat", 0, 0 },
  30448. #define osFstat(a,b,c) 0
  30449. #else
  30450. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  30451. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  30452. #endif
  30453. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  30454. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  30455. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  30456. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  30457. { "read", (sqlite3_syscall_ptr)read, 0 },
  30458. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  30459. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  30460. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  30461. #else
  30462. { "pread", (sqlite3_syscall_ptr)0, 0 },
  30463. #endif
  30464. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  30465. #if defined(USE_PREAD64)
  30466. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  30467. #else
  30468. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  30469. #endif
  30470. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  30471. { "write", (sqlite3_syscall_ptr)write, 0 },
  30472. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  30473. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  30474. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  30475. #else
  30476. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  30477. #endif
  30478. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  30479. aSyscall[12].pCurrent)
  30480. #if defined(USE_PREAD64)
  30481. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  30482. #else
  30483. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  30484. #endif
  30485. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  30486. aSyscall[13].pCurrent)
  30487. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  30488. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  30489. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  30490. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  30491. #else
  30492. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  30493. #endif
  30494. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  30495. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  30496. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  30497. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  30498. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  30499. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  30500. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  30501. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  30502. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  30503. #if defined(HAVE_FCHOWN)
  30504. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  30505. #else
  30506. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  30507. #endif
  30508. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  30509. #if defined(HAVE_FCHOWN)
  30510. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  30511. #else
  30512. { "geteuid", (sqlite3_syscall_ptr)0, 0 },
  30513. #endif
  30514. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  30515. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30516. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  30517. #else
  30518. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  30519. #endif
  30520. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  30521. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30522. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  30523. #else
  30524. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  30525. #endif
  30526. #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
  30527. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  30528. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  30529. #else
  30530. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  30531. #endif
  30532. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  30533. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30534. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  30535. #else
  30536. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  30537. #endif
  30538. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  30539. #if defined(HAVE_READLINK)
  30540. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  30541. #else
  30542. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  30543. #endif
  30544. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  30545. #if defined(HAVE_LSTAT)
  30546. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  30547. #else
  30548. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  30549. #endif
  30550. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  30551. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  30552. { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
  30553. #else
  30554. { "ioctl", (sqlite3_syscall_ptr)0, 0 },
  30555. #endif
  30556. #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
  30557. }; /* End of the overrideable system calls */
  30558. /*
  30559. ** On some systems, calls to fchown() will trigger a message in a security
  30560. ** log if they come from non-root processes. So avoid calling fchown() if
  30561. ** we are not running as root.
  30562. */
  30563. static int robustFchown(int fd, uid_t uid, gid_t gid){
  30564. #if defined(HAVE_FCHOWN)
  30565. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  30566. #else
  30567. return 0;
  30568. #endif
  30569. }
  30570. /*
  30571. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  30572. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  30573. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  30574. ** system call named zName.
  30575. */
  30576. static int unixSetSystemCall(
  30577. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  30578. const char *zName, /* Name of system call to override */
  30579. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  30580. ){
  30581. unsigned int i;
  30582. int rc = SQLITE_NOTFOUND;
  30583. UNUSED_PARAMETER(pNotUsed);
  30584. if( zName==0 ){
  30585. /* If no zName is given, restore all system calls to their default
  30586. ** settings and return NULL
  30587. */
  30588. rc = SQLITE_OK;
  30589. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30590. if( aSyscall[i].pDefault ){
  30591. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  30592. }
  30593. }
  30594. }else{
  30595. /* If zName is specified, operate on only the one system call
  30596. ** specified.
  30597. */
  30598. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30599. if( strcmp(zName, aSyscall[i].zName)==0 ){
  30600. if( aSyscall[i].pDefault==0 ){
  30601. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  30602. }
  30603. rc = SQLITE_OK;
  30604. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  30605. aSyscall[i].pCurrent = pNewFunc;
  30606. break;
  30607. }
  30608. }
  30609. }
  30610. return rc;
  30611. }
  30612. /*
  30613. ** Return the value of a system call. Return NULL if zName is not a
  30614. ** recognized system call name. NULL is also returned if the system call
  30615. ** is currently undefined.
  30616. */
  30617. static sqlite3_syscall_ptr unixGetSystemCall(
  30618. sqlite3_vfs *pNotUsed,
  30619. const char *zName
  30620. ){
  30621. unsigned int i;
  30622. UNUSED_PARAMETER(pNotUsed);
  30623. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30624. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  30625. }
  30626. return 0;
  30627. }
  30628. /*
  30629. ** Return the name of the first system call after zName. If zName==NULL
  30630. ** then return the name of the first system call. Return NULL if zName
  30631. ** is the last system call or if zName is not the name of a valid
  30632. ** system call.
  30633. */
  30634. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  30635. int i = -1;
  30636. UNUSED_PARAMETER(p);
  30637. if( zName ){
  30638. for(i=0; i<ArraySize(aSyscall)-1; i++){
  30639. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  30640. }
  30641. }
  30642. for(i++; i<ArraySize(aSyscall); i++){
  30643. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  30644. }
  30645. return 0;
  30646. }
  30647. /*
  30648. ** Do not accept any file descriptor less than this value, in order to avoid
  30649. ** opening database file using file descriptors that are commonly used for
  30650. ** standard input, output, and error.
  30651. */
  30652. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  30653. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  30654. #endif
  30655. /*
  30656. ** Invoke open(). Do so multiple times, until it either succeeds or
  30657. ** fails for some reason other than EINTR.
  30658. **
  30659. ** If the file creation mode "m" is 0 then set it to the default for
  30660. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  30661. ** 0644) as modified by the system umask. If m is not 0, then
  30662. ** make the file creation mode be exactly m ignoring the umask.
  30663. **
  30664. ** The m parameter will be non-zero only when creating -wal, -journal,
  30665. ** and -shm files. We want those files to have *exactly* the same
  30666. ** permissions as their original database, unadulterated by the umask.
  30667. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  30668. ** transaction crashes and leaves behind hot journals, then any
  30669. ** process that is able to write to the database will also be able to
  30670. ** recover the hot journals.
  30671. */
  30672. static int robust_open(const char *z, int f, mode_t m){
  30673. int fd;
  30674. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  30675. while(1){
  30676. #if defined(O_CLOEXEC)
  30677. fd = osOpen(z,f|O_CLOEXEC,m2);
  30678. #else
  30679. fd = osOpen(z,f,m2);
  30680. #endif
  30681. if( fd<0 ){
  30682. if( errno==EINTR ) continue;
  30683. break;
  30684. }
  30685. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  30686. osClose(fd);
  30687. sqlite3_log(SQLITE_WARNING,
  30688. "attempt to open \"%s\" as file descriptor %d", z, fd);
  30689. fd = -1;
  30690. if( osOpen("/dev/null", f, m)<0 ) break;
  30691. }
  30692. if( fd>=0 ){
  30693. if( m!=0 ){
  30694. struct stat statbuf;
  30695. if( osFstat(fd, &statbuf)==0
  30696. && statbuf.st_size==0
  30697. && (statbuf.st_mode&0777)!=m
  30698. ){
  30699. osFchmod(fd, m);
  30700. }
  30701. }
  30702. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  30703. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  30704. #endif
  30705. }
  30706. return fd;
  30707. }
  30708. /*
  30709. ** Helper functions to obtain and relinquish the global mutex. The
  30710. ** global mutex is used to protect the unixInodeInfo and
  30711. ** vxworksFileId objects used by this file, all of which may be
  30712. ** shared by multiple threads.
  30713. **
  30714. ** Function unixMutexHeld() is used to assert() that the global mutex
  30715. ** is held when required. This function is only used as part of assert()
  30716. ** statements. e.g.
  30717. **
  30718. ** unixEnterMutex()
  30719. ** assert( unixMutexHeld() );
  30720. ** unixEnterLeave()
  30721. */
  30722. static sqlite3_mutex *unixBigLock = 0;
  30723. static void unixEnterMutex(void){
  30724. sqlite3_mutex_enter(unixBigLock);
  30725. }
  30726. static void unixLeaveMutex(void){
  30727. sqlite3_mutex_leave(unixBigLock);
  30728. }
  30729. #ifdef SQLITE_DEBUG
  30730. static int unixMutexHeld(void) {
  30731. return sqlite3_mutex_held(unixBigLock);
  30732. }
  30733. #endif
  30734. #ifdef SQLITE_HAVE_OS_TRACE
  30735. /*
  30736. ** Helper function for printing out trace information from debugging
  30737. ** binaries. This returns the string representation of the supplied
  30738. ** integer lock-type.
  30739. */
  30740. static const char *azFileLock(int eFileLock){
  30741. switch( eFileLock ){
  30742. case NO_LOCK: return "NONE";
  30743. case SHARED_LOCK: return "SHARED";
  30744. case RESERVED_LOCK: return "RESERVED";
  30745. case PENDING_LOCK: return "PENDING";
  30746. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  30747. }
  30748. return "ERROR";
  30749. }
  30750. #endif
  30751. #ifdef SQLITE_LOCK_TRACE
  30752. /*
  30753. ** Print out information about all locking operations.
  30754. **
  30755. ** This routine is used for troubleshooting locks on multithreaded
  30756. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  30757. ** command-line option on the compiler. This code is normally
  30758. ** turned off.
  30759. */
  30760. static int lockTrace(int fd, int op, struct flock *p){
  30761. char *zOpName, *zType;
  30762. int s;
  30763. int savedErrno;
  30764. if( op==F_GETLK ){
  30765. zOpName = "GETLK";
  30766. }else if( op==F_SETLK ){
  30767. zOpName = "SETLK";
  30768. }else{
  30769. s = osFcntl(fd, op, p);
  30770. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  30771. return s;
  30772. }
  30773. if( p->l_type==F_RDLCK ){
  30774. zType = "RDLCK";
  30775. }else if( p->l_type==F_WRLCK ){
  30776. zType = "WRLCK";
  30777. }else if( p->l_type==F_UNLCK ){
  30778. zType = "UNLCK";
  30779. }else{
  30780. assert( 0 );
  30781. }
  30782. assert( p->l_whence==SEEK_SET );
  30783. s = osFcntl(fd, op, p);
  30784. savedErrno = errno;
  30785. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  30786. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  30787. (int)p->l_pid, s);
  30788. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  30789. struct flock l2;
  30790. l2 = *p;
  30791. osFcntl(fd, F_GETLK, &l2);
  30792. if( l2.l_type==F_RDLCK ){
  30793. zType = "RDLCK";
  30794. }else if( l2.l_type==F_WRLCK ){
  30795. zType = "WRLCK";
  30796. }else if( l2.l_type==F_UNLCK ){
  30797. zType = "UNLCK";
  30798. }else{
  30799. assert( 0 );
  30800. }
  30801. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  30802. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  30803. }
  30804. errno = savedErrno;
  30805. return s;
  30806. }
  30807. #undef osFcntl
  30808. #define osFcntl lockTrace
  30809. #endif /* SQLITE_LOCK_TRACE */
  30810. /*
  30811. ** Retry ftruncate() calls that fail due to EINTR
  30812. **
  30813. ** All calls to ftruncate() within this file should be made through
  30814. ** this wrapper. On the Android platform, bypassing the logic below
  30815. ** could lead to a corrupt database.
  30816. */
  30817. static int robust_ftruncate(int h, sqlite3_int64 sz){
  30818. int rc;
  30819. #ifdef __ANDROID__
  30820. /* On Android, ftruncate() always uses 32-bit offsets, even if
  30821. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  30822. ** truncate a file to any size larger than 2GiB. Silently ignore any
  30823. ** such attempts. */
  30824. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  30825. rc = SQLITE_OK;
  30826. }else
  30827. #endif
  30828. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  30829. return rc;
  30830. }
  30831. /*
  30832. ** This routine translates a standard POSIX errno code into something
  30833. ** useful to the clients of the sqlite3 functions. Specifically, it is
  30834. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  30835. ** and a variety of "please close the file descriptor NOW" errors into
  30836. ** SQLITE_IOERR
  30837. **
  30838. ** Errors during initialization of locks, or file system support for locks,
  30839. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  30840. */
  30841. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  30842. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  30843. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  30844. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  30845. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  30846. switch (posixError) {
  30847. case EACCES:
  30848. case EAGAIN:
  30849. case ETIMEDOUT:
  30850. case EBUSY:
  30851. case EINTR:
  30852. case ENOLCK:
  30853. /* random NFS retry error, unless during file system support
  30854. * introspection, in which it actually means what it says */
  30855. return SQLITE_BUSY;
  30856. case EPERM:
  30857. return SQLITE_PERM;
  30858. default:
  30859. return sqliteIOErr;
  30860. }
  30861. }
  30862. /******************************************************************************
  30863. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  30864. **
  30865. ** On most versions of unix, we can get a unique ID for a file by concatenating
  30866. ** the device number and the inode number. But this does not work on VxWorks.
  30867. ** On VxWorks, a unique file id must be based on the canonical filename.
  30868. **
  30869. ** A pointer to an instance of the following structure can be used as a
  30870. ** unique file ID in VxWorks. Each instance of this structure contains
  30871. ** a copy of the canonical filename. There is also a reference count.
  30872. ** The structure is reclaimed when the number of pointers to it drops to
  30873. ** zero.
  30874. **
  30875. ** There are never very many files open at one time and lookups are not
  30876. ** a performance-critical path, so it is sufficient to put these
  30877. ** structures on a linked list.
  30878. */
  30879. struct vxworksFileId {
  30880. struct vxworksFileId *pNext; /* Next in a list of them all */
  30881. int nRef; /* Number of references to this one */
  30882. int nName; /* Length of the zCanonicalName[] string */
  30883. char *zCanonicalName; /* Canonical filename */
  30884. };
  30885. #if OS_VXWORKS
  30886. /*
  30887. ** All unique filenames are held on a linked list headed by this
  30888. ** variable:
  30889. */
  30890. static struct vxworksFileId *vxworksFileList = 0;
  30891. /*
  30892. ** Simplify a filename into its canonical form
  30893. ** by making the following changes:
  30894. **
  30895. ** * removing any trailing and duplicate /
  30896. ** * convert /./ into just /
  30897. ** * convert /A/../ where A is any simple name into just /
  30898. **
  30899. ** Changes are made in-place. Return the new name length.
  30900. **
  30901. ** The original filename is in z[0..n-1]. Return the number of
  30902. ** characters in the simplified name.
  30903. */
  30904. static int vxworksSimplifyName(char *z, int n){
  30905. int i, j;
  30906. while( n>1 && z[n-1]=='/' ){ n--; }
  30907. for(i=j=0; i<n; i++){
  30908. if( z[i]=='/' ){
  30909. if( z[i+1]=='/' ) continue;
  30910. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  30911. i += 1;
  30912. continue;
  30913. }
  30914. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  30915. while( j>0 && z[j-1]!='/' ){ j--; }
  30916. if( j>0 ){ j--; }
  30917. i += 2;
  30918. continue;
  30919. }
  30920. }
  30921. z[j++] = z[i];
  30922. }
  30923. z[j] = 0;
  30924. return j;
  30925. }
  30926. /*
  30927. ** Find a unique file ID for the given absolute pathname. Return
  30928. ** a pointer to the vxworksFileId object. This pointer is the unique
  30929. ** file ID.
  30930. **
  30931. ** The nRef field of the vxworksFileId object is incremented before
  30932. ** the object is returned. A new vxworksFileId object is created
  30933. ** and added to the global list if necessary.
  30934. **
  30935. ** If a memory allocation error occurs, return NULL.
  30936. */
  30937. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  30938. struct vxworksFileId *pNew; /* search key and new file ID */
  30939. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  30940. int n; /* Length of zAbsoluteName string */
  30941. assert( zAbsoluteName[0]=='/' );
  30942. n = (int)strlen(zAbsoluteName);
  30943. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  30944. if( pNew==0 ) return 0;
  30945. pNew->zCanonicalName = (char*)&pNew[1];
  30946. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  30947. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  30948. /* Search for an existing entry that matching the canonical name.
  30949. ** If found, increment the reference count and return a pointer to
  30950. ** the existing file ID.
  30951. */
  30952. unixEnterMutex();
  30953. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  30954. if( pCandidate->nName==n
  30955. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  30956. ){
  30957. sqlite3_free(pNew);
  30958. pCandidate->nRef++;
  30959. unixLeaveMutex();
  30960. return pCandidate;
  30961. }
  30962. }
  30963. /* No match was found. We will make a new file ID */
  30964. pNew->nRef = 1;
  30965. pNew->nName = n;
  30966. pNew->pNext = vxworksFileList;
  30967. vxworksFileList = pNew;
  30968. unixLeaveMutex();
  30969. return pNew;
  30970. }
  30971. /*
  30972. ** Decrement the reference count on a vxworksFileId object. Free
  30973. ** the object when the reference count reaches zero.
  30974. */
  30975. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  30976. unixEnterMutex();
  30977. assert( pId->nRef>0 );
  30978. pId->nRef--;
  30979. if( pId->nRef==0 ){
  30980. struct vxworksFileId **pp;
  30981. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  30982. assert( *pp==pId );
  30983. *pp = pId->pNext;
  30984. sqlite3_free(pId);
  30985. }
  30986. unixLeaveMutex();
  30987. }
  30988. #endif /* OS_VXWORKS */
  30989. /*************** End of Unique File ID Utility Used By VxWorks ****************
  30990. ******************************************************************************/
  30991. /******************************************************************************
  30992. *************************** Posix Advisory Locking ****************************
  30993. **
  30994. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  30995. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  30996. ** sets or clears a lock, that operation overrides any prior locks set
  30997. ** by the same process. It does not explicitly say so, but this implies
  30998. ** that it overrides locks set by the same process using a different
  30999. ** file descriptor. Consider this test case:
  31000. **
  31001. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  31002. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  31003. **
  31004. ** Suppose ./file1 and ./file2 are really the same file (because
  31005. ** one is a hard or symbolic link to the other) then if you set
  31006. ** an exclusive lock on fd1, then try to get an exclusive lock
  31007. ** on fd2, it works. I would have expected the second lock to
  31008. ** fail since there was already a lock on the file due to fd1.
  31009. ** But not so. Since both locks came from the same process, the
  31010. ** second overrides the first, even though they were on different
  31011. ** file descriptors opened on different file names.
  31012. **
  31013. ** This means that we cannot use POSIX locks to synchronize file access
  31014. ** among competing threads of the same process. POSIX locks will work fine
  31015. ** to synchronize access for threads in separate processes, but not
  31016. ** threads within the same process.
  31017. **
  31018. ** To work around the problem, SQLite has to manage file locks internally
  31019. ** on its own. Whenever a new database is opened, we have to find the
  31020. ** specific inode of the database file (the inode is determined by the
  31021. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  31022. ** and check for locks already existing on that inode. When locks are
  31023. ** created or removed, we have to look at our own internal record of the
  31024. ** locks to see if another thread has previously set a lock on that same
  31025. ** inode.
  31026. **
  31027. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  31028. ** For VxWorks, we have to use the alternative unique ID system based on
  31029. ** canonical filename and implemented in the previous division.)
  31030. **
  31031. ** The sqlite3_file structure for POSIX is no longer just an integer file
  31032. ** descriptor. It is now a structure that holds the integer file
  31033. ** descriptor and a pointer to a structure that describes the internal
  31034. ** locks on the corresponding inode. There is one locking structure
  31035. ** per inode, so if the same inode is opened twice, both unixFile structures
  31036. ** point to the same locking structure. The locking structure keeps
  31037. ** a reference count (so we will know when to delete it) and a "cnt"
  31038. ** field that tells us its internal lock status. cnt==0 means the
  31039. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  31040. ** cnt>0 means there are cnt shared locks on the file.
  31041. **
  31042. ** Any attempt to lock or unlock a file first checks the locking
  31043. ** structure. The fcntl() system call is only invoked to set a
  31044. ** POSIX lock if the internal lock structure transitions between
  31045. ** a locked and an unlocked state.
  31046. **
  31047. ** But wait: there are yet more problems with POSIX advisory locks.
  31048. **
  31049. ** If you close a file descriptor that points to a file that has locks,
  31050. ** all locks on that file that are owned by the current process are
  31051. ** released. To work around this problem, each unixInodeInfo object
  31052. ** maintains a count of the number of pending locks on tha inode.
  31053. ** When an attempt is made to close an unixFile, if there are
  31054. ** other unixFile open on the same inode that are holding locks, the call
  31055. ** to close() the file descriptor is deferred until all of the locks clear.
  31056. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  31057. ** be closed and that list is walked (and cleared) when the last lock
  31058. ** clears.
  31059. **
  31060. ** Yet another problem: LinuxThreads do not play well with posix locks.
  31061. **
  31062. ** Many older versions of linux use the LinuxThreads library which is
  31063. ** not posix compliant. Under LinuxThreads, a lock created by thread
  31064. ** A cannot be modified or overridden by a different thread B.
  31065. ** Only thread A can modify the lock. Locking behavior is correct
  31066. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  31067. ** on linux - with NPTL a lock created by thread A can override locks
  31068. ** in thread B. But there is no way to know at compile-time which
  31069. ** threading library is being used. So there is no way to know at
  31070. ** compile-time whether or not thread A can override locks on thread B.
  31071. ** One has to do a run-time check to discover the behavior of the
  31072. ** current process.
  31073. **
  31074. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  31075. ** was dropped beginning with version 3.7.0. SQLite will still work with
  31076. ** LinuxThreads provided that (1) there is no more than one connection
  31077. ** per database file in the same process and (2) database connections
  31078. ** do not move across threads.
  31079. */
  31080. /*
  31081. ** An instance of the following structure serves as the key used
  31082. ** to locate a particular unixInodeInfo object.
  31083. */
  31084. struct unixFileId {
  31085. dev_t dev; /* Device number */
  31086. #if OS_VXWORKS
  31087. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  31088. #else
  31089. /* We are told that some versions of Android contain a bug that
  31090. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  31091. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  31092. ** To work around this, always allocate 64-bits for the inode number.
  31093. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  31094. ** but that should not be a big deal. */
  31095. /* WAS: ino_t ino; */
  31096. u64 ino; /* Inode number */
  31097. #endif
  31098. };
  31099. /*
  31100. ** An instance of the following structure is allocated for each open
  31101. ** inode. Or, on LinuxThreads, there is one of these structures for
  31102. ** each inode opened by each thread.
  31103. **
  31104. ** A single inode can have multiple file descriptors, so each unixFile
  31105. ** structure contains a pointer to an instance of this object and this
  31106. ** object keeps a count of the number of unixFile pointing to it.
  31107. */
  31108. struct unixInodeInfo {
  31109. struct unixFileId fileId; /* The lookup key */
  31110. int nShared; /* Number of SHARED locks held */
  31111. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  31112. unsigned char bProcessLock; /* An exclusive process lock is held */
  31113. int nRef; /* Number of pointers to this structure */
  31114. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  31115. int nLock; /* Number of outstanding file locks */
  31116. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  31117. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  31118. unixInodeInfo *pPrev; /* .... doubly linked */
  31119. #if SQLITE_ENABLE_LOCKING_STYLE
  31120. unsigned long long sharedByte; /* for AFP simulated shared lock */
  31121. #endif
  31122. #if OS_VXWORKS
  31123. sem_t *pSem; /* Named POSIX semaphore */
  31124. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  31125. #endif
  31126. };
  31127. /*
  31128. ** A lists of all unixInodeInfo objects.
  31129. */
  31130. static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
  31131. static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
  31132. /*
  31133. **
  31134. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  31135. ** unixLogError().
  31136. **
  31137. ** It is invoked after an error occurs in an OS function and errno has been
  31138. ** set. It logs a message using sqlite3_log() containing the current value of
  31139. ** errno and, if possible, the human-readable equivalent from strerror() or
  31140. ** strerror_r().
  31141. **
  31142. ** The first argument passed to the macro should be the error code that
  31143. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  31144. ** The two subsequent arguments should be the name of the OS function that
  31145. ** failed (e.g. "unlink", "open") and the associated file-system path,
  31146. ** if any.
  31147. */
  31148. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  31149. static int unixLogErrorAtLine(
  31150. int errcode, /* SQLite error code */
  31151. const char *zFunc, /* Name of OS function that failed */
  31152. const char *zPath, /* File path associated with error */
  31153. int iLine /* Source line number where error occurred */
  31154. ){
  31155. char *zErr; /* Message from strerror() or equivalent */
  31156. int iErrno = errno; /* Saved syscall error number */
  31157. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  31158. ** the strerror() function to obtain the human-readable error message
  31159. ** equivalent to errno. Otherwise, use strerror_r().
  31160. */
  31161. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  31162. char aErr[80];
  31163. memset(aErr, 0, sizeof(aErr));
  31164. zErr = aErr;
  31165. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  31166. ** assume that the system provides the GNU version of strerror_r() that
  31167. ** returns a pointer to a buffer containing the error message. That pointer
  31168. ** may point to aErr[], or it may point to some static storage somewhere.
  31169. ** Otherwise, assume that the system provides the POSIX version of
  31170. ** strerror_r(), which always writes an error message into aErr[].
  31171. **
  31172. ** If the code incorrectly assumes that it is the POSIX version that is
  31173. ** available, the error message will often be an empty string. Not a
  31174. ** huge problem. Incorrectly concluding that the GNU version is available
  31175. ** could lead to a segfault though.
  31176. */
  31177. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  31178. zErr =
  31179. # endif
  31180. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  31181. #elif SQLITE_THREADSAFE
  31182. /* This is a threadsafe build, but strerror_r() is not available. */
  31183. zErr = "";
  31184. #else
  31185. /* Non-threadsafe build, use strerror(). */
  31186. zErr = strerror(iErrno);
  31187. #endif
  31188. if( zPath==0 ) zPath = "";
  31189. sqlite3_log(errcode,
  31190. "os_unix.c:%d: (%d) %s(%s) - %s",
  31191. iLine, iErrno, zFunc, zPath, zErr
  31192. );
  31193. return errcode;
  31194. }
  31195. /*
  31196. ** Close a file descriptor.
  31197. **
  31198. ** We assume that close() almost always works, since it is only in a
  31199. ** very sick application or on a very sick platform that it might fail.
  31200. ** If it does fail, simply leak the file descriptor, but do log the
  31201. ** error.
  31202. **
  31203. ** Note that it is not safe to retry close() after EINTR since the
  31204. ** file descriptor might have already been reused by another thread.
  31205. ** So we don't even try to recover from an EINTR. Just log the error
  31206. ** and move on.
  31207. */
  31208. static void robust_close(unixFile *pFile, int h, int lineno){
  31209. if( osClose(h) ){
  31210. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  31211. pFile ? pFile->zPath : 0, lineno);
  31212. }
  31213. }
  31214. /*
  31215. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  31216. ** a convenient place to set a breakpoint.
  31217. */
  31218. static void storeLastErrno(unixFile *pFile, int error){
  31219. pFile->lastErrno = error;
  31220. }
  31221. /*
  31222. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  31223. */
  31224. static void closePendingFds(unixFile *pFile){
  31225. unixInodeInfo *pInode = pFile->pInode;
  31226. UnixUnusedFd *p;
  31227. UnixUnusedFd *pNext;
  31228. for(p=pInode->pUnused; p; p=pNext){
  31229. pNext = p->pNext;
  31230. robust_close(pFile, p->fd, __LINE__);
  31231. sqlite3_free(p);
  31232. nUnusedFd--;
  31233. }
  31234. pInode->pUnused = 0;
  31235. }
  31236. /*
  31237. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  31238. **
  31239. ** The mutex entered using the unixEnterMutex() function must be held
  31240. ** when this function is called.
  31241. */
  31242. static void releaseInodeInfo(unixFile *pFile){
  31243. unixInodeInfo *pInode = pFile->pInode;
  31244. assert( unixMutexHeld() );
  31245. if( ALWAYS(pInode) ){
  31246. pInode->nRef--;
  31247. if( pInode->nRef==0 ){
  31248. assert( pInode->pShmNode==0 );
  31249. closePendingFds(pFile);
  31250. if( pInode->pPrev ){
  31251. assert( pInode->pPrev->pNext==pInode );
  31252. pInode->pPrev->pNext = pInode->pNext;
  31253. }else{
  31254. assert( inodeList==pInode );
  31255. inodeList = pInode->pNext;
  31256. }
  31257. if( pInode->pNext ){
  31258. assert( pInode->pNext->pPrev==pInode );
  31259. pInode->pNext->pPrev = pInode->pPrev;
  31260. }
  31261. sqlite3_free(pInode);
  31262. }
  31263. }
  31264. assert( inodeList!=0 || nUnusedFd==0 );
  31265. }
  31266. /*
  31267. ** Given a file descriptor, locate the unixInodeInfo object that
  31268. ** describes that file descriptor. Create a new one if necessary. The
  31269. ** return value might be uninitialized if an error occurs.
  31270. **
  31271. ** The mutex entered using the unixEnterMutex() function must be held
  31272. ** when this function is called.
  31273. **
  31274. ** Return an appropriate error code.
  31275. */
  31276. static int findInodeInfo(
  31277. unixFile *pFile, /* Unix file with file desc used in the key */
  31278. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  31279. ){
  31280. int rc; /* System call return code */
  31281. int fd; /* The file descriptor for pFile */
  31282. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  31283. struct stat statbuf; /* Low-level file information */
  31284. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  31285. assert( unixMutexHeld() );
  31286. /* Get low-level information about the file that we can used to
  31287. ** create a unique name for the file.
  31288. */
  31289. fd = pFile->h;
  31290. rc = osFstat(fd, &statbuf);
  31291. if( rc!=0 ){
  31292. storeLastErrno(pFile, errno);
  31293. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  31294. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  31295. #endif
  31296. return SQLITE_IOERR;
  31297. }
  31298. #ifdef __APPLE__
  31299. /* On OS X on an msdos filesystem, the inode number is reported
  31300. ** incorrectly for zero-size files. See ticket #3260. To work
  31301. ** around this problem (we consider it a bug in OS X, not SQLite)
  31302. ** we always increase the file size to 1 by writing a single byte
  31303. ** prior to accessing the inode number. The one byte written is
  31304. ** an ASCII 'S' character which also happens to be the first byte
  31305. ** in the header of every SQLite database. In this way, if there
  31306. ** is a race condition such that another thread has already populated
  31307. ** the first page of the database, no damage is done.
  31308. */
  31309. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  31310. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  31311. if( rc!=1 ){
  31312. storeLastErrno(pFile, errno);
  31313. return SQLITE_IOERR;
  31314. }
  31315. rc = osFstat(fd, &statbuf);
  31316. if( rc!=0 ){
  31317. storeLastErrno(pFile, errno);
  31318. return SQLITE_IOERR;
  31319. }
  31320. }
  31321. #endif
  31322. memset(&fileId, 0, sizeof(fileId));
  31323. fileId.dev = statbuf.st_dev;
  31324. #if OS_VXWORKS
  31325. fileId.pId = pFile->pId;
  31326. #else
  31327. fileId.ino = (u64)statbuf.st_ino;
  31328. #endif
  31329. assert( inodeList!=0 || nUnusedFd==0 );
  31330. pInode = inodeList;
  31331. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  31332. pInode = pInode->pNext;
  31333. }
  31334. if( pInode==0 ){
  31335. pInode = sqlite3_malloc64( sizeof(*pInode) );
  31336. if( pInode==0 ){
  31337. return SQLITE_NOMEM_BKPT;
  31338. }
  31339. memset(pInode, 0, sizeof(*pInode));
  31340. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  31341. pInode->nRef = 1;
  31342. pInode->pNext = inodeList;
  31343. pInode->pPrev = 0;
  31344. if( inodeList ) inodeList->pPrev = pInode;
  31345. inodeList = pInode;
  31346. }else{
  31347. pInode->nRef++;
  31348. }
  31349. *ppInode = pInode;
  31350. return SQLITE_OK;
  31351. }
  31352. /*
  31353. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  31354. */
  31355. static int fileHasMoved(unixFile *pFile){
  31356. #if OS_VXWORKS
  31357. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  31358. #else
  31359. struct stat buf;
  31360. return pFile->pInode!=0 &&
  31361. (osStat(pFile->zPath, &buf)!=0
  31362. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  31363. #endif
  31364. }
  31365. /*
  31366. ** Check a unixFile that is a database. Verify the following:
  31367. **
  31368. ** (1) There is exactly one hard link on the file
  31369. ** (2) The file is not a symbolic link
  31370. ** (3) The file has not been renamed or unlinked
  31371. **
  31372. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  31373. */
  31374. static void verifyDbFile(unixFile *pFile){
  31375. struct stat buf;
  31376. int rc;
  31377. /* These verifications occurs for the main database only */
  31378. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  31379. rc = osFstat(pFile->h, &buf);
  31380. if( rc!=0 ){
  31381. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  31382. return;
  31383. }
  31384. if( buf.st_nlink==0 ){
  31385. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  31386. return;
  31387. }
  31388. if( buf.st_nlink>1 ){
  31389. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  31390. return;
  31391. }
  31392. if( fileHasMoved(pFile) ){
  31393. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  31394. return;
  31395. }
  31396. }
  31397. /*
  31398. ** This routine checks if there is a RESERVED lock held on the specified
  31399. ** file by this or any other process. If such a lock is held, set *pResOut
  31400. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31401. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31402. */
  31403. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  31404. int rc = SQLITE_OK;
  31405. int reserved = 0;
  31406. unixFile *pFile = (unixFile*)id;
  31407. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31408. assert( pFile );
  31409. assert( pFile->eFileLock<=SHARED_LOCK );
  31410. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  31411. /* Check if a thread in this process holds such a lock */
  31412. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  31413. reserved = 1;
  31414. }
  31415. /* Otherwise see if some other process holds it.
  31416. */
  31417. #ifndef __DJGPP__
  31418. if( !reserved && !pFile->pInode->bProcessLock ){
  31419. struct flock lock;
  31420. lock.l_whence = SEEK_SET;
  31421. lock.l_start = RESERVED_BYTE;
  31422. lock.l_len = 1;
  31423. lock.l_type = F_WRLCK;
  31424. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  31425. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  31426. storeLastErrno(pFile, errno);
  31427. } else if( lock.l_type!=F_UNLCK ){
  31428. reserved = 1;
  31429. }
  31430. }
  31431. #endif
  31432. unixLeaveMutex();
  31433. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  31434. *pResOut = reserved;
  31435. return rc;
  31436. }
  31437. /*
  31438. ** Set a posix-advisory-lock.
  31439. **
  31440. ** There are two versions of this routine. If compiled with
  31441. ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
  31442. ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
  31443. ** value is set, then it is the number of milliseconds to wait before
  31444. ** failing the lock. The iBusyTimeout value is always reset back to
  31445. ** zero on each call.
  31446. **
  31447. ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
  31448. ** attempt to set the lock.
  31449. */
  31450. #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
  31451. # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
  31452. #else
  31453. static int osSetPosixAdvisoryLock(
  31454. int h, /* The file descriptor on which to take the lock */
  31455. struct flock *pLock, /* The description of the lock */
  31456. unixFile *pFile /* Structure holding timeout value */
  31457. ){
  31458. int rc = osFcntl(h,F_SETLK,pLock);
  31459. while( rc<0 && pFile->iBusyTimeout>0 ){
  31460. /* On systems that support some kind of blocking file lock with a timeout,
  31461. ** make appropriate changes here to invoke that blocking file lock. On
  31462. ** generic posix, however, there is no such API. So we simply try the
  31463. ** lock once every millisecond until either the timeout expires, or until
  31464. ** the lock is obtained. */
  31465. usleep(1000);
  31466. rc = osFcntl(h,F_SETLK,pLock);
  31467. pFile->iBusyTimeout--;
  31468. }
  31469. return rc;
  31470. }
  31471. #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
  31472. /*
  31473. ** Attempt to set a system-lock on the file pFile. The lock is
  31474. ** described by pLock.
  31475. **
  31476. ** If the pFile was opened read/write from unix-excl, then the only lock
  31477. ** ever obtained is an exclusive lock, and it is obtained exactly once
  31478. ** the first time any lock is attempted. All subsequent system locking
  31479. ** operations become no-ops. Locking operations still happen internally,
  31480. ** in order to coordinate access between separate database connections
  31481. ** within this process, but all of that is handled in memory and the
  31482. ** operating system does not participate.
  31483. **
  31484. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  31485. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  31486. ** and is read-only.
  31487. **
  31488. ** Zero is returned if the call completes successfully, or -1 if a call
  31489. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  31490. */
  31491. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  31492. int rc;
  31493. unixInodeInfo *pInode = pFile->pInode;
  31494. assert( unixMutexHeld() );
  31495. assert( pInode!=0 );
  31496. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  31497. if( pInode->bProcessLock==0 ){
  31498. struct flock lock;
  31499. assert( pInode->nLock==0 );
  31500. lock.l_whence = SEEK_SET;
  31501. lock.l_start = SHARED_FIRST;
  31502. lock.l_len = SHARED_SIZE;
  31503. lock.l_type = F_WRLCK;
  31504. rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
  31505. if( rc<0 ) return rc;
  31506. pInode->bProcessLock = 1;
  31507. pInode->nLock++;
  31508. }else{
  31509. rc = 0;
  31510. }
  31511. }else{
  31512. rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
  31513. }
  31514. return rc;
  31515. }
  31516. /*
  31517. ** Lock the file with the lock specified by parameter eFileLock - one
  31518. ** of the following:
  31519. **
  31520. ** (1) SHARED_LOCK
  31521. ** (2) RESERVED_LOCK
  31522. ** (3) PENDING_LOCK
  31523. ** (4) EXCLUSIVE_LOCK
  31524. **
  31525. ** Sometimes when requesting one lock state, additional lock states
  31526. ** are inserted in between. The locking might fail on one of the later
  31527. ** transitions leaving the lock state different from what it started but
  31528. ** still short of its goal. The following chart shows the allowed
  31529. ** transitions and the inserted intermediate states:
  31530. **
  31531. ** UNLOCKED -> SHARED
  31532. ** SHARED -> RESERVED
  31533. ** SHARED -> (PENDING) -> EXCLUSIVE
  31534. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31535. ** PENDING -> EXCLUSIVE
  31536. **
  31537. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31538. ** routine to lower a locking level.
  31539. */
  31540. static int unixLock(sqlite3_file *id, int eFileLock){
  31541. /* The following describes the implementation of the various locks and
  31542. ** lock transitions in terms of the POSIX advisory shared and exclusive
  31543. ** lock primitives (called read-locks and write-locks below, to avoid
  31544. ** confusion with SQLite lock names). The algorithms are complicated
  31545. ** slightly in order to be compatible with Windows95 systems simultaneously
  31546. ** accessing the same database file, in case that is ever required.
  31547. **
  31548. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  31549. ** byte', each single bytes at well known offsets, and the 'shared byte
  31550. ** range', a range of 510 bytes at a well known offset.
  31551. **
  31552. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  31553. ** byte'. If this is successful, 'shared byte range' is read-locked
  31554. ** and the lock on the 'pending byte' released. (Legacy note: When
  31555. ** SQLite was first developed, Windows95 systems were still very common,
  31556. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  31557. ** single randomly selected by from the 'shared byte range' is locked.
  31558. ** Windows95 is now pretty much extinct, but this work-around for the
  31559. ** lack of shared-locks on Windows95 lives on, for backwards
  31560. ** compatibility.)
  31561. **
  31562. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  31563. ** A RESERVED lock is implemented by grabbing a write-lock on the
  31564. ** 'reserved byte'.
  31565. **
  31566. ** A process may only obtain a PENDING lock after it has obtained a
  31567. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  31568. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  31569. ** obtained, but existing SHARED locks are allowed to persist. A process
  31570. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  31571. ** This property is used by the algorithm for rolling back a journal file
  31572. ** after a crash.
  31573. **
  31574. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  31575. ** implemented by obtaining a write-lock on the entire 'shared byte
  31576. ** range'. Since all other locks require a read-lock on one of the bytes
  31577. ** within this range, this ensures that no other locks are held on the
  31578. ** database.
  31579. */
  31580. int rc = SQLITE_OK;
  31581. unixFile *pFile = (unixFile*)id;
  31582. unixInodeInfo *pInode;
  31583. struct flock lock;
  31584. int tErrno = 0;
  31585. assert( pFile );
  31586. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  31587. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  31588. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  31589. osGetpid(0)));
  31590. /* If there is already a lock of this type or more restrictive on the
  31591. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  31592. ** unixEnterMutex() hasn't been called yet.
  31593. */
  31594. if( pFile->eFileLock>=eFileLock ){
  31595. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  31596. azFileLock(eFileLock)));
  31597. return SQLITE_OK;
  31598. }
  31599. /* Make sure the locking sequence is correct.
  31600. ** (1) We never move from unlocked to anything higher than shared lock.
  31601. ** (2) SQLite never explicitly requests a pendig lock.
  31602. ** (3) A shared lock is always held when a reserve lock is requested.
  31603. */
  31604. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  31605. assert( eFileLock!=PENDING_LOCK );
  31606. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  31607. /* This mutex is needed because pFile->pInode is shared across threads
  31608. */
  31609. unixEnterMutex();
  31610. pInode = pFile->pInode;
  31611. /* If some thread using this PID has a lock via a different unixFile*
  31612. ** handle that precludes the requested lock, return BUSY.
  31613. */
  31614. if( (pFile->eFileLock!=pInode->eFileLock &&
  31615. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  31616. ){
  31617. rc = SQLITE_BUSY;
  31618. goto end_lock;
  31619. }
  31620. /* If a SHARED lock is requested, and some thread using this PID already
  31621. ** has a SHARED or RESERVED lock, then increment reference counts and
  31622. ** return SQLITE_OK.
  31623. */
  31624. if( eFileLock==SHARED_LOCK &&
  31625. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  31626. assert( eFileLock==SHARED_LOCK );
  31627. assert( pFile->eFileLock==0 );
  31628. assert( pInode->nShared>0 );
  31629. pFile->eFileLock = SHARED_LOCK;
  31630. pInode->nShared++;
  31631. pInode->nLock++;
  31632. goto end_lock;
  31633. }
  31634. /* A PENDING lock is needed before acquiring a SHARED lock and before
  31635. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  31636. ** be released.
  31637. */
  31638. lock.l_len = 1L;
  31639. lock.l_whence = SEEK_SET;
  31640. if( eFileLock==SHARED_LOCK
  31641. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  31642. ){
  31643. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  31644. lock.l_start = PENDING_BYTE;
  31645. if( unixFileLock(pFile, &lock) ){
  31646. tErrno = errno;
  31647. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31648. if( rc!=SQLITE_BUSY ){
  31649. storeLastErrno(pFile, tErrno);
  31650. }
  31651. goto end_lock;
  31652. }
  31653. }
  31654. /* If control gets to this point, then actually go ahead and make
  31655. ** operating system calls for the specified lock.
  31656. */
  31657. if( eFileLock==SHARED_LOCK ){
  31658. assert( pInode->nShared==0 );
  31659. assert( pInode->eFileLock==0 );
  31660. assert( rc==SQLITE_OK );
  31661. /* Now get the read-lock */
  31662. lock.l_start = SHARED_FIRST;
  31663. lock.l_len = SHARED_SIZE;
  31664. if( unixFileLock(pFile, &lock) ){
  31665. tErrno = errno;
  31666. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31667. }
  31668. /* Drop the temporary PENDING lock */
  31669. lock.l_start = PENDING_BYTE;
  31670. lock.l_len = 1L;
  31671. lock.l_type = F_UNLCK;
  31672. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  31673. /* This could happen with a network mount */
  31674. tErrno = errno;
  31675. rc = SQLITE_IOERR_UNLOCK;
  31676. }
  31677. if( rc ){
  31678. if( rc!=SQLITE_BUSY ){
  31679. storeLastErrno(pFile, tErrno);
  31680. }
  31681. goto end_lock;
  31682. }else{
  31683. pFile->eFileLock = SHARED_LOCK;
  31684. pInode->nLock++;
  31685. pInode->nShared = 1;
  31686. }
  31687. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  31688. /* We are trying for an exclusive lock but another thread in this
  31689. ** same process is still holding a shared lock. */
  31690. rc = SQLITE_BUSY;
  31691. }else{
  31692. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  31693. ** assumed that there is a SHARED or greater lock on the file
  31694. ** already.
  31695. */
  31696. assert( 0!=pFile->eFileLock );
  31697. lock.l_type = F_WRLCK;
  31698. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  31699. if( eFileLock==RESERVED_LOCK ){
  31700. lock.l_start = RESERVED_BYTE;
  31701. lock.l_len = 1L;
  31702. }else{
  31703. lock.l_start = SHARED_FIRST;
  31704. lock.l_len = SHARED_SIZE;
  31705. }
  31706. if( unixFileLock(pFile, &lock) ){
  31707. tErrno = errno;
  31708. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31709. if( rc!=SQLITE_BUSY ){
  31710. storeLastErrno(pFile, tErrno);
  31711. }
  31712. }
  31713. }
  31714. #ifdef SQLITE_DEBUG
  31715. /* Set up the transaction-counter change checking flags when
  31716. ** transitioning from a SHARED to a RESERVED lock. The change
  31717. ** from SHARED to RESERVED marks the beginning of a normal
  31718. ** write operation (not a hot journal rollback).
  31719. */
  31720. if( rc==SQLITE_OK
  31721. && pFile->eFileLock<=SHARED_LOCK
  31722. && eFileLock==RESERVED_LOCK
  31723. ){
  31724. pFile->transCntrChng = 0;
  31725. pFile->dbUpdate = 0;
  31726. pFile->inNormalWrite = 1;
  31727. }
  31728. #endif
  31729. if( rc==SQLITE_OK ){
  31730. pFile->eFileLock = eFileLock;
  31731. pInode->eFileLock = eFileLock;
  31732. }else if( eFileLock==EXCLUSIVE_LOCK ){
  31733. pFile->eFileLock = PENDING_LOCK;
  31734. pInode->eFileLock = PENDING_LOCK;
  31735. }
  31736. end_lock:
  31737. unixLeaveMutex();
  31738. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  31739. rc==SQLITE_OK ? "ok" : "failed"));
  31740. return rc;
  31741. }
  31742. /*
  31743. ** Add the file descriptor used by file handle pFile to the corresponding
  31744. ** pUnused list.
  31745. */
  31746. static void setPendingFd(unixFile *pFile){
  31747. unixInodeInfo *pInode = pFile->pInode;
  31748. UnixUnusedFd *p = pFile->pPreallocatedUnused;
  31749. p->pNext = pInode->pUnused;
  31750. pInode->pUnused = p;
  31751. pFile->h = -1;
  31752. pFile->pPreallocatedUnused = 0;
  31753. nUnusedFd++;
  31754. }
  31755. /*
  31756. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31757. ** must be either NO_LOCK or SHARED_LOCK.
  31758. **
  31759. ** If the locking level of the file descriptor is already at or below
  31760. ** the requested locking level, this routine is a no-op.
  31761. **
  31762. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  31763. ** the byte range is divided into 2 parts and the first part is unlocked then
  31764. ** set to a read lock, then the other part is simply unlocked. This works
  31765. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  31766. ** remove the write lock on a region when a read lock is set.
  31767. */
  31768. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  31769. unixFile *pFile = (unixFile*)id;
  31770. unixInodeInfo *pInode;
  31771. struct flock lock;
  31772. int rc = SQLITE_OK;
  31773. assert( pFile );
  31774. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  31775. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  31776. osGetpid(0)));
  31777. assert( eFileLock<=SHARED_LOCK );
  31778. if( pFile->eFileLock<=eFileLock ){
  31779. return SQLITE_OK;
  31780. }
  31781. unixEnterMutex();
  31782. pInode = pFile->pInode;
  31783. assert( pInode->nShared!=0 );
  31784. if( pFile->eFileLock>SHARED_LOCK ){
  31785. assert( pInode->eFileLock==pFile->eFileLock );
  31786. #ifdef SQLITE_DEBUG
  31787. /* When reducing a lock such that other processes can start
  31788. ** reading the database file again, make sure that the
  31789. ** transaction counter was updated if any part of the database
  31790. ** file changed. If the transaction counter is not updated,
  31791. ** other connections to the same file might not realize that
  31792. ** the file has changed and hence might not know to flush their
  31793. ** cache. The use of a stale cache can lead to database corruption.
  31794. */
  31795. pFile->inNormalWrite = 0;
  31796. #endif
  31797. /* downgrading to a shared lock on NFS involves clearing the write lock
  31798. ** before establishing the readlock - to avoid a race condition we downgrade
  31799. ** the lock in 2 blocks, so that part of the range will be covered by a
  31800. ** write lock until the rest is covered by a read lock:
  31801. ** 1: [WWWWW]
  31802. ** 2: [....W]
  31803. ** 3: [RRRRW]
  31804. ** 4: [RRRR.]
  31805. */
  31806. if( eFileLock==SHARED_LOCK ){
  31807. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  31808. (void)handleNFSUnlock;
  31809. assert( handleNFSUnlock==0 );
  31810. #endif
  31811. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31812. if( handleNFSUnlock ){
  31813. int tErrno; /* Error code from system call errors */
  31814. off_t divSize = SHARED_SIZE - 1;
  31815. lock.l_type = F_UNLCK;
  31816. lock.l_whence = SEEK_SET;
  31817. lock.l_start = SHARED_FIRST;
  31818. lock.l_len = divSize;
  31819. if( unixFileLock(pFile, &lock)==(-1) ){
  31820. tErrno = errno;
  31821. rc = SQLITE_IOERR_UNLOCK;
  31822. storeLastErrno(pFile, tErrno);
  31823. goto end_unlock;
  31824. }
  31825. lock.l_type = F_RDLCK;
  31826. lock.l_whence = SEEK_SET;
  31827. lock.l_start = SHARED_FIRST;
  31828. lock.l_len = divSize;
  31829. if( unixFileLock(pFile, &lock)==(-1) ){
  31830. tErrno = errno;
  31831. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  31832. if( IS_LOCK_ERROR(rc) ){
  31833. storeLastErrno(pFile, tErrno);
  31834. }
  31835. goto end_unlock;
  31836. }
  31837. lock.l_type = F_UNLCK;
  31838. lock.l_whence = SEEK_SET;
  31839. lock.l_start = SHARED_FIRST+divSize;
  31840. lock.l_len = SHARED_SIZE-divSize;
  31841. if( unixFileLock(pFile, &lock)==(-1) ){
  31842. tErrno = errno;
  31843. rc = SQLITE_IOERR_UNLOCK;
  31844. storeLastErrno(pFile, tErrno);
  31845. goto end_unlock;
  31846. }
  31847. }else
  31848. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31849. {
  31850. lock.l_type = F_RDLCK;
  31851. lock.l_whence = SEEK_SET;
  31852. lock.l_start = SHARED_FIRST;
  31853. lock.l_len = SHARED_SIZE;
  31854. if( unixFileLock(pFile, &lock) ){
  31855. /* In theory, the call to unixFileLock() cannot fail because another
  31856. ** process is holding an incompatible lock. If it does, this
  31857. ** indicates that the other process is not following the locking
  31858. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  31859. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  31860. ** an assert to fail). */
  31861. rc = SQLITE_IOERR_RDLOCK;
  31862. storeLastErrno(pFile, errno);
  31863. goto end_unlock;
  31864. }
  31865. }
  31866. }
  31867. lock.l_type = F_UNLCK;
  31868. lock.l_whence = SEEK_SET;
  31869. lock.l_start = PENDING_BYTE;
  31870. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  31871. if( unixFileLock(pFile, &lock)==0 ){
  31872. pInode->eFileLock = SHARED_LOCK;
  31873. }else{
  31874. rc = SQLITE_IOERR_UNLOCK;
  31875. storeLastErrno(pFile, errno);
  31876. goto end_unlock;
  31877. }
  31878. }
  31879. if( eFileLock==NO_LOCK ){
  31880. /* Decrement the shared lock counter. Release the lock using an
  31881. ** OS call only when all threads in this same process have released
  31882. ** the lock.
  31883. */
  31884. pInode->nShared--;
  31885. if( pInode->nShared==0 ){
  31886. lock.l_type = F_UNLCK;
  31887. lock.l_whence = SEEK_SET;
  31888. lock.l_start = lock.l_len = 0L;
  31889. if( unixFileLock(pFile, &lock)==0 ){
  31890. pInode->eFileLock = NO_LOCK;
  31891. }else{
  31892. rc = SQLITE_IOERR_UNLOCK;
  31893. storeLastErrno(pFile, errno);
  31894. pInode->eFileLock = NO_LOCK;
  31895. pFile->eFileLock = NO_LOCK;
  31896. }
  31897. }
  31898. /* Decrement the count of locks against this same file. When the
  31899. ** count reaches zero, close any other file descriptors whose close
  31900. ** was deferred because of outstanding locks.
  31901. */
  31902. pInode->nLock--;
  31903. assert( pInode->nLock>=0 );
  31904. if( pInode->nLock==0 ){
  31905. closePendingFds(pFile);
  31906. }
  31907. }
  31908. end_unlock:
  31909. unixLeaveMutex();
  31910. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  31911. return rc;
  31912. }
  31913. /*
  31914. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31915. ** must be either NO_LOCK or SHARED_LOCK.
  31916. **
  31917. ** If the locking level of the file descriptor is already at or below
  31918. ** the requested locking level, this routine is a no-op.
  31919. */
  31920. static int unixUnlock(sqlite3_file *id, int eFileLock){
  31921. #if SQLITE_MAX_MMAP_SIZE>0
  31922. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  31923. #endif
  31924. return posixUnlock(id, eFileLock, 0);
  31925. }
  31926. #if SQLITE_MAX_MMAP_SIZE>0
  31927. static int unixMapfile(unixFile *pFd, i64 nByte);
  31928. static void unixUnmapfile(unixFile *pFd);
  31929. #endif
  31930. /*
  31931. ** This function performs the parts of the "close file" operation
  31932. ** common to all locking schemes. It closes the directory and file
  31933. ** handles, if they are valid, and sets all fields of the unixFile
  31934. ** structure to 0.
  31935. **
  31936. ** It is *not* necessary to hold the mutex when this routine is called,
  31937. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  31938. ** vxworksReleaseFileId() routine.
  31939. */
  31940. static int closeUnixFile(sqlite3_file *id){
  31941. unixFile *pFile = (unixFile*)id;
  31942. #if SQLITE_MAX_MMAP_SIZE>0
  31943. unixUnmapfile(pFile);
  31944. #endif
  31945. if( pFile->h>=0 ){
  31946. robust_close(pFile, pFile->h, __LINE__);
  31947. pFile->h = -1;
  31948. }
  31949. #if OS_VXWORKS
  31950. if( pFile->pId ){
  31951. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  31952. osUnlink(pFile->pId->zCanonicalName);
  31953. }
  31954. vxworksReleaseFileId(pFile->pId);
  31955. pFile->pId = 0;
  31956. }
  31957. #endif
  31958. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  31959. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  31960. osUnlink(pFile->zPath);
  31961. sqlite3_free(*(char**)&pFile->zPath);
  31962. pFile->zPath = 0;
  31963. }
  31964. #endif
  31965. OSTRACE(("CLOSE %-3d\n", pFile->h));
  31966. OpenCounter(-1);
  31967. sqlite3_free(pFile->pPreallocatedUnused);
  31968. memset(pFile, 0, sizeof(unixFile));
  31969. return SQLITE_OK;
  31970. }
  31971. /*
  31972. ** Close a file.
  31973. */
  31974. static int unixClose(sqlite3_file *id){
  31975. int rc = SQLITE_OK;
  31976. unixFile *pFile = (unixFile *)id;
  31977. verifyDbFile(pFile);
  31978. unixUnlock(id, NO_LOCK);
  31979. unixEnterMutex();
  31980. /* unixFile.pInode is always valid here. Otherwise, a different close
  31981. ** routine (e.g. nolockClose()) would be called instead.
  31982. */
  31983. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  31984. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  31985. /* If there are outstanding locks, do not actually close the file just
  31986. ** yet because that would clear those locks. Instead, add the file
  31987. ** descriptor to pInode->pUnused list. It will be automatically closed
  31988. ** when the last lock is cleared.
  31989. */
  31990. setPendingFd(pFile);
  31991. }
  31992. releaseInodeInfo(pFile);
  31993. rc = closeUnixFile(id);
  31994. unixLeaveMutex();
  31995. return rc;
  31996. }
  31997. /************** End of the posix advisory lock implementation *****************
  31998. ******************************************************************************/
  31999. /******************************************************************************
  32000. ****************************** No-op Locking **********************************
  32001. **
  32002. ** Of the various locking implementations available, this is by far the
  32003. ** simplest: locking is ignored. No attempt is made to lock the database
  32004. ** file for reading or writing.
  32005. **
  32006. ** This locking mode is appropriate for use on read-only databases
  32007. ** (ex: databases that are burned into CD-ROM, for example.) It can
  32008. ** also be used if the application employs some external mechanism to
  32009. ** prevent simultaneous access of the same database by two or more
  32010. ** database connections. But there is a serious risk of database
  32011. ** corruption if this locking mode is used in situations where multiple
  32012. ** database connections are accessing the same database file at the same
  32013. ** time and one or more of those connections are writing.
  32014. */
  32015. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  32016. UNUSED_PARAMETER(NotUsed);
  32017. *pResOut = 0;
  32018. return SQLITE_OK;
  32019. }
  32020. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  32021. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32022. return SQLITE_OK;
  32023. }
  32024. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  32025. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32026. return SQLITE_OK;
  32027. }
  32028. /*
  32029. ** Close the file.
  32030. */
  32031. static int nolockClose(sqlite3_file *id) {
  32032. return closeUnixFile(id);
  32033. }
  32034. /******************* End of the no-op lock implementation *********************
  32035. ******************************************************************************/
  32036. /******************************************************************************
  32037. ************************* Begin dot-file Locking ******************************
  32038. **
  32039. ** The dotfile locking implementation uses the existence of separate lock
  32040. ** files (really a directory) to control access to the database. This works
  32041. ** on just about every filesystem imaginable. But there are serious downsides:
  32042. **
  32043. ** (1) There is zero concurrency. A single reader blocks all other
  32044. ** connections from reading or writing the database.
  32045. **
  32046. ** (2) An application crash or power loss can leave stale lock files
  32047. ** sitting around that need to be cleared manually.
  32048. **
  32049. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  32050. ** other locking strategy is available.
  32051. **
  32052. ** Dotfile locking works by creating a subdirectory in the same directory as
  32053. ** the database and with the same name but with a ".lock" extension added.
  32054. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  32055. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  32056. */
  32057. /*
  32058. ** The file suffix added to the data base filename in order to create the
  32059. ** lock directory.
  32060. */
  32061. #define DOTLOCK_SUFFIX ".lock"
  32062. /*
  32063. ** This routine checks if there is a RESERVED lock held on the specified
  32064. ** file by this or any other process. If such a lock is held, set *pResOut
  32065. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32066. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32067. **
  32068. ** In dotfile locking, either a lock exists or it does not. So in this
  32069. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  32070. ** is held on the file and false if the file is unlocked.
  32071. */
  32072. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  32073. int rc = SQLITE_OK;
  32074. int reserved = 0;
  32075. unixFile *pFile = (unixFile*)id;
  32076. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32077. assert( pFile );
  32078. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  32079. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  32080. *pResOut = reserved;
  32081. return rc;
  32082. }
  32083. /*
  32084. ** Lock the file with the lock specified by parameter eFileLock - one
  32085. ** of the following:
  32086. **
  32087. ** (1) SHARED_LOCK
  32088. ** (2) RESERVED_LOCK
  32089. ** (3) PENDING_LOCK
  32090. ** (4) EXCLUSIVE_LOCK
  32091. **
  32092. ** Sometimes when requesting one lock state, additional lock states
  32093. ** are inserted in between. The locking might fail on one of the later
  32094. ** transitions leaving the lock state different from what it started but
  32095. ** still short of its goal. The following chart shows the allowed
  32096. ** transitions and the inserted intermediate states:
  32097. **
  32098. ** UNLOCKED -> SHARED
  32099. ** SHARED -> RESERVED
  32100. ** SHARED -> (PENDING) -> EXCLUSIVE
  32101. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32102. ** PENDING -> EXCLUSIVE
  32103. **
  32104. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32105. ** routine to lower a locking level.
  32106. **
  32107. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  32108. ** But we track the other locking levels internally.
  32109. */
  32110. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  32111. unixFile *pFile = (unixFile*)id;
  32112. char *zLockFile = (char *)pFile->lockingContext;
  32113. int rc = SQLITE_OK;
  32114. /* If we have any lock, then the lock file already exists. All we have
  32115. ** to do is adjust our internal record of the lock level.
  32116. */
  32117. if( pFile->eFileLock > NO_LOCK ){
  32118. pFile->eFileLock = eFileLock;
  32119. /* Always update the timestamp on the old file */
  32120. #ifdef HAVE_UTIME
  32121. utime(zLockFile, NULL);
  32122. #else
  32123. utimes(zLockFile, NULL);
  32124. #endif
  32125. return SQLITE_OK;
  32126. }
  32127. /* grab an exclusive lock */
  32128. rc = osMkdir(zLockFile, 0777);
  32129. if( rc<0 ){
  32130. /* failed to open/create the lock directory */
  32131. int tErrno = errno;
  32132. if( EEXIST == tErrno ){
  32133. rc = SQLITE_BUSY;
  32134. } else {
  32135. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32136. if( rc!=SQLITE_BUSY ){
  32137. storeLastErrno(pFile, tErrno);
  32138. }
  32139. }
  32140. return rc;
  32141. }
  32142. /* got it, set the type and return ok */
  32143. pFile->eFileLock = eFileLock;
  32144. return rc;
  32145. }
  32146. /*
  32147. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32148. ** must be either NO_LOCK or SHARED_LOCK.
  32149. **
  32150. ** If the locking level of the file descriptor is already at or below
  32151. ** the requested locking level, this routine is a no-op.
  32152. **
  32153. ** When the locking level reaches NO_LOCK, delete the lock file.
  32154. */
  32155. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  32156. unixFile *pFile = (unixFile*)id;
  32157. char *zLockFile = (char *)pFile->lockingContext;
  32158. int rc;
  32159. assert( pFile );
  32160. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  32161. pFile->eFileLock, osGetpid(0)));
  32162. assert( eFileLock<=SHARED_LOCK );
  32163. /* no-op if possible */
  32164. if( pFile->eFileLock==eFileLock ){
  32165. return SQLITE_OK;
  32166. }
  32167. /* To downgrade to shared, simply update our internal notion of the
  32168. ** lock state. No need to mess with the file on disk.
  32169. */
  32170. if( eFileLock==SHARED_LOCK ){
  32171. pFile->eFileLock = SHARED_LOCK;
  32172. return SQLITE_OK;
  32173. }
  32174. /* To fully unlock the database, delete the lock file */
  32175. assert( eFileLock==NO_LOCK );
  32176. rc = osRmdir(zLockFile);
  32177. if( rc<0 ){
  32178. int tErrno = errno;
  32179. if( tErrno==ENOENT ){
  32180. rc = SQLITE_OK;
  32181. }else{
  32182. rc = SQLITE_IOERR_UNLOCK;
  32183. storeLastErrno(pFile, tErrno);
  32184. }
  32185. return rc;
  32186. }
  32187. pFile->eFileLock = NO_LOCK;
  32188. return SQLITE_OK;
  32189. }
  32190. /*
  32191. ** Close a file. Make sure the lock has been released before closing.
  32192. */
  32193. static int dotlockClose(sqlite3_file *id) {
  32194. unixFile *pFile = (unixFile*)id;
  32195. assert( id!=0 );
  32196. dotlockUnlock(id, NO_LOCK);
  32197. sqlite3_free(pFile->lockingContext);
  32198. return closeUnixFile(id);
  32199. }
  32200. /****************** End of the dot-file lock implementation *******************
  32201. ******************************************************************************/
  32202. /******************************************************************************
  32203. ************************** Begin flock Locking ********************************
  32204. **
  32205. ** Use the flock() system call to do file locking.
  32206. **
  32207. ** flock() locking is like dot-file locking in that the various
  32208. ** fine-grain locking levels supported by SQLite are collapsed into
  32209. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  32210. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  32211. ** still works when you do this, but concurrency is reduced since
  32212. ** only a single process can be reading the database at a time.
  32213. **
  32214. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  32215. */
  32216. #if SQLITE_ENABLE_LOCKING_STYLE
  32217. /*
  32218. ** Retry flock() calls that fail with EINTR
  32219. */
  32220. #ifdef EINTR
  32221. static int robust_flock(int fd, int op){
  32222. int rc;
  32223. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  32224. return rc;
  32225. }
  32226. #else
  32227. # define robust_flock(a,b) flock(a,b)
  32228. #endif
  32229. /*
  32230. ** This routine checks if there is a RESERVED lock held on the specified
  32231. ** file by this or any other process. If such a lock is held, set *pResOut
  32232. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32233. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32234. */
  32235. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  32236. int rc = SQLITE_OK;
  32237. int reserved = 0;
  32238. unixFile *pFile = (unixFile*)id;
  32239. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32240. assert( pFile );
  32241. /* Check if a thread in this process holds such a lock */
  32242. if( pFile->eFileLock>SHARED_LOCK ){
  32243. reserved = 1;
  32244. }
  32245. /* Otherwise see if some other process holds it. */
  32246. if( !reserved ){
  32247. /* attempt to get the lock */
  32248. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  32249. if( !lrc ){
  32250. /* got the lock, unlock it */
  32251. lrc = robust_flock(pFile->h, LOCK_UN);
  32252. if ( lrc ) {
  32253. int tErrno = errno;
  32254. /* unlock failed with an error */
  32255. lrc = SQLITE_IOERR_UNLOCK;
  32256. storeLastErrno(pFile, tErrno);
  32257. rc = lrc;
  32258. }
  32259. } else {
  32260. int tErrno = errno;
  32261. reserved = 1;
  32262. /* someone else might have it reserved */
  32263. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32264. if( IS_LOCK_ERROR(lrc) ){
  32265. storeLastErrno(pFile, tErrno);
  32266. rc = lrc;
  32267. }
  32268. }
  32269. }
  32270. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  32271. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  32272. if( (rc & 0xff) == SQLITE_IOERR ){
  32273. rc = SQLITE_OK;
  32274. reserved=1;
  32275. }
  32276. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  32277. *pResOut = reserved;
  32278. return rc;
  32279. }
  32280. /*
  32281. ** Lock the file with the lock specified by parameter eFileLock - one
  32282. ** of the following:
  32283. **
  32284. ** (1) SHARED_LOCK
  32285. ** (2) RESERVED_LOCK
  32286. ** (3) PENDING_LOCK
  32287. ** (4) EXCLUSIVE_LOCK
  32288. **
  32289. ** Sometimes when requesting one lock state, additional lock states
  32290. ** are inserted in between. The locking might fail on one of the later
  32291. ** transitions leaving the lock state different from what it started but
  32292. ** still short of its goal. The following chart shows the allowed
  32293. ** transitions and the inserted intermediate states:
  32294. **
  32295. ** UNLOCKED -> SHARED
  32296. ** SHARED -> RESERVED
  32297. ** SHARED -> (PENDING) -> EXCLUSIVE
  32298. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32299. ** PENDING -> EXCLUSIVE
  32300. **
  32301. ** flock() only really support EXCLUSIVE locks. We track intermediate
  32302. ** lock states in the sqlite3_file structure, but all locks SHARED or
  32303. ** above are really EXCLUSIVE locks and exclude all other processes from
  32304. ** access the file.
  32305. **
  32306. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32307. ** routine to lower a locking level.
  32308. */
  32309. static int flockLock(sqlite3_file *id, int eFileLock) {
  32310. int rc = SQLITE_OK;
  32311. unixFile *pFile = (unixFile*)id;
  32312. assert( pFile );
  32313. /* if we already have a lock, it is exclusive.
  32314. ** Just adjust level and punt on outta here. */
  32315. if (pFile->eFileLock > NO_LOCK) {
  32316. pFile->eFileLock = eFileLock;
  32317. return SQLITE_OK;
  32318. }
  32319. /* grab an exclusive lock */
  32320. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  32321. int tErrno = errno;
  32322. /* didn't get, must be busy */
  32323. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32324. if( IS_LOCK_ERROR(rc) ){
  32325. storeLastErrno(pFile, tErrno);
  32326. }
  32327. } else {
  32328. /* got it, set the type and return ok */
  32329. pFile->eFileLock = eFileLock;
  32330. }
  32331. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  32332. rc==SQLITE_OK ? "ok" : "failed"));
  32333. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  32334. if( (rc & 0xff) == SQLITE_IOERR ){
  32335. rc = SQLITE_BUSY;
  32336. }
  32337. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  32338. return rc;
  32339. }
  32340. /*
  32341. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32342. ** must be either NO_LOCK or SHARED_LOCK.
  32343. **
  32344. ** If the locking level of the file descriptor is already at or below
  32345. ** the requested locking level, this routine is a no-op.
  32346. */
  32347. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  32348. unixFile *pFile = (unixFile*)id;
  32349. assert( pFile );
  32350. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  32351. pFile->eFileLock, osGetpid(0)));
  32352. assert( eFileLock<=SHARED_LOCK );
  32353. /* no-op if possible */
  32354. if( pFile->eFileLock==eFileLock ){
  32355. return SQLITE_OK;
  32356. }
  32357. /* shared can just be set because we always have an exclusive */
  32358. if (eFileLock==SHARED_LOCK) {
  32359. pFile->eFileLock = eFileLock;
  32360. return SQLITE_OK;
  32361. }
  32362. /* no, really, unlock. */
  32363. if( robust_flock(pFile->h, LOCK_UN) ){
  32364. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  32365. return SQLITE_OK;
  32366. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  32367. return SQLITE_IOERR_UNLOCK;
  32368. }else{
  32369. pFile->eFileLock = NO_LOCK;
  32370. return SQLITE_OK;
  32371. }
  32372. }
  32373. /*
  32374. ** Close a file.
  32375. */
  32376. static int flockClose(sqlite3_file *id) {
  32377. assert( id!=0 );
  32378. flockUnlock(id, NO_LOCK);
  32379. return closeUnixFile(id);
  32380. }
  32381. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  32382. /******************* End of the flock lock implementation *********************
  32383. ******************************************************************************/
  32384. /******************************************************************************
  32385. ************************ Begin Named Semaphore Locking ************************
  32386. **
  32387. ** Named semaphore locking is only supported on VxWorks.
  32388. **
  32389. ** Semaphore locking is like dot-lock and flock in that it really only
  32390. ** supports EXCLUSIVE locking. Only a single process can read or write
  32391. ** the database file at a time. This reduces potential concurrency, but
  32392. ** makes the lock implementation much easier.
  32393. */
  32394. #if OS_VXWORKS
  32395. /*
  32396. ** This routine checks if there is a RESERVED lock held on the specified
  32397. ** file by this or any other process. If such a lock is held, set *pResOut
  32398. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32399. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32400. */
  32401. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  32402. int rc = SQLITE_OK;
  32403. int reserved = 0;
  32404. unixFile *pFile = (unixFile*)id;
  32405. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32406. assert( pFile );
  32407. /* Check if a thread in this process holds such a lock */
  32408. if( pFile->eFileLock>SHARED_LOCK ){
  32409. reserved = 1;
  32410. }
  32411. /* Otherwise see if some other process holds it. */
  32412. if( !reserved ){
  32413. sem_t *pSem = pFile->pInode->pSem;
  32414. if( sem_trywait(pSem)==-1 ){
  32415. int tErrno = errno;
  32416. if( EAGAIN != tErrno ){
  32417. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  32418. storeLastErrno(pFile, tErrno);
  32419. } else {
  32420. /* someone else has the lock when we are in NO_LOCK */
  32421. reserved = (pFile->eFileLock < SHARED_LOCK);
  32422. }
  32423. }else{
  32424. /* we could have it if we want it */
  32425. sem_post(pSem);
  32426. }
  32427. }
  32428. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  32429. *pResOut = reserved;
  32430. return rc;
  32431. }
  32432. /*
  32433. ** Lock the file with the lock specified by parameter eFileLock - one
  32434. ** of the following:
  32435. **
  32436. ** (1) SHARED_LOCK
  32437. ** (2) RESERVED_LOCK
  32438. ** (3) PENDING_LOCK
  32439. ** (4) EXCLUSIVE_LOCK
  32440. **
  32441. ** Sometimes when requesting one lock state, additional lock states
  32442. ** are inserted in between. The locking might fail on one of the later
  32443. ** transitions leaving the lock state different from what it started but
  32444. ** still short of its goal. The following chart shows the allowed
  32445. ** transitions and the inserted intermediate states:
  32446. **
  32447. ** UNLOCKED -> SHARED
  32448. ** SHARED -> RESERVED
  32449. ** SHARED -> (PENDING) -> EXCLUSIVE
  32450. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32451. ** PENDING -> EXCLUSIVE
  32452. **
  32453. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  32454. ** lock states in the sqlite3_file structure, but all locks SHARED or
  32455. ** above are really EXCLUSIVE locks and exclude all other processes from
  32456. ** access the file.
  32457. **
  32458. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32459. ** routine to lower a locking level.
  32460. */
  32461. static int semXLock(sqlite3_file *id, int eFileLock) {
  32462. unixFile *pFile = (unixFile*)id;
  32463. sem_t *pSem = pFile->pInode->pSem;
  32464. int rc = SQLITE_OK;
  32465. /* if we already have a lock, it is exclusive.
  32466. ** Just adjust level and punt on outta here. */
  32467. if (pFile->eFileLock > NO_LOCK) {
  32468. pFile->eFileLock = eFileLock;
  32469. rc = SQLITE_OK;
  32470. goto sem_end_lock;
  32471. }
  32472. /* lock semaphore now but bail out when already locked. */
  32473. if( sem_trywait(pSem)==-1 ){
  32474. rc = SQLITE_BUSY;
  32475. goto sem_end_lock;
  32476. }
  32477. /* got it, set the type and return ok */
  32478. pFile->eFileLock = eFileLock;
  32479. sem_end_lock:
  32480. return rc;
  32481. }
  32482. /*
  32483. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32484. ** must be either NO_LOCK or SHARED_LOCK.
  32485. **
  32486. ** If the locking level of the file descriptor is already at or below
  32487. ** the requested locking level, this routine is a no-op.
  32488. */
  32489. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  32490. unixFile *pFile = (unixFile*)id;
  32491. sem_t *pSem = pFile->pInode->pSem;
  32492. assert( pFile );
  32493. assert( pSem );
  32494. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  32495. pFile->eFileLock, osGetpid(0)));
  32496. assert( eFileLock<=SHARED_LOCK );
  32497. /* no-op if possible */
  32498. if( pFile->eFileLock==eFileLock ){
  32499. return SQLITE_OK;
  32500. }
  32501. /* shared can just be set because we always have an exclusive */
  32502. if (eFileLock==SHARED_LOCK) {
  32503. pFile->eFileLock = eFileLock;
  32504. return SQLITE_OK;
  32505. }
  32506. /* no, really unlock. */
  32507. if ( sem_post(pSem)==-1 ) {
  32508. int rc, tErrno = errno;
  32509. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  32510. if( IS_LOCK_ERROR(rc) ){
  32511. storeLastErrno(pFile, tErrno);
  32512. }
  32513. return rc;
  32514. }
  32515. pFile->eFileLock = NO_LOCK;
  32516. return SQLITE_OK;
  32517. }
  32518. /*
  32519. ** Close a file.
  32520. */
  32521. static int semXClose(sqlite3_file *id) {
  32522. if( id ){
  32523. unixFile *pFile = (unixFile*)id;
  32524. semXUnlock(id, NO_LOCK);
  32525. assert( pFile );
  32526. unixEnterMutex();
  32527. releaseInodeInfo(pFile);
  32528. unixLeaveMutex();
  32529. closeUnixFile(id);
  32530. }
  32531. return SQLITE_OK;
  32532. }
  32533. #endif /* OS_VXWORKS */
  32534. /*
  32535. ** Named semaphore locking is only available on VxWorks.
  32536. **
  32537. *************** End of the named semaphore lock implementation ****************
  32538. ******************************************************************************/
  32539. /******************************************************************************
  32540. *************************** Begin AFP Locking *********************************
  32541. **
  32542. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  32543. ** on Apple Macintosh computers - both OS9 and OSX.
  32544. **
  32545. ** Third-party implementations of AFP are available. But this code here
  32546. ** only works on OSX.
  32547. */
  32548. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32549. /*
  32550. ** The afpLockingContext structure contains all afp lock specific state
  32551. */
  32552. typedef struct afpLockingContext afpLockingContext;
  32553. struct afpLockingContext {
  32554. int reserved;
  32555. const char *dbPath; /* Name of the open file */
  32556. };
  32557. struct ByteRangeLockPB2
  32558. {
  32559. unsigned long long offset; /* offset to first byte to lock */
  32560. unsigned long long length; /* nbr of bytes to lock */
  32561. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  32562. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  32563. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  32564. int fd; /* file desc to assoc this lock with */
  32565. };
  32566. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  32567. /*
  32568. ** This is a utility for setting or clearing a bit-range lock on an
  32569. ** AFP filesystem.
  32570. **
  32571. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  32572. */
  32573. static int afpSetLock(
  32574. const char *path, /* Name of the file to be locked or unlocked */
  32575. unixFile *pFile, /* Open file descriptor on path */
  32576. unsigned long long offset, /* First byte to be locked */
  32577. unsigned long long length, /* Number of bytes to lock */
  32578. int setLockFlag /* True to set lock. False to clear lock */
  32579. ){
  32580. struct ByteRangeLockPB2 pb;
  32581. int err;
  32582. pb.unLockFlag = setLockFlag ? 0 : 1;
  32583. pb.startEndFlag = 0;
  32584. pb.offset = offset;
  32585. pb.length = length;
  32586. pb.fd = pFile->h;
  32587. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  32588. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  32589. offset, length));
  32590. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  32591. if ( err==-1 ) {
  32592. int rc;
  32593. int tErrno = errno;
  32594. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  32595. path, tErrno, strerror(tErrno)));
  32596. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  32597. rc = SQLITE_BUSY;
  32598. #else
  32599. rc = sqliteErrorFromPosixError(tErrno,
  32600. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  32601. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  32602. if( IS_LOCK_ERROR(rc) ){
  32603. storeLastErrno(pFile, tErrno);
  32604. }
  32605. return rc;
  32606. } else {
  32607. return SQLITE_OK;
  32608. }
  32609. }
  32610. /*
  32611. ** This routine checks if there is a RESERVED lock held on the specified
  32612. ** file by this or any other process. If such a lock is held, set *pResOut
  32613. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32614. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32615. */
  32616. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  32617. int rc = SQLITE_OK;
  32618. int reserved = 0;
  32619. unixFile *pFile = (unixFile*)id;
  32620. afpLockingContext *context;
  32621. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32622. assert( pFile );
  32623. context = (afpLockingContext *) pFile->lockingContext;
  32624. if( context->reserved ){
  32625. *pResOut = 1;
  32626. return SQLITE_OK;
  32627. }
  32628. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  32629. /* Check if a thread in this process holds such a lock */
  32630. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  32631. reserved = 1;
  32632. }
  32633. /* Otherwise see if some other process holds it.
  32634. */
  32635. if( !reserved ){
  32636. /* lock the RESERVED byte */
  32637. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  32638. if( SQLITE_OK==lrc ){
  32639. /* if we succeeded in taking the reserved lock, unlock it to restore
  32640. ** the original state */
  32641. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  32642. } else {
  32643. /* if we failed to get the lock then someone else must have it */
  32644. reserved = 1;
  32645. }
  32646. if( IS_LOCK_ERROR(lrc) ){
  32647. rc=lrc;
  32648. }
  32649. }
  32650. unixLeaveMutex();
  32651. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  32652. *pResOut = reserved;
  32653. return rc;
  32654. }
  32655. /*
  32656. ** Lock the file with the lock specified by parameter eFileLock - one
  32657. ** of the following:
  32658. **
  32659. ** (1) SHARED_LOCK
  32660. ** (2) RESERVED_LOCK
  32661. ** (3) PENDING_LOCK
  32662. ** (4) EXCLUSIVE_LOCK
  32663. **
  32664. ** Sometimes when requesting one lock state, additional lock states
  32665. ** are inserted in between. The locking might fail on one of the later
  32666. ** transitions leaving the lock state different from what it started but
  32667. ** still short of its goal. The following chart shows the allowed
  32668. ** transitions and the inserted intermediate states:
  32669. **
  32670. ** UNLOCKED -> SHARED
  32671. ** SHARED -> RESERVED
  32672. ** SHARED -> (PENDING) -> EXCLUSIVE
  32673. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32674. ** PENDING -> EXCLUSIVE
  32675. **
  32676. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32677. ** routine to lower a locking level.
  32678. */
  32679. static int afpLock(sqlite3_file *id, int eFileLock){
  32680. int rc = SQLITE_OK;
  32681. unixFile *pFile = (unixFile*)id;
  32682. unixInodeInfo *pInode = pFile->pInode;
  32683. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  32684. assert( pFile );
  32685. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  32686. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  32687. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  32688. /* If there is already a lock of this type or more restrictive on the
  32689. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  32690. ** unixEnterMutex() hasn't been called yet.
  32691. */
  32692. if( pFile->eFileLock>=eFileLock ){
  32693. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  32694. azFileLock(eFileLock)));
  32695. return SQLITE_OK;
  32696. }
  32697. /* Make sure the locking sequence is correct
  32698. ** (1) We never move from unlocked to anything higher than shared lock.
  32699. ** (2) SQLite never explicitly requests a pendig lock.
  32700. ** (3) A shared lock is always held when a reserve lock is requested.
  32701. */
  32702. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  32703. assert( eFileLock!=PENDING_LOCK );
  32704. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  32705. /* This mutex is needed because pFile->pInode is shared across threads
  32706. */
  32707. unixEnterMutex();
  32708. pInode = pFile->pInode;
  32709. /* If some thread using this PID has a lock via a different unixFile*
  32710. ** handle that precludes the requested lock, return BUSY.
  32711. */
  32712. if( (pFile->eFileLock!=pInode->eFileLock &&
  32713. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  32714. ){
  32715. rc = SQLITE_BUSY;
  32716. goto afp_end_lock;
  32717. }
  32718. /* If a SHARED lock is requested, and some thread using this PID already
  32719. ** has a SHARED or RESERVED lock, then increment reference counts and
  32720. ** return SQLITE_OK.
  32721. */
  32722. if( eFileLock==SHARED_LOCK &&
  32723. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  32724. assert( eFileLock==SHARED_LOCK );
  32725. assert( pFile->eFileLock==0 );
  32726. assert( pInode->nShared>0 );
  32727. pFile->eFileLock = SHARED_LOCK;
  32728. pInode->nShared++;
  32729. pInode->nLock++;
  32730. goto afp_end_lock;
  32731. }
  32732. /* A PENDING lock is needed before acquiring a SHARED lock and before
  32733. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  32734. ** be released.
  32735. */
  32736. if( eFileLock==SHARED_LOCK
  32737. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  32738. ){
  32739. int failed;
  32740. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  32741. if (failed) {
  32742. rc = failed;
  32743. goto afp_end_lock;
  32744. }
  32745. }
  32746. /* If control gets to this point, then actually go ahead and make
  32747. ** operating system calls for the specified lock.
  32748. */
  32749. if( eFileLock==SHARED_LOCK ){
  32750. int lrc1, lrc2, lrc1Errno = 0;
  32751. long lk, mask;
  32752. assert( pInode->nShared==0 );
  32753. assert( pInode->eFileLock==0 );
  32754. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  32755. /* Now get the read-lock SHARED_LOCK */
  32756. /* note that the quality of the randomness doesn't matter that much */
  32757. lk = random();
  32758. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  32759. lrc1 = afpSetLock(context->dbPath, pFile,
  32760. SHARED_FIRST+pInode->sharedByte, 1, 1);
  32761. if( IS_LOCK_ERROR(lrc1) ){
  32762. lrc1Errno = pFile->lastErrno;
  32763. }
  32764. /* Drop the temporary PENDING lock */
  32765. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  32766. if( IS_LOCK_ERROR(lrc1) ) {
  32767. storeLastErrno(pFile, lrc1Errno);
  32768. rc = lrc1;
  32769. goto afp_end_lock;
  32770. } else if( IS_LOCK_ERROR(lrc2) ){
  32771. rc = lrc2;
  32772. goto afp_end_lock;
  32773. } else if( lrc1 != SQLITE_OK ) {
  32774. rc = lrc1;
  32775. } else {
  32776. pFile->eFileLock = SHARED_LOCK;
  32777. pInode->nLock++;
  32778. pInode->nShared = 1;
  32779. }
  32780. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  32781. /* We are trying for an exclusive lock but another thread in this
  32782. ** same process is still holding a shared lock. */
  32783. rc = SQLITE_BUSY;
  32784. }else{
  32785. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  32786. ** assumed that there is a SHARED or greater lock on the file
  32787. ** already.
  32788. */
  32789. int failed = 0;
  32790. assert( 0!=pFile->eFileLock );
  32791. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  32792. /* Acquire a RESERVED lock */
  32793. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  32794. if( !failed ){
  32795. context->reserved = 1;
  32796. }
  32797. }
  32798. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  32799. /* Acquire an EXCLUSIVE lock */
  32800. /* Remove the shared lock before trying the range. we'll need to
  32801. ** reestablish the shared lock if we can't get the afpUnlock
  32802. */
  32803. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  32804. pInode->sharedByte, 1, 0)) ){
  32805. int failed2 = SQLITE_OK;
  32806. /* now attemmpt to get the exclusive lock range */
  32807. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  32808. SHARED_SIZE, 1);
  32809. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  32810. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  32811. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  32812. ** a critical I/O error
  32813. */
  32814. rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
  32815. SQLITE_IOERR_LOCK;
  32816. goto afp_end_lock;
  32817. }
  32818. }else{
  32819. rc = failed;
  32820. }
  32821. }
  32822. if( failed ){
  32823. rc = failed;
  32824. }
  32825. }
  32826. if( rc==SQLITE_OK ){
  32827. pFile->eFileLock = eFileLock;
  32828. pInode->eFileLock = eFileLock;
  32829. }else if( eFileLock==EXCLUSIVE_LOCK ){
  32830. pFile->eFileLock = PENDING_LOCK;
  32831. pInode->eFileLock = PENDING_LOCK;
  32832. }
  32833. afp_end_lock:
  32834. unixLeaveMutex();
  32835. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  32836. rc==SQLITE_OK ? "ok" : "failed"));
  32837. return rc;
  32838. }
  32839. /*
  32840. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32841. ** must be either NO_LOCK or SHARED_LOCK.
  32842. **
  32843. ** If the locking level of the file descriptor is already at or below
  32844. ** the requested locking level, this routine is a no-op.
  32845. */
  32846. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  32847. int rc = SQLITE_OK;
  32848. unixFile *pFile = (unixFile*)id;
  32849. unixInodeInfo *pInode;
  32850. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  32851. int skipShared = 0;
  32852. #ifdef SQLITE_TEST
  32853. int h = pFile->h;
  32854. #endif
  32855. assert( pFile );
  32856. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  32857. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  32858. osGetpid(0)));
  32859. assert( eFileLock<=SHARED_LOCK );
  32860. if( pFile->eFileLock<=eFileLock ){
  32861. return SQLITE_OK;
  32862. }
  32863. unixEnterMutex();
  32864. pInode = pFile->pInode;
  32865. assert( pInode->nShared!=0 );
  32866. if( pFile->eFileLock>SHARED_LOCK ){
  32867. assert( pInode->eFileLock==pFile->eFileLock );
  32868. SimulateIOErrorBenign(1);
  32869. SimulateIOError( h=(-1) )
  32870. SimulateIOErrorBenign(0);
  32871. #ifdef SQLITE_DEBUG
  32872. /* When reducing a lock such that other processes can start
  32873. ** reading the database file again, make sure that the
  32874. ** transaction counter was updated if any part of the database
  32875. ** file changed. If the transaction counter is not updated,
  32876. ** other connections to the same file might not realize that
  32877. ** the file has changed and hence might not know to flush their
  32878. ** cache. The use of a stale cache can lead to database corruption.
  32879. */
  32880. assert( pFile->inNormalWrite==0
  32881. || pFile->dbUpdate==0
  32882. || pFile->transCntrChng==1 );
  32883. pFile->inNormalWrite = 0;
  32884. #endif
  32885. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  32886. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  32887. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  32888. /* only re-establish the shared lock if necessary */
  32889. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  32890. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  32891. } else {
  32892. skipShared = 1;
  32893. }
  32894. }
  32895. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  32896. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  32897. }
  32898. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  32899. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  32900. if( !rc ){
  32901. context->reserved = 0;
  32902. }
  32903. }
  32904. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  32905. pInode->eFileLock = SHARED_LOCK;
  32906. }
  32907. }
  32908. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  32909. /* Decrement the shared lock counter. Release the lock using an
  32910. ** OS call only when all threads in this same process have released
  32911. ** the lock.
  32912. */
  32913. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  32914. pInode->nShared--;
  32915. if( pInode->nShared==0 ){
  32916. SimulateIOErrorBenign(1);
  32917. SimulateIOError( h=(-1) )
  32918. SimulateIOErrorBenign(0);
  32919. if( !skipShared ){
  32920. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  32921. }
  32922. if( !rc ){
  32923. pInode->eFileLock = NO_LOCK;
  32924. pFile->eFileLock = NO_LOCK;
  32925. }
  32926. }
  32927. if( rc==SQLITE_OK ){
  32928. pInode->nLock--;
  32929. assert( pInode->nLock>=0 );
  32930. if( pInode->nLock==0 ){
  32931. closePendingFds(pFile);
  32932. }
  32933. }
  32934. }
  32935. unixLeaveMutex();
  32936. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  32937. return rc;
  32938. }
  32939. /*
  32940. ** Close a file & cleanup AFP specific locking context
  32941. */
  32942. static int afpClose(sqlite3_file *id) {
  32943. int rc = SQLITE_OK;
  32944. unixFile *pFile = (unixFile*)id;
  32945. assert( id!=0 );
  32946. afpUnlock(id, NO_LOCK);
  32947. unixEnterMutex();
  32948. if( pFile->pInode && pFile->pInode->nLock ){
  32949. /* If there are outstanding locks, do not actually close the file just
  32950. ** yet because that would clear those locks. Instead, add the file
  32951. ** descriptor to pInode->aPending. It will be automatically closed when
  32952. ** the last lock is cleared.
  32953. */
  32954. setPendingFd(pFile);
  32955. }
  32956. releaseInodeInfo(pFile);
  32957. sqlite3_free(pFile->lockingContext);
  32958. rc = closeUnixFile(id);
  32959. unixLeaveMutex();
  32960. return rc;
  32961. }
  32962. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32963. /*
  32964. ** The code above is the AFP lock implementation. The code is specific
  32965. ** to MacOSX and does not work on other unix platforms. No alternative
  32966. ** is available. If you don't compile for a mac, then the "unix-afp"
  32967. ** VFS is not available.
  32968. **
  32969. ********************* End of the AFP lock implementation **********************
  32970. ******************************************************************************/
  32971. /******************************************************************************
  32972. *************************** Begin NFS Locking ********************************/
  32973. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32974. /*
  32975. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32976. ** must be either NO_LOCK or SHARED_LOCK.
  32977. **
  32978. ** If the locking level of the file descriptor is already at or below
  32979. ** the requested locking level, this routine is a no-op.
  32980. */
  32981. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  32982. return posixUnlock(id, eFileLock, 1);
  32983. }
  32984. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32985. /*
  32986. ** The code above is the NFS lock implementation. The code is specific
  32987. ** to MacOSX and does not work on other unix platforms. No alternative
  32988. ** is available.
  32989. **
  32990. ********************* End of the NFS lock implementation **********************
  32991. ******************************************************************************/
  32992. /******************************************************************************
  32993. **************** Non-locking sqlite3_file methods *****************************
  32994. **
  32995. ** The next division contains implementations for all methods of the
  32996. ** sqlite3_file object other than the locking methods. The locking
  32997. ** methods were defined in divisions above (one locking method per
  32998. ** division). Those methods that are common to all locking modes
  32999. ** are gather together into this division.
  33000. */
  33001. /*
  33002. ** Seek to the offset passed as the second argument, then read cnt
  33003. ** bytes into pBuf. Return the number of bytes actually read.
  33004. **
  33005. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  33006. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  33007. ** one system to another. Since SQLite does not define USE_PREAD
  33008. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  33009. ** See tickets #2741 and #2681.
  33010. **
  33011. ** To avoid stomping the errno value on a failed read the lastErrno value
  33012. ** is set before returning.
  33013. */
  33014. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  33015. int got;
  33016. int prior = 0;
  33017. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  33018. i64 newOffset;
  33019. #endif
  33020. TIMER_START;
  33021. assert( cnt==(cnt&0x1ffff) );
  33022. assert( id->h>2 );
  33023. do{
  33024. #if defined(USE_PREAD)
  33025. got = osPread(id->h, pBuf, cnt, offset);
  33026. SimulateIOError( got = -1 );
  33027. #elif defined(USE_PREAD64)
  33028. got = osPread64(id->h, pBuf, cnt, offset);
  33029. SimulateIOError( got = -1 );
  33030. #else
  33031. newOffset = lseek(id->h, offset, SEEK_SET);
  33032. SimulateIOError( newOffset = -1 );
  33033. if( newOffset<0 ){
  33034. storeLastErrno((unixFile*)id, errno);
  33035. return -1;
  33036. }
  33037. got = osRead(id->h, pBuf, cnt);
  33038. #endif
  33039. if( got==cnt ) break;
  33040. if( got<0 ){
  33041. if( errno==EINTR ){ got = 1; continue; }
  33042. prior = 0;
  33043. storeLastErrno((unixFile*)id, errno);
  33044. break;
  33045. }else if( got>0 ){
  33046. cnt -= got;
  33047. offset += got;
  33048. prior += got;
  33049. pBuf = (void*)(got + (char*)pBuf);
  33050. }
  33051. }while( got>0 );
  33052. TIMER_END;
  33053. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  33054. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  33055. return got+prior;
  33056. }
  33057. /*
  33058. ** Read data from a file into a buffer. Return SQLITE_OK if all
  33059. ** bytes were read successfully and SQLITE_IOERR if anything goes
  33060. ** wrong.
  33061. */
  33062. static int unixRead(
  33063. sqlite3_file *id,
  33064. void *pBuf,
  33065. int amt,
  33066. sqlite3_int64 offset
  33067. ){
  33068. unixFile *pFile = (unixFile *)id;
  33069. int got;
  33070. assert( id );
  33071. assert( offset>=0 );
  33072. assert( amt>0 );
  33073. /* If this is a database file (not a journal, master-journal or temp
  33074. ** file), the bytes in the locking range should never be read or written. */
  33075. #if 0
  33076. assert( pFile->pPreallocatedUnused==0
  33077. || offset>=PENDING_BYTE+512
  33078. || offset+amt<=PENDING_BYTE
  33079. );
  33080. #endif
  33081. #if SQLITE_MAX_MMAP_SIZE>0
  33082. /* Deal with as much of this read request as possible by transfering
  33083. ** data from the memory mapping using memcpy(). */
  33084. if( offset<pFile->mmapSize ){
  33085. if( offset+amt <= pFile->mmapSize ){
  33086. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  33087. return SQLITE_OK;
  33088. }else{
  33089. int nCopy = pFile->mmapSize - offset;
  33090. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  33091. pBuf = &((u8 *)pBuf)[nCopy];
  33092. amt -= nCopy;
  33093. offset += nCopy;
  33094. }
  33095. }
  33096. #endif
  33097. got = seekAndRead(pFile, offset, pBuf, amt);
  33098. if( got==amt ){
  33099. return SQLITE_OK;
  33100. }else if( got<0 ){
  33101. /* lastErrno set by seekAndRead */
  33102. return SQLITE_IOERR_READ;
  33103. }else{
  33104. storeLastErrno(pFile, 0); /* not a system error */
  33105. /* Unread parts of the buffer must be zero-filled */
  33106. memset(&((char*)pBuf)[got], 0, amt-got);
  33107. return SQLITE_IOERR_SHORT_READ;
  33108. }
  33109. }
  33110. /*
  33111. ** Attempt to seek the file-descriptor passed as the first argument to
  33112. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  33113. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  33114. ** return the actual number of bytes written (which may be less than
  33115. ** nBuf).
  33116. */
  33117. static int seekAndWriteFd(
  33118. int fd, /* File descriptor to write to */
  33119. i64 iOff, /* File offset to begin writing at */
  33120. const void *pBuf, /* Copy data from this buffer to the file */
  33121. int nBuf, /* Size of buffer pBuf in bytes */
  33122. int *piErrno /* OUT: Error number if error occurs */
  33123. ){
  33124. int rc = 0; /* Value returned by system call */
  33125. assert( nBuf==(nBuf&0x1ffff) );
  33126. assert( fd>2 );
  33127. assert( piErrno!=0 );
  33128. nBuf &= 0x1ffff;
  33129. TIMER_START;
  33130. #if defined(USE_PREAD)
  33131. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  33132. #elif defined(USE_PREAD64)
  33133. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  33134. #else
  33135. do{
  33136. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  33137. SimulateIOError( iSeek = -1 );
  33138. if( iSeek<0 ){
  33139. rc = -1;
  33140. break;
  33141. }
  33142. rc = osWrite(fd, pBuf, nBuf);
  33143. }while( rc<0 && errno==EINTR );
  33144. #endif
  33145. TIMER_END;
  33146. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  33147. if( rc<0 ) *piErrno = errno;
  33148. return rc;
  33149. }
  33150. /*
  33151. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  33152. ** Return the number of bytes actually read. Update the offset.
  33153. **
  33154. ** To avoid stomping the errno value on a failed write the lastErrno value
  33155. ** is set before returning.
  33156. */
  33157. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  33158. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  33159. }
  33160. /*
  33161. ** Write data from a buffer into a file. Return SQLITE_OK on success
  33162. ** or some other error code on failure.
  33163. */
  33164. static int unixWrite(
  33165. sqlite3_file *id,
  33166. const void *pBuf,
  33167. int amt,
  33168. sqlite3_int64 offset
  33169. ){
  33170. unixFile *pFile = (unixFile*)id;
  33171. int wrote = 0;
  33172. assert( id );
  33173. assert( amt>0 );
  33174. /* If this is a database file (not a journal, master-journal or temp
  33175. ** file), the bytes in the locking range should never be read or written. */
  33176. #if 0
  33177. assert( pFile->pPreallocatedUnused==0
  33178. || offset>=PENDING_BYTE+512
  33179. || offset+amt<=PENDING_BYTE
  33180. );
  33181. #endif
  33182. #ifdef SQLITE_DEBUG
  33183. /* If we are doing a normal write to a database file (as opposed to
  33184. ** doing a hot-journal rollback or a write to some file other than a
  33185. ** normal database file) then record the fact that the database
  33186. ** has changed. If the transaction counter is modified, record that
  33187. ** fact too.
  33188. */
  33189. if( pFile->inNormalWrite ){
  33190. pFile->dbUpdate = 1; /* The database has been modified */
  33191. if( offset<=24 && offset+amt>=27 ){
  33192. int rc;
  33193. char oldCntr[4];
  33194. SimulateIOErrorBenign(1);
  33195. rc = seekAndRead(pFile, 24, oldCntr, 4);
  33196. SimulateIOErrorBenign(0);
  33197. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  33198. pFile->transCntrChng = 1; /* The transaction counter has changed */
  33199. }
  33200. }
  33201. }
  33202. #endif
  33203. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  33204. /* Deal with as much of this write request as possible by transfering
  33205. ** data from the memory mapping using memcpy(). */
  33206. if( offset<pFile->mmapSize ){
  33207. if( offset+amt <= pFile->mmapSize ){
  33208. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  33209. return SQLITE_OK;
  33210. }else{
  33211. int nCopy = pFile->mmapSize - offset;
  33212. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  33213. pBuf = &((u8 *)pBuf)[nCopy];
  33214. amt -= nCopy;
  33215. offset += nCopy;
  33216. }
  33217. }
  33218. #endif
  33219. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  33220. amt -= wrote;
  33221. offset += wrote;
  33222. pBuf = &((char*)pBuf)[wrote];
  33223. }
  33224. SimulateIOError(( wrote=(-1), amt=1 ));
  33225. SimulateDiskfullError(( wrote=0, amt=1 ));
  33226. if( amt>wrote ){
  33227. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  33228. /* lastErrno set by seekAndWrite */
  33229. return SQLITE_IOERR_WRITE;
  33230. }else{
  33231. storeLastErrno(pFile, 0); /* not a system error */
  33232. return SQLITE_FULL;
  33233. }
  33234. }
  33235. return SQLITE_OK;
  33236. }
  33237. #ifdef SQLITE_TEST
  33238. /*
  33239. ** Count the number of fullsyncs and normal syncs. This is used to test
  33240. ** that syncs and fullsyncs are occurring at the right times.
  33241. */
  33242. SQLITE_API int sqlite3_sync_count = 0;
  33243. SQLITE_API int sqlite3_fullsync_count = 0;
  33244. #endif
  33245. /*
  33246. ** We do not trust systems to provide a working fdatasync(). Some do.
  33247. ** Others do no. To be safe, we will stick with the (slightly slower)
  33248. ** fsync(). If you know that your system does support fdatasync() correctly,
  33249. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  33250. */
  33251. #if !defined(fdatasync) && !HAVE_FDATASYNC
  33252. # define fdatasync fsync
  33253. #endif
  33254. /*
  33255. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  33256. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  33257. ** only available on Mac OS X. But that could change.
  33258. */
  33259. #ifdef F_FULLFSYNC
  33260. # define HAVE_FULLFSYNC 1
  33261. #else
  33262. # define HAVE_FULLFSYNC 0
  33263. #endif
  33264. /*
  33265. ** The fsync() system call does not work as advertised on many
  33266. ** unix systems. The following procedure is an attempt to make
  33267. ** it work better.
  33268. **
  33269. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  33270. ** for testing when we want to run through the test suite quickly.
  33271. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  33272. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  33273. ** or power failure will likely corrupt the database file.
  33274. **
  33275. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  33276. ** The idea behind dataOnly is that it should only write the file content
  33277. ** to disk, not the inode. We only set dataOnly if the file size is
  33278. ** unchanged since the file size is part of the inode. However,
  33279. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  33280. ** file size has changed. The only real difference between fdatasync()
  33281. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  33282. ** inode if the mtime or owner or other inode attributes have changed.
  33283. ** We only care about the file size, not the other file attributes, so
  33284. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  33285. ** So, we always use fdatasync() if it is available, regardless of
  33286. ** the value of the dataOnly flag.
  33287. */
  33288. static int full_fsync(int fd, int fullSync, int dataOnly){
  33289. int rc;
  33290. /* The following "ifdef/elif/else/" block has the same structure as
  33291. ** the one below. It is replicated here solely to avoid cluttering
  33292. ** up the real code with the UNUSED_PARAMETER() macros.
  33293. */
  33294. #ifdef SQLITE_NO_SYNC
  33295. UNUSED_PARAMETER(fd);
  33296. UNUSED_PARAMETER(fullSync);
  33297. UNUSED_PARAMETER(dataOnly);
  33298. #elif HAVE_FULLFSYNC
  33299. UNUSED_PARAMETER(dataOnly);
  33300. #else
  33301. UNUSED_PARAMETER(fullSync);
  33302. UNUSED_PARAMETER(dataOnly);
  33303. #endif
  33304. /* Record the number of times that we do a normal fsync() and
  33305. ** FULLSYNC. This is used during testing to verify that this procedure
  33306. ** gets called with the correct arguments.
  33307. */
  33308. #ifdef SQLITE_TEST
  33309. if( fullSync ) sqlite3_fullsync_count++;
  33310. sqlite3_sync_count++;
  33311. #endif
  33312. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  33313. ** no-op. But go ahead and call fstat() to validate the file
  33314. ** descriptor as we need a method to provoke a failure during
  33315. ** coverate testing.
  33316. */
  33317. #ifdef SQLITE_NO_SYNC
  33318. {
  33319. struct stat buf;
  33320. rc = osFstat(fd, &buf);
  33321. }
  33322. #elif HAVE_FULLFSYNC
  33323. if( fullSync ){
  33324. rc = osFcntl(fd, F_FULLFSYNC, 0);
  33325. }else{
  33326. rc = 1;
  33327. }
  33328. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  33329. ** It shouldn't be possible for fullfsync to fail on the local
  33330. ** file system (on OSX), so failure indicates that FULLFSYNC
  33331. ** isn't supported for this file system. So, attempt an fsync
  33332. ** and (for now) ignore the overhead of a superfluous fcntl call.
  33333. ** It'd be better to detect fullfsync support once and avoid
  33334. ** the fcntl call every time sync is called.
  33335. */
  33336. if( rc ) rc = fsync(fd);
  33337. #elif defined(__APPLE__)
  33338. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  33339. ** so currently we default to the macro that redefines fdatasync to fsync
  33340. */
  33341. rc = fsync(fd);
  33342. #else
  33343. rc = fdatasync(fd);
  33344. #if OS_VXWORKS
  33345. if( rc==-1 && errno==ENOTSUP ){
  33346. rc = fsync(fd);
  33347. }
  33348. #endif /* OS_VXWORKS */
  33349. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  33350. if( OS_VXWORKS && rc!= -1 ){
  33351. rc = 0;
  33352. }
  33353. return rc;
  33354. }
  33355. /*
  33356. ** Open a file descriptor to the directory containing file zFilename.
  33357. ** If successful, *pFd is set to the opened file descriptor and
  33358. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  33359. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  33360. ** value.
  33361. **
  33362. ** The directory file descriptor is used for only one thing - to
  33363. ** fsync() a directory to make sure file creation and deletion events
  33364. ** are flushed to disk. Such fsyncs are not needed on newer
  33365. ** journaling filesystems, but are required on older filesystems.
  33366. **
  33367. ** This routine can be overridden using the xSetSysCall interface.
  33368. ** The ability to override this routine was added in support of the
  33369. ** chromium sandbox. Opening a directory is a security risk (we are
  33370. ** told) so making it overrideable allows the chromium sandbox to
  33371. ** replace this routine with a harmless no-op. To make this routine
  33372. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  33373. ** *pFd set to a negative number.
  33374. **
  33375. ** If SQLITE_OK is returned, the caller is responsible for closing
  33376. ** the file descriptor *pFd using close().
  33377. */
  33378. static int openDirectory(const char *zFilename, int *pFd){
  33379. int ii;
  33380. int fd = -1;
  33381. char zDirname[MAX_PATHNAME+1];
  33382. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  33383. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  33384. if( ii>0 ){
  33385. zDirname[ii] = '\0';
  33386. }else{
  33387. if( zDirname[0]!='/' ) zDirname[0] = '.';
  33388. zDirname[1] = 0;
  33389. }
  33390. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  33391. if( fd>=0 ){
  33392. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  33393. }
  33394. *pFd = fd;
  33395. if( fd>=0 ) return SQLITE_OK;
  33396. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  33397. }
  33398. /*
  33399. ** Make sure all writes to a particular file are committed to disk.
  33400. **
  33401. ** If dataOnly==0 then both the file itself and its metadata (file
  33402. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  33403. ** file data is synced.
  33404. **
  33405. ** Under Unix, also make sure that the directory entry for the file
  33406. ** has been created by fsync-ing the directory that contains the file.
  33407. ** If we do not do this and we encounter a power failure, the directory
  33408. ** entry for the journal might not exist after we reboot. The next
  33409. ** SQLite to access the file will not know that the journal exists (because
  33410. ** the directory entry for the journal was never created) and the transaction
  33411. ** will not roll back - possibly leading to database corruption.
  33412. */
  33413. static int unixSync(sqlite3_file *id, int flags){
  33414. int rc;
  33415. unixFile *pFile = (unixFile*)id;
  33416. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  33417. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  33418. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  33419. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  33420. || (flags&0x0F)==SQLITE_SYNC_FULL
  33421. );
  33422. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  33423. ** line is to test that doing so does not cause any problems.
  33424. */
  33425. SimulateDiskfullError( return SQLITE_FULL );
  33426. assert( pFile );
  33427. OSTRACE(("SYNC %-3d\n", pFile->h));
  33428. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  33429. SimulateIOError( rc=1 );
  33430. if( rc ){
  33431. storeLastErrno(pFile, errno);
  33432. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  33433. }
  33434. /* Also fsync the directory containing the file if the DIRSYNC flag
  33435. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  33436. ** are unable to fsync a directory, so ignore errors on the fsync.
  33437. */
  33438. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  33439. int dirfd;
  33440. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  33441. HAVE_FULLFSYNC, isFullsync));
  33442. rc = osOpenDirectory(pFile->zPath, &dirfd);
  33443. if( rc==SQLITE_OK ){
  33444. full_fsync(dirfd, 0, 0);
  33445. robust_close(pFile, dirfd, __LINE__);
  33446. }else{
  33447. assert( rc==SQLITE_CANTOPEN );
  33448. rc = SQLITE_OK;
  33449. }
  33450. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  33451. }
  33452. return rc;
  33453. }
  33454. /*
  33455. ** Truncate an open file to a specified size
  33456. */
  33457. static int unixTruncate(sqlite3_file *id, i64 nByte){
  33458. unixFile *pFile = (unixFile *)id;
  33459. int rc;
  33460. assert( pFile );
  33461. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  33462. /* If the user has configured a chunk-size for this file, truncate the
  33463. ** file so that it consists of an integer number of chunks (i.e. the
  33464. ** actual file size after the operation may be larger than the requested
  33465. ** size).
  33466. */
  33467. if( pFile->szChunk>0 ){
  33468. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  33469. }
  33470. rc = robust_ftruncate(pFile->h, nByte);
  33471. if( rc ){
  33472. storeLastErrno(pFile, errno);
  33473. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  33474. }else{
  33475. #ifdef SQLITE_DEBUG
  33476. /* If we are doing a normal write to a database file (as opposed to
  33477. ** doing a hot-journal rollback or a write to some file other than a
  33478. ** normal database file) and we truncate the file to zero length,
  33479. ** that effectively updates the change counter. This might happen
  33480. ** when restoring a database using the backup API from a zero-length
  33481. ** source.
  33482. */
  33483. if( pFile->inNormalWrite && nByte==0 ){
  33484. pFile->transCntrChng = 1;
  33485. }
  33486. #endif
  33487. #if SQLITE_MAX_MMAP_SIZE>0
  33488. /* If the file was just truncated to a size smaller than the currently
  33489. ** mapped region, reduce the effective mapping size as well. SQLite will
  33490. ** use read() and write() to access data beyond this point from now on.
  33491. */
  33492. if( nByte<pFile->mmapSize ){
  33493. pFile->mmapSize = nByte;
  33494. }
  33495. #endif
  33496. return SQLITE_OK;
  33497. }
  33498. }
  33499. /*
  33500. ** Determine the current size of a file in bytes
  33501. */
  33502. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  33503. int rc;
  33504. struct stat buf;
  33505. assert( id );
  33506. rc = osFstat(((unixFile*)id)->h, &buf);
  33507. SimulateIOError( rc=1 );
  33508. if( rc!=0 ){
  33509. storeLastErrno((unixFile*)id, errno);
  33510. return SQLITE_IOERR_FSTAT;
  33511. }
  33512. *pSize = buf.st_size;
  33513. /* When opening a zero-size database, the findInodeInfo() procedure
  33514. ** writes a single byte into that file in order to work around a bug
  33515. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  33516. ** layers, we need to report this file size as zero even though it is
  33517. ** really 1. Ticket #3260.
  33518. */
  33519. if( *pSize==1 ) *pSize = 0;
  33520. return SQLITE_OK;
  33521. }
  33522. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33523. /*
  33524. ** Handler for proxy-locking file-control verbs. Defined below in the
  33525. ** proxying locking division.
  33526. */
  33527. static int proxyFileControl(sqlite3_file*,int,void*);
  33528. #endif
  33529. /*
  33530. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  33531. ** file-control operation. Enlarge the database to nBytes in size
  33532. ** (rounded up to the next chunk-size). If the database is already
  33533. ** nBytes or larger, this routine is a no-op.
  33534. */
  33535. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  33536. if( pFile->szChunk>0 ){
  33537. i64 nSize; /* Required file size */
  33538. struct stat buf; /* Used to hold return values of fstat() */
  33539. if( osFstat(pFile->h, &buf) ){
  33540. return SQLITE_IOERR_FSTAT;
  33541. }
  33542. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  33543. if( nSize>(i64)buf.st_size ){
  33544. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  33545. /* The code below is handling the return value of osFallocate()
  33546. ** correctly. posix_fallocate() is defined to "returns zero on success,
  33547. ** or an error number on failure". See the manpage for details. */
  33548. int err;
  33549. do{
  33550. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  33551. }while( err==EINTR );
  33552. if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
  33553. #else
  33554. /* If the OS does not have posix_fallocate(), fake it. Write a
  33555. ** single byte to the last byte in each block that falls entirely
  33556. ** within the extended region. Then, if required, a single byte
  33557. ** at offset (nSize-1), to set the size of the file correctly.
  33558. ** This is a similar technique to that used by glibc on systems
  33559. ** that do not have a real fallocate() call.
  33560. */
  33561. int nBlk = buf.st_blksize; /* File-system block size */
  33562. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  33563. i64 iWrite; /* Next offset to write to */
  33564. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  33565. assert( iWrite>=buf.st_size );
  33566. assert( ((iWrite+1)%nBlk)==0 );
  33567. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  33568. if( iWrite>=nSize ) iWrite = nSize - 1;
  33569. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  33570. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  33571. }
  33572. #endif
  33573. }
  33574. }
  33575. #if SQLITE_MAX_MMAP_SIZE>0
  33576. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  33577. int rc;
  33578. if( pFile->szChunk<=0 ){
  33579. if( robust_ftruncate(pFile->h, nByte) ){
  33580. storeLastErrno(pFile, errno);
  33581. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  33582. }
  33583. }
  33584. rc = unixMapfile(pFile, nByte);
  33585. return rc;
  33586. }
  33587. #endif
  33588. return SQLITE_OK;
  33589. }
  33590. /*
  33591. ** If *pArg is initially negative then this is a query. Set *pArg to
  33592. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  33593. **
  33594. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  33595. */
  33596. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  33597. if( *pArg<0 ){
  33598. *pArg = (pFile->ctrlFlags & mask)!=0;
  33599. }else if( (*pArg)==0 ){
  33600. pFile->ctrlFlags &= ~mask;
  33601. }else{
  33602. pFile->ctrlFlags |= mask;
  33603. }
  33604. }
  33605. /* Forward declaration */
  33606. static int unixGetTempname(int nBuf, char *zBuf);
  33607. /*
  33608. ** Information and control of an open file handle.
  33609. */
  33610. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  33611. unixFile *pFile = (unixFile*)id;
  33612. switch( op ){
  33613. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  33614. case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
  33615. int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
  33616. return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
  33617. }
  33618. case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
  33619. int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
  33620. return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
  33621. }
  33622. case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
  33623. int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
  33624. return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
  33625. }
  33626. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  33627. case SQLITE_FCNTL_LOCKSTATE: {
  33628. *(int*)pArg = pFile->eFileLock;
  33629. return SQLITE_OK;
  33630. }
  33631. case SQLITE_FCNTL_LAST_ERRNO: {
  33632. *(int*)pArg = pFile->lastErrno;
  33633. return SQLITE_OK;
  33634. }
  33635. case SQLITE_FCNTL_CHUNK_SIZE: {
  33636. pFile->szChunk = *(int *)pArg;
  33637. return SQLITE_OK;
  33638. }
  33639. case SQLITE_FCNTL_SIZE_HINT: {
  33640. int rc;
  33641. SimulateIOErrorBenign(1);
  33642. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  33643. SimulateIOErrorBenign(0);
  33644. return rc;
  33645. }
  33646. case SQLITE_FCNTL_PERSIST_WAL: {
  33647. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  33648. return SQLITE_OK;
  33649. }
  33650. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  33651. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  33652. return SQLITE_OK;
  33653. }
  33654. case SQLITE_FCNTL_VFSNAME: {
  33655. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  33656. return SQLITE_OK;
  33657. }
  33658. case SQLITE_FCNTL_TEMPFILENAME: {
  33659. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  33660. if( zTFile ){
  33661. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  33662. *(char**)pArg = zTFile;
  33663. }
  33664. return SQLITE_OK;
  33665. }
  33666. case SQLITE_FCNTL_HAS_MOVED: {
  33667. *(int*)pArg = fileHasMoved(pFile);
  33668. return SQLITE_OK;
  33669. }
  33670. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  33671. case SQLITE_FCNTL_LOCK_TIMEOUT: {
  33672. pFile->iBusyTimeout = *(int*)pArg;
  33673. return SQLITE_OK;
  33674. }
  33675. #endif
  33676. #if SQLITE_MAX_MMAP_SIZE>0
  33677. case SQLITE_FCNTL_MMAP_SIZE: {
  33678. i64 newLimit = *(i64*)pArg;
  33679. int rc = SQLITE_OK;
  33680. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  33681. newLimit = sqlite3GlobalConfig.mxMmap;
  33682. }
  33683. /* The value of newLimit may be eventually cast to (size_t) and passed
  33684. ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
  33685. ** 64-bit type. */
  33686. if( newLimit>0 && sizeof(size_t)<8 ){
  33687. newLimit = (newLimit & 0x7FFFFFFF);
  33688. }
  33689. *(i64*)pArg = pFile->mmapSizeMax;
  33690. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  33691. pFile->mmapSizeMax = newLimit;
  33692. if( pFile->mmapSize>0 ){
  33693. unixUnmapfile(pFile);
  33694. rc = unixMapfile(pFile, -1);
  33695. }
  33696. }
  33697. return rc;
  33698. }
  33699. #endif
  33700. #ifdef SQLITE_DEBUG
  33701. /* The pager calls this method to signal that it has done
  33702. ** a rollback and that the database is therefore unchanged and
  33703. ** it hence it is OK for the transaction change counter to be
  33704. ** unchanged.
  33705. */
  33706. case SQLITE_FCNTL_DB_UNCHANGED: {
  33707. ((unixFile*)id)->dbUpdate = 0;
  33708. return SQLITE_OK;
  33709. }
  33710. #endif
  33711. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33712. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  33713. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  33714. return proxyFileControl(id,op,pArg);
  33715. }
  33716. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  33717. }
  33718. return SQLITE_NOTFOUND;
  33719. }
  33720. /*
  33721. ** If pFd->sectorSize is non-zero when this function is called, it is a
  33722. ** no-op. Otherwise, the values of pFd->sectorSize and
  33723. ** pFd->deviceCharacteristics are set according to the file-system
  33724. ** characteristics.
  33725. **
  33726. ** There are two versions of this function. One for QNX and one for all
  33727. ** other systems.
  33728. */
  33729. #ifndef __QNXNTO__
  33730. static void setDeviceCharacteristics(unixFile *pFd){
  33731. assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
  33732. if( pFd->sectorSize==0 ){
  33733. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  33734. int res;
  33735. u32 f = 0;
  33736. /* Check for support for F2FS atomic batch writes. */
  33737. res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
  33738. if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
  33739. pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
  33740. }
  33741. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  33742. /* Set the POWERSAFE_OVERWRITE flag if requested. */
  33743. if( pFd->ctrlFlags & UNIXFILE_PSOW ){
  33744. pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  33745. }
  33746. pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  33747. }
  33748. }
  33749. #else
  33750. #include <sys/dcmd_blk.h>
  33751. #include <sys/statvfs.h>
  33752. static void setDeviceCharacteristics(unixFile *pFile){
  33753. if( pFile->sectorSize == 0 ){
  33754. struct statvfs fsInfo;
  33755. /* Set defaults for non-supported filesystems */
  33756. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  33757. pFile->deviceCharacteristics = 0;
  33758. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  33759. return;
  33760. }
  33761. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  33762. pFile->sectorSize = fsInfo.f_bsize;
  33763. pFile->deviceCharacteristics =
  33764. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  33765. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33766. ** the write succeeds */
  33767. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33768. ** so it is ordered */
  33769. 0;
  33770. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  33771. pFile->sectorSize = fsInfo.f_bsize;
  33772. pFile->deviceCharacteristics =
  33773. /* etfs cluster size writes are atomic */
  33774. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  33775. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33776. ** the write succeeds */
  33777. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33778. ** so it is ordered */
  33779. 0;
  33780. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  33781. pFile->sectorSize = fsInfo.f_bsize;
  33782. pFile->deviceCharacteristics =
  33783. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  33784. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33785. ** the write succeeds */
  33786. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33787. ** so it is ordered */
  33788. 0;
  33789. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  33790. pFile->sectorSize = fsInfo.f_bsize;
  33791. pFile->deviceCharacteristics =
  33792. /* full bitset of atomics from max sector size and smaller */
  33793. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  33794. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33795. ** so it is ordered */
  33796. 0;
  33797. }else if( strstr(fsInfo.f_basetype, "dos") ){
  33798. pFile->sectorSize = fsInfo.f_bsize;
  33799. pFile->deviceCharacteristics =
  33800. /* full bitset of atomics from max sector size and smaller */
  33801. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  33802. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33803. ** so it is ordered */
  33804. 0;
  33805. }else{
  33806. pFile->deviceCharacteristics =
  33807. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  33808. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33809. ** the write succeeds */
  33810. 0;
  33811. }
  33812. }
  33813. /* Last chance verification. If the sector size isn't a multiple of 512
  33814. ** then it isn't valid.*/
  33815. if( pFile->sectorSize % 512 != 0 ){
  33816. pFile->deviceCharacteristics = 0;
  33817. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  33818. }
  33819. }
  33820. #endif
  33821. /*
  33822. ** Return the sector size in bytes of the underlying block device for
  33823. ** the specified file. This is almost always 512 bytes, but may be
  33824. ** larger for some devices.
  33825. **
  33826. ** SQLite code assumes this function cannot fail. It also assumes that
  33827. ** if two files are created in the same file-system directory (i.e.
  33828. ** a database and its journal file) that the sector size will be the
  33829. ** same for both.
  33830. */
  33831. static int unixSectorSize(sqlite3_file *id){
  33832. unixFile *pFd = (unixFile*)id;
  33833. setDeviceCharacteristics(pFd);
  33834. return pFd->sectorSize;
  33835. }
  33836. /*
  33837. ** Return the device characteristics for the file.
  33838. **
  33839. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  33840. ** However, that choice is controversial since technically the underlying
  33841. ** file system does not always provide powersafe overwrites. (In other
  33842. ** words, after a power-loss event, parts of the file that were never
  33843. ** written might end up being altered.) However, non-PSOW behavior is very,
  33844. ** very rare. And asserting PSOW makes a large reduction in the amount
  33845. ** of required I/O for journaling, since a lot of padding is eliminated.
  33846. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  33847. ** available to turn it off and URI query parameter available to turn it off.
  33848. */
  33849. static int unixDeviceCharacteristics(sqlite3_file *id){
  33850. unixFile *pFd = (unixFile*)id;
  33851. setDeviceCharacteristics(pFd);
  33852. return pFd->deviceCharacteristics;
  33853. }
  33854. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  33855. /*
  33856. ** Return the system page size.
  33857. **
  33858. ** This function should not be called directly by other code in this file.
  33859. ** Instead, it should be called via macro osGetpagesize().
  33860. */
  33861. static int unixGetpagesize(void){
  33862. #if OS_VXWORKS
  33863. return 1024;
  33864. #elif defined(_BSD_SOURCE)
  33865. return getpagesize();
  33866. #else
  33867. return (int)sysconf(_SC_PAGESIZE);
  33868. #endif
  33869. }
  33870. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  33871. #ifndef SQLITE_OMIT_WAL
  33872. /*
  33873. ** Object used to represent an shared memory buffer.
  33874. **
  33875. ** When multiple threads all reference the same wal-index, each thread
  33876. ** has its own unixShm object, but they all point to a single instance
  33877. ** of this unixShmNode object. In other words, each wal-index is opened
  33878. ** only once per process.
  33879. **
  33880. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  33881. ** We could coalesce this object into unixInodeInfo, but that would mean
  33882. ** every open file that does not use shared memory (in other words, most
  33883. ** open files) would have to carry around this extra information. So
  33884. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  33885. ** and the unixShmNode object is created only when needed.
  33886. **
  33887. ** unixMutexHeld() must be true when creating or destroying
  33888. ** this object or while reading or writing the following fields:
  33889. **
  33890. ** nRef
  33891. **
  33892. ** The following fields are read-only after the object is created:
  33893. **
  33894. ** fid
  33895. ** zFilename
  33896. **
  33897. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  33898. ** unixMutexHeld() is true when reading or writing any other field
  33899. ** in this structure.
  33900. */
  33901. struct unixShmNode {
  33902. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  33903. sqlite3_mutex *mutex; /* Mutex to access this object */
  33904. char *zFilename; /* Name of the mmapped file */
  33905. int h; /* Open file descriptor */
  33906. int szRegion; /* Size of shared-memory regions */
  33907. u16 nRegion; /* Size of array apRegion */
  33908. u8 isReadonly; /* True if read-only */
  33909. u8 isUnlocked; /* True if no DMS lock held */
  33910. char **apRegion; /* Array of mapped shared-memory regions */
  33911. int nRef; /* Number of unixShm objects pointing to this */
  33912. unixShm *pFirst; /* All unixShm objects pointing to this */
  33913. #ifdef SQLITE_DEBUG
  33914. u8 exclMask; /* Mask of exclusive locks held */
  33915. u8 sharedMask; /* Mask of shared locks held */
  33916. u8 nextShmId; /* Next available unixShm.id value */
  33917. #endif
  33918. };
  33919. /*
  33920. ** Structure used internally by this VFS to record the state of an
  33921. ** open shared memory connection.
  33922. **
  33923. ** The following fields are initialized when this object is created and
  33924. ** are read-only thereafter:
  33925. **
  33926. ** unixShm.pFile
  33927. ** unixShm.id
  33928. **
  33929. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  33930. ** while accessing any read/write fields.
  33931. */
  33932. struct unixShm {
  33933. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  33934. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  33935. u8 hasMutex; /* True if holding the unixShmNode mutex */
  33936. u8 id; /* Id of this connection within its unixShmNode */
  33937. u16 sharedMask; /* Mask of shared locks held */
  33938. u16 exclMask; /* Mask of exclusive locks held */
  33939. };
  33940. /*
  33941. ** Constants used for locking
  33942. */
  33943. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  33944. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  33945. /*
  33946. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  33947. **
  33948. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  33949. ** otherwise.
  33950. */
  33951. static int unixShmSystemLock(
  33952. unixFile *pFile, /* Open connection to the WAL file */
  33953. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  33954. int ofst, /* First byte of the locking range */
  33955. int n /* Number of bytes to lock */
  33956. ){
  33957. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  33958. struct flock f; /* The posix advisory locking structure */
  33959. int rc = SQLITE_OK; /* Result code form fcntl() */
  33960. /* Access to the unixShmNode object is serialized by the caller */
  33961. pShmNode = pFile->pInode->pShmNode;
  33962. assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
  33963. /* Shared locks never span more than one byte */
  33964. assert( n==1 || lockType!=F_RDLCK );
  33965. /* Locks are within range */
  33966. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  33967. if( pShmNode->h>=0 ){
  33968. /* Initialize the locking parameters */
  33969. f.l_type = lockType;
  33970. f.l_whence = SEEK_SET;
  33971. f.l_start = ofst;
  33972. f.l_len = n;
  33973. rc = osSetPosixAdvisoryLock(pShmNode->h, &f, pFile);
  33974. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  33975. }
  33976. /* Update the global lock state and do debug tracing */
  33977. #ifdef SQLITE_DEBUG
  33978. { u16 mask;
  33979. OSTRACE(("SHM-LOCK "));
  33980. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  33981. if( rc==SQLITE_OK ){
  33982. if( lockType==F_UNLCK ){
  33983. OSTRACE(("unlock %d ok", ofst));
  33984. pShmNode->exclMask &= ~mask;
  33985. pShmNode->sharedMask &= ~mask;
  33986. }else if( lockType==F_RDLCK ){
  33987. OSTRACE(("read-lock %d ok", ofst));
  33988. pShmNode->exclMask &= ~mask;
  33989. pShmNode->sharedMask |= mask;
  33990. }else{
  33991. assert( lockType==F_WRLCK );
  33992. OSTRACE(("write-lock %d ok", ofst));
  33993. pShmNode->exclMask |= mask;
  33994. pShmNode->sharedMask &= ~mask;
  33995. }
  33996. }else{
  33997. if( lockType==F_UNLCK ){
  33998. OSTRACE(("unlock %d failed", ofst));
  33999. }else if( lockType==F_RDLCK ){
  34000. OSTRACE(("read-lock failed"));
  34001. }else{
  34002. assert( lockType==F_WRLCK );
  34003. OSTRACE(("write-lock %d failed", ofst));
  34004. }
  34005. }
  34006. OSTRACE((" - afterwards %03x,%03x\n",
  34007. pShmNode->sharedMask, pShmNode->exclMask));
  34008. }
  34009. #endif
  34010. return rc;
  34011. }
  34012. /*
  34013. ** Return the minimum number of 32KB shm regions that should be mapped at
  34014. ** a time, assuming that each mapping must be an integer multiple of the
  34015. ** current system page-size.
  34016. **
  34017. ** Usually, this is 1. The exception seems to be systems that are configured
  34018. ** to use 64KB pages - in this case each mapping must cover at least two
  34019. ** shm regions.
  34020. */
  34021. static int unixShmRegionPerMap(void){
  34022. int shmsz = 32*1024; /* SHM region size */
  34023. int pgsz = osGetpagesize(); /* System page size */
  34024. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  34025. if( pgsz<shmsz ) return 1;
  34026. return pgsz/shmsz;
  34027. }
  34028. /*
  34029. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  34030. **
  34031. ** This is not a VFS shared-memory method; it is a utility function called
  34032. ** by VFS shared-memory methods.
  34033. */
  34034. static void unixShmPurge(unixFile *pFd){
  34035. unixShmNode *p = pFd->pInode->pShmNode;
  34036. assert( unixMutexHeld() );
  34037. if( p && ALWAYS(p->nRef==0) ){
  34038. int nShmPerMap = unixShmRegionPerMap();
  34039. int i;
  34040. assert( p->pInode==pFd->pInode );
  34041. sqlite3_mutex_free(p->mutex);
  34042. for(i=0; i<p->nRegion; i+=nShmPerMap){
  34043. if( p->h>=0 ){
  34044. osMunmap(p->apRegion[i], p->szRegion);
  34045. }else{
  34046. sqlite3_free(p->apRegion[i]);
  34047. }
  34048. }
  34049. sqlite3_free(p->apRegion);
  34050. if( p->h>=0 ){
  34051. robust_close(pFd, p->h, __LINE__);
  34052. p->h = -1;
  34053. }
  34054. p->pInode->pShmNode = 0;
  34055. sqlite3_free(p);
  34056. }
  34057. }
  34058. /*
  34059. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  34060. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  34061. ** code otherwise.
  34062. **
  34063. ** If the DMS cannot be locked because this is a readonly_shm=1
  34064. ** connection and no other process already holds a lock, return
  34065. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  34066. */
  34067. static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
  34068. struct flock lock;
  34069. int rc = SQLITE_OK;
  34070. /* Use F_GETLK to determine the locks other processes are holding
  34071. ** on the DMS byte. If it indicates that another process is holding
  34072. ** a SHARED lock, then this process may also take a SHARED lock
  34073. ** and proceed with opening the *-shm file.
  34074. **
  34075. ** Or, if no other process is holding any lock, then this process
  34076. ** is the first to open it. In this case take an EXCLUSIVE lock on the
  34077. ** DMS byte and truncate the *-shm file to zero bytes in size. Then
  34078. ** downgrade to a SHARED lock on the DMS byte.
  34079. **
  34080. ** If another process is holding an EXCLUSIVE lock on the DMS byte,
  34081. ** return SQLITE_BUSY to the caller (it will try again). An earlier
  34082. ** version of this code attempted the SHARED lock at this point. But
  34083. ** this introduced a subtle race condition: if the process holding
  34084. ** EXCLUSIVE failed just before truncating the *-shm file, then this
  34085. ** process might open and use the *-shm file without truncating it.
  34086. ** And if the *-shm file has been corrupted by a power failure or
  34087. ** system crash, the database itself may also become corrupt. */
  34088. lock.l_whence = SEEK_SET;
  34089. lock.l_start = UNIX_SHM_DMS;
  34090. lock.l_len = 1;
  34091. lock.l_type = F_WRLCK;
  34092. if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
  34093. rc = SQLITE_IOERR_LOCK;
  34094. }else if( lock.l_type==F_UNLCK ){
  34095. if( pShmNode->isReadonly ){
  34096. pShmNode->isUnlocked = 1;
  34097. rc = SQLITE_READONLY_CANTINIT;
  34098. }else{
  34099. rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
  34100. if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
  34101. rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
  34102. }
  34103. }
  34104. }else if( lock.l_type==F_WRLCK ){
  34105. rc = SQLITE_BUSY;
  34106. }
  34107. if( rc==SQLITE_OK ){
  34108. assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
  34109. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  34110. }
  34111. return rc;
  34112. }
  34113. /*
  34114. ** Open a shared-memory area associated with open database file pDbFd.
  34115. ** This particular implementation uses mmapped files.
  34116. **
  34117. ** The file used to implement shared-memory is in the same directory
  34118. ** as the open database file and has the same name as the open database
  34119. ** file with the "-shm" suffix added. For example, if the database file
  34120. ** is "/home/user1/config.db" then the file that is created and mmapped
  34121. ** for shared memory will be called "/home/user1/config.db-shm".
  34122. **
  34123. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  34124. ** some other tmpfs mount. But if a file in a different directory
  34125. ** from the database file is used, then differing access permissions
  34126. ** or a chroot() might cause two different processes on the same
  34127. ** database to end up using different files for shared memory -
  34128. ** meaning that their memory would not really be shared - resulting
  34129. ** in database corruption. Nevertheless, this tmpfs file usage
  34130. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  34131. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  34132. ** option results in an incompatible build of SQLite; builds of SQLite
  34133. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  34134. ** same database file at the same time, database corruption will likely
  34135. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  34136. ** "unsupported" and may go away in a future SQLite release.
  34137. **
  34138. ** When opening a new shared-memory file, if no other instances of that
  34139. ** file are currently open, in this process or in other processes, then
  34140. ** the file must be truncated to zero length or have its header cleared.
  34141. **
  34142. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  34143. ** that means that an exclusive lock is held on the database file and
  34144. ** that no other processes are able to read or write the database. In
  34145. ** that case, we do not really need shared memory. No shared memory
  34146. ** file is created. The shared memory will be simulated with heap memory.
  34147. */
  34148. static int unixOpenSharedMemory(unixFile *pDbFd){
  34149. struct unixShm *p = 0; /* The connection to be opened */
  34150. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  34151. int rc = SQLITE_OK; /* Result code */
  34152. unixInodeInfo *pInode; /* The inode of fd */
  34153. char *zShm; /* Name of the file used for SHM */
  34154. int nShmFilename; /* Size of the SHM filename in bytes */
  34155. /* Allocate space for the new unixShm object. */
  34156. p = sqlite3_malloc64( sizeof(*p) );
  34157. if( p==0 ) return SQLITE_NOMEM_BKPT;
  34158. memset(p, 0, sizeof(*p));
  34159. assert( pDbFd->pShm==0 );
  34160. /* Check to see if a unixShmNode object already exists. Reuse an existing
  34161. ** one if present. Create a new one if necessary.
  34162. */
  34163. unixEnterMutex();
  34164. pInode = pDbFd->pInode;
  34165. pShmNode = pInode->pShmNode;
  34166. if( pShmNode==0 ){
  34167. struct stat sStat; /* fstat() info for database file */
  34168. #ifndef SQLITE_SHM_DIRECTORY
  34169. const char *zBasePath = pDbFd->zPath;
  34170. #endif
  34171. /* Call fstat() to figure out the permissions on the database file. If
  34172. ** a new *-shm file is created, an attempt will be made to create it
  34173. ** with the same permissions.
  34174. */
  34175. if( osFstat(pDbFd->h, &sStat) ){
  34176. rc = SQLITE_IOERR_FSTAT;
  34177. goto shm_open_err;
  34178. }
  34179. #ifdef SQLITE_SHM_DIRECTORY
  34180. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  34181. #else
  34182. nShmFilename = 6 + (int)strlen(zBasePath);
  34183. #endif
  34184. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  34185. if( pShmNode==0 ){
  34186. rc = SQLITE_NOMEM_BKPT;
  34187. goto shm_open_err;
  34188. }
  34189. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  34190. zShm = pShmNode->zFilename = (char*)&pShmNode[1];
  34191. #ifdef SQLITE_SHM_DIRECTORY
  34192. sqlite3_snprintf(nShmFilename, zShm,
  34193. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  34194. (u32)sStat.st_ino, (u32)sStat.st_dev);
  34195. #else
  34196. sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
  34197. sqlite3FileSuffix3(pDbFd->zPath, zShm);
  34198. #endif
  34199. pShmNode->h = -1;
  34200. pDbFd->pInode->pShmNode = pShmNode;
  34201. pShmNode->pInode = pDbFd->pInode;
  34202. if( sqlite3GlobalConfig.bCoreMutex ){
  34203. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  34204. if( pShmNode->mutex==0 ){
  34205. rc = SQLITE_NOMEM_BKPT;
  34206. goto shm_open_err;
  34207. }
  34208. }
  34209. if( pInode->bProcessLock==0 ){
  34210. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  34211. pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
  34212. }
  34213. if( pShmNode->h<0 ){
  34214. pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
  34215. if( pShmNode->h<0 ){
  34216. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
  34217. goto shm_open_err;
  34218. }
  34219. pShmNode->isReadonly = 1;
  34220. }
  34221. /* If this process is running as root, make sure that the SHM file
  34222. ** is owned by the same user that owns the original database. Otherwise,
  34223. ** the original owner will not be able to connect.
  34224. */
  34225. robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  34226. rc = unixLockSharedMemory(pDbFd, pShmNode);
  34227. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  34228. }
  34229. }
  34230. /* Make the new connection a child of the unixShmNode */
  34231. p->pShmNode = pShmNode;
  34232. #ifdef SQLITE_DEBUG
  34233. p->id = pShmNode->nextShmId++;
  34234. #endif
  34235. pShmNode->nRef++;
  34236. pDbFd->pShm = p;
  34237. unixLeaveMutex();
  34238. /* The reference count on pShmNode has already been incremented under
  34239. ** the cover of the unixEnterMutex() mutex and the pointer from the
  34240. ** new (struct unixShm) object to the pShmNode has been set. All that is
  34241. ** left to do is to link the new object into the linked list starting
  34242. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  34243. ** mutex.
  34244. */
  34245. sqlite3_mutex_enter(pShmNode->mutex);
  34246. p->pNext = pShmNode->pFirst;
  34247. pShmNode->pFirst = p;
  34248. sqlite3_mutex_leave(pShmNode->mutex);
  34249. return rc;
  34250. /* Jump here on any error */
  34251. shm_open_err:
  34252. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  34253. sqlite3_free(p);
  34254. unixLeaveMutex();
  34255. return rc;
  34256. }
  34257. /*
  34258. ** This function is called to obtain a pointer to region iRegion of the
  34259. ** shared-memory associated with the database file fd. Shared-memory regions
  34260. ** are numbered starting from zero. Each shared-memory region is szRegion
  34261. ** bytes in size.
  34262. **
  34263. ** If an error occurs, an error code is returned and *pp is set to NULL.
  34264. **
  34265. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  34266. ** region has not been allocated (by any client, including one running in a
  34267. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  34268. ** bExtend is non-zero and the requested shared-memory region has not yet
  34269. ** been allocated, it is allocated by this function.
  34270. **
  34271. ** If the shared-memory region has already been allocated or is allocated by
  34272. ** this call as described above, then it is mapped into this processes
  34273. ** address space (if it is not already), *pp is set to point to the mapped
  34274. ** memory and SQLITE_OK returned.
  34275. */
  34276. static int unixShmMap(
  34277. sqlite3_file *fd, /* Handle open on database file */
  34278. int iRegion, /* Region to retrieve */
  34279. int szRegion, /* Size of regions */
  34280. int bExtend, /* True to extend file if necessary */
  34281. void volatile **pp /* OUT: Mapped memory */
  34282. ){
  34283. unixFile *pDbFd = (unixFile*)fd;
  34284. unixShm *p;
  34285. unixShmNode *pShmNode;
  34286. int rc = SQLITE_OK;
  34287. int nShmPerMap = unixShmRegionPerMap();
  34288. int nReqRegion;
  34289. /* If the shared-memory file has not yet been opened, open it now. */
  34290. if( pDbFd->pShm==0 ){
  34291. rc = unixOpenSharedMemory(pDbFd);
  34292. if( rc!=SQLITE_OK ) return rc;
  34293. }
  34294. p = pDbFd->pShm;
  34295. pShmNode = p->pShmNode;
  34296. sqlite3_mutex_enter(pShmNode->mutex);
  34297. if( pShmNode->isUnlocked ){
  34298. rc = unixLockSharedMemory(pDbFd, pShmNode);
  34299. if( rc!=SQLITE_OK ) goto shmpage_out;
  34300. pShmNode->isUnlocked = 0;
  34301. }
  34302. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  34303. assert( pShmNode->pInode==pDbFd->pInode );
  34304. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  34305. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  34306. /* Minimum number of regions required to be mapped. */
  34307. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  34308. if( pShmNode->nRegion<nReqRegion ){
  34309. char **apNew; /* New apRegion[] array */
  34310. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  34311. struct stat sStat; /* Used by fstat() */
  34312. pShmNode->szRegion = szRegion;
  34313. if( pShmNode->h>=0 ){
  34314. /* The requested region is not mapped into this processes address space.
  34315. ** Check to see if it has been allocated (i.e. if the wal-index file is
  34316. ** large enough to contain the requested region).
  34317. */
  34318. if( osFstat(pShmNode->h, &sStat) ){
  34319. rc = SQLITE_IOERR_SHMSIZE;
  34320. goto shmpage_out;
  34321. }
  34322. if( sStat.st_size<nByte ){
  34323. /* The requested memory region does not exist. If bExtend is set to
  34324. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  34325. */
  34326. if( !bExtend ){
  34327. goto shmpage_out;
  34328. }
  34329. /* Alternatively, if bExtend is true, extend the file. Do this by
  34330. ** writing a single byte to the end of each (OS) page being
  34331. ** allocated or extended. Technically, we need only write to the
  34332. ** last page in order to extend the file. But writing to all new
  34333. ** pages forces the OS to allocate them immediately, which reduces
  34334. ** the chances of SIGBUS while accessing the mapped region later on.
  34335. */
  34336. else{
  34337. static const int pgsz = 4096;
  34338. int iPg;
  34339. /* Write to the last byte of each newly allocated or extended page */
  34340. assert( (nByte % pgsz)==0 );
  34341. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  34342. int x = 0;
  34343. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
  34344. const char *zFile = pShmNode->zFilename;
  34345. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  34346. goto shmpage_out;
  34347. }
  34348. }
  34349. }
  34350. }
  34351. }
  34352. /* Map the requested memory region into this processes address space. */
  34353. apNew = (char **)sqlite3_realloc(
  34354. pShmNode->apRegion, nReqRegion*sizeof(char *)
  34355. );
  34356. if( !apNew ){
  34357. rc = SQLITE_IOERR_NOMEM_BKPT;
  34358. goto shmpage_out;
  34359. }
  34360. pShmNode->apRegion = apNew;
  34361. while( pShmNode->nRegion<nReqRegion ){
  34362. int nMap = szRegion*nShmPerMap;
  34363. int i;
  34364. void *pMem;
  34365. if( pShmNode->h>=0 ){
  34366. pMem = osMmap(0, nMap,
  34367. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  34368. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  34369. );
  34370. if( pMem==MAP_FAILED ){
  34371. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  34372. goto shmpage_out;
  34373. }
  34374. }else{
  34375. pMem = sqlite3_malloc64(szRegion);
  34376. if( pMem==0 ){
  34377. rc = SQLITE_NOMEM_BKPT;
  34378. goto shmpage_out;
  34379. }
  34380. memset(pMem, 0, szRegion);
  34381. }
  34382. for(i=0; i<nShmPerMap; i++){
  34383. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  34384. }
  34385. pShmNode->nRegion += nShmPerMap;
  34386. }
  34387. }
  34388. shmpage_out:
  34389. if( pShmNode->nRegion>iRegion ){
  34390. *pp = pShmNode->apRegion[iRegion];
  34391. }else{
  34392. *pp = 0;
  34393. }
  34394. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  34395. sqlite3_mutex_leave(pShmNode->mutex);
  34396. return rc;
  34397. }
  34398. /*
  34399. ** Change the lock state for a shared-memory segment.
  34400. **
  34401. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  34402. ** different here than in posix. In xShmLock(), one can go from unlocked
  34403. ** to shared and back or from unlocked to exclusive and back. But one may
  34404. ** not go from shared to exclusive or from exclusive to shared.
  34405. */
  34406. static int unixShmLock(
  34407. sqlite3_file *fd, /* Database file holding the shared memory */
  34408. int ofst, /* First lock to acquire or release */
  34409. int n, /* Number of locks to acquire or release */
  34410. int flags /* What to do with the lock */
  34411. ){
  34412. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  34413. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  34414. unixShm *pX; /* For looping over all siblings */
  34415. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  34416. int rc = SQLITE_OK; /* Result code */
  34417. u16 mask; /* Mask of locks to take or release */
  34418. assert( pShmNode==pDbFd->pInode->pShmNode );
  34419. assert( pShmNode->pInode==pDbFd->pInode );
  34420. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  34421. assert( n>=1 );
  34422. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  34423. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  34424. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  34425. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  34426. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  34427. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  34428. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  34429. mask = (1<<(ofst+n)) - (1<<ofst);
  34430. assert( n>1 || mask==(1<<ofst) );
  34431. sqlite3_mutex_enter(pShmNode->mutex);
  34432. if( flags & SQLITE_SHM_UNLOCK ){
  34433. u16 allMask = 0; /* Mask of locks held by siblings */
  34434. /* See if any siblings hold this same lock */
  34435. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34436. if( pX==p ) continue;
  34437. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  34438. allMask |= pX->sharedMask;
  34439. }
  34440. /* Unlock the system-level locks */
  34441. if( (mask & allMask)==0 ){
  34442. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  34443. }else{
  34444. rc = SQLITE_OK;
  34445. }
  34446. /* Undo the local locks */
  34447. if( rc==SQLITE_OK ){
  34448. p->exclMask &= ~mask;
  34449. p->sharedMask &= ~mask;
  34450. }
  34451. }else if( flags & SQLITE_SHM_SHARED ){
  34452. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  34453. /* Find out which shared locks are already held by sibling connections.
  34454. ** If any sibling already holds an exclusive lock, go ahead and return
  34455. ** SQLITE_BUSY.
  34456. */
  34457. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34458. if( (pX->exclMask & mask)!=0 ){
  34459. rc = SQLITE_BUSY;
  34460. break;
  34461. }
  34462. allShared |= pX->sharedMask;
  34463. }
  34464. /* Get shared locks at the system level, if necessary */
  34465. if( rc==SQLITE_OK ){
  34466. if( (allShared & mask)==0 ){
  34467. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  34468. }else{
  34469. rc = SQLITE_OK;
  34470. }
  34471. }
  34472. /* Get the local shared locks */
  34473. if( rc==SQLITE_OK ){
  34474. p->sharedMask |= mask;
  34475. }
  34476. }else{
  34477. /* Make sure no sibling connections hold locks that will block this
  34478. ** lock. If any do, return SQLITE_BUSY right away.
  34479. */
  34480. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34481. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  34482. rc = SQLITE_BUSY;
  34483. break;
  34484. }
  34485. }
  34486. /* Get the exclusive locks at the system level. Then if successful
  34487. ** also mark the local connection as being locked.
  34488. */
  34489. if( rc==SQLITE_OK ){
  34490. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  34491. if( rc==SQLITE_OK ){
  34492. assert( (p->sharedMask & mask)==0 );
  34493. p->exclMask |= mask;
  34494. }
  34495. }
  34496. }
  34497. sqlite3_mutex_leave(pShmNode->mutex);
  34498. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  34499. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  34500. return rc;
  34501. }
  34502. /*
  34503. ** Implement a memory barrier or memory fence on shared memory.
  34504. **
  34505. ** All loads and stores begun before the barrier must complete before
  34506. ** any load or store begun after the barrier.
  34507. */
  34508. static void unixShmBarrier(
  34509. sqlite3_file *fd /* Database file holding the shared memory */
  34510. ){
  34511. UNUSED_PARAMETER(fd);
  34512. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  34513. unixEnterMutex(); /* Also mutex, for redundancy */
  34514. unixLeaveMutex();
  34515. }
  34516. /*
  34517. ** Close a connection to shared-memory. Delete the underlying
  34518. ** storage if deleteFlag is true.
  34519. **
  34520. ** If there is no shared memory associated with the connection then this
  34521. ** routine is a harmless no-op.
  34522. */
  34523. static int unixShmUnmap(
  34524. sqlite3_file *fd, /* The underlying database file */
  34525. int deleteFlag /* Delete shared-memory if true */
  34526. ){
  34527. unixShm *p; /* The connection to be closed */
  34528. unixShmNode *pShmNode; /* The underlying shared-memory file */
  34529. unixShm **pp; /* For looping over sibling connections */
  34530. unixFile *pDbFd; /* The underlying database file */
  34531. pDbFd = (unixFile*)fd;
  34532. p = pDbFd->pShm;
  34533. if( p==0 ) return SQLITE_OK;
  34534. pShmNode = p->pShmNode;
  34535. assert( pShmNode==pDbFd->pInode->pShmNode );
  34536. assert( pShmNode->pInode==pDbFd->pInode );
  34537. /* Remove connection p from the set of connections associated
  34538. ** with pShmNode */
  34539. sqlite3_mutex_enter(pShmNode->mutex);
  34540. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  34541. *pp = p->pNext;
  34542. /* Free the connection p */
  34543. sqlite3_free(p);
  34544. pDbFd->pShm = 0;
  34545. sqlite3_mutex_leave(pShmNode->mutex);
  34546. /* If pShmNode->nRef has reached 0, then close the underlying
  34547. ** shared-memory file, too */
  34548. unixEnterMutex();
  34549. assert( pShmNode->nRef>0 );
  34550. pShmNode->nRef--;
  34551. if( pShmNode->nRef==0 ){
  34552. if( deleteFlag && pShmNode->h>=0 ){
  34553. osUnlink(pShmNode->zFilename);
  34554. }
  34555. unixShmPurge(pDbFd);
  34556. }
  34557. unixLeaveMutex();
  34558. return SQLITE_OK;
  34559. }
  34560. #else
  34561. # define unixShmMap 0
  34562. # define unixShmLock 0
  34563. # define unixShmBarrier 0
  34564. # define unixShmUnmap 0
  34565. #endif /* #ifndef SQLITE_OMIT_WAL */
  34566. #if SQLITE_MAX_MMAP_SIZE>0
  34567. /*
  34568. ** If it is currently memory mapped, unmap file pFd.
  34569. */
  34570. static void unixUnmapfile(unixFile *pFd){
  34571. assert( pFd->nFetchOut==0 );
  34572. if( pFd->pMapRegion ){
  34573. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  34574. pFd->pMapRegion = 0;
  34575. pFd->mmapSize = 0;
  34576. pFd->mmapSizeActual = 0;
  34577. }
  34578. }
  34579. /*
  34580. ** Attempt to set the size of the memory mapping maintained by file
  34581. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  34582. **
  34583. ** If successful, this function sets the following variables:
  34584. **
  34585. ** unixFile.pMapRegion
  34586. ** unixFile.mmapSize
  34587. ** unixFile.mmapSizeActual
  34588. **
  34589. ** If unsuccessful, an error message is logged via sqlite3_log() and
  34590. ** the three variables above are zeroed. In this case SQLite should
  34591. ** continue accessing the database using the xRead() and xWrite()
  34592. ** methods.
  34593. */
  34594. static void unixRemapfile(
  34595. unixFile *pFd, /* File descriptor object */
  34596. i64 nNew /* Required mapping size */
  34597. ){
  34598. const char *zErr = "mmap";
  34599. int h = pFd->h; /* File descriptor open on db file */
  34600. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  34601. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  34602. u8 *pNew = 0; /* Location of new mapping */
  34603. int flags = PROT_READ; /* Flags to pass to mmap() */
  34604. assert( pFd->nFetchOut==0 );
  34605. assert( nNew>pFd->mmapSize );
  34606. assert( nNew<=pFd->mmapSizeMax );
  34607. assert( nNew>0 );
  34608. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  34609. assert( MAP_FAILED!=0 );
  34610. #ifdef SQLITE_MMAP_READWRITE
  34611. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  34612. #endif
  34613. if( pOrig ){
  34614. #if HAVE_MREMAP
  34615. i64 nReuse = pFd->mmapSize;
  34616. #else
  34617. const int szSyspage = osGetpagesize();
  34618. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  34619. #endif
  34620. u8 *pReq = &pOrig[nReuse];
  34621. /* Unmap any pages of the existing mapping that cannot be reused. */
  34622. if( nReuse!=nOrig ){
  34623. osMunmap(pReq, nOrig-nReuse);
  34624. }
  34625. #if HAVE_MREMAP
  34626. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  34627. zErr = "mremap";
  34628. #else
  34629. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  34630. if( pNew!=MAP_FAILED ){
  34631. if( pNew!=pReq ){
  34632. osMunmap(pNew, nNew - nReuse);
  34633. pNew = 0;
  34634. }else{
  34635. pNew = pOrig;
  34636. }
  34637. }
  34638. #endif
  34639. /* The attempt to extend the existing mapping failed. Free it. */
  34640. if( pNew==MAP_FAILED || pNew==0 ){
  34641. osMunmap(pOrig, nReuse);
  34642. }
  34643. }
  34644. /* If pNew is still NULL, try to create an entirely new mapping. */
  34645. if( pNew==0 ){
  34646. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  34647. }
  34648. if( pNew==MAP_FAILED ){
  34649. pNew = 0;
  34650. nNew = 0;
  34651. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  34652. /* If the mmap() above failed, assume that all subsequent mmap() calls
  34653. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  34654. ** in this case. */
  34655. pFd->mmapSizeMax = 0;
  34656. }
  34657. pFd->pMapRegion = (void *)pNew;
  34658. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  34659. }
  34660. /*
  34661. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  34662. ** is already mapped, the existing mapping is replaced by the new). Or, if
  34663. ** there already exists a mapping for this file, and there are still
  34664. ** outstanding xFetch() references to it, this function is a no-op.
  34665. **
  34666. ** If parameter nByte is non-negative, then it is the requested size of
  34667. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  34668. ** requested size is the size of the file on disk. The actual size of the
  34669. ** created mapping is either the requested size or the value configured
  34670. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  34671. **
  34672. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  34673. ** recreated as a result of outstanding references) or an SQLite error
  34674. ** code otherwise.
  34675. */
  34676. static int unixMapfile(unixFile *pFd, i64 nMap){
  34677. assert( nMap>=0 || pFd->nFetchOut==0 );
  34678. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  34679. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  34680. if( nMap<0 ){
  34681. struct stat statbuf; /* Low-level file information */
  34682. if( osFstat(pFd->h, &statbuf) ){
  34683. return SQLITE_IOERR_FSTAT;
  34684. }
  34685. nMap = statbuf.st_size;
  34686. }
  34687. if( nMap>pFd->mmapSizeMax ){
  34688. nMap = pFd->mmapSizeMax;
  34689. }
  34690. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  34691. if( nMap!=pFd->mmapSize ){
  34692. unixRemapfile(pFd, nMap);
  34693. }
  34694. return SQLITE_OK;
  34695. }
  34696. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  34697. /*
  34698. ** If possible, return a pointer to a mapping of file fd starting at offset
  34699. ** iOff. The mapping must be valid for at least nAmt bytes.
  34700. **
  34701. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  34702. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  34703. ** Finally, if an error does occur, return an SQLite error code. The final
  34704. ** value of *pp is undefined in this case.
  34705. **
  34706. ** If this function does return a pointer, the caller must eventually
  34707. ** release the reference by calling unixUnfetch().
  34708. */
  34709. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  34710. #if SQLITE_MAX_MMAP_SIZE>0
  34711. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  34712. #endif
  34713. *pp = 0;
  34714. #if SQLITE_MAX_MMAP_SIZE>0
  34715. if( pFd->mmapSizeMax>0 ){
  34716. if( pFd->pMapRegion==0 ){
  34717. int rc = unixMapfile(pFd, -1);
  34718. if( rc!=SQLITE_OK ) return rc;
  34719. }
  34720. if( pFd->mmapSize >= iOff+nAmt ){
  34721. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  34722. pFd->nFetchOut++;
  34723. }
  34724. }
  34725. #endif
  34726. return SQLITE_OK;
  34727. }
  34728. /*
  34729. ** If the third argument is non-NULL, then this function releases a
  34730. ** reference obtained by an earlier call to unixFetch(). The second
  34731. ** argument passed to this function must be the same as the corresponding
  34732. ** argument that was passed to the unixFetch() invocation.
  34733. **
  34734. ** Or, if the third argument is NULL, then this function is being called
  34735. ** to inform the VFS layer that, according to POSIX, any existing mapping
  34736. ** may now be invalid and should be unmapped.
  34737. */
  34738. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  34739. #if SQLITE_MAX_MMAP_SIZE>0
  34740. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  34741. UNUSED_PARAMETER(iOff);
  34742. /* If p==0 (unmap the entire file) then there must be no outstanding
  34743. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  34744. ** then there must be at least one outstanding. */
  34745. assert( (p==0)==(pFd->nFetchOut==0) );
  34746. /* If p!=0, it must match the iOff value. */
  34747. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  34748. if( p ){
  34749. pFd->nFetchOut--;
  34750. }else{
  34751. unixUnmapfile(pFd);
  34752. }
  34753. assert( pFd->nFetchOut>=0 );
  34754. #else
  34755. UNUSED_PARAMETER(fd);
  34756. UNUSED_PARAMETER(p);
  34757. UNUSED_PARAMETER(iOff);
  34758. #endif
  34759. return SQLITE_OK;
  34760. }
  34761. /*
  34762. ** Here ends the implementation of all sqlite3_file methods.
  34763. **
  34764. ********************** End sqlite3_file Methods *******************************
  34765. ******************************************************************************/
  34766. /*
  34767. ** This division contains definitions of sqlite3_io_methods objects that
  34768. ** implement various file locking strategies. It also contains definitions
  34769. ** of "finder" functions. A finder-function is used to locate the appropriate
  34770. ** sqlite3_io_methods object for a particular database file. The pAppData
  34771. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  34772. ** the correct finder-function for that VFS.
  34773. **
  34774. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  34775. ** object. The only interesting finder-function is autolockIoFinder, which
  34776. ** looks at the filesystem type and tries to guess the best locking
  34777. ** strategy from that.
  34778. **
  34779. ** For finder-function F, two objects are created:
  34780. **
  34781. ** (1) The real finder-function named "FImpt()".
  34782. **
  34783. ** (2) A constant pointer to this function named just "F".
  34784. **
  34785. **
  34786. ** A pointer to the F pointer is used as the pAppData value for VFS
  34787. ** objects. We have to do this instead of letting pAppData point
  34788. ** directly at the finder-function since C90 rules prevent a void*
  34789. ** from be cast into a function pointer.
  34790. **
  34791. **
  34792. ** Each instance of this macro generates two objects:
  34793. **
  34794. ** * A constant sqlite3_io_methods object call METHOD that has locking
  34795. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  34796. **
  34797. ** * An I/O method finder function called FINDER that returns a pointer
  34798. ** to the METHOD object in the previous bullet.
  34799. */
  34800. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  34801. static const sqlite3_io_methods METHOD = { \
  34802. VERSION, /* iVersion */ \
  34803. CLOSE, /* xClose */ \
  34804. unixRead, /* xRead */ \
  34805. unixWrite, /* xWrite */ \
  34806. unixTruncate, /* xTruncate */ \
  34807. unixSync, /* xSync */ \
  34808. unixFileSize, /* xFileSize */ \
  34809. LOCK, /* xLock */ \
  34810. UNLOCK, /* xUnlock */ \
  34811. CKLOCK, /* xCheckReservedLock */ \
  34812. unixFileControl, /* xFileControl */ \
  34813. unixSectorSize, /* xSectorSize */ \
  34814. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  34815. SHMMAP, /* xShmMap */ \
  34816. unixShmLock, /* xShmLock */ \
  34817. unixShmBarrier, /* xShmBarrier */ \
  34818. unixShmUnmap, /* xShmUnmap */ \
  34819. unixFetch, /* xFetch */ \
  34820. unixUnfetch, /* xUnfetch */ \
  34821. }; \
  34822. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  34823. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  34824. return &METHOD; \
  34825. } \
  34826. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  34827. = FINDER##Impl;
  34828. /*
  34829. ** Here are all of the sqlite3_io_methods objects for each of the
  34830. ** locking strategies. Functions that return pointers to these methods
  34831. ** are also created.
  34832. */
  34833. IOMETHODS(
  34834. posixIoFinder, /* Finder function name */
  34835. posixIoMethods, /* sqlite3_io_methods object name */
  34836. 3, /* shared memory and mmap are enabled */
  34837. unixClose, /* xClose method */
  34838. unixLock, /* xLock method */
  34839. unixUnlock, /* xUnlock method */
  34840. unixCheckReservedLock, /* xCheckReservedLock method */
  34841. unixShmMap /* xShmMap method */
  34842. )
  34843. IOMETHODS(
  34844. nolockIoFinder, /* Finder function name */
  34845. nolockIoMethods, /* sqlite3_io_methods object name */
  34846. 3, /* shared memory is disabled */
  34847. nolockClose, /* xClose method */
  34848. nolockLock, /* xLock method */
  34849. nolockUnlock, /* xUnlock method */
  34850. nolockCheckReservedLock, /* xCheckReservedLock method */
  34851. 0 /* xShmMap method */
  34852. )
  34853. IOMETHODS(
  34854. dotlockIoFinder, /* Finder function name */
  34855. dotlockIoMethods, /* sqlite3_io_methods object name */
  34856. 1, /* shared memory is disabled */
  34857. dotlockClose, /* xClose method */
  34858. dotlockLock, /* xLock method */
  34859. dotlockUnlock, /* xUnlock method */
  34860. dotlockCheckReservedLock, /* xCheckReservedLock method */
  34861. 0 /* xShmMap method */
  34862. )
  34863. #if SQLITE_ENABLE_LOCKING_STYLE
  34864. IOMETHODS(
  34865. flockIoFinder, /* Finder function name */
  34866. flockIoMethods, /* sqlite3_io_methods object name */
  34867. 1, /* shared memory is disabled */
  34868. flockClose, /* xClose method */
  34869. flockLock, /* xLock method */
  34870. flockUnlock, /* xUnlock method */
  34871. flockCheckReservedLock, /* xCheckReservedLock method */
  34872. 0 /* xShmMap method */
  34873. )
  34874. #endif
  34875. #if OS_VXWORKS
  34876. IOMETHODS(
  34877. semIoFinder, /* Finder function name */
  34878. semIoMethods, /* sqlite3_io_methods object name */
  34879. 1, /* shared memory is disabled */
  34880. semXClose, /* xClose method */
  34881. semXLock, /* xLock method */
  34882. semXUnlock, /* xUnlock method */
  34883. semXCheckReservedLock, /* xCheckReservedLock method */
  34884. 0 /* xShmMap method */
  34885. )
  34886. #endif
  34887. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34888. IOMETHODS(
  34889. afpIoFinder, /* Finder function name */
  34890. afpIoMethods, /* sqlite3_io_methods object name */
  34891. 1, /* shared memory is disabled */
  34892. afpClose, /* xClose method */
  34893. afpLock, /* xLock method */
  34894. afpUnlock, /* xUnlock method */
  34895. afpCheckReservedLock, /* xCheckReservedLock method */
  34896. 0 /* xShmMap method */
  34897. )
  34898. #endif
  34899. /*
  34900. ** The proxy locking method is a "super-method" in the sense that it
  34901. ** opens secondary file descriptors for the conch and lock files and
  34902. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  34903. ** secondary files. For this reason, the division that implements
  34904. ** proxy locking is located much further down in the file. But we need
  34905. ** to go ahead and define the sqlite3_io_methods and finder function
  34906. ** for proxy locking here. So we forward declare the I/O methods.
  34907. */
  34908. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34909. static int proxyClose(sqlite3_file*);
  34910. static int proxyLock(sqlite3_file*, int);
  34911. static int proxyUnlock(sqlite3_file*, int);
  34912. static int proxyCheckReservedLock(sqlite3_file*, int*);
  34913. IOMETHODS(
  34914. proxyIoFinder, /* Finder function name */
  34915. proxyIoMethods, /* sqlite3_io_methods object name */
  34916. 1, /* shared memory is disabled */
  34917. proxyClose, /* xClose method */
  34918. proxyLock, /* xLock method */
  34919. proxyUnlock, /* xUnlock method */
  34920. proxyCheckReservedLock, /* xCheckReservedLock method */
  34921. 0 /* xShmMap method */
  34922. )
  34923. #endif
  34924. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  34925. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34926. IOMETHODS(
  34927. nfsIoFinder, /* Finder function name */
  34928. nfsIoMethods, /* sqlite3_io_methods object name */
  34929. 1, /* shared memory is disabled */
  34930. unixClose, /* xClose method */
  34931. unixLock, /* xLock method */
  34932. nfsUnlock, /* xUnlock method */
  34933. unixCheckReservedLock, /* xCheckReservedLock method */
  34934. 0 /* xShmMap method */
  34935. )
  34936. #endif
  34937. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34938. /*
  34939. ** This "finder" function attempts to determine the best locking strategy
  34940. ** for the database file "filePath". It then returns the sqlite3_io_methods
  34941. ** object that implements that strategy.
  34942. **
  34943. ** This is for MacOSX only.
  34944. */
  34945. static const sqlite3_io_methods *autolockIoFinderImpl(
  34946. const char *filePath, /* name of the database file */
  34947. unixFile *pNew /* open file object for the database file */
  34948. ){
  34949. static const struct Mapping {
  34950. const char *zFilesystem; /* Filesystem type name */
  34951. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  34952. } aMap[] = {
  34953. { "hfs", &posixIoMethods },
  34954. { "ufs", &posixIoMethods },
  34955. { "afpfs", &afpIoMethods },
  34956. { "smbfs", &afpIoMethods },
  34957. { "webdav", &nolockIoMethods },
  34958. { 0, 0 }
  34959. };
  34960. int i;
  34961. struct statfs fsInfo;
  34962. struct flock lockInfo;
  34963. if( !filePath ){
  34964. /* If filePath==NULL that means we are dealing with a transient file
  34965. ** that does not need to be locked. */
  34966. return &nolockIoMethods;
  34967. }
  34968. if( statfs(filePath, &fsInfo) != -1 ){
  34969. if( fsInfo.f_flags & MNT_RDONLY ){
  34970. return &nolockIoMethods;
  34971. }
  34972. for(i=0; aMap[i].zFilesystem; i++){
  34973. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  34974. return aMap[i].pMethods;
  34975. }
  34976. }
  34977. }
  34978. /* Default case. Handles, amongst others, "nfs".
  34979. ** Test byte-range lock using fcntl(). If the call succeeds,
  34980. ** assume that the file-system supports POSIX style locks.
  34981. */
  34982. lockInfo.l_len = 1;
  34983. lockInfo.l_start = 0;
  34984. lockInfo.l_whence = SEEK_SET;
  34985. lockInfo.l_type = F_RDLCK;
  34986. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  34987. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  34988. return &nfsIoMethods;
  34989. } else {
  34990. return &posixIoMethods;
  34991. }
  34992. }else{
  34993. return &dotlockIoMethods;
  34994. }
  34995. }
  34996. static const sqlite3_io_methods
  34997. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  34998. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  34999. #if OS_VXWORKS
  35000. /*
  35001. ** This "finder" function for VxWorks checks to see if posix advisory
  35002. ** locking works. If it does, then that is what is used. If it does not
  35003. ** work, then fallback to named semaphore locking.
  35004. */
  35005. static const sqlite3_io_methods *vxworksIoFinderImpl(
  35006. const char *filePath, /* name of the database file */
  35007. unixFile *pNew /* the open file object */
  35008. ){
  35009. struct flock lockInfo;
  35010. if( !filePath ){
  35011. /* If filePath==NULL that means we are dealing with a transient file
  35012. ** that does not need to be locked. */
  35013. return &nolockIoMethods;
  35014. }
  35015. /* Test if fcntl() is supported and use POSIX style locks.
  35016. ** Otherwise fall back to the named semaphore method.
  35017. */
  35018. lockInfo.l_len = 1;
  35019. lockInfo.l_start = 0;
  35020. lockInfo.l_whence = SEEK_SET;
  35021. lockInfo.l_type = F_RDLCK;
  35022. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  35023. return &posixIoMethods;
  35024. }else{
  35025. return &semIoMethods;
  35026. }
  35027. }
  35028. static const sqlite3_io_methods
  35029. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  35030. #endif /* OS_VXWORKS */
  35031. /*
  35032. ** An abstract type for a pointer to an IO method finder function:
  35033. */
  35034. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  35035. /****************************************************************************
  35036. **************************** sqlite3_vfs methods ****************************
  35037. **
  35038. ** This division contains the implementation of methods on the
  35039. ** sqlite3_vfs object.
  35040. */
  35041. /*
  35042. ** Initialize the contents of the unixFile structure pointed to by pId.
  35043. */
  35044. static int fillInUnixFile(
  35045. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35046. int h, /* Open file descriptor of file being opened */
  35047. sqlite3_file *pId, /* Write to the unixFile structure here */
  35048. const char *zFilename, /* Name of the file being opened */
  35049. int ctrlFlags /* Zero or more UNIXFILE_* values */
  35050. ){
  35051. const sqlite3_io_methods *pLockingStyle;
  35052. unixFile *pNew = (unixFile *)pId;
  35053. int rc = SQLITE_OK;
  35054. assert( pNew->pInode==NULL );
  35055. /* No locking occurs in temporary files */
  35056. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  35057. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  35058. pNew->h = h;
  35059. pNew->pVfs = pVfs;
  35060. pNew->zPath = zFilename;
  35061. pNew->ctrlFlags = (u8)ctrlFlags;
  35062. #if SQLITE_MAX_MMAP_SIZE>0
  35063. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  35064. #endif
  35065. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  35066. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  35067. pNew->ctrlFlags |= UNIXFILE_PSOW;
  35068. }
  35069. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  35070. pNew->ctrlFlags |= UNIXFILE_EXCL;
  35071. }
  35072. #if OS_VXWORKS
  35073. pNew->pId = vxworksFindFileId(zFilename);
  35074. if( pNew->pId==0 ){
  35075. ctrlFlags |= UNIXFILE_NOLOCK;
  35076. rc = SQLITE_NOMEM_BKPT;
  35077. }
  35078. #endif
  35079. if( ctrlFlags & UNIXFILE_NOLOCK ){
  35080. pLockingStyle = &nolockIoMethods;
  35081. }else{
  35082. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  35083. #if SQLITE_ENABLE_LOCKING_STYLE
  35084. /* Cache zFilename in the locking context (AFP and dotlock override) for
  35085. ** proxyLock activation is possible (remote proxy is based on db name)
  35086. ** zFilename remains valid until file is closed, to support */
  35087. pNew->lockingContext = (void*)zFilename;
  35088. #endif
  35089. }
  35090. if( pLockingStyle == &posixIoMethods
  35091. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35092. || pLockingStyle == &nfsIoMethods
  35093. #endif
  35094. ){
  35095. unixEnterMutex();
  35096. rc = findInodeInfo(pNew, &pNew->pInode);
  35097. if( rc!=SQLITE_OK ){
  35098. /* If an error occurred in findInodeInfo(), close the file descriptor
  35099. ** immediately, before releasing the mutex. findInodeInfo() may fail
  35100. ** in two scenarios:
  35101. **
  35102. ** (a) A call to fstat() failed.
  35103. ** (b) A malloc failed.
  35104. **
  35105. ** Scenario (b) may only occur if the process is holding no other
  35106. ** file descriptors open on the same file. If there were other file
  35107. ** descriptors on this file, then no malloc would be required by
  35108. ** findInodeInfo(). If this is the case, it is quite safe to close
  35109. ** handle h - as it is guaranteed that no posix locks will be released
  35110. ** by doing so.
  35111. **
  35112. ** If scenario (a) caused the error then things are not so safe. The
  35113. ** implicit assumption here is that if fstat() fails, things are in
  35114. ** such bad shape that dropping a lock or two doesn't matter much.
  35115. */
  35116. robust_close(pNew, h, __LINE__);
  35117. h = -1;
  35118. }
  35119. unixLeaveMutex();
  35120. }
  35121. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35122. else if( pLockingStyle == &afpIoMethods ){
  35123. /* AFP locking uses the file path so it needs to be included in
  35124. ** the afpLockingContext.
  35125. */
  35126. afpLockingContext *pCtx;
  35127. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  35128. if( pCtx==0 ){
  35129. rc = SQLITE_NOMEM_BKPT;
  35130. }else{
  35131. /* NB: zFilename exists and remains valid until the file is closed
  35132. ** according to requirement F11141. So we do not need to make a
  35133. ** copy of the filename. */
  35134. pCtx->dbPath = zFilename;
  35135. pCtx->reserved = 0;
  35136. srandomdev();
  35137. unixEnterMutex();
  35138. rc = findInodeInfo(pNew, &pNew->pInode);
  35139. if( rc!=SQLITE_OK ){
  35140. sqlite3_free(pNew->lockingContext);
  35141. robust_close(pNew, h, __LINE__);
  35142. h = -1;
  35143. }
  35144. unixLeaveMutex();
  35145. }
  35146. }
  35147. #endif
  35148. else if( pLockingStyle == &dotlockIoMethods ){
  35149. /* Dotfile locking uses the file path so it needs to be included in
  35150. ** the dotlockLockingContext
  35151. */
  35152. char *zLockFile;
  35153. int nFilename;
  35154. assert( zFilename!=0 );
  35155. nFilename = (int)strlen(zFilename) + 6;
  35156. zLockFile = (char *)sqlite3_malloc64(nFilename);
  35157. if( zLockFile==0 ){
  35158. rc = SQLITE_NOMEM_BKPT;
  35159. }else{
  35160. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  35161. }
  35162. pNew->lockingContext = zLockFile;
  35163. }
  35164. #if OS_VXWORKS
  35165. else if( pLockingStyle == &semIoMethods ){
  35166. /* Named semaphore locking uses the file path so it needs to be
  35167. ** included in the semLockingContext
  35168. */
  35169. unixEnterMutex();
  35170. rc = findInodeInfo(pNew, &pNew->pInode);
  35171. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  35172. char *zSemName = pNew->pInode->aSemName;
  35173. int n;
  35174. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  35175. pNew->pId->zCanonicalName);
  35176. for( n=1; zSemName[n]; n++ )
  35177. if( zSemName[n]=='/' ) zSemName[n] = '_';
  35178. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  35179. if( pNew->pInode->pSem == SEM_FAILED ){
  35180. rc = SQLITE_NOMEM_BKPT;
  35181. pNew->pInode->aSemName[0] = '\0';
  35182. }
  35183. }
  35184. unixLeaveMutex();
  35185. }
  35186. #endif
  35187. storeLastErrno(pNew, 0);
  35188. #if OS_VXWORKS
  35189. if( rc!=SQLITE_OK ){
  35190. if( h>=0 ) robust_close(pNew, h, __LINE__);
  35191. h = -1;
  35192. osUnlink(zFilename);
  35193. pNew->ctrlFlags |= UNIXFILE_DELETE;
  35194. }
  35195. #endif
  35196. if( rc!=SQLITE_OK ){
  35197. if( h>=0 ) robust_close(pNew, h, __LINE__);
  35198. }else{
  35199. pNew->pMethod = pLockingStyle;
  35200. OpenCounter(+1);
  35201. verifyDbFile(pNew);
  35202. }
  35203. return rc;
  35204. }
  35205. /*
  35206. ** Return the name of a directory in which to put temporary files.
  35207. ** If no suitable temporary file directory can be found, return NULL.
  35208. */
  35209. static const char *unixTempFileDir(void){
  35210. static const char *azDirs[] = {
  35211. 0,
  35212. 0,
  35213. "/var/tmp",
  35214. "/usr/tmp",
  35215. "/tmp",
  35216. "."
  35217. };
  35218. unsigned int i = 0;
  35219. struct stat buf;
  35220. const char *zDir = sqlite3_temp_directory;
  35221. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  35222. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  35223. while(1){
  35224. if( zDir!=0
  35225. && osStat(zDir, &buf)==0
  35226. && S_ISDIR(buf.st_mode)
  35227. && osAccess(zDir, 03)==0
  35228. ){
  35229. return zDir;
  35230. }
  35231. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  35232. zDir = azDirs[i++];
  35233. }
  35234. return 0;
  35235. }
  35236. /*
  35237. ** Create a temporary file name in zBuf. zBuf must be allocated
  35238. ** by the calling process and must be big enough to hold at least
  35239. ** pVfs->mxPathname bytes.
  35240. */
  35241. static int unixGetTempname(int nBuf, char *zBuf){
  35242. const char *zDir;
  35243. int iLimit = 0;
  35244. /* It's odd to simulate an io-error here, but really this is just
  35245. ** using the io-error infrastructure to test that SQLite handles this
  35246. ** function failing.
  35247. */
  35248. zBuf[0] = 0;
  35249. SimulateIOError( return SQLITE_IOERR );
  35250. zDir = unixTempFileDir();
  35251. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  35252. do{
  35253. u64 r;
  35254. sqlite3_randomness(sizeof(r), &r);
  35255. assert( nBuf>2 );
  35256. zBuf[nBuf-2] = 0;
  35257. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  35258. zDir, r, 0);
  35259. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  35260. }while( osAccess(zBuf,0)==0 );
  35261. return SQLITE_OK;
  35262. }
  35263. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35264. /*
  35265. ** Routine to transform a unixFile into a proxy-locking unixFile.
  35266. ** Implementation in the proxy-lock division, but used by unixOpen()
  35267. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  35268. */
  35269. static int proxyTransformUnixFile(unixFile*, const char*);
  35270. #endif
  35271. /*
  35272. ** Search for an unused file descriptor that was opened on the database
  35273. ** file (not a journal or master-journal file) identified by pathname
  35274. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  35275. ** argument to this function.
  35276. **
  35277. ** Such a file descriptor may exist if a database connection was closed
  35278. ** but the associated file descriptor could not be closed because some
  35279. ** other file descriptor open on the same file is holding a file-lock.
  35280. ** Refer to comments in the unixClose() function and the lengthy comment
  35281. ** describing "Posix Advisory Locking" at the start of this file for
  35282. ** further details. Also, ticket #4018.
  35283. **
  35284. ** If a suitable file descriptor is found, then it is returned. If no
  35285. ** such file descriptor is located, -1 is returned.
  35286. */
  35287. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  35288. UnixUnusedFd *pUnused = 0;
  35289. /* Do not search for an unused file descriptor on vxworks. Not because
  35290. ** vxworks would not benefit from the change (it might, we're not sure),
  35291. ** but because no way to test it is currently available. It is better
  35292. ** not to risk breaking vxworks support for the sake of such an obscure
  35293. ** feature. */
  35294. #if !OS_VXWORKS
  35295. struct stat sStat; /* Results of stat() call */
  35296. unixEnterMutex();
  35297. /* A stat() call may fail for various reasons. If this happens, it is
  35298. ** almost certain that an open() call on the same path will also fail.
  35299. ** For this reason, if an error occurs in the stat() call here, it is
  35300. ** ignored and -1 is returned. The caller will try to open a new file
  35301. ** descriptor on the same path, fail, and return an error to SQLite.
  35302. **
  35303. ** Even if a subsequent open() call does succeed, the consequences of
  35304. ** not searching for a reusable file descriptor are not dire. */
  35305. if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
  35306. unixInodeInfo *pInode;
  35307. pInode = inodeList;
  35308. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  35309. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  35310. pInode = pInode->pNext;
  35311. }
  35312. if( pInode ){
  35313. UnixUnusedFd **pp;
  35314. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  35315. pUnused = *pp;
  35316. if( pUnused ){
  35317. nUnusedFd--;
  35318. *pp = pUnused->pNext;
  35319. }
  35320. }
  35321. }
  35322. unixLeaveMutex();
  35323. #endif /* if !OS_VXWORKS */
  35324. return pUnused;
  35325. }
  35326. /*
  35327. ** Find the mode, uid and gid of file zFile.
  35328. */
  35329. static int getFileMode(
  35330. const char *zFile, /* File name */
  35331. mode_t *pMode, /* OUT: Permissions of zFile */
  35332. uid_t *pUid, /* OUT: uid of zFile. */
  35333. gid_t *pGid /* OUT: gid of zFile. */
  35334. ){
  35335. struct stat sStat; /* Output of stat() on database file */
  35336. int rc = SQLITE_OK;
  35337. if( 0==osStat(zFile, &sStat) ){
  35338. *pMode = sStat.st_mode & 0777;
  35339. *pUid = sStat.st_uid;
  35340. *pGid = sStat.st_gid;
  35341. }else{
  35342. rc = SQLITE_IOERR_FSTAT;
  35343. }
  35344. return rc;
  35345. }
  35346. /*
  35347. ** This function is called by unixOpen() to determine the unix permissions
  35348. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  35349. ** and a value suitable for passing as the third argument to open(2) is
  35350. ** written to *pMode. If an IO error occurs, an SQLite error code is
  35351. ** returned and the value of *pMode is not modified.
  35352. **
  35353. ** In most cases, this routine sets *pMode to 0, which will become
  35354. ** an indication to robust_open() to create the file using
  35355. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  35356. ** But if the file being opened is a WAL or regular journal file, then
  35357. ** this function queries the file-system for the permissions on the
  35358. ** corresponding database file and sets *pMode to this value. Whenever
  35359. ** possible, WAL and journal files are created using the same permissions
  35360. ** as the associated database file.
  35361. **
  35362. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  35363. ** original filename is unavailable. But 8_3_NAMES is only used for
  35364. ** FAT filesystems and permissions do not matter there, so just use
  35365. ** the default permissions.
  35366. */
  35367. static int findCreateFileMode(
  35368. const char *zPath, /* Path of file (possibly) being created */
  35369. int flags, /* Flags passed as 4th argument to xOpen() */
  35370. mode_t *pMode, /* OUT: Permissions to open file with */
  35371. uid_t *pUid, /* OUT: uid to set on the file */
  35372. gid_t *pGid /* OUT: gid to set on the file */
  35373. ){
  35374. int rc = SQLITE_OK; /* Return Code */
  35375. *pMode = 0;
  35376. *pUid = 0;
  35377. *pGid = 0;
  35378. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  35379. char zDb[MAX_PATHNAME+1]; /* Database file path */
  35380. int nDb; /* Number of valid bytes in zDb */
  35381. /* zPath is a path to a WAL or journal file. The following block derives
  35382. ** the path to the associated database file from zPath. This block handles
  35383. ** the following naming conventions:
  35384. **
  35385. ** "<path to db>-journal"
  35386. ** "<path to db>-wal"
  35387. ** "<path to db>-journalNN"
  35388. ** "<path to db>-walNN"
  35389. **
  35390. ** where NN is a decimal number. The NN naming schemes are
  35391. ** used by the test_multiplex.c module.
  35392. */
  35393. nDb = sqlite3Strlen30(zPath) - 1;
  35394. while( zPath[nDb]!='-' ){
  35395. /* In normal operation, the journal file name will always contain
  35396. ** a '-' character. However in 8+3 filename mode, or if a corrupt
  35397. ** rollback journal specifies a master journal with a goofy name, then
  35398. ** the '-' might be missing. */
  35399. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  35400. nDb--;
  35401. }
  35402. memcpy(zDb, zPath, nDb);
  35403. zDb[nDb] = '\0';
  35404. rc = getFileMode(zDb, pMode, pUid, pGid);
  35405. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  35406. *pMode = 0600;
  35407. }else if( flags & SQLITE_OPEN_URI ){
  35408. /* If this is a main database file and the file was opened using a URI
  35409. ** filename, check for the "modeof" parameter. If present, interpret
  35410. ** its value as a filename and try to copy the mode, uid and gid from
  35411. ** that file. */
  35412. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  35413. if( z ){
  35414. rc = getFileMode(z, pMode, pUid, pGid);
  35415. }
  35416. }
  35417. return rc;
  35418. }
  35419. /*
  35420. ** Open the file zPath.
  35421. **
  35422. ** Previously, the SQLite OS layer used three functions in place of this
  35423. ** one:
  35424. **
  35425. ** sqlite3OsOpenReadWrite();
  35426. ** sqlite3OsOpenReadOnly();
  35427. ** sqlite3OsOpenExclusive();
  35428. **
  35429. ** These calls correspond to the following combinations of flags:
  35430. **
  35431. ** ReadWrite() -> (READWRITE | CREATE)
  35432. ** ReadOnly() -> (READONLY)
  35433. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  35434. **
  35435. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  35436. ** true, the file was configured to be automatically deleted when the
  35437. ** file handle closed. To achieve the same effect using this new
  35438. ** interface, add the DELETEONCLOSE flag to those specified above for
  35439. ** OpenExclusive().
  35440. */
  35441. static int unixOpen(
  35442. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  35443. const char *zPath, /* Pathname of file to be opened */
  35444. sqlite3_file *pFile, /* The file descriptor to be filled in */
  35445. int flags, /* Input flags to control the opening */
  35446. int *pOutFlags /* Output flags returned to SQLite core */
  35447. ){
  35448. unixFile *p = (unixFile *)pFile;
  35449. int fd = -1; /* File descriptor returned by open() */
  35450. int openFlags = 0; /* Flags to pass to open() */
  35451. int eType = flags&0xFFFFFF00; /* Type of file to open */
  35452. int noLock; /* True to omit locking primitives */
  35453. int rc = SQLITE_OK; /* Function Return Code */
  35454. int ctrlFlags = 0; /* UNIXFILE_* flags */
  35455. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  35456. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  35457. int isCreate = (flags & SQLITE_OPEN_CREATE);
  35458. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  35459. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  35460. #if SQLITE_ENABLE_LOCKING_STYLE
  35461. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  35462. #endif
  35463. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  35464. struct statfs fsInfo;
  35465. #endif
  35466. /* If creating a master or main-file journal, this function will open
  35467. ** a file-descriptor on the directory too. The first time unixSync()
  35468. ** is called the directory file descriptor will be fsync()ed and close()d.
  35469. */
  35470. int isNewJrnl = (isCreate && (
  35471. eType==SQLITE_OPEN_MASTER_JOURNAL
  35472. || eType==SQLITE_OPEN_MAIN_JOURNAL
  35473. || eType==SQLITE_OPEN_WAL
  35474. ));
  35475. /* If argument zPath is a NULL pointer, this function is required to open
  35476. ** a temporary file. Use this buffer to store the file name in.
  35477. */
  35478. char zTmpname[MAX_PATHNAME+2];
  35479. const char *zName = zPath;
  35480. /* Check the following statements are true:
  35481. **
  35482. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  35483. ** (b) if CREATE is set, then READWRITE must also be set, and
  35484. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  35485. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  35486. */
  35487. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  35488. assert(isCreate==0 || isReadWrite);
  35489. assert(isExclusive==0 || isCreate);
  35490. assert(isDelete==0 || isCreate);
  35491. /* The main DB, main journal, WAL file and master journal are never
  35492. ** automatically deleted. Nor are they ever temporary files. */
  35493. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  35494. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  35495. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  35496. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  35497. /* Assert that the upper layer has set one of the "file-type" flags. */
  35498. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  35499. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  35500. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  35501. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  35502. );
  35503. /* Detect a pid change and reset the PRNG. There is a race condition
  35504. ** here such that two or more threads all trying to open databases at
  35505. ** the same instant might all reset the PRNG. But multiple resets
  35506. ** are harmless.
  35507. */
  35508. if( randomnessPid!=osGetpid(0) ){
  35509. randomnessPid = osGetpid(0);
  35510. sqlite3_randomness(0,0);
  35511. }
  35512. memset(p, 0, sizeof(unixFile));
  35513. if( eType==SQLITE_OPEN_MAIN_DB ){
  35514. UnixUnusedFd *pUnused;
  35515. pUnused = findReusableFd(zName, flags);
  35516. if( pUnused ){
  35517. fd = pUnused->fd;
  35518. }else{
  35519. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  35520. if( !pUnused ){
  35521. return SQLITE_NOMEM_BKPT;
  35522. }
  35523. }
  35524. p->pPreallocatedUnused = pUnused;
  35525. /* Database filenames are double-zero terminated if they are not
  35526. ** URIs with parameters. Hence, they can always be passed into
  35527. ** sqlite3_uri_parameter(). */
  35528. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  35529. }else if( !zName ){
  35530. /* If zName is NULL, the upper layer is requesting a temp file. */
  35531. assert(isDelete && !isNewJrnl);
  35532. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  35533. if( rc!=SQLITE_OK ){
  35534. return rc;
  35535. }
  35536. zName = zTmpname;
  35537. /* Generated temporary filenames are always double-zero terminated
  35538. ** for use by sqlite3_uri_parameter(). */
  35539. assert( zName[strlen(zName)+1]==0 );
  35540. }
  35541. /* Determine the value of the flags parameter passed to POSIX function
  35542. ** open(). These must be calculated even if open() is not called, as
  35543. ** they may be stored as part of the file handle and used by the
  35544. ** 'conch file' locking functions later on. */
  35545. if( isReadonly ) openFlags |= O_RDONLY;
  35546. if( isReadWrite ) openFlags |= O_RDWR;
  35547. if( isCreate ) openFlags |= O_CREAT;
  35548. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  35549. openFlags |= (O_LARGEFILE|O_BINARY);
  35550. if( fd<0 ){
  35551. mode_t openMode; /* Permissions to create file with */
  35552. uid_t uid; /* Userid for the file */
  35553. gid_t gid; /* Groupid for the file */
  35554. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  35555. if( rc!=SQLITE_OK ){
  35556. assert( !p->pPreallocatedUnused );
  35557. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  35558. return rc;
  35559. }
  35560. fd = robust_open(zName, openFlags, openMode);
  35561. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  35562. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  35563. if( fd<0 ){
  35564. if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
  35565. /* If unable to create a journal because the directory is not
  35566. ** writable, change the error code to indicate that. */
  35567. rc = SQLITE_READONLY_DIRECTORY;
  35568. }else if( errno!=EISDIR && isReadWrite ){
  35569. /* Failed to open the file for read/write access. Try read-only. */
  35570. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  35571. openFlags &= ~(O_RDWR|O_CREAT);
  35572. flags |= SQLITE_OPEN_READONLY;
  35573. openFlags |= O_RDONLY;
  35574. isReadonly = 1;
  35575. fd = robust_open(zName, openFlags, openMode);
  35576. }
  35577. }
  35578. if( fd<0 ){
  35579. int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  35580. if( rc==SQLITE_OK ) rc = rc2;
  35581. goto open_finished;
  35582. }
  35583. /* If this process is running as root and if creating a new rollback
  35584. ** journal or WAL file, set the ownership of the journal or WAL to be
  35585. ** the same as the original database.
  35586. */
  35587. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  35588. robustFchown(fd, uid, gid);
  35589. }
  35590. }
  35591. assert( fd>=0 );
  35592. if( pOutFlags ){
  35593. *pOutFlags = flags;
  35594. }
  35595. if( p->pPreallocatedUnused ){
  35596. p->pPreallocatedUnused->fd = fd;
  35597. p->pPreallocatedUnused->flags = flags;
  35598. }
  35599. if( isDelete ){
  35600. #if OS_VXWORKS
  35601. zPath = zName;
  35602. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  35603. zPath = sqlite3_mprintf("%s", zName);
  35604. if( zPath==0 ){
  35605. robust_close(p, fd, __LINE__);
  35606. return SQLITE_NOMEM_BKPT;
  35607. }
  35608. #else
  35609. osUnlink(zName);
  35610. #endif
  35611. }
  35612. #if SQLITE_ENABLE_LOCKING_STYLE
  35613. else{
  35614. p->openFlags = openFlags;
  35615. }
  35616. #endif
  35617. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  35618. if( fstatfs(fd, &fsInfo) == -1 ){
  35619. storeLastErrno(p, errno);
  35620. robust_close(p, fd, __LINE__);
  35621. return SQLITE_IOERR_ACCESS;
  35622. }
  35623. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  35624. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  35625. }
  35626. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  35627. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  35628. }
  35629. #endif
  35630. /* Set up appropriate ctrlFlags */
  35631. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  35632. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  35633. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  35634. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  35635. if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
  35636. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  35637. #if SQLITE_ENABLE_LOCKING_STYLE
  35638. #if SQLITE_PREFER_PROXY_LOCKING
  35639. isAutoProxy = 1;
  35640. #endif
  35641. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  35642. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  35643. int useProxy = 0;
  35644. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  35645. ** never use proxy, NULL means use proxy for non-local files only. */
  35646. if( envforce!=NULL ){
  35647. useProxy = atoi(envforce)>0;
  35648. }else{
  35649. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  35650. }
  35651. if( useProxy ){
  35652. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  35653. if( rc==SQLITE_OK ){
  35654. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  35655. if( rc!=SQLITE_OK ){
  35656. /* Use unixClose to clean up the resources added in fillInUnixFile
  35657. ** and clear all the structure's references. Specifically,
  35658. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  35659. */
  35660. unixClose(pFile);
  35661. return rc;
  35662. }
  35663. }
  35664. goto open_finished;
  35665. }
  35666. }
  35667. #endif
  35668. assert( zPath==0 || zPath[0]=='/'
  35669. || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
  35670. );
  35671. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  35672. open_finished:
  35673. if( rc!=SQLITE_OK ){
  35674. sqlite3_free(p->pPreallocatedUnused);
  35675. }
  35676. return rc;
  35677. }
  35678. /*
  35679. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  35680. ** the directory after deleting the file.
  35681. */
  35682. static int unixDelete(
  35683. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  35684. const char *zPath, /* Name of file to be deleted */
  35685. int dirSync /* If true, fsync() directory after deleting file */
  35686. ){
  35687. int rc = SQLITE_OK;
  35688. UNUSED_PARAMETER(NotUsed);
  35689. SimulateIOError(return SQLITE_IOERR_DELETE);
  35690. if( osUnlink(zPath)==(-1) ){
  35691. if( errno==ENOENT
  35692. #if OS_VXWORKS
  35693. || osAccess(zPath,0)!=0
  35694. #endif
  35695. ){
  35696. rc = SQLITE_IOERR_DELETE_NOENT;
  35697. }else{
  35698. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  35699. }
  35700. return rc;
  35701. }
  35702. #ifndef SQLITE_DISABLE_DIRSYNC
  35703. if( (dirSync & 1)!=0 ){
  35704. int fd;
  35705. rc = osOpenDirectory(zPath, &fd);
  35706. if( rc==SQLITE_OK ){
  35707. if( full_fsync(fd,0,0) ){
  35708. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  35709. }
  35710. robust_close(0, fd, __LINE__);
  35711. }else{
  35712. assert( rc==SQLITE_CANTOPEN );
  35713. rc = SQLITE_OK;
  35714. }
  35715. }
  35716. #endif
  35717. return rc;
  35718. }
  35719. /*
  35720. ** Test the existence of or access permissions of file zPath. The
  35721. ** test performed depends on the value of flags:
  35722. **
  35723. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  35724. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  35725. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  35726. **
  35727. ** Otherwise return 0.
  35728. */
  35729. static int unixAccess(
  35730. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  35731. const char *zPath, /* Path of the file to examine */
  35732. int flags, /* What do we want to learn about the zPath file? */
  35733. int *pResOut /* Write result boolean here */
  35734. ){
  35735. UNUSED_PARAMETER(NotUsed);
  35736. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  35737. assert( pResOut!=0 );
  35738. /* The spec says there are three possible values for flags. But only
  35739. ** two of them are actually used */
  35740. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  35741. if( flags==SQLITE_ACCESS_EXISTS ){
  35742. struct stat buf;
  35743. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  35744. }else{
  35745. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  35746. }
  35747. return SQLITE_OK;
  35748. }
  35749. /*
  35750. **
  35751. */
  35752. static int mkFullPathname(
  35753. const char *zPath, /* Input path */
  35754. char *zOut, /* Output buffer */
  35755. int nOut /* Allocated size of buffer zOut */
  35756. ){
  35757. int nPath = sqlite3Strlen30(zPath);
  35758. int iOff = 0;
  35759. if( zPath[0]!='/' ){
  35760. if( osGetcwd(zOut, nOut-2)==0 ){
  35761. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  35762. }
  35763. iOff = sqlite3Strlen30(zOut);
  35764. zOut[iOff++] = '/';
  35765. }
  35766. if( (iOff+nPath+1)>nOut ){
  35767. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  35768. ** even if it returns an error. */
  35769. zOut[iOff] = '\0';
  35770. return SQLITE_CANTOPEN_BKPT;
  35771. }
  35772. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  35773. return SQLITE_OK;
  35774. }
  35775. /*
  35776. ** Turn a relative pathname into a full pathname. The relative path
  35777. ** is stored as a nul-terminated string in the buffer pointed to by
  35778. ** zPath.
  35779. **
  35780. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  35781. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  35782. ** this buffer before returning.
  35783. */
  35784. static int unixFullPathname(
  35785. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35786. const char *zPath, /* Possibly relative input path */
  35787. int nOut, /* Size of output buffer in bytes */
  35788. char *zOut /* Output buffer */
  35789. ){
  35790. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  35791. return mkFullPathname(zPath, zOut, nOut);
  35792. #else
  35793. int rc = SQLITE_OK;
  35794. int nByte;
  35795. int nLink = 1; /* Number of symbolic links followed so far */
  35796. const char *zIn = zPath; /* Input path for each iteration of loop */
  35797. char *zDel = 0;
  35798. assert( pVfs->mxPathname==MAX_PATHNAME );
  35799. UNUSED_PARAMETER(pVfs);
  35800. /* It's odd to simulate an io-error here, but really this is just
  35801. ** using the io-error infrastructure to test that SQLite handles this
  35802. ** function failing. This function could fail if, for example, the
  35803. ** current working directory has been unlinked.
  35804. */
  35805. SimulateIOError( return SQLITE_ERROR );
  35806. do {
  35807. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  35808. ** link, or false otherwise. */
  35809. int bLink = 0;
  35810. struct stat buf;
  35811. if( osLstat(zIn, &buf)!=0 ){
  35812. if( errno!=ENOENT ){
  35813. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  35814. }
  35815. }else{
  35816. bLink = S_ISLNK(buf.st_mode);
  35817. }
  35818. if( bLink ){
  35819. if( zDel==0 ){
  35820. zDel = sqlite3_malloc(nOut);
  35821. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  35822. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  35823. rc = SQLITE_CANTOPEN_BKPT;
  35824. }
  35825. if( rc==SQLITE_OK ){
  35826. nByte = osReadlink(zIn, zDel, nOut-1);
  35827. if( nByte<0 ){
  35828. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  35829. }else{
  35830. if( zDel[0]!='/' ){
  35831. int n;
  35832. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  35833. if( nByte+n+1>nOut ){
  35834. rc = SQLITE_CANTOPEN_BKPT;
  35835. }else{
  35836. memmove(&zDel[n], zDel, nByte+1);
  35837. memcpy(zDel, zIn, n);
  35838. nByte += n;
  35839. }
  35840. }
  35841. zDel[nByte] = '\0';
  35842. }
  35843. }
  35844. zIn = zDel;
  35845. }
  35846. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  35847. if( rc==SQLITE_OK && zIn!=zOut ){
  35848. rc = mkFullPathname(zIn, zOut, nOut);
  35849. }
  35850. if( bLink==0 ) break;
  35851. zIn = zOut;
  35852. }while( rc==SQLITE_OK );
  35853. sqlite3_free(zDel);
  35854. return rc;
  35855. #endif /* HAVE_READLINK && HAVE_LSTAT */
  35856. }
  35857. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  35858. /*
  35859. ** Interfaces for opening a shared library, finding entry points
  35860. ** within the shared library, and closing the shared library.
  35861. */
  35862. #include <dlfcn.h>
  35863. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  35864. UNUSED_PARAMETER(NotUsed);
  35865. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  35866. }
  35867. /*
  35868. ** SQLite calls this function immediately after a call to unixDlSym() or
  35869. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  35870. ** message is available, it is written to zBufOut. If no error message
  35871. ** is available, zBufOut is left unmodified and SQLite uses a default
  35872. ** error message.
  35873. */
  35874. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  35875. const char *zErr;
  35876. UNUSED_PARAMETER(NotUsed);
  35877. unixEnterMutex();
  35878. zErr = dlerror();
  35879. if( zErr ){
  35880. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  35881. }
  35882. unixLeaveMutex();
  35883. }
  35884. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  35885. /*
  35886. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  35887. ** cast into a pointer to a function. And yet the library dlsym() routine
  35888. ** returns a void* which is really a pointer to a function. So how do we
  35889. ** use dlsym() with -pedantic-errors?
  35890. **
  35891. ** Variable x below is defined to be a pointer to a function taking
  35892. ** parameters void* and const char* and returning a pointer to a function.
  35893. ** We initialize x by assigning it a pointer to the dlsym() function.
  35894. ** (That assignment requires a cast.) Then we call the function that
  35895. ** x points to.
  35896. **
  35897. ** This work-around is unlikely to work correctly on any system where
  35898. ** you really cannot cast a function pointer into void*. But then, on the
  35899. ** other hand, dlsym() will not work on such a system either, so we have
  35900. ** not really lost anything.
  35901. */
  35902. void (*(*x)(void*,const char*))(void);
  35903. UNUSED_PARAMETER(NotUsed);
  35904. x = (void(*(*)(void*,const char*))(void))dlsym;
  35905. return (*x)(p, zSym);
  35906. }
  35907. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  35908. UNUSED_PARAMETER(NotUsed);
  35909. dlclose(pHandle);
  35910. }
  35911. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  35912. #define unixDlOpen 0
  35913. #define unixDlError 0
  35914. #define unixDlSym 0
  35915. #define unixDlClose 0
  35916. #endif
  35917. /*
  35918. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  35919. */
  35920. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  35921. UNUSED_PARAMETER(NotUsed);
  35922. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  35923. /* We have to initialize zBuf to prevent valgrind from reporting
  35924. ** errors. The reports issued by valgrind are incorrect - we would
  35925. ** prefer that the randomness be increased by making use of the
  35926. ** uninitialized space in zBuf - but valgrind errors tend to worry
  35927. ** some users. Rather than argue, it seems easier just to initialize
  35928. ** the whole array and silence valgrind, even if that means less randomness
  35929. ** in the random seed.
  35930. **
  35931. ** When testing, initializing zBuf[] to zero is all we do. That means
  35932. ** that we always use the same random number sequence. This makes the
  35933. ** tests repeatable.
  35934. */
  35935. memset(zBuf, 0, nBuf);
  35936. randomnessPid = osGetpid(0);
  35937. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  35938. {
  35939. int fd, got;
  35940. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  35941. if( fd<0 ){
  35942. time_t t;
  35943. time(&t);
  35944. memcpy(zBuf, &t, sizeof(t));
  35945. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  35946. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  35947. nBuf = sizeof(t) + sizeof(randomnessPid);
  35948. }else{
  35949. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  35950. robust_close(0, fd, __LINE__);
  35951. }
  35952. }
  35953. #endif
  35954. return nBuf;
  35955. }
  35956. /*
  35957. ** Sleep for a little while. Return the amount of time slept.
  35958. ** The argument is the number of microseconds we want to sleep.
  35959. ** The return value is the number of microseconds of sleep actually
  35960. ** requested from the underlying operating system, a number which
  35961. ** might be greater than or equal to the argument, but not less
  35962. ** than the argument.
  35963. */
  35964. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  35965. #if OS_VXWORKS
  35966. struct timespec sp;
  35967. sp.tv_sec = microseconds / 1000000;
  35968. sp.tv_nsec = (microseconds % 1000000) * 1000;
  35969. nanosleep(&sp, NULL);
  35970. UNUSED_PARAMETER(NotUsed);
  35971. return microseconds;
  35972. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  35973. usleep(microseconds);
  35974. UNUSED_PARAMETER(NotUsed);
  35975. return microseconds;
  35976. #else
  35977. int seconds = (microseconds+999999)/1000000;
  35978. sleep(seconds);
  35979. UNUSED_PARAMETER(NotUsed);
  35980. return seconds*1000000;
  35981. #endif
  35982. }
  35983. /*
  35984. ** The following variable, if set to a non-zero value, is interpreted as
  35985. ** the number of seconds since 1970 and is used to set the result of
  35986. ** sqlite3OsCurrentTime() during testing.
  35987. */
  35988. #ifdef SQLITE_TEST
  35989. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  35990. #endif
  35991. /*
  35992. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  35993. ** the current time and date as a Julian Day number times 86_400_000. In
  35994. ** other words, write into *piNow the number of milliseconds since the Julian
  35995. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  35996. ** proleptic Gregorian calendar.
  35997. **
  35998. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  35999. ** cannot be found.
  36000. */
  36001. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  36002. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  36003. int rc = SQLITE_OK;
  36004. #if defined(NO_GETTOD)
  36005. time_t t;
  36006. time(&t);
  36007. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  36008. #elif OS_VXWORKS
  36009. struct timespec sNow;
  36010. clock_gettime(CLOCK_REALTIME, &sNow);
  36011. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  36012. #else
  36013. struct timeval sNow;
  36014. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  36015. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  36016. #endif
  36017. #ifdef SQLITE_TEST
  36018. if( sqlite3_current_time ){
  36019. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  36020. }
  36021. #endif
  36022. UNUSED_PARAMETER(NotUsed);
  36023. return rc;
  36024. }
  36025. #ifndef SQLITE_OMIT_DEPRECATED
  36026. /*
  36027. ** Find the current time (in Universal Coordinated Time). Write the
  36028. ** current time and date as a Julian Day number into *prNow and
  36029. ** return 0. Return 1 if the time and date cannot be found.
  36030. */
  36031. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  36032. sqlite3_int64 i = 0;
  36033. int rc;
  36034. UNUSED_PARAMETER(NotUsed);
  36035. rc = unixCurrentTimeInt64(0, &i);
  36036. *prNow = i/86400000.0;
  36037. return rc;
  36038. }
  36039. #else
  36040. # define unixCurrentTime 0
  36041. #endif
  36042. /*
  36043. ** The xGetLastError() method is designed to return a better
  36044. ** low-level error message when operating-system problems come up
  36045. ** during SQLite operation. Only the integer return code is currently
  36046. ** used.
  36047. */
  36048. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  36049. UNUSED_PARAMETER(NotUsed);
  36050. UNUSED_PARAMETER(NotUsed2);
  36051. UNUSED_PARAMETER(NotUsed3);
  36052. return errno;
  36053. }
  36054. /*
  36055. ************************ End of sqlite3_vfs methods ***************************
  36056. ******************************************************************************/
  36057. /******************************************************************************
  36058. ************************** Begin Proxy Locking ********************************
  36059. **
  36060. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  36061. ** other locking methods on secondary lock files. Proxy locking is a
  36062. ** meta-layer over top of the primitive locking implemented above. For
  36063. ** this reason, the division that implements of proxy locking is deferred
  36064. ** until late in the file (here) after all of the other I/O methods have
  36065. ** been defined - so that the primitive locking methods are available
  36066. ** as services to help with the implementation of proxy locking.
  36067. **
  36068. ****
  36069. **
  36070. ** The default locking schemes in SQLite use byte-range locks on the
  36071. ** database file to coordinate safe, concurrent access by multiple readers
  36072. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  36073. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  36074. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  36075. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  36076. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  36077. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  36078. ** address in the shared range is taken for a SHARED lock, the entire
  36079. ** shared range is taken for an EXCLUSIVE lock):
  36080. **
  36081. ** PENDING_BYTE 0x40000000
  36082. ** RESERVED_BYTE 0x40000001
  36083. ** SHARED_RANGE 0x40000002 -> 0x40000200
  36084. **
  36085. ** This works well on the local file system, but shows a nearly 100x
  36086. ** slowdown in read performance on AFP because the AFP client disables
  36087. ** the read cache when byte-range locks are present. Enabling the read
  36088. ** cache exposes a cache coherency problem that is present on all OS X
  36089. ** supported network file systems. NFS and AFP both observe the
  36090. ** close-to-open semantics for ensuring cache coherency
  36091. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  36092. ** address the requirements for concurrent database access by multiple
  36093. ** readers and writers
  36094. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  36095. **
  36096. ** To address the performance and cache coherency issues, proxy file locking
  36097. ** changes the way database access is controlled by limiting access to a
  36098. ** single host at a time and moving file locks off of the database file
  36099. ** and onto a proxy file on the local file system.
  36100. **
  36101. **
  36102. ** Using proxy locks
  36103. ** -----------------
  36104. **
  36105. ** C APIs
  36106. **
  36107. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  36108. ** <proxy_path> | ":auto:");
  36109. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  36110. ** &<proxy_path>);
  36111. **
  36112. **
  36113. ** SQL pragmas
  36114. **
  36115. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  36116. ** PRAGMA [database.]lock_proxy_file
  36117. **
  36118. ** Specifying ":auto:" means that if there is a conch file with a matching
  36119. ** host ID in it, the proxy path in the conch file will be used, otherwise
  36120. ** a proxy path based on the user's temp dir
  36121. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  36122. ** actual proxy file name is generated from the name and path of the
  36123. ** database file. For example:
  36124. **
  36125. ** For database path "/Users/me/foo.db"
  36126. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  36127. **
  36128. ** Once a lock proxy is configured for a database connection, it can not
  36129. ** be removed, however it may be switched to a different proxy path via
  36130. ** the above APIs (assuming the conch file is not being held by another
  36131. ** connection or process).
  36132. **
  36133. **
  36134. ** How proxy locking works
  36135. ** -----------------------
  36136. **
  36137. ** Proxy file locking relies primarily on two new supporting files:
  36138. **
  36139. ** * conch file to limit access to the database file to a single host
  36140. ** at a time
  36141. **
  36142. ** * proxy file to act as a proxy for the advisory locks normally
  36143. ** taken on the database
  36144. **
  36145. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  36146. ** by taking an sqlite-style shared lock on the conch file, reading the
  36147. ** contents and comparing the host's unique host ID (see below) and lock
  36148. ** proxy path against the values stored in the conch. The conch file is
  36149. ** stored in the same directory as the database file and the file name
  36150. ** is patterned after the database file name as ".<databasename>-conch".
  36151. ** If the conch file does not exist, or its contents do not match the
  36152. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  36153. ** lock and the conch file contents is updated with the host ID and proxy
  36154. ** path and the lock is downgraded to a shared lock again. If the conch
  36155. ** is held by another process (with a shared lock), the exclusive lock
  36156. ** will fail and SQLITE_BUSY is returned.
  36157. **
  36158. ** The proxy file - a single-byte file used for all advisory file locks
  36159. ** normally taken on the database file. This allows for safe sharing
  36160. ** of the database file for multiple readers and writers on the same
  36161. ** host (the conch ensures that they all use the same local lock file).
  36162. **
  36163. ** Requesting the lock proxy does not immediately take the conch, it is
  36164. ** only taken when the first request to lock database file is made.
  36165. ** This matches the semantics of the traditional locking behavior, where
  36166. ** opening a connection to a database file does not take a lock on it.
  36167. ** The shared lock and an open file descriptor are maintained until
  36168. ** the connection to the database is closed.
  36169. **
  36170. ** The proxy file and the lock file are never deleted so they only need
  36171. ** to be created the first time they are used.
  36172. **
  36173. ** Configuration options
  36174. ** ---------------------
  36175. **
  36176. ** SQLITE_PREFER_PROXY_LOCKING
  36177. **
  36178. ** Database files accessed on non-local file systems are
  36179. ** automatically configured for proxy locking, lock files are
  36180. ** named automatically using the same logic as
  36181. ** PRAGMA lock_proxy_file=":auto:"
  36182. **
  36183. ** SQLITE_PROXY_DEBUG
  36184. **
  36185. ** Enables the logging of error messages during host id file
  36186. ** retrieval and creation
  36187. **
  36188. ** LOCKPROXYDIR
  36189. **
  36190. ** Overrides the default directory used for lock proxy files that
  36191. ** are named automatically via the ":auto:" setting
  36192. **
  36193. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  36194. **
  36195. ** Permissions to use when creating a directory for storing the
  36196. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  36197. **
  36198. **
  36199. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  36200. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  36201. ** force proxy locking to be used for every database file opened, and 0
  36202. ** will force automatic proxy locking to be disabled for all database
  36203. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  36204. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  36205. */
  36206. /*
  36207. ** Proxy locking is only available on MacOSX
  36208. */
  36209. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36210. /*
  36211. ** The proxyLockingContext has the path and file structures for the remote
  36212. ** and local proxy files in it
  36213. */
  36214. typedef struct proxyLockingContext proxyLockingContext;
  36215. struct proxyLockingContext {
  36216. unixFile *conchFile; /* Open conch file */
  36217. char *conchFilePath; /* Name of the conch file */
  36218. unixFile *lockProxy; /* Open proxy lock file */
  36219. char *lockProxyPath; /* Name of the proxy lock file */
  36220. char *dbPath; /* Name of the open file */
  36221. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  36222. int nFails; /* Number of conch taking failures */
  36223. void *oldLockingContext; /* Original lockingcontext to restore on close */
  36224. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  36225. };
  36226. /*
  36227. ** The proxy lock file path for the database at dbPath is written into lPath,
  36228. ** which must point to valid, writable memory large enough for a maxLen length
  36229. ** file path.
  36230. */
  36231. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  36232. int len;
  36233. int dbLen;
  36234. int i;
  36235. #ifdef LOCKPROXYDIR
  36236. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  36237. #else
  36238. # ifdef _CS_DARWIN_USER_TEMP_DIR
  36239. {
  36240. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  36241. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  36242. lPath, errno, osGetpid(0)));
  36243. return SQLITE_IOERR_LOCK;
  36244. }
  36245. len = strlcat(lPath, "sqliteplocks", maxLen);
  36246. }
  36247. # else
  36248. len = strlcpy(lPath, "/tmp/", maxLen);
  36249. # endif
  36250. #endif
  36251. if( lPath[len-1]!='/' ){
  36252. len = strlcat(lPath, "/", maxLen);
  36253. }
  36254. /* transform the db path to a unique cache name */
  36255. dbLen = (int)strlen(dbPath);
  36256. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  36257. char c = dbPath[i];
  36258. lPath[i+len] = (c=='/')?'_':c;
  36259. }
  36260. lPath[i+len]='\0';
  36261. strlcat(lPath, ":auto:", maxLen);
  36262. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  36263. return SQLITE_OK;
  36264. }
  36265. /*
  36266. ** Creates the lock file and any missing directories in lockPath
  36267. */
  36268. static int proxyCreateLockPath(const char *lockPath){
  36269. int i, len;
  36270. char buf[MAXPATHLEN];
  36271. int start = 0;
  36272. assert(lockPath!=NULL);
  36273. /* try to create all the intermediate directories */
  36274. len = (int)strlen(lockPath);
  36275. buf[0] = lockPath[0];
  36276. for( i=1; i<len; i++ ){
  36277. if( lockPath[i] == '/' && (i - start > 0) ){
  36278. /* only mkdir if leaf dir != "." or "/" or ".." */
  36279. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  36280. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  36281. buf[i]='\0';
  36282. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  36283. int err=errno;
  36284. if( err!=EEXIST ) {
  36285. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  36286. "'%s' proxy lock path=%s pid=%d\n",
  36287. buf, strerror(err), lockPath, osGetpid(0)));
  36288. return err;
  36289. }
  36290. }
  36291. }
  36292. start=i+1;
  36293. }
  36294. buf[i] = lockPath[i];
  36295. }
  36296. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  36297. return 0;
  36298. }
  36299. /*
  36300. ** Create a new VFS file descriptor (stored in memory obtained from
  36301. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  36302. **
  36303. ** The caller is responsible not only for closing the file descriptor
  36304. ** but also for freeing the memory associated with the file descriptor.
  36305. */
  36306. static int proxyCreateUnixFile(
  36307. const char *path, /* path for the new unixFile */
  36308. unixFile **ppFile, /* unixFile created and returned by ref */
  36309. int islockfile /* if non zero missing dirs will be created */
  36310. ) {
  36311. int fd = -1;
  36312. unixFile *pNew;
  36313. int rc = SQLITE_OK;
  36314. int openFlags = O_RDWR | O_CREAT;
  36315. sqlite3_vfs dummyVfs;
  36316. int terrno = 0;
  36317. UnixUnusedFd *pUnused = NULL;
  36318. /* 1. first try to open/create the file
  36319. ** 2. if that fails, and this is a lock file (not-conch), try creating
  36320. ** the parent directories and then try again.
  36321. ** 3. if that fails, try to open the file read-only
  36322. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  36323. */
  36324. pUnused = findReusableFd(path, openFlags);
  36325. if( pUnused ){
  36326. fd = pUnused->fd;
  36327. }else{
  36328. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  36329. if( !pUnused ){
  36330. return SQLITE_NOMEM_BKPT;
  36331. }
  36332. }
  36333. if( fd<0 ){
  36334. fd = robust_open(path, openFlags, 0);
  36335. terrno = errno;
  36336. if( fd<0 && errno==ENOENT && islockfile ){
  36337. if( proxyCreateLockPath(path) == SQLITE_OK ){
  36338. fd = robust_open(path, openFlags, 0);
  36339. }
  36340. }
  36341. }
  36342. if( fd<0 ){
  36343. openFlags = O_RDONLY;
  36344. fd = robust_open(path, openFlags, 0);
  36345. terrno = errno;
  36346. }
  36347. if( fd<0 ){
  36348. if( islockfile ){
  36349. return SQLITE_BUSY;
  36350. }
  36351. switch (terrno) {
  36352. case EACCES:
  36353. return SQLITE_PERM;
  36354. case EIO:
  36355. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  36356. default:
  36357. return SQLITE_CANTOPEN_BKPT;
  36358. }
  36359. }
  36360. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  36361. if( pNew==NULL ){
  36362. rc = SQLITE_NOMEM_BKPT;
  36363. goto end_create_proxy;
  36364. }
  36365. memset(pNew, 0, sizeof(unixFile));
  36366. pNew->openFlags = openFlags;
  36367. memset(&dummyVfs, 0, sizeof(dummyVfs));
  36368. dummyVfs.pAppData = (void*)&autolockIoFinder;
  36369. dummyVfs.zName = "dummy";
  36370. pUnused->fd = fd;
  36371. pUnused->flags = openFlags;
  36372. pNew->pPreallocatedUnused = pUnused;
  36373. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  36374. if( rc==SQLITE_OK ){
  36375. *ppFile = pNew;
  36376. return SQLITE_OK;
  36377. }
  36378. end_create_proxy:
  36379. robust_close(pNew, fd, __LINE__);
  36380. sqlite3_free(pNew);
  36381. sqlite3_free(pUnused);
  36382. return rc;
  36383. }
  36384. #ifdef SQLITE_TEST
  36385. /* simulate multiple hosts by creating unique hostid file paths */
  36386. SQLITE_API int sqlite3_hostid_num = 0;
  36387. #endif
  36388. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  36389. #ifdef HAVE_GETHOSTUUID
  36390. /* Not always defined in the headers as it ought to be */
  36391. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  36392. #endif
  36393. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  36394. ** bytes of writable memory.
  36395. */
  36396. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  36397. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  36398. memset(pHostID, 0, PROXY_HOSTIDLEN);
  36399. #ifdef HAVE_GETHOSTUUID
  36400. {
  36401. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  36402. if( gethostuuid(pHostID, &timeout) ){
  36403. int err = errno;
  36404. if( pError ){
  36405. *pError = err;
  36406. }
  36407. return SQLITE_IOERR;
  36408. }
  36409. }
  36410. #else
  36411. UNUSED_PARAMETER(pError);
  36412. #endif
  36413. #ifdef SQLITE_TEST
  36414. /* simulate multiple hosts by creating unique hostid file paths */
  36415. if( sqlite3_hostid_num != 0){
  36416. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  36417. }
  36418. #endif
  36419. return SQLITE_OK;
  36420. }
  36421. /* The conch file contains the header, host id and lock file path
  36422. */
  36423. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  36424. #define PROXY_HEADERLEN 1 /* conch file header length */
  36425. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  36426. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  36427. /*
  36428. ** Takes an open conch file, copies the contents to a new path and then moves
  36429. ** it back. The newly created file's file descriptor is assigned to the
  36430. ** conch file structure and finally the original conch file descriptor is
  36431. ** closed. Returns zero if successful.
  36432. */
  36433. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  36434. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36435. unixFile *conchFile = pCtx->conchFile;
  36436. char tPath[MAXPATHLEN];
  36437. char buf[PROXY_MAXCONCHLEN];
  36438. char *cPath = pCtx->conchFilePath;
  36439. size_t readLen = 0;
  36440. size_t pathLen = 0;
  36441. char errmsg[64] = "";
  36442. int fd = -1;
  36443. int rc = -1;
  36444. UNUSED_PARAMETER(myHostID);
  36445. /* create a new path by replace the trailing '-conch' with '-break' */
  36446. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  36447. if( pathLen>MAXPATHLEN || pathLen<6 ||
  36448. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  36449. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  36450. goto end_breaklock;
  36451. }
  36452. /* read the conch content */
  36453. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  36454. if( readLen<PROXY_PATHINDEX ){
  36455. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  36456. goto end_breaklock;
  36457. }
  36458. /* write it out to the temporary break file */
  36459. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  36460. if( fd<0 ){
  36461. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  36462. goto end_breaklock;
  36463. }
  36464. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  36465. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  36466. goto end_breaklock;
  36467. }
  36468. if( rename(tPath, cPath) ){
  36469. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  36470. goto end_breaklock;
  36471. }
  36472. rc = 0;
  36473. fprintf(stderr, "broke stale lock on %s\n", cPath);
  36474. robust_close(pFile, conchFile->h, __LINE__);
  36475. conchFile->h = fd;
  36476. conchFile->openFlags = O_RDWR | O_CREAT;
  36477. end_breaklock:
  36478. if( rc ){
  36479. if( fd>=0 ){
  36480. osUnlink(tPath);
  36481. robust_close(pFile, fd, __LINE__);
  36482. }
  36483. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  36484. }
  36485. return rc;
  36486. }
  36487. /* Take the requested lock on the conch file and break a stale lock if the
  36488. ** host id matches.
  36489. */
  36490. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  36491. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36492. unixFile *conchFile = pCtx->conchFile;
  36493. int rc = SQLITE_OK;
  36494. int nTries = 0;
  36495. struct timespec conchModTime;
  36496. memset(&conchModTime, 0, sizeof(conchModTime));
  36497. do {
  36498. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  36499. nTries ++;
  36500. if( rc==SQLITE_BUSY ){
  36501. /* If the lock failed (busy):
  36502. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  36503. * 2nd try: fail if the mod time changed or host id is different, wait
  36504. * 10 sec and try again
  36505. * 3rd try: break the lock unless the mod time has changed.
  36506. */
  36507. struct stat buf;
  36508. if( osFstat(conchFile->h, &buf) ){
  36509. storeLastErrno(pFile, errno);
  36510. return SQLITE_IOERR_LOCK;
  36511. }
  36512. if( nTries==1 ){
  36513. conchModTime = buf.st_mtimespec;
  36514. usleep(500000); /* wait 0.5 sec and try the lock again*/
  36515. continue;
  36516. }
  36517. assert( nTries>1 );
  36518. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  36519. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  36520. return SQLITE_BUSY;
  36521. }
  36522. if( nTries==2 ){
  36523. char tBuf[PROXY_MAXCONCHLEN];
  36524. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  36525. if( len<0 ){
  36526. storeLastErrno(pFile, errno);
  36527. return SQLITE_IOERR_LOCK;
  36528. }
  36529. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  36530. /* don't break the lock if the host id doesn't match */
  36531. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  36532. return SQLITE_BUSY;
  36533. }
  36534. }else{
  36535. /* don't break the lock on short read or a version mismatch */
  36536. return SQLITE_BUSY;
  36537. }
  36538. usleep(10000000); /* wait 10 sec and try the lock again */
  36539. continue;
  36540. }
  36541. assert( nTries==3 );
  36542. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  36543. rc = SQLITE_OK;
  36544. if( lockType==EXCLUSIVE_LOCK ){
  36545. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  36546. }
  36547. if( !rc ){
  36548. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  36549. }
  36550. }
  36551. }
  36552. } while( rc==SQLITE_BUSY && nTries<3 );
  36553. return rc;
  36554. }
  36555. /* Takes the conch by taking a shared lock and read the contents conch, if
  36556. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  36557. ** lockPath means that the lockPath in the conch file will be used if the
  36558. ** host IDs match, or a new lock path will be generated automatically
  36559. ** and written to the conch file.
  36560. */
  36561. static int proxyTakeConch(unixFile *pFile){
  36562. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36563. if( pCtx->conchHeld!=0 ){
  36564. return SQLITE_OK;
  36565. }else{
  36566. unixFile *conchFile = pCtx->conchFile;
  36567. uuid_t myHostID;
  36568. int pError = 0;
  36569. char readBuf[PROXY_MAXCONCHLEN];
  36570. char lockPath[MAXPATHLEN];
  36571. char *tempLockPath = NULL;
  36572. int rc = SQLITE_OK;
  36573. int createConch = 0;
  36574. int hostIdMatch = 0;
  36575. int readLen = 0;
  36576. int tryOldLockPath = 0;
  36577. int forceNewLockPath = 0;
  36578. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  36579. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  36580. osGetpid(0)));
  36581. rc = proxyGetHostID(myHostID, &pError);
  36582. if( (rc&0xff)==SQLITE_IOERR ){
  36583. storeLastErrno(pFile, pError);
  36584. goto end_takeconch;
  36585. }
  36586. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  36587. if( rc!=SQLITE_OK ){
  36588. goto end_takeconch;
  36589. }
  36590. /* read the existing conch file */
  36591. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  36592. if( readLen<0 ){
  36593. /* I/O error: lastErrno set by seekAndRead */
  36594. storeLastErrno(pFile, conchFile->lastErrno);
  36595. rc = SQLITE_IOERR_READ;
  36596. goto end_takeconch;
  36597. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  36598. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  36599. /* a short read or version format mismatch means we need to create a new
  36600. ** conch file.
  36601. */
  36602. createConch = 1;
  36603. }
  36604. /* if the host id matches and the lock path already exists in the conch
  36605. ** we'll try to use the path there, if we can't open that path, we'll
  36606. ** retry with a new auto-generated path
  36607. */
  36608. do { /* in case we need to try again for an :auto: named lock file */
  36609. if( !createConch && !forceNewLockPath ){
  36610. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  36611. PROXY_HOSTIDLEN);
  36612. /* if the conch has data compare the contents */
  36613. if( !pCtx->lockProxyPath ){
  36614. /* for auto-named local lock file, just check the host ID and we'll
  36615. ** use the local lock file path that's already in there
  36616. */
  36617. if( hostIdMatch ){
  36618. size_t pathLen = (readLen - PROXY_PATHINDEX);
  36619. if( pathLen>=MAXPATHLEN ){
  36620. pathLen=MAXPATHLEN-1;
  36621. }
  36622. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  36623. lockPath[pathLen] = 0;
  36624. tempLockPath = lockPath;
  36625. tryOldLockPath = 1;
  36626. /* create a copy of the lock path if the conch is taken */
  36627. goto end_takeconch;
  36628. }
  36629. }else if( hostIdMatch
  36630. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  36631. readLen-PROXY_PATHINDEX)
  36632. ){
  36633. /* conch host and lock path match */
  36634. goto end_takeconch;
  36635. }
  36636. }
  36637. /* if the conch isn't writable and doesn't match, we can't take it */
  36638. if( (conchFile->openFlags&O_RDWR) == 0 ){
  36639. rc = SQLITE_BUSY;
  36640. goto end_takeconch;
  36641. }
  36642. /* either the conch didn't match or we need to create a new one */
  36643. if( !pCtx->lockProxyPath ){
  36644. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  36645. tempLockPath = lockPath;
  36646. /* create a copy of the lock path _only_ if the conch is taken */
  36647. }
  36648. /* update conch with host and path (this will fail if other process
  36649. ** has a shared lock already), if the host id matches, use the big
  36650. ** stick.
  36651. */
  36652. futimes(conchFile->h, NULL);
  36653. if( hostIdMatch && !createConch ){
  36654. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  36655. /* We are trying for an exclusive lock but another thread in this
  36656. ** same process is still holding a shared lock. */
  36657. rc = SQLITE_BUSY;
  36658. } else {
  36659. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  36660. }
  36661. }else{
  36662. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  36663. }
  36664. if( rc==SQLITE_OK ){
  36665. char writeBuffer[PROXY_MAXCONCHLEN];
  36666. int writeSize = 0;
  36667. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  36668. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  36669. if( pCtx->lockProxyPath!=NULL ){
  36670. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  36671. MAXPATHLEN);
  36672. }else{
  36673. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  36674. }
  36675. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  36676. robust_ftruncate(conchFile->h, writeSize);
  36677. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  36678. full_fsync(conchFile->h,0,0);
  36679. /* If we created a new conch file (not just updated the contents of a
  36680. ** valid conch file), try to match the permissions of the database
  36681. */
  36682. if( rc==SQLITE_OK && createConch ){
  36683. struct stat buf;
  36684. int err = osFstat(pFile->h, &buf);
  36685. if( err==0 ){
  36686. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  36687. S_IROTH|S_IWOTH);
  36688. /* try to match the database file R/W permissions, ignore failure */
  36689. #ifndef SQLITE_PROXY_DEBUG
  36690. osFchmod(conchFile->h, cmode);
  36691. #else
  36692. do{
  36693. rc = osFchmod(conchFile->h, cmode);
  36694. }while( rc==(-1) && errno==EINTR );
  36695. if( rc!=0 ){
  36696. int code = errno;
  36697. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  36698. cmode, code, strerror(code));
  36699. } else {
  36700. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  36701. }
  36702. }else{
  36703. int code = errno;
  36704. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  36705. err, code, strerror(code));
  36706. #endif
  36707. }
  36708. }
  36709. }
  36710. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  36711. end_takeconch:
  36712. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  36713. if( rc==SQLITE_OK && pFile->openFlags ){
  36714. int fd;
  36715. if( pFile->h>=0 ){
  36716. robust_close(pFile, pFile->h, __LINE__);
  36717. }
  36718. pFile->h = -1;
  36719. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  36720. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  36721. if( fd>=0 ){
  36722. pFile->h = fd;
  36723. }else{
  36724. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  36725. during locking */
  36726. }
  36727. }
  36728. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  36729. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  36730. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  36731. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  36732. /* we couldn't create the proxy lock file with the old lock file path
  36733. ** so try again via auto-naming
  36734. */
  36735. forceNewLockPath = 1;
  36736. tryOldLockPath = 0;
  36737. continue; /* go back to the do {} while start point, try again */
  36738. }
  36739. }
  36740. if( rc==SQLITE_OK ){
  36741. /* Need to make a copy of path if we extracted the value
  36742. ** from the conch file or the path was allocated on the stack
  36743. */
  36744. if( tempLockPath ){
  36745. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  36746. if( !pCtx->lockProxyPath ){
  36747. rc = SQLITE_NOMEM_BKPT;
  36748. }
  36749. }
  36750. }
  36751. if( rc==SQLITE_OK ){
  36752. pCtx->conchHeld = 1;
  36753. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  36754. afpLockingContext *afpCtx;
  36755. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  36756. afpCtx->dbPath = pCtx->lockProxyPath;
  36757. }
  36758. } else {
  36759. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  36760. }
  36761. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  36762. rc==SQLITE_OK?"ok":"failed"));
  36763. return rc;
  36764. } while (1); /* in case we need to retry the :auto: lock file -
  36765. ** we should never get here except via the 'continue' call. */
  36766. }
  36767. }
  36768. /*
  36769. ** If pFile holds a lock on a conch file, then release that lock.
  36770. */
  36771. static int proxyReleaseConch(unixFile *pFile){
  36772. int rc = SQLITE_OK; /* Subroutine return code */
  36773. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  36774. unixFile *conchFile; /* Name of the conch file */
  36775. pCtx = (proxyLockingContext *)pFile->lockingContext;
  36776. conchFile = pCtx->conchFile;
  36777. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  36778. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  36779. osGetpid(0)));
  36780. if( pCtx->conchHeld>0 ){
  36781. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  36782. }
  36783. pCtx->conchHeld = 0;
  36784. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  36785. (rc==SQLITE_OK ? "ok" : "failed")));
  36786. return rc;
  36787. }
  36788. /*
  36789. ** Given the name of a database file, compute the name of its conch file.
  36790. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  36791. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  36792. ** or SQLITE_NOMEM if unable to obtain memory.
  36793. **
  36794. ** The caller is responsible for ensuring that the allocated memory
  36795. ** space is eventually freed.
  36796. **
  36797. ** *pConchPath is set to NULL if a memory allocation error occurs.
  36798. */
  36799. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  36800. int i; /* Loop counter */
  36801. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  36802. char *conchPath; /* buffer in which to construct conch name */
  36803. /* Allocate space for the conch filename and initialize the name to
  36804. ** the name of the original database file. */
  36805. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  36806. if( conchPath==0 ){
  36807. return SQLITE_NOMEM_BKPT;
  36808. }
  36809. memcpy(conchPath, dbPath, len+1);
  36810. /* now insert a "." before the last / character */
  36811. for( i=(len-1); i>=0; i-- ){
  36812. if( conchPath[i]=='/' ){
  36813. i++;
  36814. break;
  36815. }
  36816. }
  36817. conchPath[i]='.';
  36818. while ( i<len ){
  36819. conchPath[i+1]=dbPath[i];
  36820. i++;
  36821. }
  36822. /* append the "-conch" suffix to the file */
  36823. memcpy(&conchPath[i+1], "-conch", 7);
  36824. assert( (int)strlen(conchPath) == len+7 );
  36825. return SQLITE_OK;
  36826. }
  36827. /* Takes a fully configured proxy locking-style unix file and switches
  36828. ** the local lock file path
  36829. */
  36830. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  36831. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  36832. char *oldPath = pCtx->lockProxyPath;
  36833. int rc = SQLITE_OK;
  36834. if( pFile->eFileLock!=NO_LOCK ){
  36835. return SQLITE_BUSY;
  36836. }
  36837. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  36838. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  36839. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  36840. return SQLITE_OK;
  36841. }else{
  36842. unixFile *lockProxy = pCtx->lockProxy;
  36843. pCtx->lockProxy=NULL;
  36844. pCtx->conchHeld = 0;
  36845. if( lockProxy!=NULL ){
  36846. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  36847. if( rc ) return rc;
  36848. sqlite3_free(lockProxy);
  36849. }
  36850. sqlite3_free(oldPath);
  36851. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  36852. }
  36853. return rc;
  36854. }
  36855. /*
  36856. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  36857. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  36858. **
  36859. ** This routine find the filename associated with pFile and writes it
  36860. ** int dbPath.
  36861. */
  36862. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  36863. #if defined(__APPLE__)
  36864. if( pFile->pMethod == &afpIoMethods ){
  36865. /* afp style keeps a reference to the db path in the filePath field
  36866. ** of the struct */
  36867. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  36868. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  36869. MAXPATHLEN);
  36870. } else
  36871. #endif
  36872. if( pFile->pMethod == &dotlockIoMethods ){
  36873. /* dot lock style uses the locking context to store the dot lock
  36874. ** file path */
  36875. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  36876. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  36877. }else{
  36878. /* all other styles use the locking context to store the db file path */
  36879. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  36880. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  36881. }
  36882. return SQLITE_OK;
  36883. }
  36884. /*
  36885. ** Takes an already filled in unix file and alters it so all file locking
  36886. ** will be performed on the local proxy lock file. The following fields
  36887. ** are preserved in the locking context so that they can be restored and
  36888. ** the unix structure properly cleaned up at close time:
  36889. ** ->lockingContext
  36890. ** ->pMethod
  36891. */
  36892. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  36893. proxyLockingContext *pCtx;
  36894. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  36895. char *lockPath=NULL;
  36896. int rc = SQLITE_OK;
  36897. if( pFile->eFileLock!=NO_LOCK ){
  36898. return SQLITE_BUSY;
  36899. }
  36900. proxyGetDbPathForUnixFile(pFile, dbPath);
  36901. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  36902. lockPath=NULL;
  36903. }else{
  36904. lockPath=(char *)path;
  36905. }
  36906. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  36907. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  36908. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  36909. if( pCtx==0 ){
  36910. return SQLITE_NOMEM_BKPT;
  36911. }
  36912. memset(pCtx, 0, sizeof(*pCtx));
  36913. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  36914. if( rc==SQLITE_OK ){
  36915. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  36916. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  36917. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  36918. ** (c) the file system is read-only, then enable no-locking access.
  36919. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  36920. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  36921. */
  36922. struct statfs fsInfo;
  36923. struct stat conchInfo;
  36924. int goLockless = 0;
  36925. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  36926. int err = errno;
  36927. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  36928. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  36929. }
  36930. }
  36931. if( goLockless ){
  36932. pCtx->conchHeld = -1; /* read only FS/ lockless */
  36933. rc = SQLITE_OK;
  36934. }
  36935. }
  36936. }
  36937. if( rc==SQLITE_OK && lockPath ){
  36938. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  36939. }
  36940. if( rc==SQLITE_OK ){
  36941. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  36942. if( pCtx->dbPath==NULL ){
  36943. rc = SQLITE_NOMEM_BKPT;
  36944. }
  36945. }
  36946. if( rc==SQLITE_OK ){
  36947. /* all memory is allocated, proxys are created and assigned,
  36948. ** switch the locking context and pMethod then return.
  36949. */
  36950. pCtx->oldLockingContext = pFile->lockingContext;
  36951. pFile->lockingContext = pCtx;
  36952. pCtx->pOldMethod = pFile->pMethod;
  36953. pFile->pMethod = &proxyIoMethods;
  36954. }else{
  36955. if( pCtx->conchFile ){
  36956. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  36957. sqlite3_free(pCtx->conchFile);
  36958. }
  36959. sqlite3DbFree(0, pCtx->lockProxyPath);
  36960. sqlite3_free(pCtx->conchFilePath);
  36961. sqlite3_free(pCtx);
  36962. }
  36963. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  36964. (rc==SQLITE_OK ? "ok" : "failed")));
  36965. return rc;
  36966. }
  36967. /*
  36968. ** This routine handles sqlite3_file_control() calls that are specific
  36969. ** to proxy locking.
  36970. */
  36971. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  36972. switch( op ){
  36973. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  36974. unixFile *pFile = (unixFile*)id;
  36975. if( pFile->pMethod == &proxyIoMethods ){
  36976. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  36977. proxyTakeConch(pFile);
  36978. if( pCtx->lockProxyPath ){
  36979. *(const char **)pArg = pCtx->lockProxyPath;
  36980. }else{
  36981. *(const char **)pArg = ":auto: (not held)";
  36982. }
  36983. } else {
  36984. *(const char **)pArg = NULL;
  36985. }
  36986. return SQLITE_OK;
  36987. }
  36988. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  36989. unixFile *pFile = (unixFile*)id;
  36990. int rc = SQLITE_OK;
  36991. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  36992. if( pArg==NULL || (const char *)pArg==0 ){
  36993. if( isProxyStyle ){
  36994. /* turn off proxy locking - not supported. If support is added for
  36995. ** switching proxy locking mode off then it will need to fail if
  36996. ** the journal mode is WAL mode.
  36997. */
  36998. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  36999. }else{
  37000. /* turn off proxy locking - already off - NOOP */
  37001. rc = SQLITE_OK;
  37002. }
  37003. }else{
  37004. const char *proxyPath = (const char *)pArg;
  37005. if( isProxyStyle ){
  37006. proxyLockingContext *pCtx =
  37007. (proxyLockingContext*)pFile->lockingContext;
  37008. if( !strcmp(pArg, ":auto:")
  37009. || (pCtx->lockProxyPath &&
  37010. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  37011. ){
  37012. rc = SQLITE_OK;
  37013. }else{
  37014. rc = switchLockProxyPath(pFile, proxyPath);
  37015. }
  37016. }else{
  37017. /* turn on proxy file locking */
  37018. rc = proxyTransformUnixFile(pFile, proxyPath);
  37019. }
  37020. }
  37021. return rc;
  37022. }
  37023. default: {
  37024. assert( 0 ); /* The call assures that only valid opcodes are sent */
  37025. }
  37026. }
  37027. /*NOTREACHED*/
  37028. return SQLITE_ERROR;
  37029. }
  37030. /*
  37031. ** Within this division (the proxying locking implementation) the procedures
  37032. ** above this point are all utilities. The lock-related methods of the
  37033. ** proxy-locking sqlite3_io_method object follow.
  37034. */
  37035. /*
  37036. ** This routine checks if there is a RESERVED lock held on the specified
  37037. ** file by this or any other process. If such a lock is held, set *pResOut
  37038. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  37039. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  37040. */
  37041. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  37042. unixFile *pFile = (unixFile*)id;
  37043. int rc = proxyTakeConch(pFile);
  37044. if( rc==SQLITE_OK ){
  37045. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37046. if( pCtx->conchHeld>0 ){
  37047. unixFile *proxy = pCtx->lockProxy;
  37048. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  37049. }else{ /* conchHeld < 0 is lockless */
  37050. pResOut=0;
  37051. }
  37052. }
  37053. return rc;
  37054. }
  37055. /*
  37056. ** Lock the file with the lock specified by parameter eFileLock - one
  37057. ** of the following:
  37058. **
  37059. ** (1) SHARED_LOCK
  37060. ** (2) RESERVED_LOCK
  37061. ** (3) PENDING_LOCK
  37062. ** (4) EXCLUSIVE_LOCK
  37063. **
  37064. ** Sometimes when requesting one lock state, additional lock states
  37065. ** are inserted in between. The locking might fail on one of the later
  37066. ** transitions leaving the lock state different from what it started but
  37067. ** still short of its goal. The following chart shows the allowed
  37068. ** transitions and the inserted intermediate states:
  37069. **
  37070. ** UNLOCKED -> SHARED
  37071. ** SHARED -> RESERVED
  37072. ** SHARED -> (PENDING) -> EXCLUSIVE
  37073. ** RESERVED -> (PENDING) -> EXCLUSIVE
  37074. ** PENDING -> EXCLUSIVE
  37075. **
  37076. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  37077. ** routine to lower a locking level.
  37078. */
  37079. static int proxyLock(sqlite3_file *id, int eFileLock) {
  37080. unixFile *pFile = (unixFile*)id;
  37081. int rc = proxyTakeConch(pFile);
  37082. if( rc==SQLITE_OK ){
  37083. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37084. if( pCtx->conchHeld>0 ){
  37085. unixFile *proxy = pCtx->lockProxy;
  37086. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  37087. pFile->eFileLock = proxy->eFileLock;
  37088. }else{
  37089. /* conchHeld < 0 is lockless */
  37090. }
  37091. }
  37092. return rc;
  37093. }
  37094. /*
  37095. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  37096. ** must be either NO_LOCK or SHARED_LOCK.
  37097. **
  37098. ** If the locking level of the file descriptor is already at or below
  37099. ** the requested locking level, this routine is a no-op.
  37100. */
  37101. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  37102. unixFile *pFile = (unixFile*)id;
  37103. int rc = proxyTakeConch(pFile);
  37104. if( rc==SQLITE_OK ){
  37105. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37106. if( pCtx->conchHeld>0 ){
  37107. unixFile *proxy = pCtx->lockProxy;
  37108. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  37109. pFile->eFileLock = proxy->eFileLock;
  37110. }else{
  37111. /* conchHeld < 0 is lockless */
  37112. }
  37113. }
  37114. return rc;
  37115. }
  37116. /*
  37117. ** Close a file that uses proxy locks.
  37118. */
  37119. static int proxyClose(sqlite3_file *id) {
  37120. if( ALWAYS(id) ){
  37121. unixFile *pFile = (unixFile*)id;
  37122. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37123. unixFile *lockProxy = pCtx->lockProxy;
  37124. unixFile *conchFile = pCtx->conchFile;
  37125. int rc = SQLITE_OK;
  37126. if( lockProxy ){
  37127. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  37128. if( rc ) return rc;
  37129. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  37130. if( rc ) return rc;
  37131. sqlite3_free(lockProxy);
  37132. pCtx->lockProxy = 0;
  37133. }
  37134. if( conchFile ){
  37135. if( pCtx->conchHeld ){
  37136. rc = proxyReleaseConch(pFile);
  37137. if( rc ) return rc;
  37138. }
  37139. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  37140. if( rc ) return rc;
  37141. sqlite3_free(conchFile);
  37142. }
  37143. sqlite3DbFree(0, pCtx->lockProxyPath);
  37144. sqlite3_free(pCtx->conchFilePath);
  37145. sqlite3DbFree(0, pCtx->dbPath);
  37146. /* restore the original locking context and pMethod then close it */
  37147. pFile->lockingContext = pCtx->oldLockingContext;
  37148. pFile->pMethod = pCtx->pOldMethod;
  37149. sqlite3_free(pCtx);
  37150. return pFile->pMethod->xClose(id);
  37151. }
  37152. return SQLITE_OK;
  37153. }
  37154. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  37155. /*
  37156. ** The proxy locking style is intended for use with AFP filesystems.
  37157. ** And since AFP is only supported on MacOSX, the proxy locking is also
  37158. ** restricted to MacOSX.
  37159. **
  37160. **
  37161. ******************* End of the proxy lock implementation **********************
  37162. ******************************************************************************/
  37163. /*
  37164. ** Initialize the operating system interface.
  37165. **
  37166. ** This routine registers all VFS implementations for unix-like operating
  37167. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  37168. ** should be the only routines in this file that are visible from other
  37169. ** files.
  37170. **
  37171. ** This routine is called once during SQLite initialization and by a
  37172. ** single thread. The memory allocation and mutex subsystems have not
  37173. ** necessarily been initialized when this routine is called, and so they
  37174. ** should not be used.
  37175. */
  37176. SQLITE_API int sqlite3_os_init(void){
  37177. /*
  37178. ** The following macro defines an initializer for an sqlite3_vfs object.
  37179. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  37180. ** to the "finder" function. (pAppData is a pointer to a pointer because
  37181. ** silly C90 rules prohibit a void* from being cast to a function pointer
  37182. ** and so we have to go through the intermediate pointer to avoid problems
  37183. ** when compiling with -pedantic-errors on GCC.)
  37184. **
  37185. ** The FINDER parameter to this macro is the name of the pointer to the
  37186. ** finder-function. The finder-function returns a pointer to the
  37187. ** sqlite_io_methods object that implements the desired locking
  37188. ** behaviors. See the division above that contains the IOMETHODS
  37189. ** macro for addition information on finder-functions.
  37190. **
  37191. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  37192. ** object. But the "autolockIoFinder" available on MacOSX does a little
  37193. ** more than that; it looks at the filesystem type that hosts the
  37194. ** database file and tries to choose an locking method appropriate for
  37195. ** that filesystem time.
  37196. */
  37197. #define UNIXVFS(VFSNAME, FINDER) { \
  37198. 3, /* iVersion */ \
  37199. sizeof(unixFile), /* szOsFile */ \
  37200. MAX_PATHNAME, /* mxPathname */ \
  37201. 0, /* pNext */ \
  37202. VFSNAME, /* zName */ \
  37203. (void*)&FINDER, /* pAppData */ \
  37204. unixOpen, /* xOpen */ \
  37205. unixDelete, /* xDelete */ \
  37206. unixAccess, /* xAccess */ \
  37207. unixFullPathname, /* xFullPathname */ \
  37208. unixDlOpen, /* xDlOpen */ \
  37209. unixDlError, /* xDlError */ \
  37210. unixDlSym, /* xDlSym */ \
  37211. unixDlClose, /* xDlClose */ \
  37212. unixRandomness, /* xRandomness */ \
  37213. unixSleep, /* xSleep */ \
  37214. unixCurrentTime, /* xCurrentTime */ \
  37215. unixGetLastError, /* xGetLastError */ \
  37216. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  37217. unixSetSystemCall, /* xSetSystemCall */ \
  37218. unixGetSystemCall, /* xGetSystemCall */ \
  37219. unixNextSystemCall, /* xNextSystemCall */ \
  37220. }
  37221. /*
  37222. ** All default VFSes for unix are contained in the following array.
  37223. **
  37224. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  37225. ** by the SQLite core when the VFS is registered. So the following
  37226. ** array cannot be const.
  37227. */
  37228. static sqlite3_vfs aVfs[] = {
  37229. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  37230. UNIXVFS("unix", autolockIoFinder ),
  37231. #elif OS_VXWORKS
  37232. UNIXVFS("unix", vxworksIoFinder ),
  37233. #else
  37234. UNIXVFS("unix", posixIoFinder ),
  37235. #endif
  37236. UNIXVFS("unix-none", nolockIoFinder ),
  37237. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  37238. UNIXVFS("unix-excl", posixIoFinder ),
  37239. #if OS_VXWORKS
  37240. UNIXVFS("unix-namedsem", semIoFinder ),
  37241. #endif
  37242. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  37243. UNIXVFS("unix-posix", posixIoFinder ),
  37244. #endif
  37245. #if SQLITE_ENABLE_LOCKING_STYLE
  37246. UNIXVFS("unix-flock", flockIoFinder ),
  37247. #endif
  37248. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  37249. UNIXVFS("unix-afp", afpIoFinder ),
  37250. UNIXVFS("unix-nfs", nfsIoFinder ),
  37251. UNIXVFS("unix-proxy", proxyIoFinder ),
  37252. #endif
  37253. };
  37254. unsigned int i; /* Loop counter */
  37255. /* Double-check that the aSyscall[] array has been constructed
  37256. ** correctly. See ticket [bb3a86e890c8e96ab] */
  37257. assert( ArraySize(aSyscall)==29 );
  37258. /* Register all VFSes defined in the aVfs[] array */
  37259. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  37260. sqlite3_vfs_register(&aVfs[i], i==0);
  37261. }
  37262. unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  37263. return SQLITE_OK;
  37264. }
  37265. /*
  37266. ** Shutdown the operating system interface.
  37267. **
  37268. ** Some operating systems might need to do some cleanup in this routine,
  37269. ** to release dynamically allocated objects. But not on unix.
  37270. ** This routine is a no-op for unix.
  37271. */
  37272. SQLITE_API int sqlite3_os_end(void){
  37273. unixBigLock = 0;
  37274. return SQLITE_OK;
  37275. }
  37276. #endif /* SQLITE_OS_UNIX */
  37277. /************** End of os_unix.c *********************************************/
  37278. /************** Begin file os_win.c ******************************************/
  37279. /*
  37280. ** 2004 May 22
  37281. **
  37282. ** The author disclaims copyright to this source code. In place of
  37283. ** a legal notice, here is a blessing:
  37284. **
  37285. ** May you do good and not evil.
  37286. ** May you find forgiveness for yourself and forgive others.
  37287. ** May you share freely, never taking more than you give.
  37288. **
  37289. ******************************************************************************
  37290. **
  37291. ** This file contains code that is specific to Windows.
  37292. */
  37293. /* #include "sqliteInt.h" */
  37294. #if SQLITE_OS_WIN /* This file is used for Windows only */
  37295. /*
  37296. ** Include code that is common to all os_*.c files
  37297. */
  37298. /************** Include os_common.h in the middle of os_win.c ****************/
  37299. /************** Begin file os_common.h ***************************************/
  37300. /*
  37301. ** 2004 May 22
  37302. **
  37303. ** The author disclaims copyright to this source code. In place of
  37304. ** a legal notice, here is a blessing:
  37305. **
  37306. ** May you do good and not evil.
  37307. ** May you find forgiveness for yourself and forgive others.
  37308. ** May you share freely, never taking more than you give.
  37309. **
  37310. ******************************************************************************
  37311. **
  37312. ** This file contains macros and a little bit of code that is common to
  37313. ** all of the platform-specific files (os_*.c) and is #included into those
  37314. ** files.
  37315. **
  37316. ** This file should be #included by the os_*.c files only. It is not a
  37317. ** general purpose header file.
  37318. */
  37319. #ifndef _OS_COMMON_H_
  37320. #define _OS_COMMON_H_
  37321. /*
  37322. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  37323. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  37324. ** switch. The following code should catch this problem at compile-time.
  37325. */
  37326. #ifdef MEMORY_DEBUG
  37327. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  37328. #endif
  37329. /*
  37330. ** Macros for performance tracing. Normally turned off. Only works
  37331. ** on i486 hardware.
  37332. */
  37333. #ifdef SQLITE_PERFORMANCE_TRACE
  37334. /*
  37335. ** hwtime.h contains inline assembler code for implementing
  37336. ** high-performance timing routines.
  37337. */
  37338. /************** Include hwtime.h in the middle of os_common.h ****************/
  37339. /************** Begin file hwtime.h ******************************************/
  37340. /*
  37341. ** 2008 May 27
  37342. **
  37343. ** The author disclaims copyright to this source code. In place of
  37344. ** a legal notice, here is a blessing:
  37345. **
  37346. ** May you do good and not evil.
  37347. ** May you find forgiveness for yourself and forgive others.
  37348. ** May you share freely, never taking more than you give.
  37349. **
  37350. ******************************************************************************
  37351. **
  37352. ** This file contains inline asm code for retrieving "high-performance"
  37353. ** counters for x86 class CPUs.
  37354. */
  37355. #ifndef SQLITE_HWTIME_H
  37356. #define SQLITE_HWTIME_H
  37357. /*
  37358. ** The following routine only works on pentium-class (or newer) processors.
  37359. ** It uses the RDTSC opcode to read the cycle count value out of the
  37360. ** processor and returns that value. This can be used for high-res
  37361. ** profiling.
  37362. */
  37363. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  37364. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  37365. #if defined(__GNUC__)
  37366. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  37367. unsigned int lo, hi;
  37368. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  37369. return (sqlite_uint64)hi << 32 | lo;
  37370. }
  37371. #elif defined(_MSC_VER)
  37372. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  37373. __asm {
  37374. rdtsc
  37375. ret ; return value at EDX:EAX
  37376. }
  37377. }
  37378. #endif
  37379. #elif (defined(__GNUC__) && defined(__x86_64__))
  37380. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  37381. unsigned long val;
  37382. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  37383. return val;
  37384. }
  37385. #elif (defined(__GNUC__) && defined(__ppc__))
  37386. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  37387. unsigned long long retval;
  37388. unsigned long junk;
  37389. __asm__ __volatile__ ("\n\
  37390. 1: mftbu %1\n\
  37391. mftb %L0\n\
  37392. mftbu %0\n\
  37393. cmpw %0,%1\n\
  37394. bne 1b"
  37395. : "=r" (retval), "=r" (junk));
  37396. return retval;
  37397. }
  37398. #else
  37399. #error Need implementation of sqlite3Hwtime() for your platform.
  37400. /*
  37401. ** To compile without implementing sqlite3Hwtime() for your platform,
  37402. ** you can remove the above #error and use the following
  37403. ** stub function. You will lose timing support for many
  37404. ** of the debugging and testing utilities, but it should at
  37405. ** least compile and run.
  37406. */
  37407. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  37408. #endif
  37409. #endif /* !defined(SQLITE_HWTIME_H) */
  37410. /************** End of hwtime.h **********************************************/
  37411. /************** Continuing where we left off in os_common.h ******************/
  37412. static sqlite_uint64 g_start;
  37413. static sqlite_uint64 g_elapsed;
  37414. #define TIMER_START g_start=sqlite3Hwtime()
  37415. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  37416. #define TIMER_ELAPSED g_elapsed
  37417. #else
  37418. #define TIMER_START
  37419. #define TIMER_END
  37420. #define TIMER_ELAPSED ((sqlite_uint64)0)
  37421. #endif
  37422. /*
  37423. ** If we compile with the SQLITE_TEST macro set, then the following block
  37424. ** of code will give us the ability to simulate a disk I/O error. This
  37425. ** is used for testing the I/O recovery logic.
  37426. */
  37427. #if defined(SQLITE_TEST)
  37428. SQLITE_API extern int sqlite3_io_error_hit;
  37429. SQLITE_API extern int sqlite3_io_error_hardhit;
  37430. SQLITE_API extern int sqlite3_io_error_pending;
  37431. SQLITE_API extern int sqlite3_io_error_persist;
  37432. SQLITE_API extern int sqlite3_io_error_benign;
  37433. SQLITE_API extern int sqlite3_diskfull_pending;
  37434. SQLITE_API extern int sqlite3_diskfull;
  37435. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  37436. #define SimulateIOError(CODE) \
  37437. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  37438. || sqlite3_io_error_pending-- == 1 ) \
  37439. { local_ioerr(); CODE; }
  37440. static void local_ioerr(){
  37441. IOTRACE(("IOERR\n"));
  37442. sqlite3_io_error_hit++;
  37443. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  37444. }
  37445. #define SimulateDiskfullError(CODE) \
  37446. if( sqlite3_diskfull_pending ){ \
  37447. if( sqlite3_diskfull_pending == 1 ){ \
  37448. local_ioerr(); \
  37449. sqlite3_diskfull = 1; \
  37450. sqlite3_io_error_hit = 1; \
  37451. CODE; \
  37452. }else{ \
  37453. sqlite3_diskfull_pending--; \
  37454. } \
  37455. }
  37456. #else
  37457. #define SimulateIOErrorBenign(X)
  37458. #define SimulateIOError(A)
  37459. #define SimulateDiskfullError(A)
  37460. #endif /* defined(SQLITE_TEST) */
  37461. /*
  37462. ** When testing, keep a count of the number of open files.
  37463. */
  37464. #if defined(SQLITE_TEST)
  37465. SQLITE_API extern int sqlite3_open_file_count;
  37466. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  37467. #else
  37468. #define OpenCounter(X)
  37469. #endif /* defined(SQLITE_TEST) */
  37470. #endif /* !defined(_OS_COMMON_H_) */
  37471. /************** End of os_common.h *******************************************/
  37472. /************** Continuing where we left off in os_win.c *********************/
  37473. /*
  37474. ** Include the header file for the Windows VFS.
  37475. */
  37476. /* #include "os_win.h" */
  37477. /*
  37478. ** Compiling and using WAL mode requires several APIs that are only
  37479. ** available in Windows platforms based on the NT kernel.
  37480. */
  37481. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  37482. # error "WAL mode requires support from the Windows NT kernel, compile\
  37483. with SQLITE_OMIT_WAL."
  37484. #endif
  37485. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  37486. # error "Memory mapped files require support from the Windows NT kernel,\
  37487. compile with SQLITE_MAX_MMAP_SIZE=0."
  37488. #endif
  37489. /*
  37490. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  37491. ** based on the sub-platform)?
  37492. */
  37493. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  37494. # define SQLITE_WIN32_HAS_ANSI
  37495. #endif
  37496. /*
  37497. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  37498. ** based on the sub-platform)?
  37499. */
  37500. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  37501. !defined(SQLITE_WIN32_NO_WIDE)
  37502. # define SQLITE_WIN32_HAS_WIDE
  37503. #endif
  37504. /*
  37505. ** Make sure at least one set of Win32 APIs is available.
  37506. */
  37507. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  37508. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  37509. must be defined."
  37510. #endif
  37511. /*
  37512. ** Define the required Windows SDK version constants if they are not
  37513. ** already available.
  37514. */
  37515. #ifndef NTDDI_WIN8
  37516. # define NTDDI_WIN8 0x06020000
  37517. #endif
  37518. #ifndef NTDDI_WINBLUE
  37519. # define NTDDI_WINBLUE 0x06030000
  37520. #endif
  37521. #ifndef NTDDI_WINTHRESHOLD
  37522. # define NTDDI_WINTHRESHOLD 0x06040000
  37523. #endif
  37524. /*
  37525. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  37526. ** target system. GetVersionEx was first deprecated in Win8.1.
  37527. */
  37528. #ifndef SQLITE_WIN32_GETVERSIONEX
  37529. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  37530. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  37531. # else
  37532. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  37533. # endif
  37534. #endif
  37535. /*
  37536. ** Check to see if the CreateFileMappingA function is supported on the
  37537. ** target system. It is unavailable when using "mincore.lib" on Win10.
  37538. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  37539. */
  37540. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  37541. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  37542. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  37543. # else
  37544. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  37545. # endif
  37546. #endif
  37547. /*
  37548. ** This constant should already be defined (in the "WinDef.h" SDK file).
  37549. */
  37550. #ifndef MAX_PATH
  37551. # define MAX_PATH (260)
  37552. #endif
  37553. /*
  37554. ** Maximum pathname length (in chars) for Win32. This should normally be
  37555. ** MAX_PATH.
  37556. */
  37557. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  37558. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  37559. #endif
  37560. /*
  37561. ** This constant should already be defined (in the "WinNT.h" SDK file).
  37562. */
  37563. #ifndef UNICODE_STRING_MAX_CHARS
  37564. # define UNICODE_STRING_MAX_CHARS (32767)
  37565. #endif
  37566. /*
  37567. ** Maximum pathname length (in chars) for WinNT. This should normally be
  37568. ** UNICODE_STRING_MAX_CHARS.
  37569. */
  37570. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  37571. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  37572. #endif
  37573. /*
  37574. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  37575. ** characters, so we allocate 4 bytes per character assuming worst-case of
  37576. ** 4-bytes-per-character for UTF8.
  37577. */
  37578. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  37579. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  37580. #endif
  37581. /*
  37582. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  37583. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  37584. */
  37585. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  37586. # define SQLITE_WINNT_MAX_PATH_BYTES \
  37587. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  37588. #endif
  37589. /*
  37590. ** Maximum error message length (in chars) for WinRT.
  37591. */
  37592. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  37593. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  37594. #endif
  37595. /*
  37596. ** Returns non-zero if the character should be treated as a directory
  37597. ** separator.
  37598. */
  37599. #ifndef winIsDirSep
  37600. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  37601. #endif
  37602. /*
  37603. ** This macro is used when a local variable is set to a value that is
  37604. ** [sometimes] not used by the code (e.g. via conditional compilation).
  37605. */
  37606. #ifndef UNUSED_VARIABLE_VALUE
  37607. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  37608. #endif
  37609. /*
  37610. ** Returns the character that should be used as the directory separator.
  37611. */
  37612. #ifndef winGetDirSep
  37613. # define winGetDirSep() '\\'
  37614. #endif
  37615. /*
  37616. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  37617. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  37618. ** CE SDK; however, they are not present in the header file)?
  37619. */
  37620. #if SQLITE_WIN32_FILEMAPPING_API && \
  37621. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  37622. /*
  37623. ** Two of the file mapping APIs are different under WinRT. Figure out which
  37624. ** set we need.
  37625. */
  37626. #if SQLITE_OS_WINRT
  37627. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  37628. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  37629. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  37630. #else
  37631. #if defined(SQLITE_WIN32_HAS_ANSI)
  37632. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  37633. DWORD, DWORD, DWORD, LPCSTR);
  37634. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  37635. #if defined(SQLITE_WIN32_HAS_WIDE)
  37636. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  37637. DWORD, DWORD, DWORD, LPCWSTR);
  37638. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  37639. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  37640. #endif /* SQLITE_OS_WINRT */
  37641. /*
  37642. ** These file mapping APIs are common to both Win32 and WinRT.
  37643. */
  37644. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  37645. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  37646. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  37647. /*
  37648. ** Some Microsoft compilers lack this definition.
  37649. */
  37650. #ifndef INVALID_FILE_ATTRIBUTES
  37651. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  37652. #endif
  37653. #ifndef FILE_FLAG_MASK
  37654. # define FILE_FLAG_MASK (0xFF3C0000)
  37655. #endif
  37656. #ifndef FILE_ATTRIBUTE_MASK
  37657. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  37658. #endif
  37659. #ifndef SQLITE_OMIT_WAL
  37660. /* Forward references to structures used for WAL */
  37661. typedef struct winShm winShm; /* A connection to shared-memory */
  37662. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  37663. #endif
  37664. /*
  37665. ** WinCE lacks native support for file locking so we have to fake it
  37666. ** with some code of our own.
  37667. */
  37668. #if SQLITE_OS_WINCE
  37669. typedef struct winceLock {
  37670. int nReaders; /* Number of reader locks obtained */
  37671. BOOL bPending; /* Indicates a pending lock has been obtained */
  37672. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  37673. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  37674. } winceLock;
  37675. #endif
  37676. /*
  37677. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  37678. ** portability layer.
  37679. */
  37680. typedef struct winFile winFile;
  37681. struct winFile {
  37682. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  37683. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  37684. HANDLE h; /* Handle for accessing the file */
  37685. u8 locktype; /* Type of lock currently held on this file */
  37686. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  37687. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  37688. DWORD lastErrno; /* The Windows errno from the last I/O error */
  37689. #ifndef SQLITE_OMIT_WAL
  37690. winShm *pShm; /* Instance of shared memory on this file */
  37691. #endif
  37692. const char *zPath; /* Full pathname of this file */
  37693. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  37694. #if SQLITE_OS_WINCE
  37695. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  37696. HANDLE hMutex; /* Mutex used to control access to shared lock */
  37697. HANDLE hShared; /* Shared memory segment used for locking */
  37698. winceLock local; /* Locks obtained by this instance of winFile */
  37699. winceLock *shared; /* Global shared lock memory for the file */
  37700. #endif
  37701. #if SQLITE_MAX_MMAP_SIZE>0
  37702. int nFetchOut; /* Number of outstanding xFetch references */
  37703. HANDLE hMap; /* Handle for accessing memory mapping */
  37704. void *pMapRegion; /* Area memory mapped */
  37705. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  37706. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  37707. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  37708. #endif
  37709. };
  37710. /*
  37711. ** The winVfsAppData structure is used for the pAppData member for all of the
  37712. ** Win32 VFS variants.
  37713. */
  37714. typedef struct winVfsAppData winVfsAppData;
  37715. struct winVfsAppData {
  37716. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  37717. void *pAppData; /* The extra pAppData, if any. */
  37718. BOOL bNoLock; /* Non-zero if locking is disabled. */
  37719. };
  37720. /*
  37721. ** Allowed values for winFile.ctrlFlags
  37722. */
  37723. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  37724. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  37725. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  37726. /*
  37727. * The size of the buffer used by sqlite3_win32_write_debug().
  37728. */
  37729. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  37730. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  37731. #endif
  37732. /*
  37733. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  37734. * various Win32 API heap functions instead of our own.
  37735. */
  37736. #ifdef SQLITE_WIN32_MALLOC
  37737. /*
  37738. * If this is non-zero, an isolated heap will be created by the native Win32
  37739. * allocator subsystem; otherwise, the default process heap will be used. This
  37740. * setting has no effect when compiling for WinRT. By default, this is enabled
  37741. * and an isolated heap will be created to store all allocated data.
  37742. *
  37743. ******************************************************************************
  37744. * WARNING: It is important to note that when this setting is non-zero and the
  37745. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  37746. * function), all data that was allocated using the isolated heap will
  37747. * be freed immediately and any attempt to access any of that freed
  37748. * data will almost certainly result in an immediate access violation.
  37749. ******************************************************************************
  37750. */
  37751. #ifndef SQLITE_WIN32_HEAP_CREATE
  37752. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  37753. #endif
  37754. /*
  37755. * This is the maximum possible initial size of the Win32-specific heap, in
  37756. * bytes.
  37757. */
  37758. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  37759. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  37760. #endif
  37761. /*
  37762. * This is the extra space for the initial size of the Win32-specific heap,
  37763. * in bytes. This value may be zero.
  37764. */
  37765. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  37766. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  37767. #endif
  37768. /*
  37769. * Calculate the maximum legal cache size, in pages, based on the maximum
  37770. * possible initial heap size and the default page size, setting aside the
  37771. * needed extra space.
  37772. */
  37773. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  37774. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  37775. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  37776. (SQLITE_DEFAULT_PAGE_SIZE))
  37777. #endif
  37778. /*
  37779. * This is cache size used in the calculation of the initial size of the
  37780. * Win32-specific heap. It cannot be negative.
  37781. */
  37782. #ifndef SQLITE_WIN32_CACHE_SIZE
  37783. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  37784. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  37785. # else
  37786. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  37787. # endif
  37788. #endif
  37789. /*
  37790. * Make sure that the calculated cache size, in pages, cannot cause the
  37791. * initial size of the Win32-specific heap to exceed the maximum amount
  37792. * of memory that can be specified in the call to HeapCreate.
  37793. */
  37794. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  37795. # undef SQLITE_WIN32_CACHE_SIZE
  37796. # define SQLITE_WIN32_CACHE_SIZE (2000)
  37797. #endif
  37798. /*
  37799. * The initial size of the Win32-specific heap. This value may be zero.
  37800. */
  37801. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  37802. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  37803. (SQLITE_DEFAULT_PAGE_SIZE) + \
  37804. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  37805. #endif
  37806. /*
  37807. * The maximum size of the Win32-specific heap. This value may be zero.
  37808. */
  37809. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  37810. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  37811. #endif
  37812. /*
  37813. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  37814. * zero for the default behavior.
  37815. */
  37816. #ifndef SQLITE_WIN32_HEAP_FLAGS
  37817. # define SQLITE_WIN32_HEAP_FLAGS (0)
  37818. #endif
  37819. /*
  37820. ** The winMemData structure stores information required by the Win32-specific
  37821. ** sqlite3_mem_methods implementation.
  37822. */
  37823. typedef struct winMemData winMemData;
  37824. struct winMemData {
  37825. #ifndef NDEBUG
  37826. u32 magic1; /* Magic number to detect structure corruption. */
  37827. #endif
  37828. HANDLE hHeap; /* The handle to our heap. */
  37829. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  37830. #ifndef NDEBUG
  37831. u32 magic2; /* Magic number to detect structure corruption. */
  37832. #endif
  37833. };
  37834. #ifndef NDEBUG
  37835. #define WINMEM_MAGIC1 0x42b2830b
  37836. #define WINMEM_MAGIC2 0xbd4d7cf4
  37837. #endif
  37838. static struct winMemData win_mem_data = {
  37839. #ifndef NDEBUG
  37840. WINMEM_MAGIC1,
  37841. #endif
  37842. NULL, FALSE
  37843. #ifndef NDEBUG
  37844. ,WINMEM_MAGIC2
  37845. #endif
  37846. };
  37847. #ifndef NDEBUG
  37848. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  37849. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  37850. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  37851. #else
  37852. #define winMemAssertMagic()
  37853. #endif
  37854. #define winMemGetDataPtr() &win_mem_data
  37855. #define winMemGetHeap() win_mem_data.hHeap
  37856. #define winMemGetOwned() win_mem_data.bOwned
  37857. static void *winMemMalloc(int nBytes);
  37858. static void winMemFree(void *pPrior);
  37859. static void *winMemRealloc(void *pPrior, int nBytes);
  37860. static int winMemSize(void *p);
  37861. static int winMemRoundup(int n);
  37862. static int winMemInit(void *pAppData);
  37863. static void winMemShutdown(void *pAppData);
  37864. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  37865. #endif /* SQLITE_WIN32_MALLOC */
  37866. /*
  37867. ** The following variable is (normally) set once and never changes
  37868. ** thereafter. It records whether the operating system is Win9x
  37869. ** or WinNT.
  37870. **
  37871. ** 0: Operating system unknown.
  37872. ** 1: Operating system is Win9x.
  37873. ** 2: Operating system is WinNT.
  37874. **
  37875. ** In order to facilitate testing on a WinNT system, the test fixture
  37876. ** can manually set this value to 1 to emulate Win98 behavior.
  37877. */
  37878. #ifdef SQLITE_TEST
  37879. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  37880. #else
  37881. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  37882. #endif
  37883. #ifndef SYSCALL
  37884. # define SYSCALL sqlite3_syscall_ptr
  37885. #endif
  37886. /*
  37887. ** This function is not available on Windows CE or WinRT.
  37888. */
  37889. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  37890. # define osAreFileApisANSI() 1
  37891. #endif
  37892. /*
  37893. ** Many system calls are accessed through pointer-to-functions so that
  37894. ** they may be overridden at runtime to facilitate fault injection during
  37895. ** testing and sandboxing. The following array holds the names and pointers
  37896. ** to all overrideable system calls.
  37897. */
  37898. static struct win_syscall {
  37899. const char *zName; /* Name of the system call */
  37900. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  37901. sqlite3_syscall_ptr pDefault; /* Default value */
  37902. } aSyscall[] = {
  37903. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  37904. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  37905. #else
  37906. { "AreFileApisANSI", (SYSCALL)0, 0 },
  37907. #endif
  37908. #ifndef osAreFileApisANSI
  37909. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  37910. #endif
  37911. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  37912. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  37913. #else
  37914. { "CharLowerW", (SYSCALL)0, 0 },
  37915. #endif
  37916. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  37917. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  37918. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  37919. #else
  37920. { "CharUpperW", (SYSCALL)0, 0 },
  37921. #endif
  37922. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  37923. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  37924. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  37925. #if defined(SQLITE_WIN32_HAS_ANSI)
  37926. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  37927. #else
  37928. { "CreateFileA", (SYSCALL)0, 0 },
  37929. #endif
  37930. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  37931. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  37932. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37933. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  37934. #else
  37935. { "CreateFileW", (SYSCALL)0, 0 },
  37936. #endif
  37937. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  37938. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  37939. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  37940. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  37941. SQLITE_WIN32_CREATEFILEMAPPINGA
  37942. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  37943. #else
  37944. { "CreateFileMappingA", (SYSCALL)0, 0 },
  37945. #endif
  37946. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  37947. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  37948. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  37949. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  37950. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  37951. #else
  37952. { "CreateFileMappingW", (SYSCALL)0, 0 },
  37953. #endif
  37954. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  37955. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  37956. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37957. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  37958. #else
  37959. { "CreateMutexW", (SYSCALL)0, 0 },
  37960. #endif
  37961. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  37962. LPCWSTR))aSyscall[8].pCurrent)
  37963. #if defined(SQLITE_WIN32_HAS_ANSI)
  37964. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  37965. #else
  37966. { "DeleteFileA", (SYSCALL)0, 0 },
  37967. #endif
  37968. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  37969. #if defined(SQLITE_WIN32_HAS_WIDE)
  37970. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  37971. #else
  37972. { "DeleteFileW", (SYSCALL)0, 0 },
  37973. #endif
  37974. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  37975. #if SQLITE_OS_WINCE
  37976. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  37977. #else
  37978. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  37979. #endif
  37980. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  37981. LPFILETIME))aSyscall[11].pCurrent)
  37982. #if SQLITE_OS_WINCE
  37983. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  37984. #else
  37985. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  37986. #endif
  37987. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  37988. LPSYSTEMTIME))aSyscall[12].pCurrent)
  37989. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  37990. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  37991. #if defined(SQLITE_WIN32_HAS_ANSI)
  37992. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  37993. #else
  37994. { "FormatMessageA", (SYSCALL)0, 0 },
  37995. #endif
  37996. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  37997. DWORD,va_list*))aSyscall[14].pCurrent)
  37998. #if defined(SQLITE_WIN32_HAS_WIDE)
  37999. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  38000. #else
  38001. { "FormatMessageW", (SYSCALL)0, 0 },
  38002. #endif
  38003. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  38004. DWORD,va_list*))aSyscall[15].pCurrent)
  38005. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38006. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  38007. #else
  38008. { "FreeLibrary", (SYSCALL)0, 0 },
  38009. #endif
  38010. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  38011. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  38012. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  38013. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  38014. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  38015. #else
  38016. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  38017. #endif
  38018. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  38019. LPDWORD))aSyscall[18].pCurrent)
  38020. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38021. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  38022. #else
  38023. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  38024. #endif
  38025. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  38026. LPDWORD))aSyscall[19].pCurrent)
  38027. #if defined(SQLITE_WIN32_HAS_ANSI)
  38028. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  38029. #else
  38030. { "GetFileAttributesA", (SYSCALL)0, 0 },
  38031. #endif
  38032. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  38033. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38034. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  38035. #else
  38036. { "GetFileAttributesW", (SYSCALL)0, 0 },
  38037. #endif
  38038. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  38039. #if defined(SQLITE_WIN32_HAS_WIDE)
  38040. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  38041. #else
  38042. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  38043. #endif
  38044. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  38045. LPVOID))aSyscall[22].pCurrent)
  38046. #if !SQLITE_OS_WINRT
  38047. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  38048. #else
  38049. { "GetFileSize", (SYSCALL)0, 0 },
  38050. #endif
  38051. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  38052. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  38053. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  38054. #else
  38055. { "GetFullPathNameA", (SYSCALL)0, 0 },
  38056. #endif
  38057. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  38058. LPSTR*))aSyscall[24].pCurrent)
  38059. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38060. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  38061. #else
  38062. { "GetFullPathNameW", (SYSCALL)0, 0 },
  38063. #endif
  38064. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  38065. LPWSTR*))aSyscall[25].pCurrent)
  38066. { "GetLastError", (SYSCALL)GetLastError, 0 },
  38067. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  38068. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38069. #if SQLITE_OS_WINCE
  38070. /* The GetProcAddressA() routine is only available on Windows CE. */
  38071. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  38072. #else
  38073. /* All other Windows platforms expect GetProcAddress() to take
  38074. ** an ANSI string regardless of the _UNICODE setting */
  38075. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  38076. #endif
  38077. #else
  38078. { "GetProcAddressA", (SYSCALL)0, 0 },
  38079. #endif
  38080. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  38081. LPCSTR))aSyscall[27].pCurrent)
  38082. #if !SQLITE_OS_WINRT
  38083. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  38084. #else
  38085. { "GetSystemInfo", (SYSCALL)0, 0 },
  38086. #endif
  38087. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  38088. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  38089. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  38090. #if !SQLITE_OS_WINCE
  38091. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  38092. #else
  38093. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  38094. #endif
  38095. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  38096. LPFILETIME))aSyscall[30].pCurrent)
  38097. #if defined(SQLITE_WIN32_HAS_ANSI)
  38098. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  38099. #else
  38100. { "GetTempPathA", (SYSCALL)0, 0 },
  38101. #endif
  38102. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  38103. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38104. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  38105. #else
  38106. { "GetTempPathW", (SYSCALL)0, 0 },
  38107. #endif
  38108. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  38109. #if !SQLITE_OS_WINRT
  38110. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  38111. #else
  38112. { "GetTickCount", (SYSCALL)0, 0 },
  38113. #endif
  38114. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  38115. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  38116. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  38117. #else
  38118. { "GetVersionExA", (SYSCALL)0, 0 },
  38119. #endif
  38120. #define osGetVersionExA ((BOOL(WINAPI*)( \
  38121. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  38122. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  38123. SQLITE_WIN32_GETVERSIONEX
  38124. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  38125. #else
  38126. { "GetVersionExW", (SYSCALL)0, 0 },
  38127. #endif
  38128. #define osGetVersionExW ((BOOL(WINAPI*)( \
  38129. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  38130. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  38131. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  38132. SIZE_T))aSyscall[36].pCurrent)
  38133. #if !SQLITE_OS_WINRT
  38134. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  38135. #else
  38136. { "HeapCreate", (SYSCALL)0, 0 },
  38137. #endif
  38138. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  38139. SIZE_T))aSyscall[37].pCurrent)
  38140. #if !SQLITE_OS_WINRT
  38141. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  38142. #else
  38143. { "HeapDestroy", (SYSCALL)0, 0 },
  38144. #endif
  38145. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  38146. { "HeapFree", (SYSCALL)HeapFree, 0 },
  38147. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  38148. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  38149. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  38150. SIZE_T))aSyscall[40].pCurrent)
  38151. { "HeapSize", (SYSCALL)HeapSize, 0 },
  38152. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  38153. LPCVOID))aSyscall[41].pCurrent)
  38154. #if !SQLITE_OS_WINRT
  38155. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  38156. #else
  38157. { "HeapValidate", (SYSCALL)0, 0 },
  38158. #endif
  38159. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  38160. LPCVOID))aSyscall[42].pCurrent)
  38161. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38162. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  38163. #else
  38164. { "HeapCompact", (SYSCALL)0, 0 },
  38165. #endif
  38166. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  38167. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38168. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  38169. #else
  38170. { "LoadLibraryA", (SYSCALL)0, 0 },
  38171. #endif
  38172. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  38173. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  38174. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38175. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  38176. #else
  38177. { "LoadLibraryW", (SYSCALL)0, 0 },
  38178. #endif
  38179. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  38180. #if !SQLITE_OS_WINRT
  38181. { "LocalFree", (SYSCALL)LocalFree, 0 },
  38182. #else
  38183. { "LocalFree", (SYSCALL)0, 0 },
  38184. #endif
  38185. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  38186. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38187. { "LockFile", (SYSCALL)LockFile, 0 },
  38188. #else
  38189. { "LockFile", (SYSCALL)0, 0 },
  38190. #endif
  38191. #ifndef osLockFile
  38192. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38193. DWORD))aSyscall[47].pCurrent)
  38194. #endif
  38195. #if !SQLITE_OS_WINCE
  38196. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  38197. #else
  38198. { "LockFileEx", (SYSCALL)0, 0 },
  38199. #endif
  38200. #ifndef osLockFileEx
  38201. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  38202. LPOVERLAPPED))aSyscall[48].pCurrent)
  38203. #endif
  38204. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  38205. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  38206. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  38207. #else
  38208. { "MapViewOfFile", (SYSCALL)0, 0 },
  38209. #endif
  38210. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38211. SIZE_T))aSyscall[49].pCurrent)
  38212. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  38213. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  38214. int))aSyscall[50].pCurrent)
  38215. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  38216. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  38217. LARGE_INTEGER*))aSyscall[51].pCurrent)
  38218. { "ReadFile", (SYSCALL)ReadFile, 0 },
  38219. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  38220. LPOVERLAPPED))aSyscall[52].pCurrent)
  38221. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  38222. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  38223. #if !SQLITE_OS_WINRT
  38224. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  38225. #else
  38226. { "SetFilePointer", (SYSCALL)0, 0 },
  38227. #endif
  38228. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  38229. DWORD))aSyscall[54].pCurrent)
  38230. #if !SQLITE_OS_WINRT
  38231. { "Sleep", (SYSCALL)Sleep, 0 },
  38232. #else
  38233. { "Sleep", (SYSCALL)0, 0 },
  38234. #endif
  38235. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  38236. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  38237. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  38238. LPFILETIME))aSyscall[56].pCurrent)
  38239. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38240. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  38241. #else
  38242. { "UnlockFile", (SYSCALL)0, 0 },
  38243. #endif
  38244. #ifndef osUnlockFile
  38245. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38246. DWORD))aSyscall[57].pCurrent)
  38247. #endif
  38248. #if !SQLITE_OS_WINCE
  38249. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  38250. #else
  38251. { "UnlockFileEx", (SYSCALL)0, 0 },
  38252. #endif
  38253. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  38254. LPOVERLAPPED))aSyscall[58].pCurrent)
  38255. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  38256. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  38257. #else
  38258. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  38259. #endif
  38260. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  38261. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  38262. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  38263. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  38264. { "WriteFile", (SYSCALL)WriteFile, 0 },
  38265. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  38266. LPOVERLAPPED))aSyscall[61].pCurrent)
  38267. #if SQLITE_OS_WINRT
  38268. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  38269. #else
  38270. { "CreateEventExW", (SYSCALL)0, 0 },
  38271. #endif
  38272. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  38273. DWORD,DWORD))aSyscall[62].pCurrent)
  38274. #if !SQLITE_OS_WINRT
  38275. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  38276. #else
  38277. { "WaitForSingleObject", (SYSCALL)0, 0 },
  38278. #endif
  38279. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  38280. DWORD))aSyscall[63].pCurrent)
  38281. #if !SQLITE_OS_WINCE
  38282. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  38283. #else
  38284. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  38285. #endif
  38286. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  38287. BOOL))aSyscall[64].pCurrent)
  38288. #if SQLITE_OS_WINRT
  38289. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  38290. #else
  38291. { "SetFilePointerEx", (SYSCALL)0, 0 },
  38292. #endif
  38293. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  38294. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  38295. #if SQLITE_OS_WINRT
  38296. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  38297. #else
  38298. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  38299. #endif
  38300. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  38301. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  38302. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  38303. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  38304. #else
  38305. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  38306. #endif
  38307. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  38308. SIZE_T))aSyscall[67].pCurrent)
  38309. #if SQLITE_OS_WINRT
  38310. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  38311. #else
  38312. { "CreateFile2", (SYSCALL)0, 0 },
  38313. #endif
  38314. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  38315. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  38316. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38317. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  38318. #else
  38319. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  38320. #endif
  38321. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  38322. DWORD))aSyscall[69].pCurrent)
  38323. #if SQLITE_OS_WINRT
  38324. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  38325. #else
  38326. { "GetTickCount64", (SYSCALL)0, 0 },
  38327. #endif
  38328. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  38329. #if SQLITE_OS_WINRT
  38330. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  38331. #else
  38332. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  38333. #endif
  38334. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  38335. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  38336. #if defined(SQLITE_WIN32_HAS_ANSI)
  38337. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  38338. #else
  38339. { "OutputDebugStringA", (SYSCALL)0, 0 },
  38340. #endif
  38341. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  38342. #if defined(SQLITE_WIN32_HAS_WIDE)
  38343. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  38344. #else
  38345. { "OutputDebugStringW", (SYSCALL)0, 0 },
  38346. #endif
  38347. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  38348. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  38349. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  38350. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  38351. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  38352. #else
  38353. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  38354. #endif
  38355. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  38356. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  38357. /*
  38358. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  38359. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  38360. ** So do not try to make this is into a redefinable interface.
  38361. */
  38362. #if defined(InterlockedCompareExchange)
  38363. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  38364. #define osInterlockedCompareExchange InterlockedCompareExchange
  38365. #else
  38366. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  38367. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  38368. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  38369. #endif /* defined(InterlockedCompareExchange) */
  38370. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  38371. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  38372. #else
  38373. { "UuidCreate", (SYSCALL)0, 0 },
  38374. #endif
  38375. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  38376. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  38377. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  38378. #else
  38379. { "UuidCreateSequential", (SYSCALL)0, 0 },
  38380. #endif
  38381. #define osUuidCreateSequential \
  38382. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  38383. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  38384. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  38385. #else
  38386. { "FlushViewOfFile", (SYSCALL)0, 0 },
  38387. #endif
  38388. #define osFlushViewOfFile \
  38389. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  38390. }; /* End of the overrideable system calls */
  38391. /*
  38392. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  38393. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  38394. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  38395. ** system call named zName.
  38396. */
  38397. static int winSetSystemCall(
  38398. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  38399. const char *zName, /* Name of system call to override */
  38400. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  38401. ){
  38402. unsigned int i;
  38403. int rc = SQLITE_NOTFOUND;
  38404. UNUSED_PARAMETER(pNotUsed);
  38405. if( zName==0 ){
  38406. /* If no zName is given, restore all system calls to their default
  38407. ** settings and return NULL
  38408. */
  38409. rc = SQLITE_OK;
  38410. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  38411. if( aSyscall[i].pDefault ){
  38412. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  38413. }
  38414. }
  38415. }else{
  38416. /* If zName is specified, operate on only the one system call
  38417. ** specified.
  38418. */
  38419. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  38420. if( strcmp(zName, aSyscall[i].zName)==0 ){
  38421. if( aSyscall[i].pDefault==0 ){
  38422. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  38423. }
  38424. rc = SQLITE_OK;
  38425. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  38426. aSyscall[i].pCurrent = pNewFunc;
  38427. break;
  38428. }
  38429. }
  38430. }
  38431. return rc;
  38432. }
  38433. /*
  38434. ** Return the value of a system call. Return NULL if zName is not a
  38435. ** recognized system call name. NULL is also returned if the system call
  38436. ** is currently undefined.
  38437. */
  38438. static sqlite3_syscall_ptr winGetSystemCall(
  38439. sqlite3_vfs *pNotUsed,
  38440. const char *zName
  38441. ){
  38442. unsigned int i;
  38443. UNUSED_PARAMETER(pNotUsed);
  38444. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  38445. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  38446. }
  38447. return 0;
  38448. }
  38449. /*
  38450. ** Return the name of the first system call after zName. If zName==NULL
  38451. ** then return the name of the first system call. Return NULL if zName
  38452. ** is the last system call or if zName is not the name of a valid
  38453. ** system call.
  38454. */
  38455. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  38456. int i = -1;
  38457. UNUSED_PARAMETER(p);
  38458. if( zName ){
  38459. for(i=0; i<ArraySize(aSyscall)-1; i++){
  38460. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  38461. }
  38462. }
  38463. for(i++; i<ArraySize(aSyscall); i++){
  38464. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  38465. }
  38466. return 0;
  38467. }
  38468. #ifdef SQLITE_WIN32_MALLOC
  38469. /*
  38470. ** If a Win32 native heap has been configured, this function will attempt to
  38471. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  38472. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  38473. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  38474. ** largest committed free block in the heap, in bytes.
  38475. */
  38476. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  38477. int rc = SQLITE_OK;
  38478. UINT nLargest = 0;
  38479. HANDLE hHeap;
  38480. winMemAssertMagic();
  38481. hHeap = winMemGetHeap();
  38482. assert( hHeap!=0 );
  38483. assert( hHeap!=INVALID_HANDLE_VALUE );
  38484. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38485. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38486. #endif
  38487. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38488. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  38489. DWORD lastErrno = osGetLastError();
  38490. if( lastErrno==NO_ERROR ){
  38491. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  38492. (void*)hHeap);
  38493. rc = SQLITE_NOMEM_BKPT;
  38494. }else{
  38495. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  38496. osGetLastError(), (void*)hHeap);
  38497. rc = SQLITE_ERROR;
  38498. }
  38499. }
  38500. #else
  38501. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  38502. (void*)hHeap);
  38503. rc = SQLITE_NOTFOUND;
  38504. #endif
  38505. if( pnLargest ) *pnLargest = nLargest;
  38506. return rc;
  38507. }
  38508. /*
  38509. ** If a Win32 native heap has been configured, this function will attempt to
  38510. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  38511. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  38512. ** be returned and no changes will be made to the Win32 native heap.
  38513. */
  38514. SQLITE_API int sqlite3_win32_reset_heap(){
  38515. int rc;
  38516. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  38517. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  38518. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  38519. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  38520. sqlite3_mutex_enter(pMaster);
  38521. sqlite3_mutex_enter(pMem);
  38522. winMemAssertMagic();
  38523. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  38524. /*
  38525. ** At this point, there should be no outstanding memory allocations on
  38526. ** the heap. Also, since both the master and memsys locks are currently
  38527. ** being held by us, no other function (i.e. from another thread) should
  38528. ** be able to even access the heap. Attempt to destroy and recreate our
  38529. ** isolated Win32 native heap now.
  38530. */
  38531. assert( winMemGetHeap()!=NULL );
  38532. assert( winMemGetOwned() );
  38533. assert( sqlite3_memory_used()==0 );
  38534. winMemShutdown(winMemGetDataPtr());
  38535. assert( winMemGetHeap()==NULL );
  38536. assert( !winMemGetOwned() );
  38537. assert( sqlite3_memory_used()==0 );
  38538. rc = winMemInit(winMemGetDataPtr());
  38539. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  38540. assert( rc!=SQLITE_OK || winMemGetOwned() );
  38541. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  38542. }else{
  38543. /*
  38544. ** The Win32 native heap cannot be modified because it may be in use.
  38545. */
  38546. rc = SQLITE_BUSY;
  38547. }
  38548. sqlite3_mutex_leave(pMem);
  38549. sqlite3_mutex_leave(pMaster);
  38550. return rc;
  38551. }
  38552. #endif /* SQLITE_WIN32_MALLOC */
  38553. /*
  38554. ** This function outputs the specified (ANSI) string to the Win32 debugger
  38555. ** (if available).
  38556. */
  38557. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  38558. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  38559. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  38560. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  38561. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  38562. #ifdef SQLITE_ENABLE_API_ARMOR
  38563. if( !zBuf ){
  38564. (void)SQLITE_MISUSE_BKPT;
  38565. return;
  38566. }
  38567. #endif
  38568. #if defined(SQLITE_WIN32_HAS_ANSI)
  38569. if( nMin>0 ){
  38570. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  38571. memcpy(zDbgBuf, zBuf, nMin);
  38572. osOutputDebugStringA(zDbgBuf);
  38573. }else{
  38574. osOutputDebugStringA(zBuf);
  38575. }
  38576. #elif defined(SQLITE_WIN32_HAS_WIDE)
  38577. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  38578. if ( osMultiByteToWideChar(
  38579. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  38580. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  38581. return;
  38582. }
  38583. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  38584. #else
  38585. if( nMin>0 ){
  38586. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  38587. memcpy(zDbgBuf, zBuf, nMin);
  38588. fprintf(stderr, "%s", zDbgBuf);
  38589. }else{
  38590. fprintf(stderr, "%s", zBuf);
  38591. }
  38592. #endif
  38593. }
  38594. /*
  38595. ** The following routine suspends the current thread for at least ms
  38596. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  38597. */
  38598. #if SQLITE_OS_WINRT
  38599. static HANDLE sleepObj = NULL;
  38600. #endif
  38601. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  38602. #if SQLITE_OS_WINRT
  38603. if ( sleepObj==NULL ){
  38604. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  38605. SYNCHRONIZE);
  38606. }
  38607. assert( sleepObj!=NULL );
  38608. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  38609. #else
  38610. osSleep(milliseconds);
  38611. #endif
  38612. }
  38613. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  38614. SQLITE_THREADSAFE>0
  38615. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  38616. DWORD rc;
  38617. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  38618. TRUE))==WAIT_IO_COMPLETION ){}
  38619. return rc;
  38620. }
  38621. #endif
  38622. /*
  38623. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  38624. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  38625. **
  38626. ** Here is an interesting observation: Win95, Win98, and WinME lack
  38627. ** the LockFileEx() API. But we can still statically link against that
  38628. ** API as long as we don't call it when running Win95/98/ME. A call to
  38629. ** this routine is used to determine if the host is Win95/98/ME or
  38630. ** WinNT/2K/XP so that we will know whether or not we can safely call
  38631. ** the LockFileEx() API.
  38632. */
  38633. #if !SQLITE_WIN32_GETVERSIONEX
  38634. # define osIsNT() (1)
  38635. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  38636. # define osIsNT() (1)
  38637. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  38638. # define osIsNT() (0)
  38639. #else
  38640. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  38641. #endif
  38642. /*
  38643. ** This function determines if the machine is running a version of Windows
  38644. ** based on the NT kernel.
  38645. */
  38646. SQLITE_API int sqlite3_win32_is_nt(void){
  38647. #if SQLITE_OS_WINRT
  38648. /*
  38649. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  38650. ** kernel.
  38651. */
  38652. return 1;
  38653. #elif SQLITE_WIN32_GETVERSIONEX
  38654. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  38655. #if defined(SQLITE_WIN32_HAS_ANSI)
  38656. OSVERSIONINFOA sInfo;
  38657. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  38658. osGetVersionExA(&sInfo);
  38659. osInterlockedCompareExchange(&sqlite3_os_type,
  38660. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  38661. #elif defined(SQLITE_WIN32_HAS_WIDE)
  38662. OSVERSIONINFOW sInfo;
  38663. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  38664. osGetVersionExW(&sInfo);
  38665. osInterlockedCompareExchange(&sqlite3_os_type,
  38666. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  38667. #endif
  38668. }
  38669. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  38670. #elif SQLITE_TEST
  38671. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  38672. #else
  38673. /*
  38674. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  38675. ** deprecated are always assumed to be based on the NT kernel.
  38676. */
  38677. return 1;
  38678. #endif
  38679. }
  38680. #ifdef SQLITE_WIN32_MALLOC
  38681. /*
  38682. ** Allocate nBytes of memory.
  38683. */
  38684. static void *winMemMalloc(int nBytes){
  38685. HANDLE hHeap;
  38686. void *p;
  38687. winMemAssertMagic();
  38688. hHeap = winMemGetHeap();
  38689. assert( hHeap!=0 );
  38690. assert( hHeap!=INVALID_HANDLE_VALUE );
  38691. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38692. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38693. #endif
  38694. assert( nBytes>=0 );
  38695. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  38696. if( !p ){
  38697. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  38698. nBytes, osGetLastError(), (void*)hHeap);
  38699. }
  38700. return p;
  38701. }
  38702. /*
  38703. ** Free memory.
  38704. */
  38705. static void winMemFree(void *pPrior){
  38706. HANDLE hHeap;
  38707. winMemAssertMagic();
  38708. hHeap = winMemGetHeap();
  38709. assert( hHeap!=0 );
  38710. assert( hHeap!=INVALID_HANDLE_VALUE );
  38711. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38712. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  38713. #endif
  38714. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  38715. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  38716. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  38717. pPrior, osGetLastError(), (void*)hHeap);
  38718. }
  38719. }
  38720. /*
  38721. ** Change the size of an existing memory allocation
  38722. */
  38723. static void *winMemRealloc(void *pPrior, int nBytes){
  38724. HANDLE hHeap;
  38725. void *p;
  38726. winMemAssertMagic();
  38727. hHeap = winMemGetHeap();
  38728. assert( hHeap!=0 );
  38729. assert( hHeap!=INVALID_HANDLE_VALUE );
  38730. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38731. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  38732. #endif
  38733. assert( nBytes>=0 );
  38734. if( !pPrior ){
  38735. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  38736. }else{
  38737. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  38738. }
  38739. if( !p ){
  38740. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  38741. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  38742. (void*)hHeap);
  38743. }
  38744. return p;
  38745. }
  38746. /*
  38747. ** Return the size of an outstanding allocation, in bytes.
  38748. */
  38749. static int winMemSize(void *p){
  38750. HANDLE hHeap;
  38751. SIZE_T n;
  38752. winMemAssertMagic();
  38753. hHeap = winMemGetHeap();
  38754. assert( hHeap!=0 );
  38755. assert( hHeap!=INVALID_HANDLE_VALUE );
  38756. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38757. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  38758. #endif
  38759. if( !p ) return 0;
  38760. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  38761. if( n==(SIZE_T)-1 ){
  38762. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  38763. p, osGetLastError(), (void*)hHeap);
  38764. return 0;
  38765. }
  38766. return (int)n;
  38767. }
  38768. /*
  38769. ** Round up a request size to the next valid allocation size.
  38770. */
  38771. static int winMemRoundup(int n){
  38772. return n;
  38773. }
  38774. /*
  38775. ** Initialize this module.
  38776. */
  38777. static int winMemInit(void *pAppData){
  38778. winMemData *pWinMemData = (winMemData *)pAppData;
  38779. if( !pWinMemData ) return SQLITE_ERROR;
  38780. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  38781. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  38782. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  38783. if( !pWinMemData->hHeap ){
  38784. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  38785. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  38786. if( dwMaximumSize==0 ){
  38787. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  38788. }else if( dwInitialSize>dwMaximumSize ){
  38789. dwInitialSize = dwMaximumSize;
  38790. }
  38791. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  38792. dwInitialSize, dwMaximumSize);
  38793. if( !pWinMemData->hHeap ){
  38794. sqlite3_log(SQLITE_NOMEM,
  38795. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  38796. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  38797. dwMaximumSize);
  38798. return SQLITE_NOMEM_BKPT;
  38799. }
  38800. pWinMemData->bOwned = TRUE;
  38801. assert( pWinMemData->bOwned );
  38802. }
  38803. #else
  38804. pWinMemData->hHeap = osGetProcessHeap();
  38805. if( !pWinMemData->hHeap ){
  38806. sqlite3_log(SQLITE_NOMEM,
  38807. "failed to GetProcessHeap (%lu)", osGetLastError());
  38808. return SQLITE_NOMEM_BKPT;
  38809. }
  38810. pWinMemData->bOwned = FALSE;
  38811. assert( !pWinMemData->bOwned );
  38812. #endif
  38813. assert( pWinMemData->hHeap!=0 );
  38814. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  38815. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38816. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38817. #endif
  38818. return SQLITE_OK;
  38819. }
  38820. /*
  38821. ** Deinitialize this module.
  38822. */
  38823. static void winMemShutdown(void *pAppData){
  38824. winMemData *pWinMemData = (winMemData *)pAppData;
  38825. if( !pWinMemData ) return;
  38826. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  38827. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  38828. if( pWinMemData->hHeap ){
  38829. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  38830. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38831. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38832. #endif
  38833. if( pWinMemData->bOwned ){
  38834. if( !osHeapDestroy(pWinMemData->hHeap) ){
  38835. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  38836. osGetLastError(), (void*)pWinMemData->hHeap);
  38837. }
  38838. pWinMemData->bOwned = FALSE;
  38839. }
  38840. pWinMemData->hHeap = NULL;
  38841. }
  38842. }
  38843. /*
  38844. ** Populate the low-level memory allocation function pointers in
  38845. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  38846. ** arguments specify the block of memory to manage.
  38847. **
  38848. ** This routine is only called by sqlite3_config(), and therefore
  38849. ** is not required to be threadsafe (it is not).
  38850. */
  38851. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  38852. static const sqlite3_mem_methods winMemMethods = {
  38853. winMemMalloc,
  38854. winMemFree,
  38855. winMemRealloc,
  38856. winMemSize,
  38857. winMemRoundup,
  38858. winMemInit,
  38859. winMemShutdown,
  38860. &win_mem_data
  38861. };
  38862. return &winMemMethods;
  38863. }
  38864. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  38865. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  38866. }
  38867. #endif /* SQLITE_WIN32_MALLOC */
  38868. /*
  38869. ** Convert a UTF-8 string to Microsoft Unicode.
  38870. **
  38871. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38872. */
  38873. static LPWSTR winUtf8ToUnicode(const char *zText){
  38874. int nChar;
  38875. LPWSTR zWideText;
  38876. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  38877. if( nChar==0 ){
  38878. return 0;
  38879. }
  38880. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  38881. if( zWideText==0 ){
  38882. return 0;
  38883. }
  38884. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  38885. nChar);
  38886. if( nChar==0 ){
  38887. sqlite3_free(zWideText);
  38888. zWideText = 0;
  38889. }
  38890. return zWideText;
  38891. }
  38892. /*
  38893. ** Convert a Microsoft Unicode string to UTF-8.
  38894. **
  38895. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38896. */
  38897. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  38898. int nByte;
  38899. char *zText;
  38900. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  38901. if( nByte == 0 ){
  38902. return 0;
  38903. }
  38904. zText = sqlite3MallocZero( nByte );
  38905. if( zText==0 ){
  38906. return 0;
  38907. }
  38908. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  38909. 0, 0);
  38910. if( nByte == 0 ){
  38911. sqlite3_free(zText);
  38912. zText = 0;
  38913. }
  38914. return zText;
  38915. }
  38916. /*
  38917. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  38918. ** code page.
  38919. **
  38920. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38921. */
  38922. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  38923. int nByte;
  38924. LPWSTR zMbcsText;
  38925. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  38926. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  38927. 0)*sizeof(WCHAR);
  38928. if( nByte==0 ){
  38929. return 0;
  38930. }
  38931. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  38932. if( zMbcsText==0 ){
  38933. return 0;
  38934. }
  38935. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  38936. nByte);
  38937. if( nByte==0 ){
  38938. sqlite3_free(zMbcsText);
  38939. zMbcsText = 0;
  38940. }
  38941. return zMbcsText;
  38942. }
  38943. /*
  38944. ** Convert a Microsoft Unicode string to a multi-byte character string,
  38945. ** using the ANSI or OEM code page.
  38946. **
  38947. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38948. */
  38949. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  38950. int nByte;
  38951. char *zText;
  38952. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  38953. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  38954. if( nByte == 0 ){
  38955. return 0;
  38956. }
  38957. zText = sqlite3MallocZero( nByte );
  38958. if( zText==0 ){
  38959. return 0;
  38960. }
  38961. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  38962. nByte, 0, 0);
  38963. if( nByte == 0 ){
  38964. sqlite3_free(zText);
  38965. zText = 0;
  38966. }
  38967. return zText;
  38968. }
  38969. /*
  38970. ** Convert a multi-byte character string to UTF-8.
  38971. **
  38972. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38973. */
  38974. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  38975. char *zTextUtf8;
  38976. LPWSTR zTmpWide;
  38977. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  38978. if( zTmpWide==0 ){
  38979. return 0;
  38980. }
  38981. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  38982. sqlite3_free(zTmpWide);
  38983. return zTextUtf8;
  38984. }
  38985. /*
  38986. ** Convert a UTF-8 string to a multi-byte character string.
  38987. **
  38988. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38989. */
  38990. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  38991. char *zTextMbcs;
  38992. LPWSTR zTmpWide;
  38993. zTmpWide = winUtf8ToUnicode(zText);
  38994. if( zTmpWide==0 ){
  38995. return 0;
  38996. }
  38997. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  38998. sqlite3_free(zTmpWide);
  38999. return zTextMbcs;
  39000. }
  39001. /*
  39002. ** This is a public wrapper for the winUtf8ToUnicode() function.
  39003. */
  39004. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  39005. #ifdef SQLITE_ENABLE_API_ARMOR
  39006. if( !zText ){
  39007. (void)SQLITE_MISUSE_BKPT;
  39008. return 0;
  39009. }
  39010. #endif
  39011. #ifndef SQLITE_OMIT_AUTOINIT
  39012. if( sqlite3_initialize() ) return 0;
  39013. #endif
  39014. return winUtf8ToUnicode(zText);
  39015. }
  39016. /*
  39017. ** This is a public wrapper for the winUnicodeToUtf8() function.
  39018. */
  39019. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  39020. #ifdef SQLITE_ENABLE_API_ARMOR
  39021. if( !zWideText ){
  39022. (void)SQLITE_MISUSE_BKPT;
  39023. return 0;
  39024. }
  39025. #endif
  39026. #ifndef SQLITE_OMIT_AUTOINIT
  39027. if( sqlite3_initialize() ) return 0;
  39028. #endif
  39029. return winUnicodeToUtf8(zWideText);
  39030. }
  39031. /*
  39032. ** This is a public wrapper for the winMbcsToUtf8() function.
  39033. */
  39034. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  39035. #ifdef SQLITE_ENABLE_API_ARMOR
  39036. if( !zText ){
  39037. (void)SQLITE_MISUSE_BKPT;
  39038. return 0;
  39039. }
  39040. #endif
  39041. #ifndef SQLITE_OMIT_AUTOINIT
  39042. if( sqlite3_initialize() ) return 0;
  39043. #endif
  39044. return winMbcsToUtf8(zText, osAreFileApisANSI());
  39045. }
  39046. /*
  39047. ** This is a public wrapper for the winMbcsToUtf8() function.
  39048. */
  39049. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  39050. #ifdef SQLITE_ENABLE_API_ARMOR
  39051. if( !zText ){
  39052. (void)SQLITE_MISUSE_BKPT;
  39053. return 0;
  39054. }
  39055. #endif
  39056. #ifndef SQLITE_OMIT_AUTOINIT
  39057. if( sqlite3_initialize() ) return 0;
  39058. #endif
  39059. return winMbcsToUtf8(zText, useAnsi);
  39060. }
  39061. /*
  39062. ** This is a public wrapper for the winUtf8ToMbcs() function.
  39063. */
  39064. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  39065. #ifdef SQLITE_ENABLE_API_ARMOR
  39066. if( !zText ){
  39067. (void)SQLITE_MISUSE_BKPT;
  39068. return 0;
  39069. }
  39070. #endif
  39071. #ifndef SQLITE_OMIT_AUTOINIT
  39072. if( sqlite3_initialize() ) return 0;
  39073. #endif
  39074. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  39075. }
  39076. /*
  39077. ** This is a public wrapper for the winUtf8ToMbcs() function.
  39078. */
  39079. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  39080. #ifdef SQLITE_ENABLE_API_ARMOR
  39081. if( !zText ){
  39082. (void)SQLITE_MISUSE_BKPT;
  39083. return 0;
  39084. }
  39085. #endif
  39086. #ifndef SQLITE_OMIT_AUTOINIT
  39087. if( sqlite3_initialize() ) return 0;
  39088. #endif
  39089. return winUtf8ToMbcs(zText, useAnsi);
  39090. }
  39091. /*
  39092. ** This function is the same as sqlite3_win32_set_directory (below); however,
  39093. ** it accepts a UTF-8 string.
  39094. */
  39095. SQLITE_API int sqlite3_win32_set_directory8(
  39096. unsigned long type, /* Identifier for directory being set or reset */
  39097. const char *zValue /* New value for directory being set or reset */
  39098. ){
  39099. char **ppDirectory = 0;
  39100. #ifndef SQLITE_OMIT_AUTOINIT
  39101. int rc = sqlite3_initialize();
  39102. if( rc ) return rc;
  39103. #endif
  39104. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  39105. ppDirectory = &sqlite3_data_directory;
  39106. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  39107. ppDirectory = &sqlite3_temp_directory;
  39108. }
  39109. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  39110. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  39111. );
  39112. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  39113. if( ppDirectory ){
  39114. char *zCopy = 0;
  39115. if( zValue && zValue[0] ){
  39116. zCopy = sqlite3_mprintf("%s", zValue);
  39117. if ( zCopy==0 ){
  39118. return SQLITE_NOMEM_BKPT;
  39119. }
  39120. }
  39121. sqlite3_free(*ppDirectory);
  39122. *ppDirectory = zCopy;
  39123. return SQLITE_OK;
  39124. }
  39125. return SQLITE_ERROR;
  39126. }
  39127. /*
  39128. ** This function is the same as sqlite3_win32_set_directory (below); however,
  39129. ** it accepts a UTF-16 string.
  39130. */
  39131. SQLITE_API int sqlite3_win32_set_directory16(
  39132. unsigned long type, /* Identifier for directory being set or reset */
  39133. const void *zValue /* New value for directory being set or reset */
  39134. ){
  39135. int rc;
  39136. char *zUtf8 = 0;
  39137. if( zValue ){
  39138. zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
  39139. if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
  39140. }
  39141. rc = sqlite3_win32_set_directory8(type, zUtf8);
  39142. if( zUtf8 ) sqlite3_free(zUtf8);
  39143. return rc;
  39144. }
  39145. /*
  39146. ** This function sets the data directory or the temporary directory based on
  39147. ** the provided arguments. The type argument must be 1 in order to set the
  39148. ** data directory or 2 in order to set the temporary directory. The zValue
  39149. ** argument is the name of the directory to use. The return value will be
  39150. ** SQLITE_OK if successful.
  39151. */
  39152. SQLITE_API int sqlite3_win32_set_directory(
  39153. unsigned long type, /* Identifier for directory being set or reset */
  39154. void *zValue /* New value for directory being set or reset */
  39155. ){
  39156. return sqlite3_win32_set_directory16(type, zValue);
  39157. }
  39158. /*
  39159. ** The return value of winGetLastErrorMsg
  39160. ** is zero if the error message fits in the buffer, or non-zero
  39161. ** otherwise (if the message was truncated).
  39162. */
  39163. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  39164. /* FormatMessage returns 0 on failure. Otherwise it
  39165. ** returns the number of TCHARs written to the output
  39166. ** buffer, excluding the terminating null char.
  39167. */
  39168. DWORD dwLen = 0;
  39169. char *zOut = 0;
  39170. if( osIsNT() ){
  39171. #if SQLITE_OS_WINRT
  39172. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  39173. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  39174. FORMAT_MESSAGE_IGNORE_INSERTS,
  39175. NULL,
  39176. lastErrno,
  39177. 0,
  39178. zTempWide,
  39179. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  39180. 0);
  39181. #else
  39182. LPWSTR zTempWide = NULL;
  39183. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  39184. FORMAT_MESSAGE_FROM_SYSTEM |
  39185. FORMAT_MESSAGE_IGNORE_INSERTS,
  39186. NULL,
  39187. lastErrno,
  39188. 0,
  39189. (LPWSTR) &zTempWide,
  39190. 0,
  39191. 0);
  39192. #endif
  39193. if( dwLen > 0 ){
  39194. /* allocate a buffer and convert to UTF8 */
  39195. sqlite3BeginBenignMalloc();
  39196. zOut = winUnicodeToUtf8(zTempWide);
  39197. sqlite3EndBenignMalloc();
  39198. #if !SQLITE_OS_WINRT
  39199. /* free the system buffer allocated by FormatMessage */
  39200. osLocalFree(zTempWide);
  39201. #endif
  39202. }
  39203. }
  39204. #ifdef SQLITE_WIN32_HAS_ANSI
  39205. else{
  39206. char *zTemp = NULL;
  39207. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  39208. FORMAT_MESSAGE_FROM_SYSTEM |
  39209. FORMAT_MESSAGE_IGNORE_INSERTS,
  39210. NULL,
  39211. lastErrno,
  39212. 0,
  39213. (LPSTR) &zTemp,
  39214. 0,
  39215. 0);
  39216. if( dwLen > 0 ){
  39217. /* allocate a buffer and convert to UTF8 */
  39218. sqlite3BeginBenignMalloc();
  39219. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  39220. sqlite3EndBenignMalloc();
  39221. /* free the system buffer allocated by FormatMessage */
  39222. osLocalFree(zTemp);
  39223. }
  39224. }
  39225. #endif
  39226. if( 0 == dwLen ){
  39227. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  39228. }else{
  39229. /* copy a maximum of nBuf chars to output buffer */
  39230. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  39231. /* free the UTF8 buffer */
  39232. sqlite3_free(zOut);
  39233. }
  39234. return 0;
  39235. }
  39236. /*
  39237. **
  39238. ** This function - winLogErrorAtLine() - is only ever called via the macro
  39239. ** winLogError().
  39240. **
  39241. ** This routine is invoked after an error occurs in an OS function.
  39242. ** It logs a message using sqlite3_log() containing the current value of
  39243. ** error code and, if possible, the human-readable equivalent from
  39244. ** FormatMessage.
  39245. **
  39246. ** The first argument passed to the macro should be the error code that
  39247. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  39248. ** The two subsequent arguments should be the name of the OS function that
  39249. ** failed and the associated file-system path, if any.
  39250. */
  39251. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  39252. static int winLogErrorAtLine(
  39253. int errcode, /* SQLite error code */
  39254. DWORD lastErrno, /* Win32 last error */
  39255. const char *zFunc, /* Name of OS function that failed */
  39256. const char *zPath, /* File path associated with error */
  39257. int iLine /* Source line number where error occurred */
  39258. ){
  39259. char zMsg[500]; /* Human readable error text */
  39260. int i; /* Loop counter */
  39261. zMsg[0] = 0;
  39262. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  39263. assert( errcode!=SQLITE_OK );
  39264. if( zPath==0 ) zPath = "";
  39265. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  39266. zMsg[i] = 0;
  39267. sqlite3_log(errcode,
  39268. "os_win.c:%d: (%lu) %s(%s) - %s",
  39269. iLine, lastErrno, zFunc, zPath, zMsg
  39270. );
  39271. return errcode;
  39272. }
  39273. /*
  39274. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  39275. ** will be retried following a locking error - probably caused by
  39276. ** antivirus software. Also the initial delay before the first retry.
  39277. ** The delay increases linearly with each retry.
  39278. */
  39279. #ifndef SQLITE_WIN32_IOERR_RETRY
  39280. # define SQLITE_WIN32_IOERR_RETRY 10
  39281. #endif
  39282. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  39283. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  39284. #endif
  39285. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  39286. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  39287. /*
  39288. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  39289. ** error code obtained via GetLastError() is eligible to be retried. It
  39290. ** must accept the error code DWORD as its only argument and should return
  39291. ** non-zero if the error code is transient in nature and the operation
  39292. ** responsible for generating the original error might succeed upon being
  39293. ** retried. The argument to this macro should be a variable.
  39294. **
  39295. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  39296. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  39297. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  39298. ** may be used to include additional error codes in the set that should
  39299. ** result in the failing I/O operation being retried by the caller. If
  39300. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  39301. ** identical to those of the "winIoerrCanRetry1" macro.
  39302. */
  39303. #if !defined(winIoerrCanRetry1)
  39304. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  39305. ((a)==ERROR_SHARING_VIOLATION) || \
  39306. ((a)==ERROR_LOCK_VIOLATION) || \
  39307. ((a)==ERROR_DEV_NOT_EXIST) || \
  39308. ((a)==ERROR_NETNAME_DELETED) || \
  39309. ((a)==ERROR_SEM_TIMEOUT) || \
  39310. ((a)==ERROR_NETWORK_UNREACHABLE))
  39311. #endif
  39312. /*
  39313. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  39314. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  39315. ** to give up with an error.
  39316. */
  39317. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  39318. DWORD e = osGetLastError();
  39319. if( *pnRetry>=winIoerrRetry ){
  39320. if( pError ){
  39321. *pError = e;
  39322. }
  39323. return 0;
  39324. }
  39325. if( winIoerrCanRetry1(e) ){
  39326. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  39327. ++*pnRetry;
  39328. return 1;
  39329. }
  39330. #if defined(winIoerrCanRetry2)
  39331. else if( winIoerrCanRetry2(e) ){
  39332. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  39333. ++*pnRetry;
  39334. return 1;
  39335. }
  39336. #endif
  39337. if( pError ){
  39338. *pError = e;
  39339. }
  39340. return 0;
  39341. }
  39342. /*
  39343. ** Log a I/O error retry episode.
  39344. */
  39345. static void winLogIoerr(int nRetry, int lineno){
  39346. if( nRetry ){
  39347. sqlite3_log(SQLITE_NOTICE,
  39348. "delayed %dms for lock/sharing conflict at line %d",
  39349. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  39350. );
  39351. }
  39352. }
  39353. /*
  39354. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  39355. ** corresponding section in "date.c" cannot use it.
  39356. */
  39357. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  39358. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  39359. /*
  39360. ** The MSVC CRT on Windows CE may not have a localtime() function.
  39361. ** So define a substitute.
  39362. */
  39363. /* # include <time.h> */
  39364. struct tm *__cdecl localtime(const time_t *t)
  39365. {
  39366. static struct tm y;
  39367. FILETIME uTm, lTm;
  39368. SYSTEMTIME pTm;
  39369. sqlite3_int64 t64;
  39370. t64 = *t;
  39371. t64 = (t64 + 11644473600)*10000000;
  39372. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  39373. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  39374. osFileTimeToLocalFileTime(&uTm,&lTm);
  39375. osFileTimeToSystemTime(&lTm,&pTm);
  39376. y.tm_year = pTm.wYear - 1900;
  39377. y.tm_mon = pTm.wMonth - 1;
  39378. y.tm_wday = pTm.wDayOfWeek;
  39379. y.tm_mday = pTm.wDay;
  39380. y.tm_hour = pTm.wHour;
  39381. y.tm_min = pTm.wMinute;
  39382. y.tm_sec = pTm.wSecond;
  39383. return &y;
  39384. }
  39385. #endif
  39386. #if SQLITE_OS_WINCE
  39387. /*************************************************************************
  39388. ** This section contains code for WinCE only.
  39389. */
  39390. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  39391. /*
  39392. ** Acquire a lock on the handle h
  39393. */
  39394. static void winceMutexAcquire(HANDLE h){
  39395. DWORD dwErr;
  39396. do {
  39397. dwErr = osWaitForSingleObject(h, INFINITE);
  39398. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  39399. }
  39400. /*
  39401. ** Release a lock acquired by winceMutexAcquire()
  39402. */
  39403. #define winceMutexRelease(h) ReleaseMutex(h)
  39404. /*
  39405. ** Create the mutex and shared memory used for locking in the file
  39406. ** descriptor pFile
  39407. */
  39408. static int winceCreateLock(const char *zFilename, winFile *pFile){
  39409. LPWSTR zTok;
  39410. LPWSTR zName;
  39411. DWORD lastErrno;
  39412. BOOL bLogged = FALSE;
  39413. BOOL bInit = TRUE;
  39414. zName = winUtf8ToUnicode(zFilename);
  39415. if( zName==0 ){
  39416. /* out of memory */
  39417. return SQLITE_IOERR_NOMEM_BKPT;
  39418. }
  39419. /* Initialize the local lockdata */
  39420. memset(&pFile->local, 0, sizeof(pFile->local));
  39421. /* Replace the backslashes from the filename and lowercase it
  39422. ** to derive a mutex name. */
  39423. zTok = osCharLowerW(zName);
  39424. for (;*zTok;zTok++){
  39425. if (*zTok == '\\') *zTok = '_';
  39426. }
  39427. /* Create/open the named mutex */
  39428. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  39429. if (!pFile->hMutex){
  39430. pFile->lastErrno = osGetLastError();
  39431. sqlite3_free(zName);
  39432. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  39433. "winceCreateLock1", zFilename);
  39434. }
  39435. /* Acquire the mutex before continuing */
  39436. winceMutexAcquire(pFile->hMutex);
  39437. /* Since the names of named mutexes, semaphores, file mappings etc are
  39438. ** case-sensitive, take advantage of that by uppercasing the mutex name
  39439. ** and using that as the shared filemapping name.
  39440. */
  39441. osCharUpperW(zName);
  39442. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  39443. PAGE_READWRITE, 0, sizeof(winceLock),
  39444. zName);
  39445. /* Set a flag that indicates we're the first to create the memory so it
  39446. ** must be zero-initialized */
  39447. lastErrno = osGetLastError();
  39448. if (lastErrno == ERROR_ALREADY_EXISTS){
  39449. bInit = FALSE;
  39450. }
  39451. sqlite3_free(zName);
  39452. /* If we succeeded in making the shared memory handle, map it. */
  39453. if( pFile->hShared ){
  39454. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  39455. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  39456. /* If mapping failed, close the shared memory handle and erase it */
  39457. if( !pFile->shared ){
  39458. pFile->lastErrno = osGetLastError();
  39459. winLogError(SQLITE_IOERR, pFile->lastErrno,
  39460. "winceCreateLock2", zFilename);
  39461. bLogged = TRUE;
  39462. osCloseHandle(pFile->hShared);
  39463. pFile->hShared = NULL;
  39464. }
  39465. }
  39466. /* If shared memory could not be created, then close the mutex and fail */
  39467. if( pFile->hShared==NULL ){
  39468. if( !bLogged ){
  39469. pFile->lastErrno = lastErrno;
  39470. winLogError(SQLITE_IOERR, pFile->lastErrno,
  39471. "winceCreateLock3", zFilename);
  39472. bLogged = TRUE;
  39473. }
  39474. winceMutexRelease(pFile->hMutex);
  39475. osCloseHandle(pFile->hMutex);
  39476. pFile->hMutex = NULL;
  39477. return SQLITE_IOERR;
  39478. }
  39479. /* Initialize the shared memory if we're supposed to */
  39480. if( bInit ){
  39481. memset(pFile->shared, 0, sizeof(winceLock));
  39482. }
  39483. winceMutexRelease(pFile->hMutex);
  39484. return SQLITE_OK;
  39485. }
  39486. /*
  39487. ** Destroy the part of winFile that deals with wince locks
  39488. */
  39489. static void winceDestroyLock(winFile *pFile){
  39490. if (pFile->hMutex){
  39491. /* Acquire the mutex */
  39492. winceMutexAcquire(pFile->hMutex);
  39493. /* The following blocks should probably assert in debug mode, but they
  39494. are to cleanup in case any locks remained open */
  39495. if (pFile->local.nReaders){
  39496. pFile->shared->nReaders --;
  39497. }
  39498. if (pFile->local.bReserved){
  39499. pFile->shared->bReserved = FALSE;
  39500. }
  39501. if (pFile->local.bPending){
  39502. pFile->shared->bPending = FALSE;
  39503. }
  39504. if (pFile->local.bExclusive){
  39505. pFile->shared->bExclusive = FALSE;
  39506. }
  39507. /* De-reference and close our copy of the shared memory handle */
  39508. osUnmapViewOfFile(pFile->shared);
  39509. osCloseHandle(pFile->hShared);
  39510. /* Done with the mutex */
  39511. winceMutexRelease(pFile->hMutex);
  39512. osCloseHandle(pFile->hMutex);
  39513. pFile->hMutex = NULL;
  39514. }
  39515. }
  39516. /*
  39517. ** An implementation of the LockFile() API of Windows for CE
  39518. */
  39519. static BOOL winceLockFile(
  39520. LPHANDLE phFile,
  39521. DWORD dwFileOffsetLow,
  39522. DWORD dwFileOffsetHigh,
  39523. DWORD nNumberOfBytesToLockLow,
  39524. DWORD nNumberOfBytesToLockHigh
  39525. ){
  39526. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  39527. BOOL bReturn = FALSE;
  39528. UNUSED_PARAMETER(dwFileOffsetHigh);
  39529. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  39530. if (!pFile->hMutex) return TRUE;
  39531. winceMutexAcquire(pFile->hMutex);
  39532. /* Wanting an exclusive lock? */
  39533. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  39534. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  39535. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  39536. pFile->shared->bExclusive = TRUE;
  39537. pFile->local.bExclusive = TRUE;
  39538. bReturn = TRUE;
  39539. }
  39540. }
  39541. /* Want a read-only lock? */
  39542. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  39543. nNumberOfBytesToLockLow == 1){
  39544. if (pFile->shared->bExclusive == 0){
  39545. pFile->local.nReaders ++;
  39546. if (pFile->local.nReaders == 1){
  39547. pFile->shared->nReaders ++;
  39548. }
  39549. bReturn = TRUE;
  39550. }
  39551. }
  39552. /* Want a pending lock? */
  39553. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  39554. && nNumberOfBytesToLockLow == 1){
  39555. /* If no pending lock has been acquired, then acquire it */
  39556. if (pFile->shared->bPending == 0) {
  39557. pFile->shared->bPending = TRUE;
  39558. pFile->local.bPending = TRUE;
  39559. bReturn = TRUE;
  39560. }
  39561. }
  39562. /* Want a reserved lock? */
  39563. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  39564. && nNumberOfBytesToLockLow == 1){
  39565. if (pFile->shared->bReserved == 0) {
  39566. pFile->shared->bReserved = TRUE;
  39567. pFile->local.bReserved = TRUE;
  39568. bReturn = TRUE;
  39569. }
  39570. }
  39571. winceMutexRelease(pFile->hMutex);
  39572. return bReturn;
  39573. }
  39574. /*
  39575. ** An implementation of the UnlockFile API of Windows for CE
  39576. */
  39577. static BOOL winceUnlockFile(
  39578. LPHANDLE phFile,
  39579. DWORD dwFileOffsetLow,
  39580. DWORD dwFileOffsetHigh,
  39581. DWORD nNumberOfBytesToUnlockLow,
  39582. DWORD nNumberOfBytesToUnlockHigh
  39583. ){
  39584. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  39585. BOOL bReturn = FALSE;
  39586. UNUSED_PARAMETER(dwFileOffsetHigh);
  39587. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  39588. if (!pFile->hMutex) return TRUE;
  39589. winceMutexAcquire(pFile->hMutex);
  39590. /* Releasing a reader lock or an exclusive lock */
  39591. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  39592. /* Did we have an exclusive lock? */
  39593. if (pFile->local.bExclusive){
  39594. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  39595. pFile->local.bExclusive = FALSE;
  39596. pFile->shared->bExclusive = FALSE;
  39597. bReturn = TRUE;
  39598. }
  39599. /* Did we just have a reader lock? */
  39600. else if (pFile->local.nReaders){
  39601. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  39602. || nNumberOfBytesToUnlockLow == 1);
  39603. pFile->local.nReaders --;
  39604. if (pFile->local.nReaders == 0)
  39605. {
  39606. pFile->shared->nReaders --;
  39607. }
  39608. bReturn = TRUE;
  39609. }
  39610. }
  39611. /* Releasing a pending lock */
  39612. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  39613. && nNumberOfBytesToUnlockLow == 1){
  39614. if (pFile->local.bPending){
  39615. pFile->local.bPending = FALSE;
  39616. pFile->shared->bPending = FALSE;
  39617. bReturn = TRUE;
  39618. }
  39619. }
  39620. /* Releasing a reserved lock */
  39621. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  39622. && nNumberOfBytesToUnlockLow == 1){
  39623. if (pFile->local.bReserved) {
  39624. pFile->local.bReserved = FALSE;
  39625. pFile->shared->bReserved = FALSE;
  39626. bReturn = TRUE;
  39627. }
  39628. }
  39629. winceMutexRelease(pFile->hMutex);
  39630. return bReturn;
  39631. }
  39632. /*
  39633. ** End of the special code for wince
  39634. *****************************************************************************/
  39635. #endif /* SQLITE_OS_WINCE */
  39636. /*
  39637. ** Lock a file region.
  39638. */
  39639. static BOOL winLockFile(
  39640. LPHANDLE phFile,
  39641. DWORD flags,
  39642. DWORD offsetLow,
  39643. DWORD offsetHigh,
  39644. DWORD numBytesLow,
  39645. DWORD numBytesHigh
  39646. ){
  39647. #if SQLITE_OS_WINCE
  39648. /*
  39649. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  39650. ** API LockFile.
  39651. */
  39652. return winceLockFile(phFile, offsetLow, offsetHigh,
  39653. numBytesLow, numBytesHigh);
  39654. #else
  39655. if( osIsNT() ){
  39656. OVERLAPPED ovlp;
  39657. memset(&ovlp, 0, sizeof(OVERLAPPED));
  39658. ovlp.Offset = offsetLow;
  39659. ovlp.OffsetHigh = offsetHigh;
  39660. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  39661. }else{
  39662. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  39663. numBytesHigh);
  39664. }
  39665. #endif
  39666. }
  39667. /*
  39668. ** Unlock a file region.
  39669. */
  39670. static BOOL winUnlockFile(
  39671. LPHANDLE phFile,
  39672. DWORD offsetLow,
  39673. DWORD offsetHigh,
  39674. DWORD numBytesLow,
  39675. DWORD numBytesHigh
  39676. ){
  39677. #if SQLITE_OS_WINCE
  39678. /*
  39679. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  39680. ** API UnlockFile.
  39681. */
  39682. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  39683. numBytesLow, numBytesHigh);
  39684. #else
  39685. if( osIsNT() ){
  39686. OVERLAPPED ovlp;
  39687. memset(&ovlp, 0, sizeof(OVERLAPPED));
  39688. ovlp.Offset = offsetLow;
  39689. ovlp.OffsetHigh = offsetHigh;
  39690. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  39691. }else{
  39692. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  39693. numBytesHigh);
  39694. }
  39695. #endif
  39696. }
  39697. /*****************************************************************************
  39698. ** The next group of routines implement the I/O methods specified
  39699. ** by the sqlite3_io_methods object.
  39700. ******************************************************************************/
  39701. /*
  39702. ** Some Microsoft compilers lack this definition.
  39703. */
  39704. #ifndef INVALID_SET_FILE_POINTER
  39705. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  39706. #endif
  39707. /*
  39708. ** Move the current position of the file handle passed as the first
  39709. ** argument to offset iOffset within the file. If successful, return 0.
  39710. ** Otherwise, set pFile->lastErrno and return non-zero.
  39711. */
  39712. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  39713. #if !SQLITE_OS_WINRT
  39714. LONG upperBits; /* Most sig. 32 bits of new offset */
  39715. LONG lowerBits; /* Least sig. 32 bits of new offset */
  39716. DWORD dwRet; /* Value returned by SetFilePointer() */
  39717. DWORD lastErrno; /* Value returned by GetLastError() */
  39718. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  39719. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  39720. lowerBits = (LONG)(iOffset & 0xffffffff);
  39721. /* API oddity: If successful, SetFilePointer() returns a dword
  39722. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  39723. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  39724. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  39725. ** whether an error has actually occurred, it is also necessary to call
  39726. ** GetLastError().
  39727. */
  39728. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  39729. if( (dwRet==INVALID_SET_FILE_POINTER
  39730. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  39731. pFile->lastErrno = lastErrno;
  39732. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  39733. "winSeekFile", pFile->zPath);
  39734. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  39735. return 1;
  39736. }
  39737. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  39738. return 0;
  39739. #else
  39740. /*
  39741. ** Same as above, except that this implementation works for WinRT.
  39742. */
  39743. LARGE_INTEGER x; /* The new offset */
  39744. BOOL bRet; /* Value returned by SetFilePointerEx() */
  39745. x.QuadPart = iOffset;
  39746. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  39747. if(!bRet){
  39748. pFile->lastErrno = osGetLastError();
  39749. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  39750. "winSeekFile", pFile->zPath);
  39751. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  39752. return 1;
  39753. }
  39754. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  39755. return 0;
  39756. #endif
  39757. }
  39758. #if SQLITE_MAX_MMAP_SIZE>0
  39759. /* Forward references to VFS helper methods used for memory mapped files */
  39760. static int winMapfile(winFile*, sqlite3_int64);
  39761. static int winUnmapfile(winFile*);
  39762. #endif
  39763. /*
  39764. ** Close a file.
  39765. **
  39766. ** It is reported that an attempt to close a handle might sometimes
  39767. ** fail. This is a very unreasonable result, but Windows is notorious
  39768. ** for being unreasonable so I do not doubt that it might happen. If
  39769. ** the close fails, we pause for 100 milliseconds and try again. As
  39770. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  39771. ** giving up and returning an error.
  39772. */
  39773. #define MX_CLOSE_ATTEMPT 3
  39774. static int winClose(sqlite3_file *id){
  39775. int rc, cnt = 0;
  39776. winFile *pFile = (winFile*)id;
  39777. assert( id!=0 );
  39778. #ifndef SQLITE_OMIT_WAL
  39779. assert( pFile->pShm==0 );
  39780. #endif
  39781. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  39782. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  39783. osGetCurrentProcessId(), pFile, pFile->h));
  39784. #if SQLITE_MAX_MMAP_SIZE>0
  39785. winUnmapfile(pFile);
  39786. #endif
  39787. do{
  39788. rc = osCloseHandle(pFile->h);
  39789. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  39790. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  39791. #if SQLITE_OS_WINCE
  39792. #define WINCE_DELETION_ATTEMPTS 3
  39793. {
  39794. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  39795. if( pAppData==NULL || !pAppData->bNoLock ){
  39796. winceDestroyLock(pFile);
  39797. }
  39798. }
  39799. if( pFile->zDeleteOnClose ){
  39800. int cnt = 0;
  39801. while(
  39802. osDeleteFileW(pFile->zDeleteOnClose)==0
  39803. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  39804. && cnt++ < WINCE_DELETION_ATTEMPTS
  39805. ){
  39806. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  39807. }
  39808. sqlite3_free(pFile->zDeleteOnClose);
  39809. }
  39810. #endif
  39811. if( rc ){
  39812. pFile->h = NULL;
  39813. }
  39814. OpenCounter(-1);
  39815. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  39816. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  39817. return rc ? SQLITE_OK
  39818. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  39819. "winClose", pFile->zPath);
  39820. }
  39821. /*
  39822. ** Read data from a file into a buffer. Return SQLITE_OK if all
  39823. ** bytes were read successfully and SQLITE_IOERR if anything goes
  39824. ** wrong.
  39825. */
  39826. static int winRead(
  39827. sqlite3_file *id, /* File to read from */
  39828. void *pBuf, /* Write content into this buffer */
  39829. int amt, /* Number of bytes to read */
  39830. sqlite3_int64 offset /* Begin reading at this offset */
  39831. ){
  39832. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39833. OVERLAPPED overlapped; /* The offset for ReadFile. */
  39834. #endif
  39835. winFile *pFile = (winFile*)id; /* file handle */
  39836. DWORD nRead; /* Number of bytes actually read from file */
  39837. int nRetry = 0; /* Number of retrys */
  39838. assert( id!=0 );
  39839. assert( amt>0 );
  39840. assert( offset>=0 );
  39841. SimulateIOError(return SQLITE_IOERR_READ);
  39842. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  39843. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  39844. pFile->h, pBuf, amt, offset, pFile->locktype));
  39845. #if SQLITE_MAX_MMAP_SIZE>0
  39846. /* Deal with as much of this read request as possible by transfering
  39847. ** data from the memory mapping using memcpy(). */
  39848. if( offset<pFile->mmapSize ){
  39849. if( offset+amt <= pFile->mmapSize ){
  39850. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  39851. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39852. osGetCurrentProcessId(), pFile, pFile->h));
  39853. return SQLITE_OK;
  39854. }else{
  39855. int nCopy = (int)(pFile->mmapSize - offset);
  39856. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  39857. pBuf = &((u8 *)pBuf)[nCopy];
  39858. amt -= nCopy;
  39859. offset += nCopy;
  39860. }
  39861. }
  39862. #endif
  39863. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  39864. if( winSeekFile(pFile, offset) ){
  39865. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  39866. osGetCurrentProcessId(), pFile, pFile->h));
  39867. return SQLITE_FULL;
  39868. }
  39869. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  39870. #else
  39871. memset(&overlapped, 0, sizeof(OVERLAPPED));
  39872. overlapped.Offset = (LONG)(offset & 0xffffffff);
  39873. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  39874. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  39875. osGetLastError()!=ERROR_HANDLE_EOF ){
  39876. #endif
  39877. DWORD lastErrno;
  39878. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  39879. pFile->lastErrno = lastErrno;
  39880. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  39881. osGetCurrentProcessId(), pFile, pFile->h));
  39882. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  39883. "winRead", pFile->zPath);
  39884. }
  39885. winLogIoerr(nRetry, __LINE__);
  39886. if( nRead<(DWORD)amt ){
  39887. /* Unread parts of the buffer must be zero-filled */
  39888. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  39889. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  39890. osGetCurrentProcessId(), pFile, pFile->h));
  39891. return SQLITE_IOERR_SHORT_READ;
  39892. }
  39893. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39894. osGetCurrentProcessId(), pFile, pFile->h));
  39895. return SQLITE_OK;
  39896. }
  39897. /*
  39898. ** Write data from a buffer into a file. Return SQLITE_OK on success
  39899. ** or some other error code on failure.
  39900. */
  39901. static int winWrite(
  39902. sqlite3_file *id, /* File to write into */
  39903. const void *pBuf, /* The bytes to be written */
  39904. int amt, /* Number of bytes to write */
  39905. sqlite3_int64 offset /* Offset into the file to begin writing at */
  39906. ){
  39907. int rc = 0; /* True if error has occurred, else false */
  39908. winFile *pFile = (winFile*)id; /* File handle */
  39909. int nRetry = 0; /* Number of retries */
  39910. assert( amt>0 );
  39911. assert( pFile );
  39912. SimulateIOError(return SQLITE_IOERR_WRITE);
  39913. SimulateDiskfullError(return SQLITE_FULL);
  39914. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  39915. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  39916. pFile->h, pBuf, amt, offset, pFile->locktype));
  39917. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  39918. /* Deal with as much of this write request as possible by transfering
  39919. ** data from the memory mapping using memcpy(). */
  39920. if( offset<pFile->mmapSize ){
  39921. if( offset+amt <= pFile->mmapSize ){
  39922. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  39923. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39924. osGetCurrentProcessId(), pFile, pFile->h));
  39925. return SQLITE_OK;
  39926. }else{
  39927. int nCopy = (int)(pFile->mmapSize - offset);
  39928. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  39929. pBuf = &((u8 *)pBuf)[nCopy];
  39930. amt -= nCopy;
  39931. offset += nCopy;
  39932. }
  39933. }
  39934. #endif
  39935. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  39936. rc = winSeekFile(pFile, offset);
  39937. if( rc==0 ){
  39938. #else
  39939. {
  39940. #endif
  39941. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39942. OVERLAPPED overlapped; /* The offset for WriteFile. */
  39943. #endif
  39944. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  39945. int nRem = amt; /* Number of bytes yet to be written */
  39946. DWORD nWrite; /* Bytes written by each WriteFile() call */
  39947. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  39948. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39949. memset(&overlapped, 0, sizeof(OVERLAPPED));
  39950. overlapped.Offset = (LONG)(offset & 0xffffffff);
  39951. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  39952. #endif
  39953. while( nRem>0 ){
  39954. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  39955. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  39956. #else
  39957. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  39958. #endif
  39959. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  39960. break;
  39961. }
  39962. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  39963. if( nWrite==0 || nWrite>(DWORD)nRem ){
  39964. lastErrno = osGetLastError();
  39965. break;
  39966. }
  39967. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39968. offset += nWrite;
  39969. overlapped.Offset = (LONG)(offset & 0xffffffff);
  39970. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  39971. #endif
  39972. aRem += nWrite;
  39973. nRem -= nWrite;
  39974. }
  39975. if( nRem>0 ){
  39976. pFile->lastErrno = lastErrno;
  39977. rc = 1;
  39978. }
  39979. }
  39980. if( rc ){
  39981. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  39982. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  39983. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  39984. osGetCurrentProcessId(), pFile, pFile->h));
  39985. return winLogError(SQLITE_FULL, pFile->lastErrno,
  39986. "winWrite1", pFile->zPath);
  39987. }
  39988. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  39989. osGetCurrentProcessId(), pFile, pFile->h));
  39990. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  39991. "winWrite2", pFile->zPath);
  39992. }else{
  39993. winLogIoerr(nRetry, __LINE__);
  39994. }
  39995. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39996. osGetCurrentProcessId(), pFile, pFile->h));
  39997. return SQLITE_OK;
  39998. }
  39999. /*
  40000. ** Truncate an open file to a specified size
  40001. */
  40002. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  40003. winFile *pFile = (winFile*)id; /* File handle object */
  40004. int rc = SQLITE_OK; /* Return code for this function */
  40005. DWORD lastErrno;
  40006. assert( pFile );
  40007. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  40008. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  40009. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  40010. /* If the user has configured a chunk-size for this file, truncate the
  40011. ** file so that it consists of an integer number of chunks (i.e. the
  40012. ** actual file size after the operation may be larger than the requested
  40013. ** size).
  40014. */
  40015. if( pFile->szChunk>0 ){
  40016. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  40017. }
  40018. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  40019. if( winSeekFile(pFile, nByte) ){
  40020. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  40021. "winTruncate1", pFile->zPath);
  40022. }else if( 0==osSetEndOfFile(pFile->h) &&
  40023. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  40024. pFile->lastErrno = lastErrno;
  40025. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  40026. "winTruncate2", pFile->zPath);
  40027. }
  40028. #if SQLITE_MAX_MMAP_SIZE>0
  40029. /* If the file was truncated to a size smaller than the currently
  40030. ** mapped region, reduce the effective mapping size as well. SQLite will
  40031. ** use read() and write() to access data beyond this point from now on.
  40032. */
  40033. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  40034. pFile->mmapSize = nByte;
  40035. }
  40036. #endif
  40037. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  40038. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  40039. return rc;
  40040. }
  40041. #ifdef SQLITE_TEST
  40042. /*
  40043. ** Count the number of fullsyncs and normal syncs. This is used to test
  40044. ** that syncs and fullsyncs are occuring at the right times.
  40045. */
  40046. SQLITE_API int sqlite3_sync_count = 0;
  40047. SQLITE_API int sqlite3_fullsync_count = 0;
  40048. #endif
  40049. /*
  40050. ** Make sure all writes to a particular file are committed to disk.
  40051. */
  40052. static int winSync(sqlite3_file *id, int flags){
  40053. #ifndef SQLITE_NO_SYNC
  40054. /*
  40055. ** Used only when SQLITE_NO_SYNC is not defined.
  40056. */
  40057. BOOL rc;
  40058. #endif
  40059. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  40060. defined(SQLITE_HAVE_OS_TRACE)
  40061. /*
  40062. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  40063. ** OSTRACE() macros.
  40064. */
  40065. winFile *pFile = (winFile*)id;
  40066. #else
  40067. UNUSED_PARAMETER(id);
  40068. #endif
  40069. assert( pFile );
  40070. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  40071. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  40072. || (flags&0x0F)==SQLITE_SYNC_FULL
  40073. );
  40074. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  40075. ** line is to test that doing so does not cause any problems.
  40076. */
  40077. SimulateDiskfullError( return SQLITE_FULL );
  40078. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  40079. osGetCurrentProcessId(), pFile, pFile->h, flags,
  40080. pFile->locktype));
  40081. #ifndef SQLITE_TEST
  40082. UNUSED_PARAMETER(flags);
  40083. #else
  40084. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  40085. sqlite3_fullsync_count++;
  40086. }
  40087. sqlite3_sync_count++;
  40088. #endif
  40089. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  40090. ** no-op
  40091. */
  40092. #ifdef SQLITE_NO_SYNC
  40093. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40094. osGetCurrentProcessId(), pFile, pFile->h));
  40095. return SQLITE_OK;
  40096. #else
  40097. #if SQLITE_MAX_MMAP_SIZE>0
  40098. if( pFile->pMapRegion ){
  40099. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  40100. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  40101. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  40102. pFile, pFile->pMapRegion));
  40103. }else{
  40104. pFile->lastErrno = osGetLastError();
  40105. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  40106. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  40107. pFile, pFile->pMapRegion));
  40108. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  40109. "winSync1", pFile->zPath);
  40110. }
  40111. }
  40112. #endif
  40113. rc = osFlushFileBuffers(pFile->h);
  40114. SimulateIOError( rc=FALSE );
  40115. if( rc ){
  40116. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40117. osGetCurrentProcessId(), pFile, pFile->h));
  40118. return SQLITE_OK;
  40119. }else{
  40120. pFile->lastErrno = osGetLastError();
  40121. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  40122. osGetCurrentProcessId(), pFile, pFile->h));
  40123. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  40124. "winSync2", pFile->zPath);
  40125. }
  40126. #endif
  40127. }
  40128. /*
  40129. ** Determine the current size of a file in bytes
  40130. */
  40131. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  40132. winFile *pFile = (winFile*)id;
  40133. int rc = SQLITE_OK;
  40134. assert( id!=0 );
  40135. assert( pSize!=0 );
  40136. SimulateIOError(return SQLITE_IOERR_FSTAT);
  40137. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  40138. #if SQLITE_OS_WINRT
  40139. {
  40140. FILE_STANDARD_INFO info;
  40141. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  40142. &info, sizeof(info)) ){
  40143. *pSize = info.EndOfFile.QuadPart;
  40144. }else{
  40145. pFile->lastErrno = osGetLastError();
  40146. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  40147. "winFileSize", pFile->zPath);
  40148. }
  40149. }
  40150. #else
  40151. {
  40152. DWORD upperBits;
  40153. DWORD lowerBits;
  40154. DWORD lastErrno;
  40155. lowerBits = osGetFileSize(pFile->h, &upperBits);
  40156. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  40157. if( (lowerBits == INVALID_FILE_SIZE)
  40158. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  40159. pFile->lastErrno = lastErrno;
  40160. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  40161. "winFileSize", pFile->zPath);
  40162. }
  40163. }
  40164. #endif
  40165. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  40166. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  40167. return rc;
  40168. }
  40169. /*
  40170. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  40171. */
  40172. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  40173. # define LOCKFILE_FAIL_IMMEDIATELY 1
  40174. #endif
  40175. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  40176. # define LOCKFILE_EXCLUSIVE_LOCK 2
  40177. #endif
  40178. /*
  40179. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  40180. ** When the LockFile function was used, it was always expected to fail
  40181. ** immediately if the lock could not be obtained. Also, it always expected to
  40182. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  40183. ** and reflect those expectations; therefore, they should not be changed.
  40184. */
  40185. #ifndef SQLITE_LOCKFILE_FLAGS
  40186. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  40187. LOCKFILE_EXCLUSIVE_LOCK)
  40188. #endif
  40189. /*
  40190. ** Currently, SQLite never calls the LockFileEx function without wanting the
  40191. ** call to fail immediately if the lock cannot be obtained.
  40192. */
  40193. #ifndef SQLITE_LOCKFILEEX_FLAGS
  40194. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  40195. #endif
  40196. /*
  40197. ** Acquire a reader lock.
  40198. ** Different API routines are called depending on whether or not this
  40199. ** is Win9x or WinNT.
  40200. */
  40201. static int winGetReadLock(winFile *pFile){
  40202. int res;
  40203. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  40204. if( osIsNT() ){
  40205. #if SQLITE_OS_WINCE
  40206. /*
  40207. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40208. ** API LockFileEx.
  40209. */
  40210. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  40211. #else
  40212. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  40213. SHARED_SIZE, 0);
  40214. #endif
  40215. }
  40216. #ifdef SQLITE_WIN32_HAS_ANSI
  40217. else{
  40218. int lk;
  40219. sqlite3_randomness(sizeof(lk), &lk);
  40220. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  40221. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  40222. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  40223. }
  40224. #endif
  40225. if( res == 0 ){
  40226. pFile->lastErrno = osGetLastError();
  40227. /* No need to log a failure to lock */
  40228. }
  40229. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  40230. return res;
  40231. }
  40232. /*
  40233. ** Undo a readlock
  40234. */
  40235. static int winUnlockReadLock(winFile *pFile){
  40236. int res;
  40237. DWORD lastErrno;
  40238. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  40239. if( osIsNT() ){
  40240. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  40241. }
  40242. #ifdef SQLITE_WIN32_HAS_ANSI
  40243. else{
  40244. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  40245. }
  40246. #endif
  40247. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  40248. pFile->lastErrno = lastErrno;
  40249. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  40250. "winUnlockReadLock", pFile->zPath);
  40251. }
  40252. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  40253. return res;
  40254. }
  40255. /*
  40256. ** Lock the file with the lock specified by parameter locktype - one
  40257. ** of the following:
  40258. **
  40259. ** (1) SHARED_LOCK
  40260. ** (2) RESERVED_LOCK
  40261. ** (3) PENDING_LOCK
  40262. ** (4) EXCLUSIVE_LOCK
  40263. **
  40264. ** Sometimes when requesting one lock state, additional lock states
  40265. ** are inserted in between. The locking might fail on one of the later
  40266. ** transitions leaving the lock state different from what it started but
  40267. ** still short of its goal. The following chart shows the allowed
  40268. ** transitions and the inserted intermediate states:
  40269. **
  40270. ** UNLOCKED -> SHARED
  40271. ** SHARED -> RESERVED
  40272. ** SHARED -> (PENDING) -> EXCLUSIVE
  40273. ** RESERVED -> (PENDING) -> EXCLUSIVE
  40274. ** PENDING -> EXCLUSIVE
  40275. **
  40276. ** This routine will only increase a lock. The winUnlock() routine
  40277. ** erases all locks at once and returns us immediately to locking level 0.
  40278. ** It is not possible to lower the locking level one step at a time. You
  40279. ** must go straight to locking level 0.
  40280. */
  40281. static int winLock(sqlite3_file *id, int locktype){
  40282. int rc = SQLITE_OK; /* Return code from subroutines */
  40283. int res = 1; /* Result of a Windows lock call */
  40284. int newLocktype; /* Set pFile->locktype to this value before exiting */
  40285. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  40286. winFile *pFile = (winFile*)id;
  40287. DWORD lastErrno = NO_ERROR;
  40288. assert( id!=0 );
  40289. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  40290. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  40291. /* If there is already a lock of this type or more restrictive on the
  40292. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  40293. ** sqlite3OsEnterMutex() hasn't been called yet.
  40294. */
  40295. if( pFile->locktype>=locktype ){
  40296. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  40297. return SQLITE_OK;
  40298. }
  40299. /* Do not allow any kind of write-lock on a read-only database
  40300. */
  40301. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  40302. return SQLITE_IOERR_LOCK;
  40303. }
  40304. /* Make sure the locking sequence is correct
  40305. */
  40306. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  40307. assert( locktype!=PENDING_LOCK );
  40308. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  40309. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  40310. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  40311. ** the PENDING_LOCK byte is temporary.
  40312. */
  40313. newLocktype = pFile->locktype;
  40314. if( pFile->locktype==NO_LOCK
  40315. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  40316. ){
  40317. int cnt = 3;
  40318. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  40319. PENDING_BYTE, 0, 1, 0))==0 ){
  40320. /* Try 3 times to get the pending lock. This is needed to work
  40321. ** around problems caused by indexing and/or anti-virus software on
  40322. ** Windows systems.
  40323. ** If you are using this code as a model for alternative VFSes, do not
  40324. ** copy this retry logic. It is a hack intended for Windows only.
  40325. */
  40326. lastErrno = osGetLastError();
  40327. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  40328. pFile->h, cnt, res));
  40329. if( lastErrno==ERROR_INVALID_HANDLE ){
  40330. pFile->lastErrno = lastErrno;
  40331. rc = SQLITE_IOERR_LOCK;
  40332. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  40333. pFile->h, cnt, sqlite3ErrName(rc)));
  40334. return rc;
  40335. }
  40336. if( cnt ) sqlite3_win32_sleep(1);
  40337. }
  40338. gotPendingLock = res;
  40339. if( !res ){
  40340. lastErrno = osGetLastError();
  40341. }
  40342. }
  40343. /* Acquire a shared lock
  40344. */
  40345. if( locktype==SHARED_LOCK && res ){
  40346. assert( pFile->locktype==NO_LOCK );
  40347. res = winGetReadLock(pFile);
  40348. if( res ){
  40349. newLocktype = SHARED_LOCK;
  40350. }else{
  40351. lastErrno = osGetLastError();
  40352. }
  40353. }
  40354. /* Acquire a RESERVED lock
  40355. */
  40356. if( locktype==RESERVED_LOCK && res ){
  40357. assert( pFile->locktype==SHARED_LOCK );
  40358. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  40359. if( res ){
  40360. newLocktype = RESERVED_LOCK;
  40361. }else{
  40362. lastErrno = osGetLastError();
  40363. }
  40364. }
  40365. /* Acquire a PENDING lock
  40366. */
  40367. if( locktype==EXCLUSIVE_LOCK && res ){
  40368. newLocktype = PENDING_LOCK;
  40369. gotPendingLock = 0;
  40370. }
  40371. /* Acquire an EXCLUSIVE lock
  40372. */
  40373. if( locktype==EXCLUSIVE_LOCK && res ){
  40374. assert( pFile->locktype>=SHARED_LOCK );
  40375. res = winUnlockReadLock(pFile);
  40376. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  40377. SHARED_SIZE, 0);
  40378. if( res ){
  40379. newLocktype = EXCLUSIVE_LOCK;
  40380. }else{
  40381. lastErrno = osGetLastError();
  40382. winGetReadLock(pFile);
  40383. }
  40384. }
  40385. /* If we are holding a PENDING lock that ought to be released, then
  40386. ** release it now.
  40387. */
  40388. if( gotPendingLock && locktype==SHARED_LOCK ){
  40389. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  40390. }
  40391. /* Update the state of the lock has held in the file descriptor then
  40392. ** return the appropriate result code.
  40393. */
  40394. if( res ){
  40395. rc = SQLITE_OK;
  40396. }else{
  40397. pFile->lastErrno = lastErrno;
  40398. rc = SQLITE_BUSY;
  40399. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  40400. pFile->h, locktype, newLocktype));
  40401. }
  40402. pFile->locktype = (u8)newLocktype;
  40403. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  40404. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  40405. return rc;
  40406. }
  40407. /*
  40408. ** This routine checks if there is a RESERVED lock held on the specified
  40409. ** file by this or any other process. If such a lock is held, return
  40410. ** non-zero, otherwise zero.
  40411. */
  40412. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  40413. int res;
  40414. winFile *pFile = (winFile*)id;
  40415. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  40416. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  40417. assert( id!=0 );
  40418. if( pFile->locktype>=RESERVED_LOCK ){
  40419. res = 1;
  40420. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  40421. }else{
  40422. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  40423. if( res ){
  40424. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  40425. }
  40426. res = !res;
  40427. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  40428. }
  40429. *pResOut = res;
  40430. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  40431. pFile->h, pResOut, *pResOut));
  40432. return SQLITE_OK;
  40433. }
  40434. /*
  40435. ** Lower the locking level on file descriptor id to locktype. locktype
  40436. ** must be either NO_LOCK or SHARED_LOCK.
  40437. **
  40438. ** If the locking level of the file descriptor is already at or below
  40439. ** the requested locking level, this routine is a no-op.
  40440. **
  40441. ** It is not possible for this routine to fail if the second argument
  40442. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  40443. ** might return SQLITE_IOERR;
  40444. */
  40445. static int winUnlock(sqlite3_file *id, int locktype){
  40446. int type;
  40447. winFile *pFile = (winFile*)id;
  40448. int rc = SQLITE_OK;
  40449. assert( pFile!=0 );
  40450. assert( locktype<=SHARED_LOCK );
  40451. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  40452. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  40453. type = pFile->locktype;
  40454. if( type>=EXCLUSIVE_LOCK ){
  40455. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  40456. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  40457. /* This should never happen. We should always be able to
  40458. ** reacquire the read lock */
  40459. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  40460. "winUnlock", pFile->zPath);
  40461. }
  40462. }
  40463. if( type>=RESERVED_LOCK ){
  40464. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  40465. }
  40466. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  40467. winUnlockReadLock(pFile);
  40468. }
  40469. if( type>=PENDING_LOCK ){
  40470. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  40471. }
  40472. pFile->locktype = (u8)locktype;
  40473. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  40474. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  40475. return rc;
  40476. }
  40477. /******************************************************************************
  40478. ****************************** No-op Locking **********************************
  40479. **
  40480. ** Of the various locking implementations available, this is by far the
  40481. ** simplest: locking is ignored. No attempt is made to lock the database
  40482. ** file for reading or writing.
  40483. **
  40484. ** This locking mode is appropriate for use on read-only databases
  40485. ** (ex: databases that are burned into CD-ROM, for example.) It can
  40486. ** also be used if the application employs some external mechanism to
  40487. ** prevent simultaneous access of the same database by two or more
  40488. ** database connections. But there is a serious risk of database
  40489. ** corruption if this locking mode is used in situations where multiple
  40490. ** database connections are accessing the same database file at the same
  40491. ** time and one or more of those connections are writing.
  40492. */
  40493. static int winNolockLock(sqlite3_file *id, int locktype){
  40494. UNUSED_PARAMETER(id);
  40495. UNUSED_PARAMETER(locktype);
  40496. return SQLITE_OK;
  40497. }
  40498. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  40499. UNUSED_PARAMETER(id);
  40500. UNUSED_PARAMETER(pResOut);
  40501. return SQLITE_OK;
  40502. }
  40503. static int winNolockUnlock(sqlite3_file *id, int locktype){
  40504. UNUSED_PARAMETER(id);
  40505. UNUSED_PARAMETER(locktype);
  40506. return SQLITE_OK;
  40507. }
  40508. /******************* End of the no-op lock implementation *********************
  40509. ******************************************************************************/
  40510. /*
  40511. ** If *pArg is initially negative then this is a query. Set *pArg to
  40512. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  40513. **
  40514. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  40515. */
  40516. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  40517. if( *pArg<0 ){
  40518. *pArg = (pFile->ctrlFlags & mask)!=0;
  40519. }else if( (*pArg)==0 ){
  40520. pFile->ctrlFlags &= ~mask;
  40521. }else{
  40522. pFile->ctrlFlags |= mask;
  40523. }
  40524. }
  40525. /* Forward references to VFS helper methods used for temporary files */
  40526. static int winGetTempname(sqlite3_vfs *, char **);
  40527. static int winIsDir(const void *);
  40528. static BOOL winIsDriveLetterAndColon(const char *);
  40529. /*
  40530. ** Control and query of the open file handle.
  40531. */
  40532. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  40533. winFile *pFile = (winFile*)id;
  40534. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  40535. switch( op ){
  40536. case SQLITE_FCNTL_LOCKSTATE: {
  40537. *(int*)pArg = pFile->locktype;
  40538. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40539. return SQLITE_OK;
  40540. }
  40541. case SQLITE_FCNTL_LAST_ERRNO: {
  40542. *(int*)pArg = (int)pFile->lastErrno;
  40543. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40544. return SQLITE_OK;
  40545. }
  40546. case SQLITE_FCNTL_CHUNK_SIZE: {
  40547. pFile->szChunk = *(int *)pArg;
  40548. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40549. return SQLITE_OK;
  40550. }
  40551. case SQLITE_FCNTL_SIZE_HINT: {
  40552. if( pFile->szChunk>0 ){
  40553. sqlite3_int64 oldSz;
  40554. int rc = winFileSize(id, &oldSz);
  40555. if( rc==SQLITE_OK ){
  40556. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  40557. if( newSz>oldSz ){
  40558. SimulateIOErrorBenign(1);
  40559. rc = winTruncate(id, newSz);
  40560. SimulateIOErrorBenign(0);
  40561. }
  40562. }
  40563. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  40564. return rc;
  40565. }
  40566. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40567. return SQLITE_OK;
  40568. }
  40569. case SQLITE_FCNTL_PERSIST_WAL: {
  40570. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  40571. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40572. return SQLITE_OK;
  40573. }
  40574. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  40575. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  40576. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40577. return SQLITE_OK;
  40578. }
  40579. case SQLITE_FCNTL_VFSNAME: {
  40580. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  40581. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40582. return SQLITE_OK;
  40583. }
  40584. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  40585. int *a = (int*)pArg;
  40586. if( a[0]>0 ){
  40587. winIoerrRetry = a[0];
  40588. }else{
  40589. a[0] = winIoerrRetry;
  40590. }
  40591. if( a[1]>0 ){
  40592. winIoerrRetryDelay = a[1];
  40593. }else{
  40594. a[1] = winIoerrRetryDelay;
  40595. }
  40596. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40597. return SQLITE_OK;
  40598. }
  40599. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  40600. LPHANDLE phFile = (LPHANDLE)pArg;
  40601. *phFile = pFile->h;
  40602. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40603. return SQLITE_OK;
  40604. }
  40605. #ifdef SQLITE_TEST
  40606. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  40607. LPHANDLE phFile = (LPHANDLE)pArg;
  40608. HANDLE hOldFile = pFile->h;
  40609. pFile->h = *phFile;
  40610. *phFile = hOldFile;
  40611. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  40612. hOldFile, pFile->h));
  40613. return SQLITE_OK;
  40614. }
  40615. #endif
  40616. case SQLITE_FCNTL_TEMPFILENAME: {
  40617. char *zTFile = 0;
  40618. int rc = winGetTempname(pFile->pVfs, &zTFile);
  40619. if( rc==SQLITE_OK ){
  40620. *(char**)pArg = zTFile;
  40621. }
  40622. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  40623. return rc;
  40624. }
  40625. #if SQLITE_MAX_MMAP_SIZE>0
  40626. case SQLITE_FCNTL_MMAP_SIZE: {
  40627. i64 newLimit = *(i64*)pArg;
  40628. int rc = SQLITE_OK;
  40629. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  40630. newLimit = sqlite3GlobalConfig.mxMmap;
  40631. }
  40632. /* The value of newLimit may be eventually cast to (SIZE_T) and passed
  40633. ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
  40634. ** least a 64-bit type. */
  40635. if( newLimit>0 && sizeof(SIZE_T)<8 ){
  40636. newLimit = (newLimit & 0x7FFFFFFF);
  40637. }
  40638. *(i64*)pArg = pFile->mmapSizeMax;
  40639. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  40640. pFile->mmapSizeMax = newLimit;
  40641. if( pFile->mmapSize>0 ){
  40642. winUnmapfile(pFile);
  40643. rc = winMapfile(pFile, -1);
  40644. }
  40645. }
  40646. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  40647. return rc;
  40648. }
  40649. #endif
  40650. }
  40651. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  40652. return SQLITE_NOTFOUND;
  40653. }
  40654. /*
  40655. ** Return the sector size in bytes of the underlying block device for
  40656. ** the specified file. This is almost always 512 bytes, but may be
  40657. ** larger for some devices.
  40658. **
  40659. ** SQLite code assumes this function cannot fail. It also assumes that
  40660. ** if two files are created in the same file-system directory (i.e.
  40661. ** a database and its journal file) that the sector size will be the
  40662. ** same for both.
  40663. */
  40664. static int winSectorSize(sqlite3_file *id){
  40665. (void)id;
  40666. return SQLITE_DEFAULT_SECTOR_SIZE;
  40667. }
  40668. /*
  40669. ** Return a vector of device characteristics.
  40670. */
  40671. static int winDeviceCharacteristics(sqlite3_file *id){
  40672. winFile *p = (winFile*)id;
  40673. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  40674. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  40675. }
  40676. /*
  40677. ** Windows will only let you create file view mappings
  40678. ** on allocation size granularity boundaries.
  40679. ** During sqlite3_os_init() we do a GetSystemInfo()
  40680. ** to get the granularity size.
  40681. */
  40682. static SYSTEM_INFO winSysInfo;
  40683. #ifndef SQLITE_OMIT_WAL
  40684. /*
  40685. ** Helper functions to obtain and relinquish the global mutex. The
  40686. ** global mutex is used to protect the winLockInfo objects used by
  40687. ** this file, all of which may be shared by multiple threads.
  40688. **
  40689. ** Function winShmMutexHeld() is used to assert() that the global mutex
  40690. ** is held when required. This function is only used as part of assert()
  40691. ** statements. e.g.
  40692. **
  40693. ** winShmEnterMutex()
  40694. ** assert( winShmMutexHeld() );
  40695. ** winShmLeaveMutex()
  40696. */
  40697. static sqlite3_mutex *winBigLock = 0;
  40698. static void winShmEnterMutex(void){
  40699. sqlite3_mutex_enter(winBigLock);
  40700. }
  40701. static void winShmLeaveMutex(void){
  40702. sqlite3_mutex_leave(winBigLock);
  40703. }
  40704. #ifndef NDEBUG
  40705. static int winShmMutexHeld(void) {
  40706. return sqlite3_mutex_held(winBigLock);
  40707. }
  40708. #endif
  40709. /*
  40710. ** Object used to represent a single file opened and mmapped to provide
  40711. ** shared memory. When multiple threads all reference the same
  40712. ** log-summary, each thread has its own winFile object, but they all
  40713. ** point to a single instance of this object. In other words, each
  40714. ** log-summary is opened only once per process.
  40715. **
  40716. ** winShmMutexHeld() must be true when creating or destroying
  40717. ** this object or while reading or writing the following fields:
  40718. **
  40719. ** nRef
  40720. ** pNext
  40721. **
  40722. ** The following fields are read-only after the object is created:
  40723. **
  40724. ** fid
  40725. ** zFilename
  40726. **
  40727. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  40728. ** winShmMutexHeld() is true when reading or writing any other field
  40729. ** in this structure.
  40730. **
  40731. */
  40732. struct winShmNode {
  40733. sqlite3_mutex *mutex; /* Mutex to access this object */
  40734. char *zFilename; /* Name of the file */
  40735. winFile hFile; /* File handle from winOpen */
  40736. int szRegion; /* Size of shared-memory regions */
  40737. int nRegion; /* Size of array apRegion */
  40738. u8 isReadonly; /* True if read-only */
  40739. u8 isUnlocked; /* True if no DMS lock held */
  40740. struct ShmRegion {
  40741. HANDLE hMap; /* File handle from CreateFileMapping */
  40742. void *pMap;
  40743. } *aRegion;
  40744. DWORD lastErrno; /* The Windows errno from the last I/O error */
  40745. int nRef; /* Number of winShm objects pointing to this */
  40746. winShm *pFirst; /* All winShm objects pointing to this */
  40747. winShmNode *pNext; /* Next in list of all winShmNode objects */
  40748. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  40749. u8 nextShmId; /* Next available winShm.id value */
  40750. #endif
  40751. };
  40752. /*
  40753. ** A global array of all winShmNode objects.
  40754. **
  40755. ** The winShmMutexHeld() must be true while reading or writing this list.
  40756. */
  40757. static winShmNode *winShmNodeList = 0;
  40758. /*
  40759. ** Structure used internally by this VFS to record the state of an
  40760. ** open shared memory connection.
  40761. **
  40762. ** The following fields are initialized when this object is created and
  40763. ** are read-only thereafter:
  40764. **
  40765. ** winShm.pShmNode
  40766. ** winShm.id
  40767. **
  40768. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  40769. ** while accessing any read/write fields.
  40770. */
  40771. struct winShm {
  40772. winShmNode *pShmNode; /* The underlying winShmNode object */
  40773. winShm *pNext; /* Next winShm with the same winShmNode */
  40774. u8 hasMutex; /* True if holding the winShmNode mutex */
  40775. u16 sharedMask; /* Mask of shared locks held */
  40776. u16 exclMask; /* Mask of exclusive locks held */
  40777. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  40778. u8 id; /* Id of this connection with its winShmNode */
  40779. #endif
  40780. };
  40781. /*
  40782. ** Constants used for locking
  40783. */
  40784. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  40785. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  40786. /*
  40787. ** Apply advisory locks for all n bytes beginning at ofst.
  40788. */
  40789. #define WINSHM_UNLCK 1
  40790. #define WINSHM_RDLCK 2
  40791. #define WINSHM_WRLCK 3
  40792. static int winShmSystemLock(
  40793. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  40794. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  40795. int ofst, /* Offset to first byte to be locked/unlocked */
  40796. int nByte /* Number of bytes to lock or unlock */
  40797. ){
  40798. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  40799. /* Access to the winShmNode object is serialized by the caller */
  40800. assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
  40801. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  40802. pFile->hFile.h, lockType, ofst, nByte));
  40803. /* Release/Acquire the system-level lock */
  40804. if( lockType==WINSHM_UNLCK ){
  40805. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  40806. }else{
  40807. /* Initialize the locking parameters */
  40808. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  40809. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  40810. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  40811. }
  40812. if( rc!= 0 ){
  40813. rc = SQLITE_OK;
  40814. }else{
  40815. pFile->lastErrno = osGetLastError();
  40816. rc = SQLITE_BUSY;
  40817. }
  40818. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  40819. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  40820. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  40821. return rc;
  40822. }
  40823. /* Forward references to VFS methods */
  40824. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  40825. static int winDelete(sqlite3_vfs *,const char*,int);
  40826. /*
  40827. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  40828. **
  40829. ** This is not a VFS shared-memory method; it is a utility function called
  40830. ** by VFS shared-memory methods.
  40831. */
  40832. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  40833. winShmNode **pp;
  40834. winShmNode *p;
  40835. assert( winShmMutexHeld() );
  40836. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  40837. osGetCurrentProcessId(), deleteFlag));
  40838. pp = &winShmNodeList;
  40839. while( (p = *pp)!=0 ){
  40840. if( p->nRef==0 ){
  40841. int i;
  40842. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  40843. for(i=0; i<p->nRegion; i++){
  40844. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  40845. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  40846. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  40847. UNUSED_VARIABLE_VALUE(bRc);
  40848. bRc = osCloseHandle(p->aRegion[i].hMap);
  40849. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  40850. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  40851. UNUSED_VARIABLE_VALUE(bRc);
  40852. }
  40853. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  40854. SimulateIOErrorBenign(1);
  40855. winClose((sqlite3_file *)&p->hFile);
  40856. SimulateIOErrorBenign(0);
  40857. }
  40858. if( deleteFlag ){
  40859. SimulateIOErrorBenign(1);
  40860. sqlite3BeginBenignMalloc();
  40861. winDelete(pVfs, p->zFilename, 0);
  40862. sqlite3EndBenignMalloc();
  40863. SimulateIOErrorBenign(0);
  40864. }
  40865. *pp = p->pNext;
  40866. sqlite3_free(p->aRegion);
  40867. sqlite3_free(p);
  40868. }else{
  40869. pp = &p->pNext;
  40870. }
  40871. }
  40872. }
  40873. /*
  40874. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  40875. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  40876. ** code otherwise.
  40877. **
  40878. ** If the DMS cannot be locked because this is a readonly_shm=1
  40879. ** connection and no other process already holds a lock, return
  40880. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  40881. */
  40882. static int winLockSharedMemory(winShmNode *pShmNode){
  40883. int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
  40884. if( rc==SQLITE_OK ){
  40885. if( pShmNode->isReadonly ){
  40886. pShmNode->isUnlocked = 1;
  40887. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40888. return SQLITE_READONLY_CANTINIT;
  40889. }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
  40890. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40891. return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  40892. "winLockSharedMemory", pShmNode->zFilename);
  40893. }
  40894. }
  40895. if( rc==SQLITE_OK ){
  40896. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40897. }
  40898. return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  40899. }
  40900. /*
  40901. ** Open the shared-memory area associated with database file pDbFd.
  40902. **
  40903. ** When opening a new shared-memory file, if no other instances of that
  40904. ** file are currently open, in this process or in other processes, then
  40905. ** the file must be truncated to zero length or have its header cleared.
  40906. */
  40907. static int winOpenSharedMemory(winFile *pDbFd){
  40908. struct winShm *p; /* The connection to be opened */
  40909. winShmNode *pShmNode = 0; /* The underlying mmapped file */
  40910. int rc = SQLITE_OK; /* Result code */
  40911. winShmNode *pNew; /* Newly allocated winShmNode */
  40912. int nName; /* Size of zName in bytes */
  40913. assert( pDbFd->pShm==0 ); /* Not previously opened */
  40914. /* Allocate space for the new sqlite3_shm object. Also speculatively
  40915. ** allocate space for a new winShmNode and filename.
  40916. */
  40917. p = sqlite3MallocZero( sizeof(*p) );
  40918. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  40919. nName = sqlite3Strlen30(pDbFd->zPath);
  40920. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  40921. if( pNew==0 ){
  40922. sqlite3_free(p);
  40923. return SQLITE_IOERR_NOMEM_BKPT;
  40924. }
  40925. pNew->zFilename = (char*)&pNew[1];
  40926. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  40927. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  40928. /* Look to see if there is an existing winShmNode that can be used.
  40929. ** If no matching winShmNode currently exists, create a new one.
  40930. */
  40931. winShmEnterMutex();
  40932. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  40933. /* TBD need to come up with better match here. Perhaps
  40934. ** use FILE_ID_BOTH_DIR_INFO Structure.
  40935. */
  40936. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  40937. }
  40938. if( pShmNode ){
  40939. sqlite3_free(pNew);
  40940. }else{
  40941. int inFlags = SQLITE_OPEN_WAL;
  40942. int outFlags = 0;
  40943. pShmNode = pNew;
  40944. pNew = 0;
  40945. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  40946. pShmNode->pNext = winShmNodeList;
  40947. winShmNodeList = pShmNode;
  40948. if( sqlite3GlobalConfig.bCoreMutex ){
  40949. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  40950. if( pShmNode->mutex==0 ){
  40951. rc = SQLITE_IOERR_NOMEM_BKPT;
  40952. goto shm_open_err;
  40953. }
  40954. }
  40955. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  40956. inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  40957. }else{
  40958. inFlags |= SQLITE_OPEN_READONLY;
  40959. }
  40960. rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
  40961. (sqlite3_file*)&pShmNode->hFile,
  40962. inFlags, &outFlags);
  40963. if( rc!=SQLITE_OK ){
  40964. rc = winLogError(rc, osGetLastError(), "winOpenShm",
  40965. pShmNode->zFilename);
  40966. goto shm_open_err;
  40967. }
  40968. if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
  40969. rc = winLockSharedMemory(pShmNode);
  40970. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  40971. }
  40972. /* Make the new connection a child of the winShmNode */
  40973. p->pShmNode = pShmNode;
  40974. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  40975. p->id = pShmNode->nextShmId++;
  40976. #endif
  40977. pShmNode->nRef++;
  40978. pDbFd->pShm = p;
  40979. winShmLeaveMutex();
  40980. /* The reference count on pShmNode has already been incremented under
  40981. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  40982. ** new (struct winShm) object to the pShmNode has been set. All that is
  40983. ** left to do is to link the new object into the linked list starting
  40984. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  40985. ** mutex.
  40986. */
  40987. sqlite3_mutex_enter(pShmNode->mutex);
  40988. p->pNext = pShmNode->pFirst;
  40989. pShmNode->pFirst = p;
  40990. sqlite3_mutex_leave(pShmNode->mutex);
  40991. return rc;
  40992. /* Jump here on any error */
  40993. shm_open_err:
  40994. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40995. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  40996. sqlite3_free(p);
  40997. sqlite3_free(pNew);
  40998. winShmLeaveMutex();
  40999. return rc;
  41000. }
  41001. /*
  41002. ** Close a connection to shared-memory. Delete the underlying
  41003. ** storage if deleteFlag is true.
  41004. */
  41005. static int winShmUnmap(
  41006. sqlite3_file *fd, /* Database holding shared memory */
  41007. int deleteFlag /* Delete after closing if true */
  41008. ){
  41009. winFile *pDbFd; /* Database holding shared-memory */
  41010. winShm *p; /* The connection to be closed */
  41011. winShmNode *pShmNode; /* The underlying shared-memory file */
  41012. winShm **pp; /* For looping over sibling connections */
  41013. pDbFd = (winFile*)fd;
  41014. p = pDbFd->pShm;
  41015. if( p==0 ) return SQLITE_OK;
  41016. pShmNode = p->pShmNode;
  41017. /* Remove connection p from the set of connections associated
  41018. ** with pShmNode */
  41019. sqlite3_mutex_enter(pShmNode->mutex);
  41020. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  41021. *pp = p->pNext;
  41022. /* Free the connection p */
  41023. sqlite3_free(p);
  41024. pDbFd->pShm = 0;
  41025. sqlite3_mutex_leave(pShmNode->mutex);
  41026. /* If pShmNode->nRef has reached 0, then close the underlying
  41027. ** shared-memory file, too */
  41028. winShmEnterMutex();
  41029. assert( pShmNode->nRef>0 );
  41030. pShmNode->nRef--;
  41031. if( pShmNode->nRef==0 ){
  41032. winShmPurge(pDbFd->pVfs, deleteFlag);
  41033. }
  41034. winShmLeaveMutex();
  41035. return SQLITE_OK;
  41036. }
  41037. /*
  41038. ** Change the lock state for a shared-memory segment.
  41039. */
  41040. static int winShmLock(
  41041. sqlite3_file *fd, /* Database file holding the shared memory */
  41042. int ofst, /* First lock to acquire or release */
  41043. int n, /* Number of locks to acquire or release */
  41044. int flags /* What to do with the lock */
  41045. ){
  41046. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  41047. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  41048. winShm *pX; /* For looping over all siblings */
  41049. winShmNode *pShmNode = p->pShmNode;
  41050. int rc = SQLITE_OK; /* Result code */
  41051. u16 mask; /* Mask of locks to take or release */
  41052. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  41053. assert( n>=1 );
  41054. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  41055. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  41056. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  41057. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  41058. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  41059. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  41060. assert( n>1 || mask==(1<<ofst) );
  41061. sqlite3_mutex_enter(pShmNode->mutex);
  41062. if( flags & SQLITE_SHM_UNLOCK ){
  41063. u16 allMask = 0; /* Mask of locks held by siblings */
  41064. /* See if any siblings hold this same lock */
  41065. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  41066. if( pX==p ) continue;
  41067. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  41068. allMask |= pX->sharedMask;
  41069. }
  41070. /* Unlock the system-level locks */
  41071. if( (mask & allMask)==0 ){
  41072. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  41073. }else{
  41074. rc = SQLITE_OK;
  41075. }
  41076. /* Undo the local locks */
  41077. if( rc==SQLITE_OK ){
  41078. p->exclMask &= ~mask;
  41079. p->sharedMask &= ~mask;
  41080. }
  41081. }else if( flags & SQLITE_SHM_SHARED ){
  41082. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  41083. /* Find out which shared locks are already held by sibling connections.
  41084. ** If any sibling already holds an exclusive lock, go ahead and return
  41085. ** SQLITE_BUSY.
  41086. */
  41087. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  41088. if( (pX->exclMask & mask)!=0 ){
  41089. rc = SQLITE_BUSY;
  41090. break;
  41091. }
  41092. allShared |= pX->sharedMask;
  41093. }
  41094. /* Get shared locks at the system level, if necessary */
  41095. if( rc==SQLITE_OK ){
  41096. if( (allShared & mask)==0 ){
  41097. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  41098. }else{
  41099. rc = SQLITE_OK;
  41100. }
  41101. }
  41102. /* Get the local shared locks */
  41103. if( rc==SQLITE_OK ){
  41104. p->sharedMask |= mask;
  41105. }
  41106. }else{
  41107. /* Make sure no sibling connections hold locks that will block this
  41108. ** lock. If any do, return SQLITE_BUSY right away.
  41109. */
  41110. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  41111. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  41112. rc = SQLITE_BUSY;
  41113. break;
  41114. }
  41115. }
  41116. /* Get the exclusive locks at the system level. Then if successful
  41117. ** also mark the local connection as being locked.
  41118. */
  41119. if( rc==SQLITE_OK ){
  41120. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  41121. if( rc==SQLITE_OK ){
  41122. assert( (p->sharedMask & mask)==0 );
  41123. p->exclMask |= mask;
  41124. }
  41125. }
  41126. }
  41127. sqlite3_mutex_leave(pShmNode->mutex);
  41128. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  41129. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  41130. sqlite3ErrName(rc)));
  41131. return rc;
  41132. }
  41133. /*
  41134. ** Implement a memory barrier or memory fence on shared memory.
  41135. **
  41136. ** All loads and stores begun before the barrier must complete before
  41137. ** any load or store begun after the barrier.
  41138. */
  41139. static void winShmBarrier(
  41140. sqlite3_file *fd /* Database holding the shared memory */
  41141. ){
  41142. UNUSED_PARAMETER(fd);
  41143. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  41144. winShmEnterMutex(); /* Also mutex, for redundancy */
  41145. winShmLeaveMutex();
  41146. }
  41147. /*
  41148. ** This function is called to obtain a pointer to region iRegion of the
  41149. ** shared-memory associated with the database file fd. Shared-memory regions
  41150. ** are numbered starting from zero. Each shared-memory region is szRegion
  41151. ** bytes in size.
  41152. **
  41153. ** If an error occurs, an error code is returned and *pp is set to NULL.
  41154. **
  41155. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  41156. ** region has not been allocated (by any client, including one running in a
  41157. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  41158. ** isWrite is non-zero and the requested shared-memory region has not yet
  41159. ** been allocated, it is allocated by this function.
  41160. **
  41161. ** If the shared-memory region has already been allocated or is allocated by
  41162. ** this call as described above, then it is mapped into this processes
  41163. ** address space (if it is not already), *pp is set to point to the mapped
  41164. ** memory and SQLITE_OK returned.
  41165. */
  41166. static int winShmMap(
  41167. sqlite3_file *fd, /* Handle open on database file */
  41168. int iRegion, /* Region to retrieve */
  41169. int szRegion, /* Size of regions */
  41170. int isWrite, /* True to extend file if necessary */
  41171. void volatile **pp /* OUT: Mapped memory */
  41172. ){
  41173. winFile *pDbFd = (winFile*)fd;
  41174. winShm *pShm = pDbFd->pShm;
  41175. winShmNode *pShmNode;
  41176. DWORD protect = PAGE_READWRITE;
  41177. DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
  41178. int rc = SQLITE_OK;
  41179. if( !pShm ){
  41180. rc = winOpenSharedMemory(pDbFd);
  41181. if( rc!=SQLITE_OK ) return rc;
  41182. pShm = pDbFd->pShm;
  41183. }
  41184. pShmNode = pShm->pShmNode;
  41185. sqlite3_mutex_enter(pShmNode->mutex);
  41186. if( pShmNode->isUnlocked ){
  41187. rc = winLockSharedMemory(pShmNode);
  41188. if( rc!=SQLITE_OK ) goto shmpage_out;
  41189. pShmNode->isUnlocked = 0;
  41190. }
  41191. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  41192. if( pShmNode->nRegion<=iRegion ){
  41193. struct ShmRegion *apNew; /* New aRegion[] array */
  41194. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  41195. sqlite3_int64 sz; /* Current size of wal-index file */
  41196. pShmNode->szRegion = szRegion;
  41197. /* The requested region is not mapped into this processes address space.
  41198. ** Check to see if it has been allocated (i.e. if the wal-index file is
  41199. ** large enough to contain the requested region).
  41200. */
  41201. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  41202. if( rc!=SQLITE_OK ){
  41203. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  41204. "winShmMap1", pDbFd->zPath);
  41205. goto shmpage_out;
  41206. }
  41207. if( sz<nByte ){
  41208. /* The requested memory region does not exist. If isWrite is set to
  41209. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  41210. **
  41211. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  41212. ** the requested memory region.
  41213. */
  41214. if( !isWrite ) goto shmpage_out;
  41215. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  41216. if( rc!=SQLITE_OK ){
  41217. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  41218. "winShmMap2", pDbFd->zPath);
  41219. goto shmpage_out;
  41220. }
  41221. }
  41222. /* Map the requested memory region into this processes address space. */
  41223. apNew = (struct ShmRegion *)sqlite3_realloc64(
  41224. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  41225. );
  41226. if( !apNew ){
  41227. rc = SQLITE_IOERR_NOMEM_BKPT;
  41228. goto shmpage_out;
  41229. }
  41230. pShmNode->aRegion = apNew;
  41231. if( pShmNode->isReadonly ){
  41232. protect = PAGE_READONLY;
  41233. flags = FILE_MAP_READ;
  41234. }
  41235. while( pShmNode->nRegion<=iRegion ){
  41236. HANDLE hMap = NULL; /* file-mapping handle */
  41237. void *pMap = 0; /* Mapped memory region */
  41238. #if SQLITE_OS_WINRT
  41239. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  41240. NULL, protect, nByte, NULL
  41241. );
  41242. #elif defined(SQLITE_WIN32_HAS_WIDE)
  41243. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  41244. NULL, protect, 0, nByte, NULL
  41245. );
  41246. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  41247. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  41248. NULL, protect, 0, nByte, NULL
  41249. );
  41250. #endif
  41251. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  41252. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  41253. hMap ? "ok" : "failed"));
  41254. if( hMap ){
  41255. int iOffset = pShmNode->nRegion*szRegion;
  41256. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  41257. #if SQLITE_OS_WINRT
  41258. pMap = osMapViewOfFileFromApp(hMap, flags,
  41259. iOffset - iOffsetShift, szRegion + iOffsetShift
  41260. );
  41261. #else
  41262. pMap = osMapViewOfFile(hMap, flags,
  41263. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  41264. );
  41265. #endif
  41266. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  41267. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  41268. szRegion, pMap ? "ok" : "failed"));
  41269. }
  41270. if( !pMap ){
  41271. pShmNode->lastErrno = osGetLastError();
  41272. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  41273. "winShmMap3", pDbFd->zPath);
  41274. if( hMap ) osCloseHandle(hMap);
  41275. goto shmpage_out;
  41276. }
  41277. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  41278. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  41279. pShmNode->nRegion++;
  41280. }
  41281. }
  41282. shmpage_out:
  41283. if( pShmNode->nRegion>iRegion ){
  41284. int iOffset = iRegion*szRegion;
  41285. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  41286. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  41287. *pp = (void *)&p[iOffsetShift];
  41288. }else{
  41289. *pp = 0;
  41290. }
  41291. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  41292. sqlite3_mutex_leave(pShmNode->mutex);
  41293. return rc;
  41294. }
  41295. #else
  41296. # define winShmMap 0
  41297. # define winShmLock 0
  41298. # define winShmBarrier 0
  41299. # define winShmUnmap 0
  41300. #endif /* #ifndef SQLITE_OMIT_WAL */
  41301. /*
  41302. ** Cleans up the mapped region of the specified file, if any.
  41303. */
  41304. #if SQLITE_MAX_MMAP_SIZE>0
  41305. static int winUnmapfile(winFile *pFile){
  41306. assert( pFile!=0 );
  41307. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  41308. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  41309. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  41310. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  41311. if( pFile->pMapRegion ){
  41312. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  41313. pFile->lastErrno = osGetLastError();
  41314. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  41315. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  41316. pFile->pMapRegion));
  41317. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  41318. "winUnmapfile1", pFile->zPath);
  41319. }
  41320. pFile->pMapRegion = 0;
  41321. pFile->mmapSize = 0;
  41322. pFile->mmapSizeActual = 0;
  41323. }
  41324. if( pFile->hMap!=NULL ){
  41325. if( !osCloseHandle(pFile->hMap) ){
  41326. pFile->lastErrno = osGetLastError();
  41327. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  41328. osGetCurrentProcessId(), pFile, pFile->hMap));
  41329. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  41330. "winUnmapfile2", pFile->zPath);
  41331. }
  41332. pFile->hMap = NULL;
  41333. }
  41334. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  41335. osGetCurrentProcessId(), pFile));
  41336. return SQLITE_OK;
  41337. }
  41338. /*
  41339. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  41340. ** is already mapped, the existing mapping is replaced by the new). Or, if
  41341. ** there already exists a mapping for this file, and there are still
  41342. ** outstanding xFetch() references to it, this function is a no-op.
  41343. **
  41344. ** If parameter nByte is non-negative, then it is the requested size of
  41345. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  41346. ** requested size is the size of the file on disk. The actual size of the
  41347. ** created mapping is either the requested size or the value configured
  41348. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  41349. **
  41350. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  41351. ** recreated as a result of outstanding references) or an SQLite error
  41352. ** code otherwise.
  41353. */
  41354. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  41355. sqlite3_int64 nMap = nByte;
  41356. int rc;
  41357. assert( nMap>=0 || pFd->nFetchOut==0 );
  41358. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  41359. osGetCurrentProcessId(), pFd, nByte));
  41360. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  41361. if( nMap<0 ){
  41362. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  41363. if( rc ){
  41364. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  41365. osGetCurrentProcessId(), pFd));
  41366. return SQLITE_IOERR_FSTAT;
  41367. }
  41368. }
  41369. if( nMap>pFd->mmapSizeMax ){
  41370. nMap = pFd->mmapSizeMax;
  41371. }
  41372. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  41373. if( nMap==0 && pFd->mmapSize>0 ){
  41374. winUnmapfile(pFd);
  41375. }
  41376. if( nMap!=pFd->mmapSize ){
  41377. void *pNew = 0;
  41378. DWORD protect = PAGE_READONLY;
  41379. DWORD flags = FILE_MAP_READ;
  41380. winUnmapfile(pFd);
  41381. #ifdef SQLITE_MMAP_READWRITE
  41382. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  41383. protect = PAGE_READWRITE;
  41384. flags |= FILE_MAP_WRITE;
  41385. }
  41386. #endif
  41387. #if SQLITE_OS_WINRT
  41388. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  41389. #elif defined(SQLITE_WIN32_HAS_WIDE)
  41390. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  41391. (DWORD)((nMap>>32) & 0xffffffff),
  41392. (DWORD)(nMap & 0xffffffff), NULL);
  41393. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  41394. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  41395. (DWORD)((nMap>>32) & 0xffffffff),
  41396. (DWORD)(nMap & 0xffffffff), NULL);
  41397. #endif
  41398. if( pFd->hMap==NULL ){
  41399. pFd->lastErrno = osGetLastError();
  41400. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  41401. "winMapfile1", pFd->zPath);
  41402. /* Log the error, but continue normal operation using xRead/xWrite */
  41403. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  41404. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  41405. return SQLITE_OK;
  41406. }
  41407. assert( (nMap % winSysInfo.dwPageSize)==0 );
  41408. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  41409. #if SQLITE_OS_WINRT
  41410. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  41411. #else
  41412. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  41413. #endif
  41414. if( pNew==NULL ){
  41415. osCloseHandle(pFd->hMap);
  41416. pFd->hMap = NULL;
  41417. pFd->lastErrno = osGetLastError();
  41418. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  41419. "winMapfile2", pFd->zPath);
  41420. /* Log the error, but continue normal operation using xRead/xWrite */
  41421. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  41422. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  41423. return SQLITE_OK;
  41424. }
  41425. pFd->pMapRegion = pNew;
  41426. pFd->mmapSize = nMap;
  41427. pFd->mmapSizeActual = nMap;
  41428. }
  41429. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  41430. osGetCurrentProcessId(), pFd));
  41431. return SQLITE_OK;
  41432. }
  41433. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  41434. /*
  41435. ** If possible, return a pointer to a mapping of file fd starting at offset
  41436. ** iOff. The mapping must be valid for at least nAmt bytes.
  41437. **
  41438. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  41439. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  41440. ** Finally, if an error does occur, return an SQLite error code. The final
  41441. ** value of *pp is undefined in this case.
  41442. **
  41443. ** If this function does return a pointer, the caller must eventually
  41444. ** release the reference by calling winUnfetch().
  41445. */
  41446. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  41447. #if SQLITE_MAX_MMAP_SIZE>0
  41448. winFile *pFd = (winFile*)fd; /* The underlying database file */
  41449. #endif
  41450. *pp = 0;
  41451. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  41452. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  41453. #if SQLITE_MAX_MMAP_SIZE>0
  41454. if( pFd->mmapSizeMax>0 ){
  41455. if( pFd->pMapRegion==0 ){
  41456. int rc = winMapfile(pFd, -1);
  41457. if( rc!=SQLITE_OK ){
  41458. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  41459. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  41460. return rc;
  41461. }
  41462. }
  41463. if( pFd->mmapSize >= iOff+nAmt ){
  41464. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  41465. pFd->nFetchOut++;
  41466. }
  41467. }
  41468. #endif
  41469. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  41470. osGetCurrentProcessId(), fd, pp, *pp));
  41471. return SQLITE_OK;
  41472. }
  41473. /*
  41474. ** If the third argument is non-NULL, then this function releases a
  41475. ** reference obtained by an earlier call to winFetch(). The second
  41476. ** argument passed to this function must be the same as the corresponding
  41477. ** argument that was passed to the winFetch() invocation.
  41478. **
  41479. ** Or, if the third argument is NULL, then this function is being called
  41480. ** to inform the VFS layer that, according to POSIX, any existing mapping
  41481. ** may now be invalid and should be unmapped.
  41482. */
  41483. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  41484. #if SQLITE_MAX_MMAP_SIZE>0
  41485. winFile *pFd = (winFile*)fd; /* The underlying database file */
  41486. /* If p==0 (unmap the entire file) then there must be no outstanding
  41487. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  41488. ** then there must be at least one outstanding. */
  41489. assert( (p==0)==(pFd->nFetchOut==0) );
  41490. /* If p!=0, it must match the iOff value. */
  41491. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  41492. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  41493. osGetCurrentProcessId(), pFd, iOff, p));
  41494. if( p ){
  41495. pFd->nFetchOut--;
  41496. }else{
  41497. /* FIXME: If Windows truly always prevents truncating or deleting a
  41498. ** file while a mapping is held, then the following winUnmapfile() call
  41499. ** is unnecessary can be omitted - potentially improving
  41500. ** performance. */
  41501. winUnmapfile(pFd);
  41502. }
  41503. assert( pFd->nFetchOut>=0 );
  41504. #endif
  41505. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  41506. osGetCurrentProcessId(), fd));
  41507. return SQLITE_OK;
  41508. }
  41509. /*
  41510. ** Here ends the implementation of all sqlite3_file methods.
  41511. **
  41512. ********************** End sqlite3_file Methods *******************************
  41513. ******************************************************************************/
  41514. /*
  41515. ** This vector defines all the methods that can operate on an
  41516. ** sqlite3_file for win32.
  41517. */
  41518. static const sqlite3_io_methods winIoMethod = {
  41519. 3, /* iVersion */
  41520. winClose, /* xClose */
  41521. winRead, /* xRead */
  41522. winWrite, /* xWrite */
  41523. winTruncate, /* xTruncate */
  41524. winSync, /* xSync */
  41525. winFileSize, /* xFileSize */
  41526. winLock, /* xLock */
  41527. winUnlock, /* xUnlock */
  41528. winCheckReservedLock, /* xCheckReservedLock */
  41529. winFileControl, /* xFileControl */
  41530. winSectorSize, /* xSectorSize */
  41531. winDeviceCharacteristics, /* xDeviceCharacteristics */
  41532. winShmMap, /* xShmMap */
  41533. winShmLock, /* xShmLock */
  41534. winShmBarrier, /* xShmBarrier */
  41535. winShmUnmap, /* xShmUnmap */
  41536. winFetch, /* xFetch */
  41537. winUnfetch /* xUnfetch */
  41538. };
  41539. /*
  41540. ** This vector defines all the methods that can operate on an
  41541. ** sqlite3_file for win32 without performing any locking.
  41542. */
  41543. static const sqlite3_io_methods winIoNolockMethod = {
  41544. 3, /* iVersion */
  41545. winClose, /* xClose */
  41546. winRead, /* xRead */
  41547. winWrite, /* xWrite */
  41548. winTruncate, /* xTruncate */
  41549. winSync, /* xSync */
  41550. winFileSize, /* xFileSize */
  41551. winNolockLock, /* xLock */
  41552. winNolockUnlock, /* xUnlock */
  41553. winNolockCheckReservedLock, /* xCheckReservedLock */
  41554. winFileControl, /* xFileControl */
  41555. winSectorSize, /* xSectorSize */
  41556. winDeviceCharacteristics, /* xDeviceCharacteristics */
  41557. winShmMap, /* xShmMap */
  41558. winShmLock, /* xShmLock */
  41559. winShmBarrier, /* xShmBarrier */
  41560. winShmUnmap, /* xShmUnmap */
  41561. winFetch, /* xFetch */
  41562. winUnfetch /* xUnfetch */
  41563. };
  41564. static winVfsAppData winAppData = {
  41565. &winIoMethod, /* pMethod */
  41566. 0, /* pAppData */
  41567. 0 /* bNoLock */
  41568. };
  41569. static winVfsAppData winNolockAppData = {
  41570. &winIoNolockMethod, /* pMethod */
  41571. 0, /* pAppData */
  41572. 1 /* bNoLock */
  41573. };
  41574. /****************************************************************************
  41575. **************************** sqlite3_vfs methods ****************************
  41576. **
  41577. ** This division contains the implementation of methods on the
  41578. ** sqlite3_vfs object.
  41579. */
  41580. #if defined(__CYGWIN__)
  41581. /*
  41582. ** Convert a filename from whatever the underlying operating system
  41583. ** supports for filenames into UTF-8. Space to hold the result is
  41584. ** obtained from malloc and must be freed by the calling function.
  41585. */
  41586. static char *winConvertToUtf8Filename(const void *zFilename){
  41587. char *zConverted = 0;
  41588. if( osIsNT() ){
  41589. zConverted = winUnicodeToUtf8(zFilename);
  41590. }
  41591. #ifdef SQLITE_WIN32_HAS_ANSI
  41592. else{
  41593. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  41594. }
  41595. #endif
  41596. /* caller will handle out of memory */
  41597. return zConverted;
  41598. }
  41599. #endif
  41600. /*
  41601. ** Convert a UTF-8 filename into whatever form the underlying
  41602. ** operating system wants filenames in. Space to hold the result
  41603. ** is obtained from malloc and must be freed by the calling
  41604. ** function.
  41605. */
  41606. static void *winConvertFromUtf8Filename(const char *zFilename){
  41607. void *zConverted = 0;
  41608. if( osIsNT() ){
  41609. zConverted = winUtf8ToUnicode(zFilename);
  41610. }
  41611. #ifdef SQLITE_WIN32_HAS_ANSI
  41612. else{
  41613. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  41614. }
  41615. #endif
  41616. /* caller will handle out of memory */
  41617. return zConverted;
  41618. }
  41619. /*
  41620. ** This function returns non-zero if the specified UTF-8 string buffer
  41621. ** ends with a directory separator character or one was successfully
  41622. ** added to it.
  41623. */
  41624. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  41625. if( zBuf ){
  41626. int nLen = sqlite3Strlen30(zBuf);
  41627. if( nLen>0 ){
  41628. if( winIsDirSep(zBuf[nLen-1]) ){
  41629. return 1;
  41630. }else if( nLen+1<nBuf ){
  41631. zBuf[nLen] = winGetDirSep();
  41632. zBuf[nLen+1] = '\0';
  41633. return 1;
  41634. }
  41635. }
  41636. }
  41637. return 0;
  41638. }
  41639. /*
  41640. ** Create a temporary file name and store the resulting pointer into pzBuf.
  41641. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  41642. */
  41643. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  41644. static char zChars[] =
  41645. "abcdefghijklmnopqrstuvwxyz"
  41646. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  41647. "0123456789";
  41648. size_t i, j;
  41649. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  41650. int nMax, nBuf, nDir, nLen;
  41651. char *zBuf;
  41652. /* It's odd to simulate an io-error here, but really this is just
  41653. ** using the io-error infrastructure to test that SQLite handles this
  41654. ** function failing.
  41655. */
  41656. SimulateIOError( return SQLITE_IOERR );
  41657. /* Allocate a temporary buffer to store the fully qualified file
  41658. ** name for the temporary file. If this fails, we cannot continue.
  41659. */
  41660. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  41661. zBuf = sqlite3MallocZero( nBuf );
  41662. if( !zBuf ){
  41663. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41664. return SQLITE_IOERR_NOMEM_BKPT;
  41665. }
  41666. /* Figure out the effective temporary directory. First, check if one
  41667. ** has been explicitly set by the application; otherwise, use the one
  41668. ** configured by the operating system.
  41669. */
  41670. nDir = nMax - (nPre + 15);
  41671. assert( nDir>0 );
  41672. if( sqlite3_temp_directory ){
  41673. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  41674. if( nDirLen>0 ){
  41675. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  41676. nDirLen++;
  41677. }
  41678. if( nDirLen>nDir ){
  41679. sqlite3_free(zBuf);
  41680. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  41681. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  41682. }
  41683. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  41684. }
  41685. }
  41686. #if defined(__CYGWIN__)
  41687. else{
  41688. static const char *azDirs[] = {
  41689. 0, /* getenv("SQLITE_TMPDIR") */
  41690. 0, /* getenv("TMPDIR") */
  41691. 0, /* getenv("TMP") */
  41692. 0, /* getenv("TEMP") */
  41693. 0, /* getenv("USERPROFILE") */
  41694. "/var/tmp",
  41695. "/usr/tmp",
  41696. "/tmp",
  41697. ".",
  41698. 0 /* List terminator */
  41699. };
  41700. unsigned int i;
  41701. const char *zDir = 0;
  41702. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  41703. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  41704. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  41705. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  41706. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  41707. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  41708. void *zConverted;
  41709. if( zDir==0 ) continue;
  41710. /* If the path starts with a drive letter followed by the colon
  41711. ** character, assume it is already a native Win32 path; otherwise,
  41712. ** it must be converted to a native Win32 path via the Cygwin API
  41713. ** prior to using it.
  41714. */
  41715. if( winIsDriveLetterAndColon(zDir) ){
  41716. zConverted = winConvertFromUtf8Filename(zDir);
  41717. if( !zConverted ){
  41718. sqlite3_free(zBuf);
  41719. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41720. return SQLITE_IOERR_NOMEM_BKPT;
  41721. }
  41722. if( winIsDir(zConverted) ){
  41723. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  41724. sqlite3_free(zConverted);
  41725. break;
  41726. }
  41727. sqlite3_free(zConverted);
  41728. }else{
  41729. zConverted = sqlite3MallocZero( nMax+1 );
  41730. if( !zConverted ){
  41731. sqlite3_free(zBuf);
  41732. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41733. return SQLITE_IOERR_NOMEM_BKPT;
  41734. }
  41735. if( cygwin_conv_path(
  41736. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  41737. zConverted, nMax+1)<0 ){
  41738. sqlite3_free(zConverted);
  41739. sqlite3_free(zBuf);
  41740. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  41741. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  41742. "winGetTempname2", zDir);
  41743. }
  41744. if( winIsDir(zConverted) ){
  41745. /* At this point, we know the candidate directory exists and should
  41746. ** be used. However, we may need to convert the string containing
  41747. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  41748. */
  41749. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  41750. if( !zUtf8 ){
  41751. sqlite3_free(zConverted);
  41752. sqlite3_free(zBuf);
  41753. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41754. return SQLITE_IOERR_NOMEM_BKPT;
  41755. }
  41756. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  41757. sqlite3_free(zUtf8);
  41758. sqlite3_free(zConverted);
  41759. break;
  41760. }
  41761. sqlite3_free(zConverted);
  41762. }
  41763. }
  41764. }
  41765. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  41766. else if( osIsNT() ){
  41767. char *zMulti;
  41768. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  41769. if( !zWidePath ){
  41770. sqlite3_free(zBuf);
  41771. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41772. return SQLITE_IOERR_NOMEM_BKPT;
  41773. }
  41774. if( osGetTempPathW(nMax, zWidePath)==0 ){
  41775. sqlite3_free(zWidePath);
  41776. sqlite3_free(zBuf);
  41777. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  41778. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  41779. "winGetTempname2", 0);
  41780. }
  41781. zMulti = winUnicodeToUtf8(zWidePath);
  41782. if( zMulti ){
  41783. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  41784. sqlite3_free(zMulti);
  41785. sqlite3_free(zWidePath);
  41786. }else{
  41787. sqlite3_free(zWidePath);
  41788. sqlite3_free(zBuf);
  41789. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41790. return SQLITE_IOERR_NOMEM_BKPT;
  41791. }
  41792. }
  41793. #ifdef SQLITE_WIN32_HAS_ANSI
  41794. else{
  41795. char *zUtf8;
  41796. char *zMbcsPath = sqlite3MallocZero( nMax );
  41797. if( !zMbcsPath ){
  41798. sqlite3_free(zBuf);
  41799. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41800. return SQLITE_IOERR_NOMEM_BKPT;
  41801. }
  41802. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  41803. sqlite3_free(zBuf);
  41804. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  41805. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  41806. "winGetTempname3", 0);
  41807. }
  41808. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  41809. if( zUtf8 ){
  41810. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  41811. sqlite3_free(zUtf8);
  41812. }else{
  41813. sqlite3_free(zBuf);
  41814. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41815. return SQLITE_IOERR_NOMEM_BKPT;
  41816. }
  41817. }
  41818. #endif /* SQLITE_WIN32_HAS_ANSI */
  41819. #endif /* !SQLITE_OS_WINRT */
  41820. /*
  41821. ** Check to make sure the temporary directory ends with an appropriate
  41822. ** separator. If it does not and there is not enough space left to add
  41823. ** one, fail.
  41824. */
  41825. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  41826. sqlite3_free(zBuf);
  41827. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  41828. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  41829. }
  41830. /*
  41831. ** Check that the output buffer is large enough for the temporary file
  41832. ** name in the following format:
  41833. **
  41834. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  41835. **
  41836. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  41837. ** account for the space used by the 15 character random suffix and the
  41838. ** two trailing NUL characters. The final directory separator character
  41839. ** has already added if it was not already present.
  41840. */
  41841. nLen = sqlite3Strlen30(zBuf);
  41842. if( (nLen + nPre + 17) > nBuf ){
  41843. sqlite3_free(zBuf);
  41844. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  41845. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  41846. }
  41847. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  41848. j = sqlite3Strlen30(zBuf);
  41849. sqlite3_randomness(15, &zBuf[j]);
  41850. for(i=0; i<15; i++, j++){
  41851. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  41852. }
  41853. zBuf[j] = 0;
  41854. zBuf[j+1] = 0;
  41855. *pzBuf = zBuf;
  41856. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  41857. return SQLITE_OK;
  41858. }
  41859. /*
  41860. ** Return TRUE if the named file is really a directory. Return false if
  41861. ** it is something other than a directory, or if there is any kind of memory
  41862. ** allocation failure.
  41863. */
  41864. static int winIsDir(const void *zConverted){
  41865. DWORD attr;
  41866. int rc = 0;
  41867. DWORD lastErrno;
  41868. if( osIsNT() ){
  41869. int cnt = 0;
  41870. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  41871. memset(&sAttrData, 0, sizeof(sAttrData));
  41872. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  41873. GetFileExInfoStandard,
  41874. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  41875. if( !rc ){
  41876. return 0; /* Invalid name? */
  41877. }
  41878. attr = sAttrData.dwFileAttributes;
  41879. #if SQLITE_OS_WINCE==0
  41880. }else{
  41881. attr = osGetFileAttributesA((char*)zConverted);
  41882. #endif
  41883. }
  41884. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  41885. }
  41886. /* forward reference */
  41887. static int winAccess(
  41888. sqlite3_vfs *pVfs, /* Not used on win32 */
  41889. const char *zFilename, /* Name of file to check */
  41890. int flags, /* Type of test to make on this file */
  41891. int *pResOut /* OUT: Result */
  41892. );
  41893. /*
  41894. ** Open a file.
  41895. */
  41896. static int winOpen(
  41897. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  41898. const char *zName, /* Name of the file (UTF-8) */
  41899. sqlite3_file *id, /* Write the SQLite file handle here */
  41900. int flags, /* Open mode flags */
  41901. int *pOutFlags /* Status return flags */
  41902. ){
  41903. HANDLE h;
  41904. DWORD lastErrno = 0;
  41905. DWORD dwDesiredAccess;
  41906. DWORD dwShareMode;
  41907. DWORD dwCreationDisposition;
  41908. DWORD dwFlagsAndAttributes = 0;
  41909. #if SQLITE_OS_WINCE
  41910. int isTemp = 0;
  41911. #endif
  41912. winVfsAppData *pAppData;
  41913. winFile *pFile = (winFile*)id;
  41914. void *zConverted; /* Filename in OS encoding */
  41915. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  41916. int cnt = 0;
  41917. /* If argument zPath is a NULL pointer, this function is required to open
  41918. ** a temporary file. Use this buffer to store the file name in.
  41919. */
  41920. char *zTmpname = 0; /* For temporary filename, if necessary. */
  41921. int rc = SQLITE_OK; /* Function Return Code */
  41922. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  41923. int eType = flags&0xFFFFFF00; /* Type of file to open */
  41924. #endif
  41925. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  41926. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  41927. int isCreate = (flags & SQLITE_OPEN_CREATE);
  41928. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  41929. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  41930. #ifndef NDEBUG
  41931. int isOpenJournal = (isCreate && (
  41932. eType==SQLITE_OPEN_MASTER_JOURNAL
  41933. || eType==SQLITE_OPEN_MAIN_JOURNAL
  41934. || eType==SQLITE_OPEN_WAL
  41935. ));
  41936. #endif
  41937. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  41938. zUtf8Name, id, flags, pOutFlags));
  41939. /* Check the following statements are true:
  41940. **
  41941. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  41942. ** (b) if CREATE is set, then READWRITE must also be set, and
  41943. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  41944. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  41945. */
  41946. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  41947. assert(isCreate==0 || isReadWrite);
  41948. assert(isExclusive==0 || isCreate);
  41949. assert(isDelete==0 || isCreate);
  41950. /* The main DB, main journal, WAL file and master journal are never
  41951. ** automatically deleted. Nor are they ever temporary files. */
  41952. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  41953. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  41954. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  41955. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  41956. /* Assert that the upper layer has set one of the "file-type" flags. */
  41957. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  41958. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  41959. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  41960. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  41961. );
  41962. assert( pFile!=0 );
  41963. memset(pFile, 0, sizeof(winFile));
  41964. pFile->h = INVALID_HANDLE_VALUE;
  41965. #if SQLITE_OS_WINRT
  41966. if( !zUtf8Name && !sqlite3_temp_directory ){
  41967. sqlite3_log(SQLITE_ERROR,
  41968. "sqlite3_temp_directory variable should be set for WinRT");
  41969. }
  41970. #endif
  41971. /* If the second argument to this function is NULL, generate a
  41972. ** temporary file name to use
  41973. */
  41974. if( !zUtf8Name ){
  41975. assert( isDelete && !isOpenJournal );
  41976. rc = winGetTempname(pVfs, &zTmpname);
  41977. if( rc!=SQLITE_OK ){
  41978. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  41979. return rc;
  41980. }
  41981. zUtf8Name = zTmpname;
  41982. }
  41983. /* Database filenames are double-zero terminated if they are not
  41984. ** URIs with parameters. Hence, they can always be passed into
  41985. ** sqlite3_uri_parameter().
  41986. */
  41987. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  41988. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  41989. /* Convert the filename to the system encoding. */
  41990. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  41991. if( zConverted==0 ){
  41992. sqlite3_free(zTmpname);
  41993. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  41994. return SQLITE_IOERR_NOMEM_BKPT;
  41995. }
  41996. if( winIsDir(zConverted) ){
  41997. sqlite3_free(zConverted);
  41998. sqlite3_free(zTmpname);
  41999. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  42000. return SQLITE_CANTOPEN_ISDIR;
  42001. }
  42002. if( isReadWrite ){
  42003. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  42004. }else{
  42005. dwDesiredAccess = GENERIC_READ;
  42006. }
  42007. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  42008. ** created. SQLite doesn't use it to indicate "exclusive access"
  42009. ** as it is usually understood.
  42010. */
  42011. if( isExclusive ){
  42012. /* Creates a new file, only if it does not already exist. */
  42013. /* If the file exists, it fails. */
  42014. dwCreationDisposition = CREATE_NEW;
  42015. }else if( isCreate ){
  42016. /* Open existing file, or create if it doesn't exist */
  42017. dwCreationDisposition = OPEN_ALWAYS;
  42018. }else{
  42019. /* Opens a file, only if it exists. */
  42020. dwCreationDisposition = OPEN_EXISTING;
  42021. }
  42022. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  42023. if( isDelete ){
  42024. #if SQLITE_OS_WINCE
  42025. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  42026. isTemp = 1;
  42027. #else
  42028. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  42029. | FILE_ATTRIBUTE_HIDDEN
  42030. | FILE_FLAG_DELETE_ON_CLOSE;
  42031. #endif
  42032. }else{
  42033. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  42034. }
  42035. /* Reports from the internet are that performance is always
  42036. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  42037. #if SQLITE_OS_WINCE
  42038. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  42039. #endif
  42040. if( osIsNT() ){
  42041. #if SQLITE_OS_WINRT
  42042. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  42043. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  42044. extendedParameters.dwFileAttributes =
  42045. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  42046. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  42047. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  42048. extendedParameters.lpSecurityAttributes = NULL;
  42049. extendedParameters.hTemplateFile = NULL;
  42050. do{
  42051. h = osCreateFile2((LPCWSTR)zConverted,
  42052. dwDesiredAccess,
  42053. dwShareMode,
  42054. dwCreationDisposition,
  42055. &extendedParameters);
  42056. if( h!=INVALID_HANDLE_VALUE ) break;
  42057. if( isReadWrite ){
  42058. int rc2, isRO = 0;
  42059. sqlite3BeginBenignMalloc();
  42060. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  42061. sqlite3EndBenignMalloc();
  42062. if( rc2==SQLITE_OK && isRO ) break;
  42063. }
  42064. }while( winRetryIoerr(&cnt, &lastErrno) );
  42065. #else
  42066. do{
  42067. h = osCreateFileW((LPCWSTR)zConverted,
  42068. dwDesiredAccess,
  42069. dwShareMode, NULL,
  42070. dwCreationDisposition,
  42071. dwFlagsAndAttributes,
  42072. NULL);
  42073. if( h!=INVALID_HANDLE_VALUE ) break;
  42074. if( isReadWrite ){
  42075. int rc2, isRO = 0;
  42076. sqlite3BeginBenignMalloc();
  42077. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  42078. sqlite3EndBenignMalloc();
  42079. if( rc2==SQLITE_OK && isRO ) break;
  42080. }
  42081. }while( winRetryIoerr(&cnt, &lastErrno) );
  42082. #endif
  42083. }
  42084. #ifdef SQLITE_WIN32_HAS_ANSI
  42085. else{
  42086. do{
  42087. h = osCreateFileA((LPCSTR)zConverted,
  42088. dwDesiredAccess,
  42089. dwShareMode, NULL,
  42090. dwCreationDisposition,
  42091. dwFlagsAndAttributes,
  42092. NULL);
  42093. if( h!=INVALID_HANDLE_VALUE ) break;
  42094. if( isReadWrite ){
  42095. int rc2, isRO = 0;
  42096. sqlite3BeginBenignMalloc();
  42097. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  42098. sqlite3EndBenignMalloc();
  42099. if( rc2==SQLITE_OK && isRO ) break;
  42100. }
  42101. }while( winRetryIoerr(&cnt, &lastErrno) );
  42102. }
  42103. #endif
  42104. winLogIoerr(cnt, __LINE__);
  42105. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  42106. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  42107. if( h==INVALID_HANDLE_VALUE ){
  42108. sqlite3_free(zConverted);
  42109. sqlite3_free(zTmpname);
  42110. if( isReadWrite && !isExclusive ){
  42111. return winOpen(pVfs, zName, id,
  42112. ((flags|SQLITE_OPEN_READONLY) &
  42113. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  42114. pOutFlags);
  42115. }else{
  42116. pFile->lastErrno = lastErrno;
  42117. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  42118. return SQLITE_CANTOPEN_BKPT;
  42119. }
  42120. }
  42121. if( pOutFlags ){
  42122. if( isReadWrite ){
  42123. *pOutFlags = SQLITE_OPEN_READWRITE;
  42124. }else{
  42125. *pOutFlags = SQLITE_OPEN_READONLY;
  42126. }
  42127. }
  42128. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  42129. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  42130. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  42131. pAppData = (winVfsAppData*)pVfs->pAppData;
  42132. #if SQLITE_OS_WINCE
  42133. {
  42134. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  42135. && ((pAppData==NULL) || !pAppData->bNoLock)
  42136. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  42137. ){
  42138. osCloseHandle(h);
  42139. sqlite3_free(zConverted);
  42140. sqlite3_free(zTmpname);
  42141. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  42142. return rc;
  42143. }
  42144. }
  42145. if( isTemp ){
  42146. pFile->zDeleteOnClose = zConverted;
  42147. }else
  42148. #endif
  42149. {
  42150. sqlite3_free(zConverted);
  42151. }
  42152. sqlite3_free(zTmpname);
  42153. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  42154. pFile->pVfs = pVfs;
  42155. pFile->h = h;
  42156. if( isReadonly ){
  42157. pFile->ctrlFlags |= WINFILE_RDONLY;
  42158. }
  42159. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  42160. pFile->ctrlFlags |= WINFILE_PSOW;
  42161. }
  42162. pFile->lastErrno = NO_ERROR;
  42163. pFile->zPath = zName;
  42164. #if SQLITE_MAX_MMAP_SIZE>0
  42165. pFile->hMap = NULL;
  42166. pFile->pMapRegion = 0;
  42167. pFile->mmapSize = 0;
  42168. pFile->mmapSizeActual = 0;
  42169. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  42170. #endif
  42171. OpenCounter(+1);
  42172. return rc;
  42173. }
  42174. /*
  42175. ** Delete the named file.
  42176. **
  42177. ** Note that Windows does not allow a file to be deleted if some other
  42178. ** process has it open. Sometimes a virus scanner or indexing program
  42179. ** will open a journal file shortly after it is created in order to do
  42180. ** whatever it does. While this other process is holding the
  42181. ** file open, we will be unable to delete it. To work around this
  42182. ** problem, we delay 100 milliseconds and try to delete again. Up
  42183. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  42184. ** up and returning an error.
  42185. */
  42186. static int winDelete(
  42187. sqlite3_vfs *pVfs, /* Not used on win32 */
  42188. const char *zFilename, /* Name of file to delete */
  42189. int syncDir /* Not used on win32 */
  42190. ){
  42191. int cnt = 0;
  42192. int rc;
  42193. DWORD attr;
  42194. DWORD lastErrno = 0;
  42195. void *zConverted;
  42196. UNUSED_PARAMETER(pVfs);
  42197. UNUSED_PARAMETER(syncDir);
  42198. SimulateIOError(return SQLITE_IOERR_DELETE);
  42199. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  42200. zConverted = winConvertFromUtf8Filename(zFilename);
  42201. if( zConverted==0 ){
  42202. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  42203. return SQLITE_IOERR_NOMEM_BKPT;
  42204. }
  42205. if( osIsNT() ){
  42206. do {
  42207. #if SQLITE_OS_WINRT
  42208. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  42209. memset(&sAttrData, 0, sizeof(sAttrData));
  42210. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  42211. &sAttrData) ){
  42212. attr = sAttrData.dwFileAttributes;
  42213. }else{
  42214. lastErrno = osGetLastError();
  42215. if( lastErrno==ERROR_FILE_NOT_FOUND
  42216. || lastErrno==ERROR_PATH_NOT_FOUND ){
  42217. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  42218. }else{
  42219. rc = SQLITE_ERROR;
  42220. }
  42221. break;
  42222. }
  42223. #else
  42224. attr = osGetFileAttributesW(zConverted);
  42225. #endif
  42226. if ( attr==INVALID_FILE_ATTRIBUTES ){
  42227. lastErrno = osGetLastError();
  42228. if( lastErrno==ERROR_FILE_NOT_FOUND
  42229. || lastErrno==ERROR_PATH_NOT_FOUND ){
  42230. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  42231. }else{
  42232. rc = SQLITE_ERROR;
  42233. }
  42234. break;
  42235. }
  42236. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  42237. rc = SQLITE_ERROR; /* Files only. */
  42238. break;
  42239. }
  42240. if ( osDeleteFileW(zConverted) ){
  42241. rc = SQLITE_OK; /* Deleted OK. */
  42242. break;
  42243. }
  42244. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  42245. rc = SQLITE_ERROR; /* No more retries. */
  42246. break;
  42247. }
  42248. } while(1);
  42249. }
  42250. #ifdef SQLITE_WIN32_HAS_ANSI
  42251. else{
  42252. do {
  42253. attr = osGetFileAttributesA(zConverted);
  42254. if ( attr==INVALID_FILE_ATTRIBUTES ){
  42255. lastErrno = osGetLastError();
  42256. if( lastErrno==ERROR_FILE_NOT_FOUND
  42257. || lastErrno==ERROR_PATH_NOT_FOUND ){
  42258. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  42259. }else{
  42260. rc = SQLITE_ERROR;
  42261. }
  42262. break;
  42263. }
  42264. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  42265. rc = SQLITE_ERROR; /* Files only. */
  42266. break;
  42267. }
  42268. if ( osDeleteFileA(zConverted) ){
  42269. rc = SQLITE_OK; /* Deleted OK. */
  42270. break;
  42271. }
  42272. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  42273. rc = SQLITE_ERROR; /* No more retries. */
  42274. break;
  42275. }
  42276. } while(1);
  42277. }
  42278. #endif
  42279. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  42280. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  42281. }else{
  42282. winLogIoerr(cnt, __LINE__);
  42283. }
  42284. sqlite3_free(zConverted);
  42285. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  42286. return rc;
  42287. }
  42288. /*
  42289. ** Check the existence and status of a file.
  42290. */
  42291. static int winAccess(
  42292. sqlite3_vfs *pVfs, /* Not used on win32 */
  42293. const char *zFilename, /* Name of file to check */
  42294. int flags, /* Type of test to make on this file */
  42295. int *pResOut /* OUT: Result */
  42296. ){
  42297. DWORD attr;
  42298. int rc = 0;
  42299. DWORD lastErrno = 0;
  42300. void *zConverted;
  42301. UNUSED_PARAMETER(pVfs);
  42302. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  42303. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  42304. zFilename, flags, pResOut));
  42305. zConverted = winConvertFromUtf8Filename(zFilename);
  42306. if( zConverted==0 ){
  42307. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  42308. return SQLITE_IOERR_NOMEM_BKPT;
  42309. }
  42310. if( osIsNT() ){
  42311. int cnt = 0;
  42312. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  42313. memset(&sAttrData, 0, sizeof(sAttrData));
  42314. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  42315. GetFileExInfoStandard,
  42316. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  42317. if( rc ){
  42318. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  42319. ** as if it does not exist.
  42320. */
  42321. if( flags==SQLITE_ACCESS_EXISTS
  42322. && sAttrData.nFileSizeHigh==0
  42323. && sAttrData.nFileSizeLow==0 ){
  42324. attr = INVALID_FILE_ATTRIBUTES;
  42325. }else{
  42326. attr = sAttrData.dwFileAttributes;
  42327. }
  42328. }else{
  42329. winLogIoerr(cnt, __LINE__);
  42330. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  42331. sqlite3_free(zConverted);
  42332. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  42333. zFilename);
  42334. }else{
  42335. attr = INVALID_FILE_ATTRIBUTES;
  42336. }
  42337. }
  42338. }
  42339. #ifdef SQLITE_WIN32_HAS_ANSI
  42340. else{
  42341. attr = osGetFileAttributesA((char*)zConverted);
  42342. }
  42343. #endif
  42344. sqlite3_free(zConverted);
  42345. switch( flags ){
  42346. case SQLITE_ACCESS_READ:
  42347. case SQLITE_ACCESS_EXISTS:
  42348. rc = attr!=INVALID_FILE_ATTRIBUTES;
  42349. break;
  42350. case SQLITE_ACCESS_READWRITE:
  42351. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  42352. (attr & FILE_ATTRIBUTE_READONLY)==0;
  42353. break;
  42354. default:
  42355. assert(!"Invalid flags argument");
  42356. }
  42357. *pResOut = rc;
  42358. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  42359. zFilename, pResOut, *pResOut));
  42360. return SQLITE_OK;
  42361. }
  42362. /*
  42363. ** Returns non-zero if the specified path name starts with a drive letter
  42364. ** followed by a colon character.
  42365. */
  42366. static BOOL winIsDriveLetterAndColon(
  42367. const char *zPathname
  42368. ){
  42369. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  42370. }
  42371. /*
  42372. ** Returns non-zero if the specified path name should be used verbatim. If
  42373. ** non-zero is returned from this function, the calling function must simply
  42374. ** use the provided path name verbatim -OR- resolve it into a full path name
  42375. ** using the GetFullPathName Win32 API function (if available).
  42376. */
  42377. static BOOL winIsVerbatimPathname(
  42378. const char *zPathname
  42379. ){
  42380. /*
  42381. ** If the path name starts with a forward slash or a backslash, it is either
  42382. ** a legal UNC name, a volume relative path, or an absolute path name in the
  42383. ** "Unix" format on Windows. There is no easy way to differentiate between
  42384. ** the final two cases; therefore, we return the safer return value of TRUE
  42385. ** so that callers of this function will simply use it verbatim.
  42386. */
  42387. if ( winIsDirSep(zPathname[0]) ){
  42388. return TRUE;
  42389. }
  42390. /*
  42391. ** If the path name starts with a letter and a colon it is either a volume
  42392. ** relative path or an absolute path. Callers of this function must not
  42393. ** attempt to treat it as a relative path name (i.e. they should simply use
  42394. ** it verbatim).
  42395. */
  42396. if ( winIsDriveLetterAndColon(zPathname) ){
  42397. return TRUE;
  42398. }
  42399. /*
  42400. ** If we get to this point, the path name should almost certainly be a purely
  42401. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  42402. */
  42403. return FALSE;
  42404. }
  42405. /*
  42406. ** Turn a relative pathname into a full pathname. Write the full
  42407. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  42408. ** bytes in size.
  42409. */
  42410. static int winFullPathname(
  42411. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  42412. const char *zRelative, /* Possibly relative input path */
  42413. int nFull, /* Size of output buffer in bytes */
  42414. char *zFull /* Output buffer */
  42415. ){
  42416. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  42417. DWORD nByte;
  42418. void *zConverted;
  42419. char *zOut;
  42420. #endif
  42421. /* If this path name begins with "/X:", where "X" is any alphabetic
  42422. ** character, discard the initial "/" from the pathname.
  42423. */
  42424. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  42425. zRelative++;
  42426. }
  42427. #if defined(__CYGWIN__)
  42428. SimulateIOError( return SQLITE_ERROR );
  42429. UNUSED_PARAMETER(nFull);
  42430. assert( nFull>=pVfs->mxPathname );
  42431. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  42432. /*
  42433. ** NOTE: We are dealing with a relative path name and the data
  42434. ** directory has been set. Therefore, use it as the basis
  42435. ** for converting the relative path name to an absolute
  42436. ** one by prepending the data directory and a slash.
  42437. */
  42438. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  42439. if( !zOut ){
  42440. return SQLITE_IOERR_NOMEM_BKPT;
  42441. }
  42442. if( cygwin_conv_path(
  42443. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  42444. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  42445. sqlite3_free(zOut);
  42446. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  42447. "winFullPathname1", zRelative);
  42448. }else{
  42449. char *zUtf8 = winConvertToUtf8Filename(zOut);
  42450. if( !zUtf8 ){
  42451. sqlite3_free(zOut);
  42452. return SQLITE_IOERR_NOMEM_BKPT;
  42453. }
  42454. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  42455. sqlite3_data_directory, winGetDirSep(), zUtf8);
  42456. sqlite3_free(zUtf8);
  42457. sqlite3_free(zOut);
  42458. }
  42459. }else{
  42460. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  42461. if( !zOut ){
  42462. return SQLITE_IOERR_NOMEM_BKPT;
  42463. }
  42464. if( cygwin_conv_path(
  42465. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  42466. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  42467. sqlite3_free(zOut);
  42468. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  42469. "winFullPathname2", zRelative);
  42470. }else{
  42471. char *zUtf8 = winConvertToUtf8Filename(zOut);
  42472. if( !zUtf8 ){
  42473. sqlite3_free(zOut);
  42474. return SQLITE_IOERR_NOMEM_BKPT;
  42475. }
  42476. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  42477. sqlite3_free(zUtf8);
  42478. sqlite3_free(zOut);
  42479. }
  42480. }
  42481. return SQLITE_OK;
  42482. #endif
  42483. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  42484. SimulateIOError( return SQLITE_ERROR );
  42485. /* WinCE has no concept of a relative pathname, or so I am told. */
  42486. /* WinRT has no way to convert a relative path to an absolute one. */
  42487. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  42488. /*
  42489. ** NOTE: We are dealing with a relative path name and the data
  42490. ** directory has been set. Therefore, use it as the basis
  42491. ** for converting the relative path name to an absolute
  42492. ** one by prepending the data directory and a backslash.
  42493. */
  42494. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  42495. sqlite3_data_directory, winGetDirSep(), zRelative);
  42496. }else{
  42497. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  42498. }
  42499. return SQLITE_OK;
  42500. #endif
  42501. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  42502. /* It's odd to simulate an io-error here, but really this is just
  42503. ** using the io-error infrastructure to test that SQLite handles this
  42504. ** function failing. This function could fail if, for example, the
  42505. ** current working directory has been unlinked.
  42506. */
  42507. SimulateIOError( return SQLITE_ERROR );
  42508. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  42509. /*
  42510. ** NOTE: We are dealing with a relative path name and the data
  42511. ** directory has been set. Therefore, use it as the basis
  42512. ** for converting the relative path name to an absolute
  42513. ** one by prepending the data directory and a backslash.
  42514. */
  42515. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  42516. sqlite3_data_directory, winGetDirSep(), zRelative);
  42517. return SQLITE_OK;
  42518. }
  42519. zConverted = winConvertFromUtf8Filename(zRelative);
  42520. if( zConverted==0 ){
  42521. return SQLITE_IOERR_NOMEM_BKPT;
  42522. }
  42523. if( osIsNT() ){
  42524. LPWSTR zTemp;
  42525. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  42526. if( nByte==0 ){
  42527. sqlite3_free(zConverted);
  42528. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42529. "winFullPathname1", zRelative);
  42530. }
  42531. nByte += 3;
  42532. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  42533. if( zTemp==0 ){
  42534. sqlite3_free(zConverted);
  42535. return SQLITE_IOERR_NOMEM_BKPT;
  42536. }
  42537. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  42538. if( nByte==0 ){
  42539. sqlite3_free(zConverted);
  42540. sqlite3_free(zTemp);
  42541. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42542. "winFullPathname2", zRelative);
  42543. }
  42544. sqlite3_free(zConverted);
  42545. zOut = winUnicodeToUtf8(zTemp);
  42546. sqlite3_free(zTemp);
  42547. }
  42548. #ifdef SQLITE_WIN32_HAS_ANSI
  42549. else{
  42550. char *zTemp;
  42551. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  42552. if( nByte==0 ){
  42553. sqlite3_free(zConverted);
  42554. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42555. "winFullPathname3", zRelative);
  42556. }
  42557. nByte += 3;
  42558. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  42559. if( zTemp==0 ){
  42560. sqlite3_free(zConverted);
  42561. return SQLITE_IOERR_NOMEM_BKPT;
  42562. }
  42563. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  42564. if( nByte==0 ){
  42565. sqlite3_free(zConverted);
  42566. sqlite3_free(zTemp);
  42567. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42568. "winFullPathname4", zRelative);
  42569. }
  42570. sqlite3_free(zConverted);
  42571. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  42572. sqlite3_free(zTemp);
  42573. }
  42574. #endif
  42575. if( zOut ){
  42576. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  42577. sqlite3_free(zOut);
  42578. return SQLITE_OK;
  42579. }else{
  42580. return SQLITE_IOERR_NOMEM_BKPT;
  42581. }
  42582. #endif
  42583. }
  42584. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  42585. /*
  42586. ** Interfaces for opening a shared library, finding entry points
  42587. ** within the shared library, and closing the shared library.
  42588. */
  42589. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  42590. HANDLE h;
  42591. #if defined(__CYGWIN__)
  42592. int nFull = pVfs->mxPathname+1;
  42593. char *zFull = sqlite3MallocZero( nFull );
  42594. void *zConverted = 0;
  42595. if( zFull==0 ){
  42596. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  42597. return 0;
  42598. }
  42599. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  42600. sqlite3_free(zFull);
  42601. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  42602. return 0;
  42603. }
  42604. zConverted = winConvertFromUtf8Filename(zFull);
  42605. sqlite3_free(zFull);
  42606. #else
  42607. void *zConverted = winConvertFromUtf8Filename(zFilename);
  42608. UNUSED_PARAMETER(pVfs);
  42609. #endif
  42610. if( zConverted==0 ){
  42611. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  42612. return 0;
  42613. }
  42614. if( osIsNT() ){
  42615. #if SQLITE_OS_WINRT
  42616. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  42617. #else
  42618. h = osLoadLibraryW((LPCWSTR)zConverted);
  42619. #endif
  42620. }
  42621. #ifdef SQLITE_WIN32_HAS_ANSI
  42622. else{
  42623. h = osLoadLibraryA((char*)zConverted);
  42624. }
  42625. #endif
  42626. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  42627. sqlite3_free(zConverted);
  42628. return (void*)h;
  42629. }
  42630. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  42631. UNUSED_PARAMETER(pVfs);
  42632. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  42633. }
  42634. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  42635. FARPROC proc;
  42636. UNUSED_PARAMETER(pVfs);
  42637. proc = osGetProcAddressA((HANDLE)pH, zSym);
  42638. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  42639. (void*)pH, zSym, (void*)proc));
  42640. return (void(*)(void))proc;
  42641. }
  42642. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  42643. UNUSED_PARAMETER(pVfs);
  42644. osFreeLibrary((HANDLE)pHandle);
  42645. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  42646. }
  42647. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  42648. #define winDlOpen 0
  42649. #define winDlError 0
  42650. #define winDlSym 0
  42651. #define winDlClose 0
  42652. #endif
  42653. /* State information for the randomness gatherer. */
  42654. typedef struct EntropyGatherer EntropyGatherer;
  42655. struct EntropyGatherer {
  42656. unsigned char *a; /* Gather entropy into this buffer */
  42657. int na; /* Size of a[] in bytes */
  42658. int i; /* XOR next input into a[i] */
  42659. int nXor; /* Number of XOR operations done */
  42660. };
  42661. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  42662. /* Mix sz bytes of entropy into p. */
  42663. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  42664. int j, k;
  42665. for(j=0, k=p->i; j<sz; j++){
  42666. p->a[k++] ^= x[j];
  42667. if( k>=p->na ) k = 0;
  42668. }
  42669. p->i = k;
  42670. p->nXor += sz;
  42671. }
  42672. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  42673. /*
  42674. ** Write up to nBuf bytes of randomness into zBuf.
  42675. */
  42676. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  42677. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  42678. UNUSED_PARAMETER(pVfs);
  42679. memset(zBuf, 0, nBuf);
  42680. return nBuf;
  42681. #else
  42682. EntropyGatherer e;
  42683. UNUSED_PARAMETER(pVfs);
  42684. memset(zBuf, 0, nBuf);
  42685. e.a = (unsigned char*)zBuf;
  42686. e.na = nBuf;
  42687. e.nXor = 0;
  42688. e.i = 0;
  42689. {
  42690. SYSTEMTIME x;
  42691. osGetSystemTime(&x);
  42692. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  42693. }
  42694. {
  42695. DWORD pid = osGetCurrentProcessId();
  42696. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  42697. }
  42698. #if SQLITE_OS_WINRT
  42699. {
  42700. ULONGLONG cnt = osGetTickCount64();
  42701. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  42702. }
  42703. #else
  42704. {
  42705. DWORD cnt = osGetTickCount();
  42706. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  42707. }
  42708. #endif /* SQLITE_OS_WINRT */
  42709. {
  42710. LARGE_INTEGER i;
  42711. osQueryPerformanceCounter(&i);
  42712. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  42713. }
  42714. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  42715. {
  42716. UUID id;
  42717. memset(&id, 0, sizeof(UUID));
  42718. osUuidCreate(&id);
  42719. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  42720. memset(&id, 0, sizeof(UUID));
  42721. osUuidCreateSequential(&id);
  42722. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  42723. }
  42724. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  42725. return e.nXor>nBuf ? nBuf : e.nXor;
  42726. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  42727. }
  42728. /*
  42729. ** Sleep for a little while. Return the amount of time slept.
  42730. */
  42731. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  42732. sqlite3_win32_sleep((microsec+999)/1000);
  42733. UNUSED_PARAMETER(pVfs);
  42734. return ((microsec+999)/1000)*1000;
  42735. }
  42736. /*
  42737. ** The following variable, if set to a non-zero value, is interpreted as
  42738. ** the number of seconds since 1970 and is used to set the result of
  42739. ** sqlite3OsCurrentTime() during testing.
  42740. */
  42741. #ifdef SQLITE_TEST
  42742. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  42743. #endif
  42744. /*
  42745. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  42746. ** the current time and date as a Julian Day number times 86_400_000. In
  42747. ** other words, write into *piNow the number of milliseconds since the Julian
  42748. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  42749. ** proleptic Gregorian calendar.
  42750. **
  42751. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  42752. ** cannot be found.
  42753. */
  42754. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  42755. /* FILETIME structure is a 64-bit value representing the number of
  42756. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  42757. */
  42758. FILETIME ft;
  42759. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  42760. #ifdef SQLITE_TEST
  42761. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  42762. #endif
  42763. /* 2^32 - to avoid use of LL and warnings in gcc */
  42764. static const sqlite3_int64 max32BitValue =
  42765. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  42766. (sqlite3_int64)294967296;
  42767. #if SQLITE_OS_WINCE
  42768. SYSTEMTIME time;
  42769. osGetSystemTime(&time);
  42770. /* if SystemTimeToFileTime() fails, it returns zero. */
  42771. if (!osSystemTimeToFileTime(&time,&ft)){
  42772. return SQLITE_ERROR;
  42773. }
  42774. #else
  42775. osGetSystemTimeAsFileTime( &ft );
  42776. #endif
  42777. *piNow = winFiletimeEpoch +
  42778. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  42779. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  42780. #ifdef SQLITE_TEST
  42781. if( sqlite3_current_time ){
  42782. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  42783. }
  42784. #endif
  42785. UNUSED_PARAMETER(pVfs);
  42786. return SQLITE_OK;
  42787. }
  42788. /*
  42789. ** Find the current time (in Universal Coordinated Time). Write the
  42790. ** current time and date as a Julian Day number into *prNow and
  42791. ** return 0. Return 1 if the time and date cannot be found.
  42792. */
  42793. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  42794. int rc;
  42795. sqlite3_int64 i;
  42796. rc = winCurrentTimeInt64(pVfs, &i);
  42797. if( !rc ){
  42798. *prNow = i/86400000.0;
  42799. }
  42800. return rc;
  42801. }
  42802. /*
  42803. ** The idea is that this function works like a combination of
  42804. ** GetLastError() and FormatMessage() on Windows (or errno and
  42805. ** strerror_r() on Unix). After an error is returned by an OS
  42806. ** function, SQLite calls this function with zBuf pointing to
  42807. ** a buffer of nBuf bytes. The OS layer should populate the
  42808. ** buffer with a nul-terminated UTF-8 encoded error message
  42809. ** describing the last IO error to have occurred within the calling
  42810. ** thread.
  42811. **
  42812. ** If the error message is too large for the supplied buffer,
  42813. ** it should be truncated. The return value of xGetLastError
  42814. ** is zero if the error message fits in the buffer, or non-zero
  42815. ** otherwise (if the message was truncated). If non-zero is returned,
  42816. ** then it is not necessary to include the nul-terminator character
  42817. ** in the output buffer.
  42818. **
  42819. ** Not supplying an error message will have no adverse effect
  42820. ** on SQLite. It is fine to have an implementation that never
  42821. ** returns an error message:
  42822. **
  42823. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  42824. ** assert(zBuf[0]=='\0');
  42825. ** return 0;
  42826. ** }
  42827. **
  42828. ** However if an error message is supplied, it will be incorporated
  42829. ** by sqlite into the error message available to the user using
  42830. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  42831. */
  42832. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  42833. DWORD e = osGetLastError();
  42834. UNUSED_PARAMETER(pVfs);
  42835. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  42836. return e;
  42837. }
  42838. /*
  42839. ** Initialize and deinitialize the operating system interface.
  42840. */
  42841. SQLITE_API int sqlite3_os_init(void){
  42842. static sqlite3_vfs winVfs = {
  42843. 3, /* iVersion */
  42844. sizeof(winFile), /* szOsFile */
  42845. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  42846. 0, /* pNext */
  42847. "win32", /* zName */
  42848. &winAppData, /* pAppData */
  42849. winOpen, /* xOpen */
  42850. winDelete, /* xDelete */
  42851. winAccess, /* xAccess */
  42852. winFullPathname, /* xFullPathname */
  42853. winDlOpen, /* xDlOpen */
  42854. winDlError, /* xDlError */
  42855. winDlSym, /* xDlSym */
  42856. winDlClose, /* xDlClose */
  42857. winRandomness, /* xRandomness */
  42858. winSleep, /* xSleep */
  42859. winCurrentTime, /* xCurrentTime */
  42860. winGetLastError, /* xGetLastError */
  42861. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42862. winSetSystemCall, /* xSetSystemCall */
  42863. winGetSystemCall, /* xGetSystemCall */
  42864. winNextSystemCall, /* xNextSystemCall */
  42865. };
  42866. #if defined(SQLITE_WIN32_HAS_WIDE)
  42867. static sqlite3_vfs winLongPathVfs = {
  42868. 3, /* iVersion */
  42869. sizeof(winFile), /* szOsFile */
  42870. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  42871. 0, /* pNext */
  42872. "win32-longpath", /* zName */
  42873. &winAppData, /* pAppData */
  42874. winOpen, /* xOpen */
  42875. winDelete, /* xDelete */
  42876. winAccess, /* xAccess */
  42877. winFullPathname, /* xFullPathname */
  42878. winDlOpen, /* xDlOpen */
  42879. winDlError, /* xDlError */
  42880. winDlSym, /* xDlSym */
  42881. winDlClose, /* xDlClose */
  42882. winRandomness, /* xRandomness */
  42883. winSleep, /* xSleep */
  42884. winCurrentTime, /* xCurrentTime */
  42885. winGetLastError, /* xGetLastError */
  42886. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42887. winSetSystemCall, /* xSetSystemCall */
  42888. winGetSystemCall, /* xGetSystemCall */
  42889. winNextSystemCall, /* xNextSystemCall */
  42890. };
  42891. #endif
  42892. static sqlite3_vfs winNolockVfs = {
  42893. 3, /* iVersion */
  42894. sizeof(winFile), /* szOsFile */
  42895. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  42896. 0, /* pNext */
  42897. "win32-none", /* zName */
  42898. &winNolockAppData, /* pAppData */
  42899. winOpen, /* xOpen */
  42900. winDelete, /* xDelete */
  42901. winAccess, /* xAccess */
  42902. winFullPathname, /* xFullPathname */
  42903. winDlOpen, /* xDlOpen */
  42904. winDlError, /* xDlError */
  42905. winDlSym, /* xDlSym */
  42906. winDlClose, /* xDlClose */
  42907. winRandomness, /* xRandomness */
  42908. winSleep, /* xSleep */
  42909. winCurrentTime, /* xCurrentTime */
  42910. winGetLastError, /* xGetLastError */
  42911. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42912. winSetSystemCall, /* xSetSystemCall */
  42913. winGetSystemCall, /* xGetSystemCall */
  42914. winNextSystemCall, /* xNextSystemCall */
  42915. };
  42916. #if defined(SQLITE_WIN32_HAS_WIDE)
  42917. static sqlite3_vfs winLongPathNolockVfs = {
  42918. 3, /* iVersion */
  42919. sizeof(winFile), /* szOsFile */
  42920. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  42921. 0, /* pNext */
  42922. "win32-longpath-none", /* zName */
  42923. &winNolockAppData, /* pAppData */
  42924. winOpen, /* xOpen */
  42925. winDelete, /* xDelete */
  42926. winAccess, /* xAccess */
  42927. winFullPathname, /* xFullPathname */
  42928. winDlOpen, /* xDlOpen */
  42929. winDlError, /* xDlError */
  42930. winDlSym, /* xDlSym */
  42931. winDlClose, /* xDlClose */
  42932. winRandomness, /* xRandomness */
  42933. winSleep, /* xSleep */
  42934. winCurrentTime, /* xCurrentTime */
  42935. winGetLastError, /* xGetLastError */
  42936. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42937. winSetSystemCall, /* xSetSystemCall */
  42938. winGetSystemCall, /* xGetSystemCall */
  42939. winNextSystemCall, /* xNextSystemCall */
  42940. };
  42941. #endif
  42942. /* Double-check that the aSyscall[] array has been constructed
  42943. ** correctly. See ticket [bb3a86e890c8e96ab] */
  42944. assert( ArraySize(aSyscall)==80 );
  42945. /* get memory map allocation granularity */
  42946. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  42947. #if SQLITE_OS_WINRT
  42948. osGetNativeSystemInfo(&winSysInfo);
  42949. #else
  42950. osGetSystemInfo(&winSysInfo);
  42951. #endif
  42952. assert( winSysInfo.dwAllocationGranularity>0 );
  42953. assert( winSysInfo.dwPageSize>0 );
  42954. sqlite3_vfs_register(&winVfs, 1);
  42955. #if defined(SQLITE_WIN32_HAS_WIDE)
  42956. sqlite3_vfs_register(&winLongPathVfs, 0);
  42957. #endif
  42958. sqlite3_vfs_register(&winNolockVfs, 0);
  42959. #if defined(SQLITE_WIN32_HAS_WIDE)
  42960. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  42961. #endif
  42962. #ifndef SQLITE_OMIT_WAL
  42963. winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  42964. #endif
  42965. return SQLITE_OK;
  42966. }
  42967. SQLITE_API int sqlite3_os_end(void){
  42968. #if SQLITE_OS_WINRT
  42969. if( sleepObj!=NULL ){
  42970. osCloseHandle(sleepObj);
  42971. sleepObj = NULL;
  42972. }
  42973. #endif
  42974. #ifndef SQLITE_OMIT_WAL
  42975. winBigLock = 0;
  42976. #endif
  42977. return SQLITE_OK;
  42978. }
  42979. #endif /* SQLITE_OS_WIN */
  42980. /************** End of os_win.c **********************************************/
  42981. /************** Begin file memdb.c *******************************************/
  42982. /*
  42983. ** 2016-09-07
  42984. **
  42985. ** The author disclaims copyright to this source code. In place of
  42986. ** a legal notice, here is a blessing:
  42987. **
  42988. ** May you do good and not evil.
  42989. ** May you find forgiveness for yourself and forgive others.
  42990. ** May you share freely, never taking more than you give.
  42991. **
  42992. ******************************************************************************
  42993. **
  42994. ** This file implements an in-memory VFS. A database is held as a contiguous
  42995. ** block of memory.
  42996. **
  42997. ** This file also implements interface sqlite3_serialize() and
  42998. ** sqlite3_deserialize().
  42999. */
  43000. #ifdef SQLITE_ENABLE_DESERIALIZE
  43001. /* #include "sqliteInt.h" */
  43002. /*
  43003. ** Forward declaration of objects used by this utility
  43004. */
  43005. typedef struct sqlite3_vfs MemVfs;
  43006. typedef struct MemFile MemFile;
  43007. /* Access to a lower-level VFS that (might) implement dynamic loading,
  43008. ** access to randomness, etc.
  43009. */
  43010. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  43011. /* An open file */
  43012. struct MemFile {
  43013. sqlite3_file base; /* IO methods */
  43014. sqlite3_int64 sz; /* Size of the file */
  43015. sqlite3_int64 szMax; /* Space allocated to aData */
  43016. unsigned char *aData; /* content of the file */
  43017. int nMmap; /* Number of memory mapped pages */
  43018. unsigned mFlags; /* Flags */
  43019. int eLock; /* Most recent lock against this file */
  43020. };
  43021. /*
  43022. ** Methods for MemFile
  43023. */
  43024. static int memdbClose(sqlite3_file*);
  43025. static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  43026. static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  43027. static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
  43028. static int memdbSync(sqlite3_file*, int flags);
  43029. static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  43030. static int memdbLock(sqlite3_file*, int);
  43031. /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
  43032. static int memdbFileControl(sqlite3_file*, int op, void *pArg);
  43033. /* static int memdbSectorSize(sqlite3_file*); // not used */
  43034. static int memdbDeviceCharacteristics(sqlite3_file*);
  43035. static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  43036. static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  43037. /*
  43038. ** Methods for MemVfs
  43039. */
  43040. static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  43041. /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
  43042. static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  43043. static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  43044. static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
  43045. static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  43046. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  43047. static void memdbDlClose(sqlite3_vfs*, void*);
  43048. static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
  43049. static int memdbSleep(sqlite3_vfs*, int microseconds);
  43050. /* static int memdbCurrentTime(sqlite3_vfs*, double*); */
  43051. static int memdbGetLastError(sqlite3_vfs*, int, char *);
  43052. static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  43053. static sqlite3_vfs memdb_vfs = {
  43054. 2, /* iVersion */
  43055. 0, /* szOsFile (set when registered) */
  43056. 1024, /* mxPathname */
  43057. 0, /* pNext */
  43058. "memdb", /* zName */
  43059. 0, /* pAppData (set when registered) */
  43060. memdbOpen, /* xOpen */
  43061. 0, /* memdbDelete, */ /* xDelete */
  43062. memdbAccess, /* xAccess */
  43063. memdbFullPathname, /* xFullPathname */
  43064. memdbDlOpen, /* xDlOpen */
  43065. memdbDlError, /* xDlError */
  43066. memdbDlSym, /* xDlSym */
  43067. memdbDlClose, /* xDlClose */
  43068. memdbRandomness, /* xRandomness */
  43069. memdbSleep, /* xSleep */
  43070. 0, /* memdbCurrentTime, */ /* xCurrentTime */
  43071. memdbGetLastError, /* xGetLastError */
  43072. memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
  43073. };
  43074. static const sqlite3_io_methods memdb_io_methods = {
  43075. 3, /* iVersion */
  43076. memdbClose, /* xClose */
  43077. memdbRead, /* xRead */
  43078. memdbWrite, /* xWrite */
  43079. memdbTruncate, /* xTruncate */
  43080. memdbSync, /* xSync */
  43081. memdbFileSize, /* xFileSize */
  43082. memdbLock, /* xLock */
  43083. memdbLock, /* xUnlock - same as xLock in this case */
  43084. 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
  43085. memdbFileControl, /* xFileControl */
  43086. 0, /* memdbSectorSize,*/ /* xSectorSize */
  43087. memdbDeviceCharacteristics, /* xDeviceCharacteristics */
  43088. 0, /* xShmMap */
  43089. 0, /* xShmLock */
  43090. 0, /* xShmBarrier */
  43091. 0, /* xShmUnmap */
  43092. memdbFetch, /* xFetch */
  43093. memdbUnfetch /* xUnfetch */
  43094. };
  43095. /*
  43096. ** Close an memdb-file.
  43097. **
  43098. ** The pData pointer is owned by the application, so there is nothing
  43099. ** to free.
  43100. */
  43101. static int memdbClose(sqlite3_file *pFile){
  43102. MemFile *p = (MemFile *)pFile;
  43103. if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
  43104. return SQLITE_OK;
  43105. }
  43106. /*
  43107. ** Read data from an memdb-file.
  43108. */
  43109. static int memdbRead(
  43110. sqlite3_file *pFile,
  43111. void *zBuf,
  43112. int iAmt,
  43113. sqlite_int64 iOfst
  43114. ){
  43115. MemFile *p = (MemFile *)pFile;
  43116. if( iOfst+iAmt>p->sz ){
  43117. memset(zBuf, 0, iAmt);
  43118. if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
  43119. return SQLITE_IOERR_SHORT_READ;
  43120. }
  43121. memcpy(zBuf, p->aData+iOfst, iAmt);
  43122. return SQLITE_OK;
  43123. }
  43124. /*
  43125. ** Try to enlarge the memory allocation to hold at least sz bytes
  43126. */
  43127. static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
  43128. unsigned char *pNew;
  43129. if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
  43130. return SQLITE_FULL;
  43131. }
  43132. pNew = sqlite3_realloc64(p->aData, newSz);
  43133. if( pNew==0 ) return SQLITE_NOMEM;
  43134. p->aData = pNew;
  43135. p->szMax = newSz;
  43136. return SQLITE_OK;
  43137. }
  43138. /*
  43139. ** Write data to an memdb-file.
  43140. */
  43141. static int memdbWrite(
  43142. sqlite3_file *pFile,
  43143. const void *z,
  43144. int iAmt,
  43145. sqlite_int64 iOfst
  43146. ){
  43147. MemFile *p = (MemFile *)pFile;
  43148. if( iOfst+iAmt>p->sz ){
  43149. int rc;
  43150. if( iOfst+iAmt>p->szMax
  43151. && (rc = memdbEnlarge(p, (iOfst+iAmt)*2))!=SQLITE_OK
  43152. ){
  43153. return rc;
  43154. }
  43155. if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
  43156. p->sz = iOfst+iAmt;
  43157. }
  43158. memcpy(p->aData+iOfst, z, iAmt);
  43159. return SQLITE_OK;
  43160. }
  43161. /*
  43162. ** Truncate an memdb-file.
  43163. **
  43164. ** In rollback mode (which is always the case for memdb, as it does not
  43165. ** support WAL mode) the truncate() method is only used to reduce
  43166. ** the size of a file, never to increase the size.
  43167. */
  43168. static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
  43169. MemFile *p = (MemFile *)pFile;
  43170. if( NEVER(size>p->sz) ) return SQLITE_FULL;
  43171. p->sz = size;
  43172. return SQLITE_OK;
  43173. }
  43174. /*
  43175. ** Sync an memdb-file.
  43176. */
  43177. static int memdbSync(sqlite3_file *pFile, int flags){
  43178. return SQLITE_OK;
  43179. }
  43180. /*
  43181. ** Return the current file-size of an memdb-file.
  43182. */
  43183. static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  43184. MemFile *p = (MemFile *)pFile;
  43185. *pSize = p->sz;
  43186. return SQLITE_OK;
  43187. }
  43188. /*
  43189. ** Lock an memdb-file.
  43190. */
  43191. static int memdbLock(sqlite3_file *pFile, int eLock){
  43192. MemFile *p = (MemFile *)pFile;
  43193. p->eLock = eLock;
  43194. return SQLITE_OK;
  43195. }
  43196. #if 0 /* Never used because memdbAccess() always returns false */
  43197. /*
  43198. ** Check if another file-handle holds a RESERVED lock on an memdb-file.
  43199. */
  43200. static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  43201. *pResOut = 0;
  43202. return SQLITE_OK;
  43203. }
  43204. #endif
  43205. /*
  43206. ** File control method. For custom operations on an memdb-file.
  43207. */
  43208. static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
  43209. MemFile *p = (MemFile *)pFile;
  43210. int rc = SQLITE_NOTFOUND;
  43211. if( op==SQLITE_FCNTL_VFSNAME ){
  43212. *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
  43213. rc = SQLITE_OK;
  43214. }
  43215. return rc;
  43216. }
  43217. #if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  43218. /*
  43219. ** Return the sector-size in bytes for an memdb-file.
  43220. */
  43221. static int memdbSectorSize(sqlite3_file *pFile){
  43222. return 1024;
  43223. }
  43224. #endif
  43225. /*
  43226. ** Return the device characteristic flags supported by an memdb-file.
  43227. */
  43228. static int memdbDeviceCharacteristics(sqlite3_file *pFile){
  43229. return SQLITE_IOCAP_ATOMIC |
  43230. SQLITE_IOCAP_POWERSAFE_OVERWRITE |
  43231. SQLITE_IOCAP_SAFE_APPEND |
  43232. SQLITE_IOCAP_SEQUENTIAL;
  43233. }
  43234. /* Fetch a page of a memory-mapped file */
  43235. static int memdbFetch(
  43236. sqlite3_file *pFile,
  43237. sqlite3_int64 iOfst,
  43238. int iAmt,
  43239. void **pp
  43240. ){
  43241. MemFile *p = (MemFile *)pFile;
  43242. p->nMmap++;
  43243. *pp = (void*)(p->aData + iOfst);
  43244. return SQLITE_OK;
  43245. }
  43246. /* Release a memory-mapped page */
  43247. static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  43248. MemFile *p = (MemFile *)pFile;
  43249. p->nMmap--;
  43250. return SQLITE_OK;
  43251. }
  43252. /*
  43253. ** Open an mem file handle.
  43254. */
  43255. static int memdbOpen(
  43256. sqlite3_vfs *pVfs,
  43257. const char *zName,
  43258. sqlite3_file *pFile,
  43259. int flags,
  43260. int *pOutFlags
  43261. ){
  43262. MemFile *p = (MemFile*)pFile;
  43263. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  43264. return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
  43265. }
  43266. memset(p, 0, sizeof(*p));
  43267. p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
  43268. assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
  43269. *pOutFlags = flags | SQLITE_OPEN_MEMORY;
  43270. p->base.pMethods = &memdb_io_methods;
  43271. return SQLITE_OK;
  43272. }
  43273. #if 0 /* Only used to delete rollback journals, master journals, and WAL
  43274. ** files, none of which exist in memdb. So this routine is never used */
  43275. /*
  43276. ** Delete the file located at zPath. If the dirSync argument is true,
  43277. ** ensure the file-system modifications are synced to disk before
  43278. ** returning.
  43279. */
  43280. static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  43281. return SQLITE_IOERR_DELETE;
  43282. }
  43283. #endif
  43284. /*
  43285. ** Test for access permissions. Return true if the requested permission
  43286. ** is available, or false otherwise.
  43287. **
  43288. ** With memdb, no files ever exist on disk. So always return false.
  43289. */
  43290. static int memdbAccess(
  43291. sqlite3_vfs *pVfs,
  43292. const char *zPath,
  43293. int flags,
  43294. int *pResOut
  43295. ){
  43296. *pResOut = 0;
  43297. return SQLITE_OK;
  43298. }
  43299. /*
  43300. ** Populate buffer zOut with the full canonical pathname corresponding
  43301. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  43302. ** of at least (INST_MAX_PATHNAME+1) bytes.
  43303. */
  43304. static int memdbFullPathname(
  43305. sqlite3_vfs *pVfs,
  43306. const char *zPath,
  43307. int nOut,
  43308. char *zOut
  43309. ){
  43310. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  43311. return SQLITE_OK;
  43312. }
  43313. /*
  43314. ** Open the dynamic library located at zPath and return a handle.
  43315. */
  43316. static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  43317. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  43318. }
  43319. /*
  43320. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  43321. ** utf-8 string describing the most recent error encountered associated
  43322. ** with dynamic libraries.
  43323. */
  43324. static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  43325. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  43326. }
  43327. /*
  43328. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  43329. */
  43330. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  43331. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  43332. }
  43333. /*
  43334. ** Close the dynamic library handle pHandle.
  43335. */
  43336. static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
  43337. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  43338. }
  43339. /*
  43340. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  43341. ** random data.
  43342. */
  43343. static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  43344. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  43345. }
  43346. /*
  43347. ** Sleep for nMicro microseconds. Return the number of microseconds
  43348. ** actually slept.
  43349. */
  43350. static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
  43351. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  43352. }
  43353. #if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
  43354. /*
  43355. ** Return the current time as a Julian Day number in *pTimeOut.
  43356. */
  43357. static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  43358. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  43359. }
  43360. #endif
  43361. static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  43362. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  43363. }
  43364. static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  43365. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  43366. }
  43367. /*
  43368. ** Translate a database connection pointer and schema name into a
  43369. ** MemFile pointer.
  43370. */
  43371. static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
  43372. MemFile *p = 0;
  43373. int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
  43374. if( rc ) return 0;
  43375. if( p->base.pMethods!=&memdb_io_methods ) return 0;
  43376. return p;
  43377. }
  43378. /*
  43379. ** Return the serialization of a database
  43380. */
  43381. SQLITE_API unsigned char *sqlite3_serialize(
  43382. sqlite3 *db, /* The database connection */
  43383. const char *zSchema, /* Which database within the connection */
  43384. sqlite3_int64 *piSize, /* Write size here, if not NULL */
  43385. unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
  43386. ){
  43387. MemFile *p;
  43388. int iDb;
  43389. Btree *pBt;
  43390. sqlite3_int64 sz;
  43391. int szPage = 0;
  43392. sqlite3_stmt *pStmt = 0;
  43393. unsigned char *pOut;
  43394. char *zSql;
  43395. int rc;
  43396. #ifdef SQLITE_ENABLE_API_ARMOR
  43397. if( !sqlite3SafetyCheckOk(db) ){
  43398. (void)SQLITE_MISUSE_BKPT;
  43399. return 0;
  43400. }
  43401. #endif
  43402. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  43403. p = memdbFromDbSchema(db, zSchema);
  43404. iDb = sqlite3FindDbName(db, zSchema);
  43405. if( piSize ) *piSize = -1;
  43406. if( iDb<0 ) return 0;
  43407. if( p ){
  43408. if( piSize ) *piSize = p->sz;
  43409. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  43410. pOut = p->aData;
  43411. }else{
  43412. pOut = sqlite3_malloc64( p->sz );
  43413. if( pOut ) memcpy(pOut, p->aData, p->sz);
  43414. }
  43415. return pOut;
  43416. }
  43417. pBt = db->aDb[iDb].pBt;
  43418. if( pBt==0 ) return 0;
  43419. szPage = sqlite3BtreeGetPageSize(pBt);
  43420. zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
  43421. rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
  43422. sqlite3_free(zSql);
  43423. if( rc ) return 0;
  43424. rc = sqlite3_step(pStmt);
  43425. if( rc!=SQLITE_ROW ){
  43426. pOut = 0;
  43427. }else{
  43428. sz = sqlite3_column_int64(pStmt, 0)*szPage;
  43429. if( piSize ) *piSize = sz;
  43430. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  43431. pOut = 0;
  43432. }else{
  43433. pOut = sqlite3_malloc64( sz );
  43434. if( pOut ){
  43435. int nPage = sqlite3_column_int(pStmt, 0);
  43436. Pager *pPager = sqlite3BtreePager(pBt);
  43437. int pgno;
  43438. for(pgno=1; pgno<=nPage; pgno++){
  43439. DbPage *pPage = 0;
  43440. unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
  43441. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
  43442. if( rc==SQLITE_OK ){
  43443. memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
  43444. }else{
  43445. memset(pTo, 0, szPage);
  43446. }
  43447. sqlite3PagerUnref(pPage);
  43448. }
  43449. }
  43450. }
  43451. }
  43452. sqlite3_finalize(pStmt);
  43453. return pOut;
  43454. }
  43455. /* Convert zSchema to a MemDB and initialize its content.
  43456. */
  43457. SQLITE_API int sqlite3_deserialize(
  43458. sqlite3 *db, /* The database connection */
  43459. const char *zSchema, /* Which DB to reopen with the deserialization */
  43460. unsigned char *pData, /* The serialized database content */
  43461. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  43462. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  43463. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  43464. ){
  43465. MemFile *p;
  43466. char *zSql;
  43467. sqlite3_stmt *pStmt = 0;
  43468. int rc;
  43469. int iDb;
  43470. #ifdef SQLITE_ENABLE_API_ARMOR
  43471. if( !sqlite3SafetyCheckOk(db) ){
  43472. return SQLITE_MISUSE_BKPT;
  43473. }
  43474. if( szDb<0 ) return SQLITE_MISUSE_BKPT;
  43475. if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
  43476. #endif
  43477. sqlite3_mutex_enter(db->mutex);
  43478. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  43479. iDb = sqlite3FindDbName(db, zSchema);
  43480. if( iDb<0 ){
  43481. rc = SQLITE_ERROR;
  43482. goto end_deserialize;
  43483. }
  43484. zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
  43485. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  43486. sqlite3_free(zSql);
  43487. if( rc ) goto end_deserialize;
  43488. db->init.iDb = (u8)iDb;
  43489. db->init.reopenMemdb = 1;
  43490. rc = sqlite3_step(pStmt);
  43491. db->init.reopenMemdb = 0;
  43492. if( rc!=SQLITE_DONE ){
  43493. rc = SQLITE_ERROR;
  43494. goto end_deserialize;
  43495. }
  43496. p = memdbFromDbSchema(db, zSchema);
  43497. if( p==0 ){
  43498. rc = SQLITE_ERROR;
  43499. }else{
  43500. p->aData = pData;
  43501. p->sz = szDb;
  43502. p->szMax = szBuf;
  43503. p->mFlags = mFlags;
  43504. rc = SQLITE_OK;
  43505. }
  43506. end_deserialize:
  43507. sqlite3_finalize(pStmt);
  43508. sqlite3_mutex_leave(db->mutex);
  43509. return rc;
  43510. }
  43511. /*
  43512. ** This routine is called when the extension is loaded.
  43513. ** Register the new VFS.
  43514. */
  43515. SQLITE_PRIVATE int sqlite3MemdbInit(void){
  43516. sqlite3_vfs *pLower = sqlite3_vfs_find(0);
  43517. int sz = pLower->szOsFile;
  43518. memdb_vfs.pAppData = pLower;
  43519. /* In all known configurations of SQLite, the size of a default
  43520. ** sqlite3_file is greater than the size of a memdb sqlite3_file.
  43521. ** Should that ever change, remove the following NEVER() */
  43522. if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile);
  43523. memdb_vfs.szOsFile = sz;
  43524. return sqlite3_vfs_register(&memdb_vfs, 0);
  43525. }
  43526. #endif /* SQLITE_ENABLE_DESERIALIZE */
  43527. /************** End of memdb.c ***********************************************/
  43528. /************** Begin file bitvec.c ******************************************/
  43529. /*
  43530. ** 2008 February 16
  43531. **
  43532. ** The author disclaims copyright to this source code. In place of
  43533. ** a legal notice, here is a blessing:
  43534. **
  43535. ** May you do good and not evil.
  43536. ** May you find forgiveness for yourself and forgive others.
  43537. ** May you share freely, never taking more than you give.
  43538. **
  43539. *************************************************************************
  43540. ** This file implements an object that represents a fixed-length
  43541. ** bitmap. Bits are numbered starting with 1.
  43542. **
  43543. ** A bitmap is used to record which pages of a database file have been
  43544. ** journalled during a transaction, or which pages have the "dont-write"
  43545. ** property. Usually only a few pages are meet either condition.
  43546. ** So the bitmap is usually sparse and has low cardinality.
  43547. ** But sometimes (for example when during a DROP of a large table) most
  43548. ** or all of the pages in a database can get journalled. In those cases,
  43549. ** the bitmap becomes dense with high cardinality. The algorithm needs
  43550. ** to handle both cases well.
  43551. **
  43552. ** The size of the bitmap is fixed when the object is created.
  43553. **
  43554. ** All bits are clear when the bitmap is created. Individual bits
  43555. ** may be set or cleared one at a time.
  43556. **
  43557. ** Test operations are about 100 times more common that set operations.
  43558. ** Clear operations are exceedingly rare. There are usually between
  43559. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  43560. ** sometimes grow into tens of thousands or larger. The size of the
  43561. ** Bitvec object is the number of pages in the database file at the
  43562. ** start of a transaction, and is thus usually less than a few thousand,
  43563. ** but can be as large as 2 billion for a really big database.
  43564. */
  43565. /* #include "sqliteInt.h" */
  43566. /* Size of the Bitvec structure in bytes. */
  43567. #define BITVEC_SZ 512
  43568. /* Round the union size down to the nearest pointer boundary, since that's how
  43569. ** it will be aligned within the Bitvec struct. */
  43570. #define BITVEC_USIZE \
  43571. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  43572. /* Type of the array "element" for the bitmap representation.
  43573. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  43574. ** Setting this to the "natural word" size of your CPU may improve
  43575. ** performance. */
  43576. #define BITVEC_TELEM u8
  43577. /* Size, in bits, of the bitmap element. */
  43578. #define BITVEC_SZELEM 8
  43579. /* Number of elements in a bitmap array. */
  43580. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  43581. /* Number of bits in the bitmap array. */
  43582. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  43583. /* Number of u32 values in hash table. */
  43584. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  43585. /* Maximum number of entries in hash table before
  43586. ** sub-dividing and re-hashing. */
  43587. #define BITVEC_MXHASH (BITVEC_NINT/2)
  43588. /* Hashing function for the aHash representation.
  43589. ** Empirical testing showed that the *37 multiplier
  43590. ** (an arbitrary prime)in the hash function provided
  43591. ** no fewer collisions than the no-op *1. */
  43592. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  43593. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  43594. /*
  43595. ** A bitmap is an instance of the following structure.
  43596. **
  43597. ** This bitmap records the existence of zero or more bits
  43598. ** with values between 1 and iSize, inclusive.
  43599. **
  43600. ** There are three possible representations of the bitmap.
  43601. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  43602. ** bitmap. The least significant bit is bit 1.
  43603. **
  43604. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  43605. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  43606. **
  43607. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  43608. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  43609. ** handles up to iDivisor separate values of i. apSub[0] holds
  43610. ** values between 1 and iDivisor. apSub[1] holds values between
  43611. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  43612. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  43613. ** to hold deal with values between 1 and iDivisor.
  43614. */
  43615. struct Bitvec {
  43616. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  43617. u32 nSet; /* Number of bits that are set - only valid for aHash
  43618. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  43619. ** this would be 125. */
  43620. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  43621. /* Should >=0 for apSub element. */
  43622. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  43623. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  43624. union {
  43625. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  43626. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  43627. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  43628. } u;
  43629. };
  43630. /*
  43631. ** Create a new bitmap object able to handle bits between 0 and iSize,
  43632. ** inclusive. Return a pointer to the new object. Return NULL if
  43633. ** malloc fails.
  43634. */
  43635. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  43636. Bitvec *p;
  43637. assert( sizeof(*p)==BITVEC_SZ );
  43638. p = sqlite3MallocZero( sizeof(*p) );
  43639. if( p ){
  43640. p->iSize = iSize;
  43641. }
  43642. return p;
  43643. }
  43644. /*
  43645. ** Check to see if the i-th bit is set. Return true or false.
  43646. ** If p is NULL (if the bitmap has not been created) or if
  43647. ** i is out of range, then return false.
  43648. */
  43649. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  43650. assert( p!=0 );
  43651. i--;
  43652. if( i>=p->iSize ) return 0;
  43653. while( p->iDivisor ){
  43654. u32 bin = i/p->iDivisor;
  43655. i = i%p->iDivisor;
  43656. p = p->u.apSub[bin];
  43657. if (!p) {
  43658. return 0;
  43659. }
  43660. }
  43661. if( p->iSize<=BITVEC_NBIT ){
  43662. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  43663. } else{
  43664. u32 h = BITVEC_HASH(i++);
  43665. while( p->u.aHash[h] ){
  43666. if( p->u.aHash[h]==i ) return 1;
  43667. h = (h+1) % BITVEC_NINT;
  43668. }
  43669. return 0;
  43670. }
  43671. }
  43672. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  43673. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  43674. }
  43675. /*
  43676. ** Set the i-th bit. Return 0 on success and an error code if
  43677. ** anything goes wrong.
  43678. **
  43679. ** This routine might cause sub-bitmaps to be allocated. Failing
  43680. ** to get the memory needed to hold the sub-bitmap is the only
  43681. ** that can go wrong with an insert, assuming p and i are valid.
  43682. **
  43683. ** The calling function must ensure that p is a valid Bitvec object
  43684. ** and that the value for "i" is within range of the Bitvec object.
  43685. ** Otherwise the behavior is undefined.
  43686. */
  43687. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  43688. u32 h;
  43689. if( p==0 ) return SQLITE_OK;
  43690. assert( i>0 );
  43691. assert( i<=p->iSize );
  43692. i--;
  43693. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  43694. u32 bin = i/p->iDivisor;
  43695. i = i%p->iDivisor;
  43696. if( p->u.apSub[bin]==0 ){
  43697. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  43698. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  43699. }
  43700. p = p->u.apSub[bin];
  43701. }
  43702. if( p->iSize<=BITVEC_NBIT ){
  43703. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  43704. return SQLITE_OK;
  43705. }
  43706. h = BITVEC_HASH(i++);
  43707. /* if there wasn't a hash collision, and this doesn't */
  43708. /* completely fill the hash, then just add it without */
  43709. /* worring about sub-dividing and re-hashing. */
  43710. if( !p->u.aHash[h] ){
  43711. if (p->nSet<(BITVEC_NINT-1)) {
  43712. goto bitvec_set_end;
  43713. } else {
  43714. goto bitvec_set_rehash;
  43715. }
  43716. }
  43717. /* there was a collision, check to see if it's already */
  43718. /* in hash, if not, try to find a spot for it */
  43719. do {
  43720. if( p->u.aHash[h]==i ) return SQLITE_OK;
  43721. h++;
  43722. if( h>=BITVEC_NINT ) h = 0;
  43723. } while( p->u.aHash[h] );
  43724. /* we didn't find it in the hash. h points to the first */
  43725. /* available free spot. check to see if this is going to */
  43726. /* make our hash too "full". */
  43727. bitvec_set_rehash:
  43728. if( p->nSet>=BITVEC_MXHASH ){
  43729. unsigned int j;
  43730. int rc;
  43731. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  43732. if( aiValues==0 ){
  43733. return SQLITE_NOMEM_BKPT;
  43734. }else{
  43735. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  43736. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  43737. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  43738. rc = sqlite3BitvecSet(p, i);
  43739. for(j=0; j<BITVEC_NINT; j++){
  43740. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  43741. }
  43742. sqlite3StackFree(0, aiValues);
  43743. return rc;
  43744. }
  43745. }
  43746. bitvec_set_end:
  43747. p->nSet++;
  43748. p->u.aHash[h] = i;
  43749. return SQLITE_OK;
  43750. }
  43751. /*
  43752. ** Clear the i-th bit.
  43753. **
  43754. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  43755. ** that BitvecClear can use to rebuilt its hash table.
  43756. */
  43757. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  43758. if( p==0 ) return;
  43759. assert( i>0 );
  43760. i--;
  43761. while( p->iDivisor ){
  43762. u32 bin = i/p->iDivisor;
  43763. i = i%p->iDivisor;
  43764. p = p->u.apSub[bin];
  43765. if (!p) {
  43766. return;
  43767. }
  43768. }
  43769. if( p->iSize<=BITVEC_NBIT ){
  43770. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  43771. }else{
  43772. unsigned int j;
  43773. u32 *aiValues = pBuf;
  43774. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  43775. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  43776. p->nSet = 0;
  43777. for(j=0; j<BITVEC_NINT; j++){
  43778. if( aiValues[j] && aiValues[j]!=(i+1) ){
  43779. u32 h = BITVEC_HASH(aiValues[j]-1);
  43780. p->nSet++;
  43781. while( p->u.aHash[h] ){
  43782. h++;
  43783. if( h>=BITVEC_NINT ) h = 0;
  43784. }
  43785. p->u.aHash[h] = aiValues[j];
  43786. }
  43787. }
  43788. }
  43789. }
  43790. /*
  43791. ** Destroy a bitmap object. Reclaim all memory used.
  43792. */
  43793. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  43794. if( p==0 ) return;
  43795. if( p->iDivisor ){
  43796. unsigned int i;
  43797. for(i=0; i<BITVEC_NPTR; i++){
  43798. sqlite3BitvecDestroy(p->u.apSub[i]);
  43799. }
  43800. }
  43801. sqlite3_free(p);
  43802. }
  43803. /*
  43804. ** Return the value of the iSize parameter specified when Bitvec *p
  43805. ** was created.
  43806. */
  43807. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  43808. return p->iSize;
  43809. }
  43810. #ifndef SQLITE_UNTESTABLE
  43811. /*
  43812. ** Let V[] be an array of unsigned characters sufficient to hold
  43813. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  43814. ** Then the following macros can be used to set, clear, or test
  43815. ** individual bits within V.
  43816. */
  43817. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  43818. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  43819. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  43820. /*
  43821. ** This routine runs an extensive test of the Bitvec code.
  43822. **
  43823. ** The input is an array of integers that acts as a program
  43824. ** to test the Bitvec. The integers are opcodes followed
  43825. ** by 0, 1, or 3 operands, depending on the opcode. Another
  43826. ** opcode follows immediately after the last operand.
  43827. **
  43828. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  43829. ** "halt" opcode and causes the test to end.
  43830. **
  43831. ** 0 Halt and return the number of errors
  43832. ** 1 N S X Set N bits beginning with S and incrementing by X
  43833. ** 2 N S X Clear N bits beginning with S and incrementing by X
  43834. ** 3 N Set N randomly chosen bits
  43835. ** 4 N Clear N randomly chosen bits
  43836. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  43837. **
  43838. ** The opcodes 1 through 4 perform set and clear operations are performed
  43839. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  43840. ** Opcode 5 works on the linear array only, not on the Bitvec.
  43841. ** Opcode 5 is used to deliberately induce a fault in order to
  43842. ** confirm that error detection works.
  43843. **
  43844. ** At the conclusion of the test the linear array is compared
  43845. ** against the Bitvec object. If there are any differences,
  43846. ** an error is returned. If they are the same, zero is returned.
  43847. **
  43848. ** If a memory allocation error occurs, return -1.
  43849. */
  43850. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  43851. Bitvec *pBitvec = 0;
  43852. unsigned char *pV = 0;
  43853. int rc = -1;
  43854. int i, nx, pc, op;
  43855. void *pTmpSpace;
  43856. /* Allocate the Bitvec to be tested and a linear array of
  43857. ** bits to act as the reference */
  43858. pBitvec = sqlite3BitvecCreate( sz );
  43859. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  43860. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  43861. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  43862. /* NULL pBitvec tests */
  43863. sqlite3BitvecSet(0, 1);
  43864. sqlite3BitvecClear(0, 1, pTmpSpace);
  43865. /* Run the program */
  43866. pc = 0;
  43867. while( (op = aOp[pc])!=0 ){
  43868. switch( op ){
  43869. case 1:
  43870. case 2:
  43871. case 5: {
  43872. nx = 4;
  43873. i = aOp[pc+2] - 1;
  43874. aOp[pc+2] += aOp[pc+3];
  43875. break;
  43876. }
  43877. case 3:
  43878. case 4:
  43879. default: {
  43880. nx = 2;
  43881. sqlite3_randomness(sizeof(i), &i);
  43882. break;
  43883. }
  43884. }
  43885. if( (--aOp[pc+1]) > 0 ) nx = 0;
  43886. pc += nx;
  43887. i = (i & 0x7fffffff)%sz;
  43888. if( (op & 1)!=0 ){
  43889. SETBIT(pV, (i+1));
  43890. if( op!=5 ){
  43891. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  43892. }
  43893. }else{
  43894. CLEARBIT(pV, (i+1));
  43895. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  43896. }
  43897. }
  43898. /* Test to make sure the linear array exactly matches the
  43899. ** Bitvec object. Start with the assumption that they do
  43900. ** match (rc==0). Change rc to non-zero if a discrepancy
  43901. ** is found.
  43902. */
  43903. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  43904. + sqlite3BitvecTest(pBitvec, 0)
  43905. + (sqlite3BitvecSize(pBitvec) - sz);
  43906. for(i=1; i<=sz; i++){
  43907. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  43908. rc = i;
  43909. break;
  43910. }
  43911. }
  43912. /* Free allocated structure */
  43913. bitvec_end:
  43914. sqlite3_free(pTmpSpace);
  43915. sqlite3_free(pV);
  43916. sqlite3BitvecDestroy(pBitvec);
  43917. return rc;
  43918. }
  43919. #endif /* SQLITE_UNTESTABLE */
  43920. /************** End of bitvec.c **********************************************/
  43921. /************** Begin file pcache.c ******************************************/
  43922. /*
  43923. ** 2008 August 05
  43924. **
  43925. ** The author disclaims copyright to this source code. In place of
  43926. ** a legal notice, here is a blessing:
  43927. **
  43928. ** May you do good and not evil.
  43929. ** May you find forgiveness for yourself and forgive others.
  43930. ** May you share freely, never taking more than you give.
  43931. **
  43932. *************************************************************************
  43933. ** This file implements that page cache.
  43934. */
  43935. /* #include "sqliteInt.h" */
  43936. /*
  43937. ** A complete page cache is an instance of this structure. Every
  43938. ** entry in the cache holds a single page of the database file. The
  43939. ** btree layer only operates on the cached copy of the database pages.
  43940. **
  43941. ** A page cache entry is "clean" if it exactly matches what is currently
  43942. ** on disk. A page is "dirty" if it has been modified and needs to be
  43943. ** persisted to disk.
  43944. **
  43945. ** pDirty, pDirtyTail, pSynced:
  43946. ** All dirty pages are linked into the doubly linked list using
  43947. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  43948. ** such that p was added to the list more recently than p->pDirtyNext.
  43949. ** PCache.pDirty points to the first (newest) element in the list and
  43950. ** pDirtyTail to the last (oldest).
  43951. **
  43952. ** The PCache.pSynced variable is used to optimize searching for a dirty
  43953. ** page to eject from the cache mid-transaction. It is better to eject
  43954. ** a page that does not require a journal sync than one that does.
  43955. ** Therefore, pSynced is maintained to that it *almost* always points
  43956. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  43957. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  43958. ** (so that the right page to eject can be found by following pDirtyPrev
  43959. ** pointers).
  43960. */
  43961. struct PCache {
  43962. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  43963. PgHdr *pSynced; /* Last synced page in dirty page list */
  43964. int nRefSum; /* Sum of ref counts over all pages */
  43965. int szCache; /* Configured cache size */
  43966. int szSpill; /* Size before spilling occurs */
  43967. int szPage; /* Size of every page in this cache */
  43968. int szExtra; /* Size of extra space for each page */
  43969. u8 bPurgeable; /* True if pages are on backing store */
  43970. u8 eCreate; /* eCreate value for for xFetch() */
  43971. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  43972. void *pStress; /* Argument to xStress */
  43973. sqlite3_pcache *pCache; /* Pluggable cache module */
  43974. };
  43975. /********************************** Test and Debug Logic **********************/
  43976. /*
  43977. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  43978. ** recompiling.
  43979. **
  43980. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  43981. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  43982. ** is displayed for many operations, resulting in a lot of output.
  43983. */
  43984. #if defined(SQLITE_DEBUG) && 0
  43985. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  43986. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  43987. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  43988. void pcacheDump(PCache *pCache){
  43989. int N;
  43990. int i, j;
  43991. sqlite3_pcache_page *pLower;
  43992. PgHdr *pPg;
  43993. unsigned char *a;
  43994. if( sqlite3PcacheTrace<2 ) return;
  43995. if( pCache->pCache==0 ) return;
  43996. N = sqlite3PcachePagecount(pCache);
  43997. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  43998. for(i=1; i<=N; i++){
  43999. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  44000. if( pLower==0 ) continue;
  44001. pPg = (PgHdr*)pLower->pExtra;
  44002. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  44003. a = (unsigned char *)pLower->pBuf;
  44004. for(j=0; j<12; j++) printf("%02x", a[j]);
  44005. printf("\n");
  44006. if( pPg->pPage==0 ){
  44007. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  44008. }
  44009. }
  44010. }
  44011. #else
  44012. # define pcacheTrace(X)
  44013. # define pcacheDump(X)
  44014. #endif
  44015. /*
  44016. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  44017. ** Return false if any invariant is violated.
  44018. **
  44019. ** This routine is for use inside of assert() statements only. For
  44020. ** example:
  44021. **
  44022. ** assert( sqlite3PcachePageSanity(pPg) );
  44023. */
  44024. #ifdef SQLITE_DEBUG
  44025. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  44026. PCache *pCache;
  44027. assert( pPg!=0 );
  44028. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  44029. pCache = pPg->pCache;
  44030. assert( pCache!=0 ); /* Every page has an associated PCache */
  44031. if( pPg->flags & PGHDR_CLEAN ){
  44032. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  44033. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  44034. assert( pCache->pDirtyTail!=pPg );
  44035. }
  44036. /* WRITEABLE pages must also be DIRTY */
  44037. if( pPg->flags & PGHDR_WRITEABLE ){
  44038. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  44039. }
  44040. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  44041. ** for example, when using the sqlite3PagerDontWrite() optimization:
  44042. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  44043. ** (2) Page X moved to freelist, WRITEABLE is cleared
  44044. ** (3) Page X reused, WRITEABLE is set again
  44045. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  44046. ** in step 3, and page might be written into the database without first
  44047. ** syncing the rollback journal, which might cause corruption on a power
  44048. ** loss.
  44049. **
  44050. ** Another example is when the database page size is smaller than the
  44051. ** disk sector size. When any page of a sector is journalled, all pages
  44052. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  44053. ** in case they are later modified, since all pages in the same sector
  44054. ** must be journalled and synced before any of those pages can be safely
  44055. ** written.
  44056. */
  44057. return 1;
  44058. }
  44059. #endif /* SQLITE_DEBUG */
  44060. /********************************** Linked List Management ********************/
  44061. /* Allowed values for second argument to pcacheManageDirtyList() */
  44062. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  44063. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  44064. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  44065. /*
  44066. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  44067. ** argument determines what operation to do. The 0x01 bit means first
  44068. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  44069. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  44070. */
  44071. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  44072. PCache *p = pPage->pCache;
  44073. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  44074. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  44075. pPage->pgno));
  44076. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  44077. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  44078. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  44079. /* Update the PCache1.pSynced variable if necessary. */
  44080. if( p->pSynced==pPage ){
  44081. p->pSynced = pPage->pDirtyPrev;
  44082. }
  44083. if( pPage->pDirtyNext ){
  44084. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  44085. }else{
  44086. assert( pPage==p->pDirtyTail );
  44087. p->pDirtyTail = pPage->pDirtyPrev;
  44088. }
  44089. if( pPage->pDirtyPrev ){
  44090. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  44091. }else{
  44092. /* If there are now no dirty pages in the cache, set eCreate to 2.
  44093. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  44094. ** searching for a dirty page to eject from the cache when it might
  44095. ** otherwise have to. */
  44096. assert( pPage==p->pDirty );
  44097. p->pDirty = pPage->pDirtyNext;
  44098. assert( p->bPurgeable || p->eCreate==2 );
  44099. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  44100. assert( p->bPurgeable==0 || p->eCreate==1 );
  44101. p->eCreate = 2;
  44102. }
  44103. }
  44104. }
  44105. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  44106. pPage->pDirtyPrev = 0;
  44107. pPage->pDirtyNext = p->pDirty;
  44108. if( pPage->pDirtyNext ){
  44109. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  44110. pPage->pDirtyNext->pDirtyPrev = pPage;
  44111. }else{
  44112. p->pDirtyTail = pPage;
  44113. if( p->bPurgeable ){
  44114. assert( p->eCreate==2 );
  44115. p->eCreate = 1;
  44116. }
  44117. }
  44118. p->pDirty = pPage;
  44119. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  44120. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  44121. ** optimization, as if pSynced points to a page with the NEED_SYNC
  44122. ** flag set sqlite3PcacheFetchStress() searches through all newer
  44123. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  44124. if( !p->pSynced
  44125. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  44126. ){
  44127. p->pSynced = pPage;
  44128. }
  44129. }
  44130. pcacheDump(p);
  44131. }
  44132. /*
  44133. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  44134. ** being used for an in-memory database, this function is a no-op.
  44135. */
  44136. static void pcacheUnpin(PgHdr *p){
  44137. if( p->pCache->bPurgeable ){
  44138. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  44139. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  44140. pcacheDump(p->pCache);
  44141. }
  44142. }
  44143. /*
  44144. ** Compute the number of pages of cache requested. p->szCache is the
  44145. ** cache size requested by the "PRAGMA cache_size" statement.
  44146. */
  44147. static int numberOfCachePages(PCache *p){
  44148. if( p->szCache>=0 ){
  44149. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  44150. ** suggested cache size is set to N. */
  44151. return p->szCache;
  44152. }else{
  44153. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  44154. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  44155. ** bytes of memory. */
  44156. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  44157. }
  44158. }
  44159. /*************************************************** General Interfaces ******
  44160. **
  44161. ** Initialize and shutdown the page cache subsystem. Neither of these
  44162. ** functions are threadsafe.
  44163. */
  44164. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  44165. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  44166. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  44167. ** built-in default page cache is used instead of the application defined
  44168. ** page cache. */
  44169. sqlite3PCacheSetDefault();
  44170. }
  44171. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  44172. }
  44173. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  44174. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  44175. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  44176. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  44177. }
  44178. }
  44179. /*
  44180. ** Return the size in bytes of a PCache object.
  44181. */
  44182. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  44183. /*
  44184. ** Create a new PCache object. Storage space to hold the object
  44185. ** has already been allocated and is passed in as the p pointer.
  44186. ** The caller discovers how much space needs to be allocated by
  44187. ** calling sqlite3PcacheSize().
  44188. **
  44189. ** szExtra is some extra space allocated for each page. The first
  44190. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  44191. ** but remaining content will be uninitialized. Though it is opaque
  44192. ** to this module, the extra space really ends up being the MemPage
  44193. ** structure in the pager.
  44194. */
  44195. SQLITE_PRIVATE int sqlite3PcacheOpen(
  44196. int szPage, /* Size of every page */
  44197. int szExtra, /* Extra space associated with each page */
  44198. int bPurgeable, /* True if pages are on backing store */
  44199. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  44200. void *pStress, /* Argument to xStress */
  44201. PCache *p /* Preallocated space for the PCache */
  44202. ){
  44203. memset(p, 0, sizeof(PCache));
  44204. p->szPage = 1;
  44205. p->szExtra = szExtra;
  44206. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  44207. p->bPurgeable = bPurgeable;
  44208. p->eCreate = 2;
  44209. p->xStress = xStress;
  44210. p->pStress = pStress;
  44211. p->szCache = 100;
  44212. p->szSpill = 1;
  44213. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  44214. return sqlite3PcacheSetPageSize(p, szPage);
  44215. }
  44216. /*
  44217. ** Change the page size for PCache object. The caller must ensure that there
  44218. ** are no outstanding page references when this function is called.
  44219. */
  44220. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  44221. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  44222. if( pCache->szPage ){
  44223. sqlite3_pcache *pNew;
  44224. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  44225. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  44226. pCache->bPurgeable
  44227. );
  44228. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  44229. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  44230. if( pCache->pCache ){
  44231. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  44232. }
  44233. pCache->pCache = pNew;
  44234. pCache->szPage = szPage;
  44235. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  44236. }
  44237. return SQLITE_OK;
  44238. }
  44239. /*
  44240. ** Try to obtain a page from the cache.
  44241. **
  44242. ** This routine returns a pointer to an sqlite3_pcache_page object if
  44243. ** such an object is already in cache, or if a new one is created.
  44244. ** This routine returns a NULL pointer if the object was not in cache
  44245. ** and could not be created.
  44246. **
  44247. ** The createFlags should be 0 to check for existing pages and should
  44248. ** be 3 (not 1, but 3) to try to create a new page.
  44249. **
  44250. ** If the createFlag is 0, then NULL is always returned if the page
  44251. ** is not already in the cache. If createFlag is 1, then a new page
  44252. ** is created only if that can be done without spilling dirty pages
  44253. ** and without exceeding the cache size limit.
  44254. **
  44255. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  44256. ** initialize the sqlite3_pcache_page object and convert it into a
  44257. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  44258. ** routines are split this way for performance reasons. When separated
  44259. ** they can both (usually) operate without having to push values to
  44260. ** the stack on entry and pop them back off on exit, which saves a
  44261. ** lot of pushing and popping.
  44262. */
  44263. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  44264. PCache *pCache, /* Obtain the page from this cache */
  44265. Pgno pgno, /* Page number to obtain */
  44266. int createFlag /* If true, create page if it does not exist already */
  44267. ){
  44268. int eCreate;
  44269. sqlite3_pcache_page *pRes;
  44270. assert( pCache!=0 );
  44271. assert( pCache->pCache!=0 );
  44272. assert( createFlag==3 || createFlag==0 );
  44273. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  44274. /* eCreate defines what to do if the page does not exist.
  44275. ** 0 Do not allocate a new page. (createFlag==0)
  44276. ** 1 Allocate a new page if doing so is inexpensive.
  44277. ** (createFlag==1 AND bPurgeable AND pDirty)
  44278. ** 2 Allocate a new page even it doing so is difficult.
  44279. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  44280. */
  44281. eCreate = createFlag & pCache->eCreate;
  44282. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  44283. assert( createFlag==0 || pCache->eCreate==eCreate );
  44284. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  44285. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  44286. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  44287. createFlag?" create":"",pRes));
  44288. return pRes;
  44289. }
  44290. /*
  44291. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  44292. ** page because no clean pages are available for reuse and the cache
  44293. ** size limit has been reached, then this routine can be invoked to
  44294. ** try harder to allocate a page. This routine might invoke the stress
  44295. ** callback to spill dirty pages to the journal. It will then try to
  44296. ** allocate the new page and will only fail to allocate a new page on
  44297. ** an OOM error.
  44298. **
  44299. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  44300. */
  44301. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  44302. PCache *pCache, /* Obtain the page from this cache */
  44303. Pgno pgno, /* Page number to obtain */
  44304. sqlite3_pcache_page **ppPage /* Write result here */
  44305. ){
  44306. PgHdr *pPg;
  44307. if( pCache->eCreate==2 ) return 0;
  44308. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  44309. /* Find a dirty page to write-out and recycle. First try to find a
  44310. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  44311. ** cleared), but if that is not possible settle for any other
  44312. ** unreferenced dirty page.
  44313. **
  44314. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  44315. ** flag is currently referenced, then the following may leave pSynced
  44316. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  44317. ** cleared). This is Ok, as pSynced is just an optimization. */
  44318. for(pPg=pCache->pSynced;
  44319. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  44320. pPg=pPg->pDirtyPrev
  44321. );
  44322. pCache->pSynced = pPg;
  44323. if( !pPg ){
  44324. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  44325. }
  44326. if( pPg ){
  44327. int rc;
  44328. #ifdef SQLITE_LOG_CACHE_SPILL
  44329. sqlite3_log(SQLITE_FULL,
  44330. "spill page %d making room for %d - cache used: %d/%d",
  44331. pPg->pgno, pgno,
  44332. sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
  44333. numberOfCachePages(pCache));
  44334. #endif
  44335. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  44336. rc = pCache->xStress(pCache->pStress, pPg);
  44337. pcacheDump(pCache);
  44338. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  44339. return rc;
  44340. }
  44341. }
  44342. }
  44343. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  44344. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  44345. }
  44346. /*
  44347. ** This is a helper routine for sqlite3PcacheFetchFinish()
  44348. **
  44349. ** In the uncommon case where the page being fetched has not been
  44350. ** initialized, this routine is invoked to do the initialization.
  44351. ** This routine is broken out into a separate function since it
  44352. ** requires extra stack manipulation that can be avoided in the common
  44353. ** case.
  44354. */
  44355. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  44356. PCache *pCache, /* Obtain the page from this cache */
  44357. Pgno pgno, /* Page number obtained */
  44358. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  44359. ){
  44360. PgHdr *pPgHdr;
  44361. assert( pPage!=0 );
  44362. pPgHdr = (PgHdr*)pPage->pExtra;
  44363. assert( pPgHdr->pPage==0 );
  44364. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  44365. pPgHdr->pPage = pPage;
  44366. pPgHdr->pData = pPage->pBuf;
  44367. pPgHdr->pExtra = (void *)&pPgHdr[1];
  44368. memset(pPgHdr->pExtra, 0, 8);
  44369. pPgHdr->pCache = pCache;
  44370. pPgHdr->pgno = pgno;
  44371. pPgHdr->flags = PGHDR_CLEAN;
  44372. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  44373. }
  44374. /*
  44375. ** This routine converts the sqlite3_pcache_page object returned by
  44376. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  44377. ** must be called after sqlite3PcacheFetch() in order to get a usable
  44378. ** result.
  44379. */
  44380. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  44381. PCache *pCache, /* Obtain the page from this cache */
  44382. Pgno pgno, /* Page number obtained */
  44383. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  44384. ){
  44385. PgHdr *pPgHdr;
  44386. assert( pPage!=0 );
  44387. pPgHdr = (PgHdr *)pPage->pExtra;
  44388. if( !pPgHdr->pPage ){
  44389. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  44390. }
  44391. pCache->nRefSum++;
  44392. pPgHdr->nRef++;
  44393. assert( sqlite3PcachePageSanity(pPgHdr) );
  44394. return pPgHdr;
  44395. }
  44396. /*
  44397. ** Decrement the reference count on a page. If the page is clean and the
  44398. ** reference count drops to 0, then it is made eligible for recycling.
  44399. */
  44400. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  44401. assert( p->nRef>0 );
  44402. p->pCache->nRefSum--;
  44403. if( (--p->nRef)==0 ){
  44404. if( p->flags&PGHDR_CLEAN ){
  44405. pcacheUnpin(p);
  44406. }else{
  44407. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  44408. }
  44409. }
  44410. }
  44411. /*
  44412. ** Increase the reference count of a supplied page by 1.
  44413. */
  44414. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  44415. assert(p->nRef>0);
  44416. assert( sqlite3PcachePageSanity(p) );
  44417. p->nRef++;
  44418. p->pCache->nRefSum++;
  44419. }
  44420. /*
  44421. ** Drop a page from the cache. There must be exactly one reference to the
  44422. ** page. This function deletes that reference, so after it returns the
  44423. ** page pointed to by p is invalid.
  44424. */
  44425. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  44426. assert( p->nRef==1 );
  44427. assert( sqlite3PcachePageSanity(p) );
  44428. if( p->flags&PGHDR_DIRTY ){
  44429. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  44430. }
  44431. p->pCache->nRefSum--;
  44432. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  44433. }
  44434. /*
  44435. ** Make sure the page is marked as dirty. If it isn't dirty already,
  44436. ** make it so.
  44437. */
  44438. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  44439. assert( p->nRef>0 );
  44440. assert( sqlite3PcachePageSanity(p) );
  44441. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  44442. p->flags &= ~PGHDR_DONT_WRITE;
  44443. if( p->flags & PGHDR_CLEAN ){
  44444. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  44445. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  44446. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  44447. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  44448. }
  44449. assert( sqlite3PcachePageSanity(p) );
  44450. }
  44451. }
  44452. /*
  44453. ** Make sure the page is marked as clean. If it isn't clean already,
  44454. ** make it so.
  44455. */
  44456. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  44457. assert( sqlite3PcachePageSanity(p) );
  44458. assert( (p->flags & PGHDR_DIRTY)!=0 );
  44459. assert( (p->flags & PGHDR_CLEAN)==0 );
  44460. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  44461. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  44462. p->flags |= PGHDR_CLEAN;
  44463. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  44464. assert( sqlite3PcachePageSanity(p) );
  44465. if( p->nRef==0 ){
  44466. pcacheUnpin(p);
  44467. }
  44468. }
  44469. /*
  44470. ** Make every page in the cache clean.
  44471. */
  44472. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  44473. PgHdr *p;
  44474. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  44475. while( (p = pCache->pDirty)!=0 ){
  44476. sqlite3PcacheMakeClean(p);
  44477. }
  44478. }
  44479. /*
  44480. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  44481. */
  44482. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  44483. PgHdr *p;
  44484. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  44485. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  44486. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  44487. }
  44488. pCache->pSynced = pCache->pDirtyTail;
  44489. }
  44490. /*
  44491. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  44492. */
  44493. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  44494. PgHdr *p;
  44495. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  44496. p->flags &= ~PGHDR_NEED_SYNC;
  44497. }
  44498. pCache->pSynced = pCache->pDirtyTail;
  44499. }
  44500. /*
  44501. ** Change the page number of page p to newPgno.
  44502. */
  44503. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  44504. PCache *pCache = p->pCache;
  44505. assert( p->nRef>0 );
  44506. assert( newPgno>0 );
  44507. assert( sqlite3PcachePageSanity(p) );
  44508. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  44509. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  44510. p->pgno = newPgno;
  44511. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  44512. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  44513. }
  44514. }
  44515. /*
  44516. ** Drop every cache entry whose page number is greater than "pgno". The
  44517. ** caller must ensure that there are no outstanding references to any pages
  44518. ** other than page 1 with a page number greater than pgno.
  44519. **
  44520. ** If there is a reference to page 1 and the pgno parameter passed to this
  44521. ** function is 0, then the data area associated with page 1 is zeroed, but
  44522. ** the page object is not dropped.
  44523. */
  44524. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  44525. if( pCache->pCache ){
  44526. PgHdr *p;
  44527. PgHdr *pNext;
  44528. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  44529. for(p=pCache->pDirty; p; p=pNext){
  44530. pNext = p->pDirtyNext;
  44531. /* This routine never gets call with a positive pgno except right
  44532. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  44533. ** it must be that pgno==0.
  44534. */
  44535. assert( p->pgno>0 );
  44536. if( p->pgno>pgno ){
  44537. assert( p->flags&PGHDR_DIRTY );
  44538. sqlite3PcacheMakeClean(p);
  44539. }
  44540. }
  44541. if( pgno==0 && pCache->nRefSum ){
  44542. sqlite3_pcache_page *pPage1;
  44543. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  44544. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  44545. ** pCache->nRefSum>0 */
  44546. memset(pPage1->pBuf, 0, pCache->szPage);
  44547. pgno = 1;
  44548. }
  44549. }
  44550. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  44551. }
  44552. }
  44553. /*
  44554. ** Close a cache.
  44555. */
  44556. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  44557. assert( pCache->pCache!=0 );
  44558. pcacheTrace(("%p.CLOSE\n",pCache));
  44559. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  44560. }
  44561. /*
  44562. ** Discard the contents of the cache.
  44563. */
  44564. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  44565. sqlite3PcacheTruncate(pCache, 0);
  44566. }
  44567. /*
  44568. ** Merge two lists of pages connected by pDirty and in pgno order.
  44569. ** Do not bother fixing the pDirtyPrev pointers.
  44570. */
  44571. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  44572. PgHdr result, *pTail;
  44573. pTail = &result;
  44574. assert( pA!=0 && pB!=0 );
  44575. for(;;){
  44576. if( pA->pgno<pB->pgno ){
  44577. pTail->pDirty = pA;
  44578. pTail = pA;
  44579. pA = pA->pDirty;
  44580. if( pA==0 ){
  44581. pTail->pDirty = pB;
  44582. break;
  44583. }
  44584. }else{
  44585. pTail->pDirty = pB;
  44586. pTail = pB;
  44587. pB = pB->pDirty;
  44588. if( pB==0 ){
  44589. pTail->pDirty = pA;
  44590. break;
  44591. }
  44592. }
  44593. }
  44594. return result.pDirty;
  44595. }
  44596. /*
  44597. ** Sort the list of pages in accending order by pgno. Pages are
  44598. ** connected by pDirty pointers. The pDirtyPrev pointers are
  44599. ** corrupted by this sort.
  44600. **
  44601. ** Since there cannot be more than 2^31 distinct pages in a database,
  44602. ** there cannot be more than 31 buckets required by the merge sorter.
  44603. ** One extra bucket is added to catch overflow in case something
  44604. ** ever changes to make the previous sentence incorrect.
  44605. */
  44606. #define N_SORT_BUCKET 32
  44607. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  44608. PgHdr *a[N_SORT_BUCKET], *p;
  44609. int i;
  44610. memset(a, 0, sizeof(a));
  44611. while( pIn ){
  44612. p = pIn;
  44613. pIn = p->pDirty;
  44614. p->pDirty = 0;
  44615. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  44616. if( a[i]==0 ){
  44617. a[i] = p;
  44618. break;
  44619. }else{
  44620. p = pcacheMergeDirtyList(a[i], p);
  44621. a[i] = 0;
  44622. }
  44623. }
  44624. if( NEVER(i==N_SORT_BUCKET-1) ){
  44625. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  44626. ** the input list. But that is impossible.
  44627. */
  44628. a[i] = pcacheMergeDirtyList(a[i], p);
  44629. }
  44630. }
  44631. p = a[0];
  44632. for(i=1; i<N_SORT_BUCKET; i++){
  44633. if( a[i]==0 ) continue;
  44634. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  44635. }
  44636. return p;
  44637. }
  44638. /*
  44639. ** Return a list of all dirty pages in the cache, sorted by page number.
  44640. */
  44641. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  44642. PgHdr *p;
  44643. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  44644. p->pDirty = p->pDirtyNext;
  44645. }
  44646. return pcacheSortDirtyList(pCache->pDirty);
  44647. }
  44648. /*
  44649. ** Return the total number of references to all pages held by the cache.
  44650. **
  44651. ** This is not the total number of pages referenced, but the sum of the
  44652. ** reference count for all pages.
  44653. */
  44654. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  44655. return pCache->nRefSum;
  44656. }
  44657. /*
  44658. ** Return the number of references to the page supplied as an argument.
  44659. */
  44660. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  44661. return p->nRef;
  44662. }
  44663. /*
  44664. ** Return the total number of pages in the cache.
  44665. */
  44666. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  44667. assert( pCache->pCache!=0 );
  44668. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  44669. }
  44670. #ifdef SQLITE_TEST
  44671. /*
  44672. ** Get the suggested cache-size value.
  44673. */
  44674. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  44675. return numberOfCachePages(pCache);
  44676. }
  44677. #endif
  44678. /*
  44679. ** Set the suggested cache-size value.
  44680. */
  44681. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  44682. assert( pCache->pCache!=0 );
  44683. pCache->szCache = mxPage;
  44684. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  44685. numberOfCachePages(pCache));
  44686. }
  44687. /*
  44688. ** Set the suggested cache-spill value. Make no changes if if the
  44689. ** argument is zero. Return the effective cache-spill size, which will
  44690. ** be the larger of the szSpill and szCache.
  44691. */
  44692. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  44693. int res;
  44694. assert( p->pCache!=0 );
  44695. if( mxPage ){
  44696. if( mxPage<0 ){
  44697. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  44698. }
  44699. p->szSpill = mxPage;
  44700. }
  44701. res = numberOfCachePages(p);
  44702. if( res<p->szSpill ) res = p->szSpill;
  44703. return res;
  44704. }
  44705. /*
  44706. ** Free up as much memory as possible from the page cache.
  44707. */
  44708. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  44709. assert( pCache->pCache!=0 );
  44710. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  44711. }
  44712. /*
  44713. ** Return the size of the header added by this middleware layer
  44714. ** in the page-cache hierarchy.
  44715. */
  44716. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  44717. /*
  44718. ** Return the number of dirty pages currently in the cache, as a percentage
  44719. ** of the configured cache size.
  44720. */
  44721. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  44722. PgHdr *pDirty;
  44723. int nDirty = 0;
  44724. int nCache = numberOfCachePages(pCache);
  44725. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  44726. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  44727. }
  44728. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  44729. /*
  44730. ** For all dirty pages currently in the cache, invoke the specified
  44731. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  44732. ** defined.
  44733. */
  44734. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  44735. PgHdr *pDirty;
  44736. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  44737. xIter(pDirty);
  44738. }
  44739. }
  44740. #endif
  44741. /************** End of pcache.c **********************************************/
  44742. /************** Begin file pcache1.c *****************************************/
  44743. /*
  44744. ** 2008 November 05
  44745. **
  44746. ** The author disclaims copyright to this source code. In place of
  44747. ** a legal notice, here is a blessing:
  44748. **
  44749. ** May you do good and not evil.
  44750. ** May you find forgiveness for yourself and forgive others.
  44751. ** May you share freely, never taking more than you give.
  44752. **
  44753. *************************************************************************
  44754. **
  44755. ** This file implements the default page cache implementation (the
  44756. ** sqlite3_pcache interface). It also contains part of the implementation
  44757. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  44758. ** If the default page cache implementation is overridden, then neither of
  44759. ** these two features are available.
  44760. **
  44761. ** A Page cache line looks like this:
  44762. **
  44763. ** -------------------------------------------------------------
  44764. ** | database page content | PgHdr1 | MemPage | PgHdr |
  44765. ** -------------------------------------------------------------
  44766. **
  44767. ** The database page content is up front (so that buffer overreads tend to
  44768. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  44769. ** is the extension added by the btree.c module containing information such
  44770. ** as the database page number and how that database page is used. PgHdr
  44771. ** is added by the pcache.c layer and contains information used to keep track
  44772. ** of which pages are "dirty". PgHdr1 is an extension added by this
  44773. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  44774. ** PgHdr1 contains information needed to look up a page by its page number.
  44775. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  44776. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  44777. **
  44778. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  44779. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  44780. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  44781. ** size can vary according to architecture, compile-time options, and
  44782. ** SQLite library version number.
  44783. **
  44784. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  44785. ** using a separate memory allocation from the database page content. This
  44786. ** seeks to overcome the "clownshoe" problem (also called "internal
  44787. ** fragmentation" in academic literature) of allocating a few bytes more
  44788. ** than a power of two with the memory allocator rounding up to the next
  44789. ** power of two, and leaving the rounded-up space unused.
  44790. **
  44791. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  44792. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  44793. **
  44794. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  44795. ** The btree.c module deals with pointers to MemPage objects.
  44796. **
  44797. ** SOURCE OF PAGE CACHE MEMORY:
  44798. **
  44799. ** Memory for a page might come from any of three sources:
  44800. **
  44801. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  44802. ** (2) Global page-cache memory provided using sqlite3_config() with
  44803. ** SQLITE_CONFIG_PAGECACHE.
  44804. ** (3) PCache-local bulk allocation.
  44805. **
  44806. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  44807. ** that is allocated when the page cache is created. The size of the local
  44808. ** bulk allocation can be adjusted using
  44809. **
  44810. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  44811. **
  44812. ** If N is positive, then N pages worth of memory are allocated using a single
  44813. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  44814. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  44815. ** for as many pages as can be accomodated.
  44816. **
  44817. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  44818. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  44819. ** memory allocator (1).
  44820. **
  44821. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  44822. ** show that method (3) with N==100 provides about a 5% performance boost for
  44823. ** common workloads.
  44824. */
  44825. /* #include "sqliteInt.h" */
  44826. typedef struct PCache1 PCache1;
  44827. typedef struct PgHdr1 PgHdr1;
  44828. typedef struct PgFreeslot PgFreeslot;
  44829. typedef struct PGroup PGroup;
  44830. /*
  44831. ** Each cache entry is represented by an instance of the following
  44832. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  44833. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  44834. ** in memory.
  44835. */
  44836. struct PgHdr1 {
  44837. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  44838. unsigned int iKey; /* Key value (page number) */
  44839. u8 isBulkLocal; /* This page from bulk local storage */
  44840. u8 isAnchor; /* This is the PGroup.lru element */
  44841. PgHdr1 *pNext; /* Next in hash table chain */
  44842. PCache1 *pCache; /* Cache that currently owns this page */
  44843. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  44844. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  44845. };
  44846. /*
  44847. ** A page is pinned if it is no on the LRU list
  44848. */
  44849. #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
  44850. #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
  44851. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  44852. ** of one or more PCaches that are able to recycle each other's unpinned
  44853. ** pages when they are under memory pressure. A PGroup is an instance of
  44854. ** the following object.
  44855. **
  44856. ** This page cache implementation works in one of two modes:
  44857. **
  44858. ** (1) Every PCache is the sole member of its own PGroup. There is
  44859. ** one PGroup per PCache.
  44860. **
  44861. ** (2) There is a single global PGroup that all PCaches are a member
  44862. ** of.
  44863. **
  44864. ** Mode 1 uses more memory (since PCache instances are not able to rob
  44865. ** unused pages from other PCaches) but it also operates without a mutex,
  44866. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  44867. ** threadsafe, but recycles pages more efficiently.
  44868. **
  44869. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  44870. ** PGroup which is the pcache1.grp global variable and its mutex is
  44871. ** SQLITE_MUTEX_STATIC_LRU.
  44872. */
  44873. struct PGroup {
  44874. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  44875. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  44876. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  44877. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  44878. unsigned int nPurgeable; /* Number of purgeable pages allocated */
  44879. PgHdr1 lru; /* The beginning and end of the LRU list */
  44880. };
  44881. /* Each page cache is an instance of the following object. Every
  44882. ** open database file (including each in-memory database and each
  44883. ** temporary or transient database) has a single page cache which
  44884. ** is an instance of this object.
  44885. **
  44886. ** Pointers to structures of this type are cast and returned as
  44887. ** opaque sqlite3_pcache* handles.
  44888. */
  44889. struct PCache1 {
  44890. /* Cache configuration parameters. Page size (szPage) and the purgeable
  44891. ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
  44892. ** cache is created and are never changed thereafter. nMax may be
  44893. ** modified at any time by a call to the pcache1Cachesize() method.
  44894. ** The PGroup mutex must be held when accessing nMax.
  44895. */
  44896. PGroup *pGroup; /* PGroup this cache belongs to */
  44897. unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
  44898. int szPage; /* Size of database content section */
  44899. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  44900. int szAlloc; /* Total size of one pcache line */
  44901. int bPurgeable; /* True if cache is purgeable */
  44902. unsigned int nMin; /* Minimum number of pages reserved */
  44903. unsigned int nMax; /* Configured "cache_size" value */
  44904. unsigned int n90pct; /* nMax*9/10 */
  44905. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  44906. /* Hash table of all pages. The following variables may only be accessed
  44907. ** when the accessor is holding the PGroup mutex.
  44908. */
  44909. unsigned int nRecyclable; /* Number of pages in the LRU list */
  44910. unsigned int nPage; /* Total number of pages in apHash */
  44911. unsigned int nHash; /* Number of slots in apHash[] */
  44912. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  44913. PgHdr1 *pFree; /* List of unused pcache-local pages */
  44914. void *pBulk; /* Bulk memory used by pcache-local */
  44915. };
  44916. /*
  44917. ** Free slots in the allocator used to divide up the global page cache
  44918. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  44919. */
  44920. struct PgFreeslot {
  44921. PgFreeslot *pNext; /* Next free slot */
  44922. };
  44923. /*
  44924. ** Global data used by this cache.
  44925. */
  44926. static SQLITE_WSD struct PCacheGlobal {
  44927. PGroup grp; /* The global PGroup for mode (2) */
  44928. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  44929. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  44930. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  44931. ** The nFreeSlot and pFree values do require mutex protection.
  44932. */
  44933. int isInit; /* True if initialized */
  44934. int separateCache; /* Use a new PGroup for each PCache */
  44935. int nInitPage; /* Initial bulk allocation size */
  44936. int szSlot; /* Size of each free slot */
  44937. int nSlot; /* The number of pcache slots */
  44938. int nReserve; /* Try to keep nFreeSlot above this */
  44939. void *pStart, *pEnd; /* Bounds of global page cache memory */
  44940. /* Above requires no mutex. Use mutex below for variable that follow. */
  44941. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  44942. PgFreeslot *pFree; /* Free page blocks */
  44943. int nFreeSlot; /* Number of unused pcache slots */
  44944. /* The following value requires a mutex to change. We skip the mutex on
  44945. ** reading because (1) most platforms read a 32-bit integer atomically and
  44946. ** (2) even if an incorrect value is read, no great harm is done since this
  44947. ** is really just an optimization. */
  44948. int bUnderPressure; /* True if low on PAGECACHE memory */
  44949. } pcache1_g;
  44950. /*
  44951. ** All code in this file should access the global structure above via the
  44952. ** alias "pcache1". This ensures that the WSD emulation is used when
  44953. ** compiling for systems that do not support real WSD.
  44954. */
  44955. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  44956. /*
  44957. ** Macros to enter and leave the PCache LRU mutex.
  44958. */
  44959. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  44960. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  44961. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  44962. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  44963. #else
  44964. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  44965. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  44966. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  44967. #endif
  44968. /******************************************************************************/
  44969. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  44970. /*
  44971. ** This function is called during initialization if a static buffer is
  44972. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  44973. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  44974. ** enough to contain 'n' buffers of 'sz' bytes each.
  44975. **
  44976. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  44977. ** to be serialized already. There is no need for further mutexing.
  44978. */
  44979. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  44980. if( pcache1.isInit ){
  44981. PgFreeslot *p;
  44982. if( pBuf==0 ) sz = n = 0;
  44983. if( n==0 ) sz = 0;
  44984. sz = ROUNDDOWN8(sz);
  44985. pcache1.szSlot = sz;
  44986. pcache1.nSlot = pcache1.nFreeSlot = n;
  44987. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  44988. pcache1.pStart = pBuf;
  44989. pcache1.pFree = 0;
  44990. pcache1.bUnderPressure = 0;
  44991. while( n-- ){
  44992. p = (PgFreeslot*)pBuf;
  44993. p->pNext = pcache1.pFree;
  44994. pcache1.pFree = p;
  44995. pBuf = (void*)&((char*)pBuf)[sz];
  44996. }
  44997. pcache1.pEnd = pBuf;
  44998. }
  44999. }
  45000. /*
  45001. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  45002. ** true if pCache->pFree ends up containing one or more free pages.
  45003. */
  45004. static int pcache1InitBulk(PCache1 *pCache){
  45005. i64 szBulk;
  45006. char *zBulk;
  45007. if( pcache1.nInitPage==0 ) return 0;
  45008. /* Do not bother with a bulk allocation if the cache size very small */
  45009. if( pCache->nMax<3 ) return 0;
  45010. sqlite3BeginBenignMalloc();
  45011. if( pcache1.nInitPage>0 ){
  45012. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  45013. }else{
  45014. szBulk = -1024 * (i64)pcache1.nInitPage;
  45015. }
  45016. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  45017. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  45018. }
  45019. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  45020. sqlite3EndBenignMalloc();
  45021. if( zBulk ){
  45022. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  45023. do{
  45024. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  45025. pX->page.pBuf = zBulk;
  45026. pX->page.pExtra = &pX[1];
  45027. pX->isBulkLocal = 1;
  45028. pX->isAnchor = 0;
  45029. pX->pNext = pCache->pFree;
  45030. pCache->pFree = pX;
  45031. zBulk += pCache->szAlloc;
  45032. }while( --nBulk );
  45033. }
  45034. return pCache->pFree!=0;
  45035. }
  45036. /*
  45037. ** Malloc function used within this file to allocate space from the buffer
  45038. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  45039. ** such buffer exists or there is no space left in it, this function falls
  45040. ** back to sqlite3Malloc().
  45041. **
  45042. ** Multiple threads can run this routine at the same time. Global variables
  45043. ** in pcache1 need to be protected via mutex.
  45044. */
  45045. static void *pcache1Alloc(int nByte){
  45046. void *p = 0;
  45047. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  45048. if( nByte<=pcache1.szSlot ){
  45049. sqlite3_mutex_enter(pcache1.mutex);
  45050. p = (PgHdr1 *)pcache1.pFree;
  45051. if( p ){
  45052. pcache1.pFree = pcache1.pFree->pNext;
  45053. pcache1.nFreeSlot--;
  45054. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  45055. assert( pcache1.nFreeSlot>=0 );
  45056. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  45057. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  45058. }
  45059. sqlite3_mutex_leave(pcache1.mutex);
  45060. }
  45061. if( p==0 ){
  45062. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  45063. ** it from sqlite3Malloc instead.
  45064. */
  45065. p = sqlite3Malloc(nByte);
  45066. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  45067. if( p ){
  45068. int sz = sqlite3MallocSize(p);
  45069. sqlite3_mutex_enter(pcache1.mutex);
  45070. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  45071. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  45072. sqlite3_mutex_leave(pcache1.mutex);
  45073. }
  45074. #endif
  45075. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  45076. }
  45077. return p;
  45078. }
  45079. /*
  45080. ** Free an allocated buffer obtained from pcache1Alloc().
  45081. */
  45082. static void pcache1Free(void *p){
  45083. if( p==0 ) return;
  45084. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  45085. PgFreeslot *pSlot;
  45086. sqlite3_mutex_enter(pcache1.mutex);
  45087. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  45088. pSlot = (PgFreeslot*)p;
  45089. pSlot->pNext = pcache1.pFree;
  45090. pcache1.pFree = pSlot;
  45091. pcache1.nFreeSlot++;
  45092. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  45093. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  45094. sqlite3_mutex_leave(pcache1.mutex);
  45095. }else{
  45096. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  45097. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  45098. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  45099. {
  45100. int nFreed = 0;
  45101. nFreed = sqlite3MallocSize(p);
  45102. sqlite3_mutex_enter(pcache1.mutex);
  45103. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  45104. sqlite3_mutex_leave(pcache1.mutex);
  45105. }
  45106. #endif
  45107. sqlite3_free(p);
  45108. }
  45109. }
  45110. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45111. /*
  45112. ** Return the size of a pcache allocation
  45113. */
  45114. static int pcache1MemSize(void *p){
  45115. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  45116. return pcache1.szSlot;
  45117. }else{
  45118. int iSize;
  45119. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  45120. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  45121. iSize = sqlite3MallocSize(p);
  45122. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  45123. return iSize;
  45124. }
  45125. }
  45126. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  45127. /*
  45128. ** Allocate a new page object initially associated with cache pCache.
  45129. */
  45130. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  45131. PgHdr1 *p = 0;
  45132. void *pPg;
  45133. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  45134. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  45135. p = pCache->pFree;
  45136. pCache->pFree = p->pNext;
  45137. p->pNext = 0;
  45138. }else{
  45139. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45140. /* The group mutex must be released before pcache1Alloc() is called. This
  45141. ** is because it might call sqlite3_release_memory(), which assumes that
  45142. ** this mutex is not held. */
  45143. assert( pcache1.separateCache==0 );
  45144. assert( pCache->pGroup==&pcache1.grp );
  45145. pcache1LeaveMutex(pCache->pGroup);
  45146. #endif
  45147. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  45148. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  45149. pPg = pcache1Alloc(pCache->szPage);
  45150. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  45151. if( !pPg || !p ){
  45152. pcache1Free(pPg);
  45153. sqlite3_free(p);
  45154. pPg = 0;
  45155. }
  45156. #else
  45157. pPg = pcache1Alloc(pCache->szAlloc);
  45158. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  45159. #endif
  45160. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  45161. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45162. pcache1EnterMutex(pCache->pGroup);
  45163. #endif
  45164. if( pPg==0 ) return 0;
  45165. p->page.pBuf = pPg;
  45166. p->page.pExtra = &p[1];
  45167. p->isBulkLocal = 0;
  45168. p->isAnchor = 0;
  45169. }
  45170. (*pCache->pnPurgeable)++;
  45171. return p;
  45172. }
  45173. /*
  45174. ** Free a page object allocated by pcache1AllocPage().
  45175. */
  45176. static void pcache1FreePage(PgHdr1 *p){
  45177. PCache1 *pCache;
  45178. assert( p!=0 );
  45179. pCache = p->pCache;
  45180. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  45181. if( p->isBulkLocal ){
  45182. p->pNext = pCache->pFree;
  45183. pCache->pFree = p;
  45184. }else{
  45185. pcache1Free(p->page.pBuf);
  45186. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  45187. sqlite3_free(p);
  45188. #endif
  45189. }
  45190. (*pCache->pnPurgeable)--;
  45191. }
  45192. /*
  45193. ** Malloc function used by SQLite to obtain space from the buffer configured
  45194. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  45195. ** exists, this function falls back to sqlite3Malloc().
  45196. */
  45197. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  45198. return pcache1Alloc(sz);
  45199. }
  45200. /*
  45201. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  45202. */
  45203. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  45204. pcache1Free(p);
  45205. }
  45206. /*
  45207. ** Return true if it desirable to avoid allocating a new page cache
  45208. ** entry.
  45209. **
  45210. ** If memory was allocated specifically to the page cache using
  45211. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  45212. ** it is desirable to avoid allocating a new page cache entry because
  45213. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  45214. ** for all page cache needs and we should not need to spill the
  45215. ** allocation onto the heap.
  45216. **
  45217. ** Or, the heap is used for all page cache memory but the heap is
  45218. ** under memory pressure, then again it is desirable to avoid
  45219. ** allocating a new page cache entry in order to avoid stressing
  45220. ** the heap even further.
  45221. */
  45222. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  45223. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  45224. return pcache1.bUnderPressure;
  45225. }else{
  45226. return sqlite3HeapNearlyFull();
  45227. }
  45228. }
  45229. /******************************************************************************/
  45230. /******** General Implementation Functions ************************************/
  45231. /*
  45232. ** This function is used to resize the hash table used by the cache passed
  45233. ** as the first argument.
  45234. **
  45235. ** The PCache mutex must be held when this function is called.
  45236. */
  45237. static void pcache1ResizeHash(PCache1 *p){
  45238. PgHdr1 **apNew;
  45239. unsigned int nNew;
  45240. unsigned int i;
  45241. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  45242. nNew = p->nHash*2;
  45243. if( nNew<256 ){
  45244. nNew = 256;
  45245. }
  45246. pcache1LeaveMutex(p->pGroup);
  45247. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  45248. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  45249. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  45250. pcache1EnterMutex(p->pGroup);
  45251. if( apNew ){
  45252. for(i=0; i<p->nHash; i++){
  45253. PgHdr1 *pPage;
  45254. PgHdr1 *pNext = p->apHash[i];
  45255. while( (pPage = pNext)!=0 ){
  45256. unsigned int h = pPage->iKey % nNew;
  45257. pNext = pPage->pNext;
  45258. pPage->pNext = apNew[h];
  45259. apNew[h] = pPage;
  45260. }
  45261. }
  45262. sqlite3_free(p->apHash);
  45263. p->apHash = apNew;
  45264. p->nHash = nNew;
  45265. }
  45266. }
  45267. /*
  45268. ** This function is used internally to remove the page pPage from the
  45269. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  45270. ** LRU list, then this function is a no-op.
  45271. **
  45272. ** The PGroup mutex must be held when this function is called.
  45273. */
  45274. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  45275. assert( pPage!=0 );
  45276. assert( PAGE_IS_UNPINNED(pPage) );
  45277. assert( pPage->pLruNext );
  45278. assert( pPage->pLruPrev );
  45279. assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
  45280. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  45281. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  45282. pPage->pLruNext = 0;
  45283. pPage->pLruPrev = 0;
  45284. assert( pPage->isAnchor==0 );
  45285. assert( pPage->pCache->pGroup->lru.isAnchor==1 );
  45286. pPage->pCache->nRecyclable--;
  45287. return pPage;
  45288. }
  45289. /*
  45290. ** Remove the page supplied as an argument from the hash table
  45291. ** (PCache1.apHash structure) that it is currently stored in.
  45292. ** Also free the page if freePage is true.
  45293. **
  45294. ** The PGroup mutex must be held when this function is called.
  45295. */
  45296. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  45297. unsigned int h;
  45298. PCache1 *pCache = pPage->pCache;
  45299. PgHdr1 **pp;
  45300. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  45301. h = pPage->iKey % pCache->nHash;
  45302. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  45303. *pp = (*pp)->pNext;
  45304. pCache->nPage--;
  45305. if( freeFlag ) pcache1FreePage(pPage);
  45306. }
  45307. /*
  45308. ** If there are currently more than nMaxPage pages allocated, try
  45309. ** to recycle pages to reduce the number allocated to nMaxPage.
  45310. */
  45311. static void pcache1EnforceMaxPage(PCache1 *pCache){
  45312. PGroup *pGroup = pCache->pGroup;
  45313. PgHdr1 *p;
  45314. assert( sqlite3_mutex_held(pGroup->mutex) );
  45315. while( pGroup->nPurgeable>pGroup->nMaxPage
  45316. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  45317. ){
  45318. assert( p->pCache->pGroup==pGroup );
  45319. assert( PAGE_IS_UNPINNED(p) );
  45320. pcache1PinPage(p);
  45321. pcache1RemoveFromHash(p, 1);
  45322. }
  45323. if( pCache->nPage==0 && pCache->pBulk ){
  45324. sqlite3_free(pCache->pBulk);
  45325. pCache->pBulk = pCache->pFree = 0;
  45326. }
  45327. }
  45328. /*
  45329. ** Discard all pages from cache pCache with a page number (key value)
  45330. ** greater than or equal to iLimit. Any pinned pages that meet this
  45331. ** criteria are unpinned before they are discarded.
  45332. **
  45333. ** The PCache mutex must be held when this function is called.
  45334. */
  45335. static void pcache1TruncateUnsafe(
  45336. PCache1 *pCache, /* The cache to truncate */
  45337. unsigned int iLimit /* Drop pages with this pgno or larger */
  45338. ){
  45339. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  45340. unsigned int h, iStop;
  45341. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  45342. assert( pCache->iMaxKey >= iLimit );
  45343. assert( pCache->nHash > 0 );
  45344. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  45345. /* If we are just shaving the last few pages off the end of the
  45346. ** cache, then there is no point in scanning the entire hash table.
  45347. ** Only scan those hash slots that might contain pages that need to
  45348. ** be removed. */
  45349. h = iLimit % pCache->nHash;
  45350. iStop = pCache->iMaxKey % pCache->nHash;
  45351. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  45352. }else{
  45353. /* This is the general case where many pages are being removed.
  45354. ** It is necessary to scan the entire hash table */
  45355. h = pCache->nHash/2;
  45356. iStop = h - 1;
  45357. }
  45358. for(;;){
  45359. PgHdr1 **pp;
  45360. PgHdr1 *pPage;
  45361. assert( h<pCache->nHash );
  45362. pp = &pCache->apHash[h];
  45363. while( (pPage = *pp)!=0 ){
  45364. if( pPage->iKey>=iLimit ){
  45365. pCache->nPage--;
  45366. *pp = pPage->pNext;
  45367. if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
  45368. pcache1FreePage(pPage);
  45369. }else{
  45370. pp = &pPage->pNext;
  45371. TESTONLY( if( nPage>=0 ) nPage++; )
  45372. }
  45373. }
  45374. if( h==iStop ) break;
  45375. h = (h+1) % pCache->nHash;
  45376. }
  45377. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  45378. }
  45379. /******************************************************************************/
  45380. /******** sqlite3_pcache Methods **********************************************/
  45381. /*
  45382. ** Implementation of the sqlite3_pcache.xInit method.
  45383. */
  45384. static int pcache1Init(void *NotUsed){
  45385. UNUSED_PARAMETER(NotUsed);
  45386. assert( pcache1.isInit==0 );
  45387. memset(&pcache1, 0, sizeof(pcache1));
  45388. /*
  45389. ** The pcache1.separateCache variable is true if each PCache has its own
  45390. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  45391. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  45392. **
  45393. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  45394. **
  45395. ** * Use a unified cache in single-threaded applications that have
  45396. ** configured a start-time buffer for use as page-cache memory using
  45397. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  45398. ** pBuf argument.
  45399. **
  45400. ** * Otherwise use separate caches (mode-1)
  45401. */
  45402. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  45403. pcache1.separateCache = 0;
  45404. #elif SQLITE_THREADSAFE
  45405. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  45406. || sqlite3GlobalConfig.bCoreMutex>0;
  45407. #else
  45408. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  45409. #endif
  45410. #if SQLITE_THREADSAFE
  45411. if( sqlite3GlobalConfig.bCoreMutex ){
  45412. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  45413. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  45414. }
  45415. #endif
  45416. if( pcache1.separateCache
  45417. && sqlite3GlobalConfig.nPage!=0
  45418. && sqlite3GlobalConfig.pPage==0
  45419. ){
  45420. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  45421. }else{
  45422. pcache1.nInitPage = 0;
  45423. }
  45424. pcache1.grp.mxPinned = 10;
  45425. pcache1.isInit = 1;
  45426. return SQLITE_OK;
  45427. }
  45428. /*
  45429. ** Implementation of the sqlite3_pcache.xShutdown method.
  45430. ** Note that the static mutex allocated in xInit does
  45431. ** not need to be freed.
  45432. */
  45433. static void pcache1Shutdown(void *NotUsed){
  45434. UNUSED_PARAMETER(NotUsed);
  45435. assert( pcache1.isInit!=0 );
  45436. memset(&pcache1, 0, sizeof(pcache1));
  45437. }
  45438. /* forward declaration */
  45439. static void pcache1Destroy(sqlite3_pcache *p);
  45440. /*
  45441. ** Implementation of the sqlite3_pcache.xCreate method.
  45442. **
  45443. ** Allocate a new cache.
  45444. */
  45445. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  45446. PCache1 *pCache; /* The newly created page cache */
  45447. PGroup *pGroup; /* The group the new page cache will belong to */
  45448. int sz; /* Bytes of memory required to allocate the new cache */
  45449. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  45450. assert( szExtra < 300 );
  45451. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  45452. pCache = (PCache1 *)sqlite3MallocZero(sz);
  45453. if( pCache ){
  45454. if( pcache1.separateCache ){
  45455. pGroup = (PGroup*)&pCache[1];
  45456. pGroup->mxPinned = 10;
  45457. }else{
  45458. pGroup = &pcache1.grp;
  45459. }
  45460. if( pGroup->lru.isAnchor==0 ){
  45461. pGroup->lru.isAnchor = 1;
  45462. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  45463. }
  45464. pCache->pGroup = pGroup;
  45465. pCache->szPage = szPage;
  45466. pCache->szExtra = szExtra;
  45467. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  45468. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  45469. pcache1EnterMutex(pGroup);
  45470. pcache1ResizeHash(pCache);
  45471. if( bPurgeable ){
  45472. pCache->nMin = 10;
  45473. pGroup->nMinPage += pCache->nMin;
  45474. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  45475. pCache->pnPurgeable = &pGroup->nPurgeable;
  45476. }else{
  45477. static unsigned int dummyCurrentPage;
  45478. pCache->pnPurgeable = &dummyCurrentPage;
  45479. }
  45480. pcache1LeaveMutex(pGroup);
  45481. if( pCache->nHash==0 ){
  45482. pcache1Destroy((sqlite3_pcache*)pCache);
  45483. pCache = 0;
  45484. }
  45485. }
  45486. return (sqlite3_pcache *)pCache;
  45487. }
  45488. /*
  45489. ** Implementation of the sqlite3_pcache.xCachesize method.
  45490. **
  45491. ** Configure the cache_size limit for a cache.
  45492. */
  45493. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  45494. PCache1 *pCache = (PCache1 *)p;
  45495. if( pCache->bPurgeable ){
  45496. PGroup *pGroup = pCache->pGroup;
  45497. pcache1EnterMutex(pGroup);
  45498. pGroup->nMaxPage += (nMax - pCache->nMax);
  45499. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  45500. pCache->nMax = nMax;
  45501. pCache->n90pct = pCache->nMax*9/10;
  45502. pcache1EnforceMaxPage(pCache);
  45503. pcache1LeaveMutex(pGroup);
  45504. }
  45505. }
  45506. /*
  45507. ** Implementation of the sqlite3_pcache.xShrink method.
  45508. **
  45509. ** Free up as much memory as possible.
  45510. */
  45511. static void pcache1Shrink(sqlite3_pcache *p){
  45512. PCache1 *pCache = (PCache1*)p;
  45513. if( pCache->bPurgeable ){
  45514. PGroup *pGroup = pCache->pGroup;
  45515. int savedMaxPage;
  45516. pcache1EnterMutex(pGroup);
  45517. savedMaxPage = pGroup->nMaxPage;
  45518. pGroup->nMaxPage = 0;
  45519. pcache1EnforceMaxPage(pCache);
  45520. pGroup->nMaxPage = savedMaxPage;
  45521. pcache1LeaveMutex(pGroup);
  45522. }
  45523. }
  45524. /*
  45525. ** Implementation of the sqlite3_pcache.xPagecount method.
  45526. */
  45527. static int pcache1Pagecount(sqlite3_pcache *p){
  45528. int n;
  45529. PCache1 *pCache = (PCache1*)p;
  45530. pcache1EnterMutex(pCache->pGroup);
  45531. n = pCache->nPage;
  45532. pcache1LeaveMutex(pCache->pGroup);
  45533. return n;
  45534. }
  45535. /*
  45536. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  45537. ** in the header of the pcache1Fetch() procedure.
  45538. **
  45539. ** This steps are broken out into a separate procedure because they are
  45540. ** usually not needed, and by avoiding the stack initialization required
  45541. ** for these steps, the main pcache1Fetch() procedure can run faster.
  45542. */
  45543. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  45544. PCache1 *pCache,
  45545. unsigned int iKey,
  45546. int createFlag
  45547. ){
  45548. unsigned int nPinned;
  45549. PGroup *pGroup = pCache->pGroup;
  45550. PgHdr1 *pPage = 0;
  45551. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  45552. assert( pCache->nPage >= pCache->nRecyclable );
  45553. nPinned = pCache->nPage - pCache->nRecyclable;
  45554. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  45555. assert( pCache->n90pct == pCache->nMax*9/10 );
  45556. if( createFlag==1 && (
  45557. nPinned>=pGroup->mxPinned
  45558. || nPinned>=pCache->n90pct
  45559. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  45560. )){
  45561. return 0;
  45562. }
  45563. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  45564. assert( pCache->nHash>0 && pCache->apHash );
  45565. /* Step 4. Try to recycle a page. */
  45566. if( pCache->bPurgeable
  45567. && !pGroup->lru.pLruPrev->isAnchor
  45568. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  45569. ){
  45570. PCache1 *pOther;
  45571. pPage = pGroup->lru.pLruPrev;
  45572. assert( PAGE_IS_UNPINNED(pPage) );
  45573. pcache1RemoveFromHash(pPage, 0);
  45574. pcache1PinPage(pPage);
  45575. pOther = pPage->pCache;
  45576. if( pOther->szAlloc != pCache->szAlloc ){
  45577. pcache1FreePage(pPage);
  45578. pPage = 0;
  45579. }else{
  45580. pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
  45581. }
  45582. }
  45583. /* Step 5. If a usable page buffer has still not been found,
  45584. ** attempt to allocate a new one.
  45585. */
  45586. if( !pPage ){
  45587. pPage = pcache1AllocPage(pCache, createFlag==1);
  45588. }
  45589. if( pPage ){
  45590. unsigned int h = iKey % pCache->nHash;
  45591. pCache->nPage++;
  45592. pPage->iKey = iKey;
  45593. pPage->pNext = pCache->apHash[h];
  45594. pPage->pCache = pCache;
  45595. pPage->pLruPrev = 0;
  45596. pPage->pLruNext = 0;
  45597. *(void **)pPage->page.pExtra = 0;
  45598. pCache->apHash[h] = pPage;
  45599. if( iKey>pCache->iMaxKey ){
  45600. pCache->iMaxKey = iKey;
  45601. }
  45602. }
  45603. return pPage;
  45604. }
  45605. /*
  45606. ** Implementation of the sqlite3_pcache.xFetch method.
  45607. **
  45608. ** Fetch a page by key value.
  45609. **
  45610. ** Whether or not a new page may be allocated by this function depends on
  45611. ** the value of the createFlag argument. 0 means do not allocate a new
  45612. ** page. 1 means allocate a new page if space is easily available. 2
  45613. ** means to try really hard to allocate a new page.
  45614. **
  45615. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  45616. ** database) there is really no difference between createFlag 1 and 2. So
  45617. ** the calling function (pcache.c) will never have a createFlag of 1 on
  45618. ** a non-purgeable cache.
  45619. **
  45620. ** There are three different approaches to obtaining space for a page,
  45621. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  45622. **
  45623. ** 1. Regardless of the value of createFlag, the cache is searched for a
  45624. ** copy of the requested page. If one is found, it is returned.
  45625. **
  45626. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  45627. ** returned.
  45628. **
  45629. ** 3. If createFlag is 1, and the page is not already in the cache, then
  45630. ** return NULL (do not allocate a new page) if any of the following
  45631. ** conditions are true:
  45632. **
  45633. ** (a) the number of pages pinned by the cache is greater than
  45634. ** PCache1.nMax, or
  45635. **
  45636. ** (b) the number of pages pinned by the cache is greater than
  45637. ** the sum of nMax for all purgeable caches, less the sum of
  45638. ** nMin for all other purgeable caches, or
  45639. **
  45640. ** 4. If none of the first three conditions apply and the cache is marked
  45641. ** as purgeable, and if one of the following is true:
  45642. **
  45643. ** (a) The number of pages allocated for the cache is already
  45644. ** PCache1.nMax, or
  45645. **
  45646. ** (b) The number of pages allocated for all purgeable caches is
  45647. ** already equal to or greater than the sum of nMax for all
  45648. ** purgeable caches,
  45649. **
  45650. ** (c) The system is under memory pressure and wants to avoid
  45651. ** unnecessary pages cache entry allocations
  45652. **
  45653. ** then attempt to recycle a page from the LRU list. If it is the right
  45654. ** size, return the recycled buffer. Otherwise, free the buffer and
  45655. ** proceed to step 5.
  45656. **
  45657. ** 5. Otherwise, allocate and return a new page buffer.
  45658. **
  45659. ** There are two versions of this routine. pcache1FetchWithMutex() is
  45660. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  45661. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  45662. ** invokes the appropriate routine.
  45663. */
  45664. static PgHdr1 *pcache1FetchNoMutex(
  45665. sqlite3_pcache *p,
  45666. unsigned int iKey,
  45667. int createFlag
  45668. ){
  45669. PCache1 *pCache = (PCache1 *)p;
  45670. PgHdr1 *pPage = 0;
  45671. /* Step 1: Search the hash table for an existing entry. */
  45672. pPage = pCache->apHash[iKey % pCache->nHash];
  45673. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  45674. /* Step 2: If the page was found in the hash table, then return it.
  45675. ** If the page was not in the hash table and createFlag is 0, abort.
  45676. ** Otherwise (page not in hash and createFlag!=0) continue with
  45677. ** subsequent steps to try to create the page. */
  45678. if( pPage ){
  45679. if( PAGE_IS_UNPINNED(pPage) ){
  45680. return pcache1PinPage(pPage);
  45681. }else{
  45682. return pPage;
  45683. }
  45684. }else if( createFlag ){
  45685. /* Steps 3, 4, and 5 implemented by this subroutine */
  45686. return pcache1FetchStage2(pCache, iKey, createFlag);
  45687. }else{
  45688. return 0;
  45689. }
  45690. }
  45691. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  45692. static PgHdr1 *pcache1FetchWithMutex(
  45693. sqlite3_pcache *p,
  45694. unsigned int iKey,
  45695. int createFlag
  45696. ){
  45697. PCache1 *pCache = (PCache1 *)p;
  45698. PgHdr1 *pPage;
  45699. pcache1EnterMutex(pCache->pGroup);
  45700. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  45701. assert( pPage==0 || pCache->iMaxKey>=iKey );
  45702. pcache1LeaveMutex(pCache->pGroup);
  45703. return pPage;
  45704. }
  45705. #endif
  45706. static sqlite3_pcache_page *pcache1Fetch(
  45707. sqlite3_pcache *p,
  45708. unsigned int iKey,
  45709. int createFlag
  45710. ){
  45711. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  45712. PCache1 *pCache = (PCache1 *)p;
  45713. #endif
  45714. assert( offsetof(PgHdr1,page)==0 );
  45715. assert( pCache->bPurgeable || createFlag!=1 );
  45716. assert( pCache->bPurgeable || pCache->nMin==0 );
  45717. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  45718. assert( pCache->nMin==0 || pCache->bPurgeable );
  45719. assert( pCache->nHash>0 );
  45720. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  45721. if( pCache->pGroup->mutex ){
  45722. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  45723. }else
  45724. #endif
  45725. {
  45726. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  45727. }
  45728. }
  45729. /*
  45730. ** Implementation of the sqlite3_pcache.xUnpin method.
  45731. **
  45732. ** Mark a page as unpinned (eligible for asynchronous recycling).
  45733. */
  45734. static void pcache1Unpin(
  45735. sqlite3_pcache *p,
  45736. sqlite3_pcache_page *pPg,
  45737. int reuseUnlikely
  45738. ){
  45739. PCache1 *pCache = (PCache1 *)p;
  45740. PgHdr1 *pPage = (PgHdr1 *)pPg;
  45741. PGroup *pGroup = pCache->pGroup;
  45742. assert( pPage->pCache==pCache );
  45743. pcache1EnterMutex(pGroup);
  45744. /* It is an error to call this function if the page is already
  45745. ** part of the PGroup LRU list.
  45746. */
  45747. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  45748. assert( PAGE_IS_PINNED(pPage) );
  45749. if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
  45750. pcache1RemoveFromHash(pPage, 1);
  45751. }else{
  45752. /* Add the page to the PGroup LRU list. */
  45753. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  45754. pPage->pLruPrev = &pGroup->lru;
  45755. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  45756. *ppFirst = pPage;
  45757. pCache->nRecyclable++;
  45758. }
  45759. pcache1LeaveMutex(pCache->pGroup);
  45760. }
  45761. /*
  45762. ** Implementation of the sqlite3_pcache.xRekey method.
  45763. */
  45764. static void pcache1Rekey(
  45765. sqlite3_pcache *p,
  45766. sqlite3_pcache_page *pPg,
  45767. unsigned int iOld,
  45768. unsigned int iNew
  45769. ){
  45770. PCache1 *pCache = (PCache1 *)p;
  45771. PgHdr1 *pPage = (PgHdr1 *)pPg;
  45772. PgHdr1 **pp;
  45773. unsigned int h;
  45774. assert( pPage->iKey==iOld );
  45775. assert( pPage->pCache==pCache );
  45776. pcache1EnterMutex(pCache->pGroup);
  45777. h = iOld%pCache->nHash;
  45778. pp = &pCache->apHash[h];
  45779. while( (*pp)!=pPage ){
  45780. pp = &(*pp)->pNext;
  45781. }
  45782. *pp = pPage->pNext;
  45783. h = iNew%pCache->nHash;
  45784. pPage->iKey = iNew;
  45785. pPage->pNext = pCache->apHash[h];
  45786. pCache->apHash[h] = pPage;
  45787. if( iNew>pCache->iMaxKey ){
  45788. pCache->iMaxKey = iNew;
  45789. }
  45790. pcache1LeaveMutex(pCache->pGroup);
  45791. }
  45792. /*
  45793. ** Implementation of the sqlite3_pcache.xTruncate method.
  45794. **
  45795. ** Discard all unpinned pages in the cache with a page number equal to
  45796. ** or greater than parameter iLimit. Any pinned pages with a page number
  45797. ** equal to or greater than iLimit are implicitly unpinned.
  45798. */
  45799. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  45800. PCache1 *pCache = (PCache1 *)p;
  45801. pcache1EnterMutex(pCache->pGroup);
  45802. if( iLimit<=pCache->iMaxKey ){
  45803. pcache1TruncateUnsafe(pCache, iLimit);
  45804. pCache->iMaxKey = iLimit-1;
  45805. }
  45806. pcache1LeaveMutex(pCache->pGroup);
  45807. }
  45808. /*
  45809. ** Implementation of the sqlite3_pcache.xDestroy method.
  45810. **
  45811. ** Destroy a cache allocated using pcache1Create().
  45812. */
  45813. static void pcache1Destroy(sqlite3_pcache *p){
  45814. PCache1 *pCache = (PCache1 *)p;
  45815. PGroup *pGroup = pCache->pGroup;
  45816. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  45817. pcache1EnterMutex(pGroup);
  45818. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  45819. assert( pGroup->nMaxPage >= pCache->nMax );
  45820. pGroup->nMaxPage -= pCache->nMax;
  45821. assert( pGroup->nMinPage >= pCache->nMin );
  45822. pGroup->nMinPage -= pCache->nMin;
  45823. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  45824. pcache1EnforceMaxPage(pCache);
  45825. pcache1LeaveMutex(pGroup);
  45826. sqlite3_free(pCache->pBulk);
  45827. sqlite3_free(pCache->apHash);
  45828. sqlite3_free(pCache);
  45829. }
  45830. /*
  45831. ** This function is called during initialization (sqlite3_initialize()) to
  45832. ** install the default pluggable cache module, assuming the user has not
  45833. ** already provided an alternative.
  45834. */
  45835. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  45836. static const sqlite3_pcache_methods2 defaultMethods = {
  45837. 1, /* iVersion */
  45838. 0, /* pArg */
  45839. pcache1Init, /* xInit */
  45840. pcache1Shutdown, /* xShutdown */
  45841. pcache1Create, /* xCreate */
  45842. pcache1Cachesize, /* xCachesize */
  45843. pcache1Pagecount, /* xPagecount */
  45844. pcache1Fetch, /* xFetch */
  45845. pcache1Unpin, /* xUnpin */
  45846. pcache1Rekey, /* xRekey */
  45847. pcache1Truncate, /* xTruncate */
  45848. pcache1Destroy, /* xDestroy */
  45849. pcache1Shrink /* xShrink */
  45850. };
  45851. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  45852. }
  45853. /*
  45854. ** Return the size of the header on each page of this PCACHE implementation.
  45855. */
  45856. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  45857. /*
  45858. ** Return the global mutex used by this PCACHE implementation. The
  45859. ** sqlite3_status() routine needs access to this mutex.
  45860. */
  45861. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  45862. return pcache1.mutex;
  45863. }
  45864. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45865. /*
  45866. ** This function is called to free superfluous dynamically allocated memory
  45867. ** held by the pager system. Memory in use by any SQLite pager allocated
  45868. ** by the current thread may be sqlite3_free()ed.
  45869. **
  45870. ** nReq is the number of bytes of memory required. Once this much has
  45871. ** been released, the function returns. The return value is the total number
  45872. ** of bytes of memory released.
  45873. */
  45874. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  45875. int nFree = 0;
  45876. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  45877. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  45878. if( sqlite3GlobalConfig.pPage==0 ){
  45879. PgHdr1 *p;
  45880. pcache1EnterMutex(&pcache1.grp);
  45881. while( (nReq<0 || nFree<nReq)
  45882. && (p=pcache1.grp.lru.pLruPrev)!=0
  45883. && p->isAnchor==0
  45884. ){
  45885. nFree += pcache1MemSize(p->page.pBuf);
  45886. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  45887. nFree += sqlite3MemSize(p);
  45888. #endif
  45889. assert( PAGE_IS_UNPINNED(p) );
  45890. pcache1PinPage(p);
  45891. pcache1RemoveFromHash(p, 1);
  45892. }
  45893. pcache1LeaveMutex(&pcache1.grp);
  45894. }
  45895. return nFree;
  45896. }
  45897. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  45898. #ifdef SQLITE_TEST
  45899. /*
  45900. ** This function is used by test procedures to inspect the internal state
  45901. ** of the global cache.
  45902. */
  45903. SQLITE_PRIVATE void sqlite3PcacheStats(
  45904. int *pnCurrent, /* OUT: Total number of pages cached */
  45905. int *pnMax, /* OUT: Global maximum cache size */
  45906. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  45907. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  45908. ){
  45909. PgHdr1 *p;
  45910. int nRecyclable = 0;
  45911. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  45912. assert( PAGE_IS_UNPINNED(p) );
  45913. nRecyclable++;
  45914. }
  45915. *pnCurrent = pcache1.grp.nPurgeable;
  45916. *pnMax = (int)pcache1.grp.nMaxPage;
  45917. *pnMin = (int)pcache1.grp.nMinPage;
  45918. *pnRecyclable = nRecyclable;
  45919. }
  45920. #endif
  45921. /************** End of pcache1.c *********************************************/
  45922. /************** Begin file rowset.c ******************************************/
  45923. /*
  45924. ** 2008 December 3
  45925. **
  45926. ** The author disclaims copyright to this source code. In place of
  45927. ** a legal notice, here is a blessing:
  45928. **
  45929. ** May you do good and not evil.
  45930. ** May you find forgiveness for yourself and forgive others.
  45931. ** May you share freely, never taking more than you give.
  45932. **
  45933. *************************************************************************
  45934. **
  45935. ** This module implements an object we call a "RowSet".
  45936. **
  45937. ** The RowSet object is a collection of rowids. Rowids
  45938. ** are inserted into the RowSet in an arbitrary order. Inserts
  45939. ** can be intermixed with tests to see if a given rowid has been
  45940. ** previously inserted into the RowSet.
  45941. **
  45942. ** After all inserts are finished, it is possible to extract the
  45943. ** elements of the RowSet in sorted order. Once this extraction
  45944. ** process has started, no new elements may be inserted.
  45945. **
  45946. ** Hence, the primitive operations for a RowSet are:
  45947. **
  45948. ** CREATE
  45949. ** INSERT
  45950. ** TEST
  45951. ** SMALLEST
  45952. ** DESTROY
  45953. **
  45954. ** The CREATE and DESTROY primitives are the constructor and destructor,
  45955. ** obviously. The INSERT primitive adds a new element to the RowSet.
  45956. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  45957. ** extracts the least value from the RowSet.
  45958. **
  45959. ** The INSERT primitive might allocate additional memory. Memory is
  45960. ** allocated in chunks so most INSERTs do no allocation. There is an
  45961. ** upper bound on the size of allocated memory. No memory is freed
  45962. ** until DESTROY.
  45963. **
  45964. ** The TEST primitive includes a "batch" number. The TEST primitive
  45965. ** will only see elements that were inserted before the last change
  45966. ** in the batch number. In other words, if an INSERT occurs between
  45967. ** two TESTs where the TESTs have the same batch nubmer, then the
  45968. ** value added by the INSERT will not be visible to the second TEST.
  45969. ** The initial batch number is zero, so if the very first TEST contains
  45970. ** a non-zero batch number, it will see all prior INSERTs.
  45971. **
  45972. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  45973. ** that is attempted.
  45974. **
  45975. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  45976. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  45977. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  45978. ** The cost of a TEST using the same batch number is O(logN). The cost
  45979. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  45980. ** primitives are constant time. The cost of DESTROY is O(N).
  45981. **
  45982. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  45983. ** be possible, but the feature was not used, so it was removed in order
  45984. ** to simplify the code.
  45985. */
  45986. /* #include "sqliteInt.h" */
  45987. /*
  45988. ** Target size for allocation chunks.
  45989. */
  45990. #define ROWSET_ALLOCATION_SIZE 1024
  45991. /*
  45992. ** The number of rowset entries per allocation chunk.
  45993. */
  45994. #define ROWSET_ENTRY_PER_CHUNK \
  45995. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  45996. /*
  45997. ** Each entry in a RowSet is an instance of the following object.
  45998. **
  45999. ** This same object is reused to store a linked list of trees of RowSetEntry
  46000. ** objects. In that alternative use, pRight points to the next entry
  46001. ** in the list, pLeft points to the tree, and v is unused. The
  46002. ** RowSet.pForest value points to the head of this forest list.
  46003. */
  46004. struct RowSetEntry {
  46005. i64 v; /* ROWID value for this entry */
  46006. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  46007. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  46008. };
  46009. /*
  46010. ** RowSetEntry objects are allocated in large chunks (instances of the
  46011. ** following structure) to reduce memory allocation overhead. The
  46012. ** chunks are kept on a linked list so that they can be deallocated
  46013. ** when the RowSet is destroyed.
  46014. */
  46015. struct RowSetChunk {
  46016. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  46017. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  46018. };
  46019. /*
  46020. ** A RowSet in an instance of the following structure.
  46021. **
  46022. ** A typedef of this structure if found in sqliteInt.h.
  46023. */
  46024. struct RowSet {
  46025. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  46026. sqlite3 *db; /* The database connection */
  46027. struct RowSetEntry *pEntry; /* List of entries using pRight */
  46028. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  46029. struct RowSetEntry *pFresh; /* Source of new entry objects */
  46030. struct RowSetEntry *pForest; /* List of binary trees of entries */
  46031. u16 nFresh; /* Number of objects on pFresh */
  46032. u16 rsFlags; /* Various flags */
  46033. int iBatch; /* Current insert batch */
  46034. };
  46035. /*
  46036. ** Allowed values for RowSet.rsFlags
  46037. */
  46038. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  46039. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  46040. /*
  46041. ** Turn bulk memory into a RowSet object. N bytes of memory
  46042. ** are available at pSpace. The db pointer is used as a memory context
  46043. ** for any subsequent allocations that need to occur.
  46044. ** Return a pointer to the new RowSet object.
  46045. **
  46046. ** It must be the case that N is sufficient to make a Rowset. If not
  46047. ** an assertion fault occurs.
  46048. **
  46049. ** If N is larger than the minimum, use the surplus as an initial
  46050. ** allocation of entries available to be filled.
  46051. */
  46052. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  46053. RowSet *p;
  46054. assert( N >= ROUND8(sizeof(*p)) );
  46055. p = pSpace;
  46056. p->pChunk = 0;
  46057. p->db = db;
  46058. p->pEntry = 0;
  46059. p->pLast = 0;
  46060. p->pForest = 0;
  46061. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  46062. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  46063. p->rsFlags = ROWSET_SORTED;
  46064. p->iBatch = 0;
  46065. return p;
  46066. }
  46067. /*
  46068. ** Deallocate all chunks from a RowSet. This frees all memory that
  46069. ** the RowSet has allocated over its lifetime. This routine is
  46070. ** the destructor for the RowSet.
  46071. */
  46072. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  46073. struct RowSetChunk *pChunk, *pNextChunk;
  46074. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  46075. pNextChunk = pChunk->pNextChunk;
  46076. sqlite3DbFree(p->db, pChunk);
  46077. }
  46078. p->pChunk = 0;
  46079. p->nFresh = 0;
  46080. p->pEntry = 0;
  46081. p->pLast = 0;
  46082. p->pForest = 0;
  46083. p->rsFlags = ROWSET_SORTED;
  46084. }
  46085. /*
  46086. ** Allocate a new RowSetEntry object that is associated with the
  46087. ** given RowSet. Return a pointer to the new and completely uninitialized
  46088. ** objected.
  46089. **
  46090. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  46091. ** routine returns NULL.
  46092. */
  46093. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  46094. assert( p!=0 );
  46095. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  46096. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  46097. ** is more efficient to pull a preallocated entry from the pool */
  46098. struct RowSetChunk *pNew;
  46099. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  46100. if( pNew==0 ){
  46101. return 0;
  46102. }
  46103. pNew->pNextChunk = p->pChunk;
  46104. p->pChunk = pNew;
  46105. p->pFresh = pNew->aEntry;
  46106. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  46107. }
  46108. p->nFresh--;
  46109. return p->pFresh++;
  46110. }
  46111. /*
  46112. ** Insert a new value into a RowSet.
  46113. **
  46114. ** The mallocFailed flag of the database connection is set if a
  46115. ** memory allocation fails.
  46116. */
  46117. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  46118. struct RowSetEntry *pEntry; /* The new entry */
  46119. struct RowSetEntry *pLast; /* The last prior entry */
  46120. /* This routine is never called after sqlite3RowSetNext() */
  46121. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  46122. pEntry = rowSetEntryAlloc(p);
  46123. if( pEntry==0 ) return;
  46124. pEntry->v = rowid;
  46125. pEntry->pRight = 0;
  46126. pLast = p->pLast;
  46127. if( pLast ){
  46128. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  46129. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  46130. ** where possible */
  46131. p->rsFlags &= ~ROWSET_SORTED;
  46132. }
  46133. pLast->pRight = pEntry;
  46134. }else{
  46135. p->pEntry = pEntry;
  46136. }
  46137. p->pLast = pEntry;
  46138. }
  46139. /*
  46140. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  46141. **
  46142. ** The input lists are connected via pRight pointers and are
  46143. ** assumed to each already be in sorted order.
  46144. */
  46145. static struct RowSetEntry *rowSetEntryMerge(
  46146. struct RowSetEntry *pA, /* First sorted list to be merged */
  46147. struct RowSetEntry *pB /* Second sorted list to be merged */
  46148. ){
  46149. struct RowSetEntry head;
  46150. struct RowSetEntry *pTail;
  46151. pTail = &head;
  46152. assert( pA!=0 && pB!=0 );
  46153. for(;;){
  46154. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  46155. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  46156. if( pA->v<=pB->v ){
  46157. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  46158. pA = pA->pRight;
  46159. if( pA==0 ){
  46160. pTail->pRight = pB;
  46161. break;
  46162. }
  46163. }else{
  46164. pTail = pTail->pRight = pB;
  46165. pB = pB->pRight;
  46166. if( pB==0 ){
  46167. pTail->pRight = pA;
  46168. break;
  46169. }
  46170. }
  46171. }
  46172. return head.pRight;
  46173. }
  46174. /*
  46175. ** Sort all elements on the list of RowSetEntry objects into order of
  46176. ** increasing v.
  46177. */
  46178. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  46179. unsigned int i;
  46180. struct RowSetEntry *pNext, *aBucket[40];
  46181. memset(aBucket, 0, sizeof(aBucket));
  46182. while( pIn ){
  46183. pNext = pIn->pRight;
  46184. pIn->pRight = 0;
  46185. for(i=0; aBucket[i]; i++){
  46186. pIn = rowSetEntryMerge(aBucket[i], pIn);
  46187. aBucket[i] = 0;
  46188. }
  46189. aBucket[i] = pIn;
  46190. pIn = pNext;
  46191. }
  46192. pIn = aBucket[0];
  46193. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  46194. if( aBucket[i]==0 ) continue;
  46195. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  46196. }
  46197. return pIn;
  46198. }
  46199. /*
  46200. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  46201. ** Convert this tree into a linked list connected by the pRight pointers
  46202. ** and return pointers to the first and last elements of the new list.
  46203. */
  46204. static void rowSetTreeToList(
  46205. struct RowSetEntry *pIn, /* Root of the input tree */
  46206. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  46207. struct RowSetEntry **ppLast /* Write tail of the output list here */
  46208. ){
  46209. assert( pIn!=0 );
  46210. if( pIn->pLeft ){
  46211. struct RowSetEntry *p;
  46212. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  46213. p->pRight = pIn;
  46214. }else{
  46215. *ppFirst = pIn;
  46216. }
  46217. if( pIn->pRight ){
  46218. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  46219. }else{
  46220. *ppLast = pIn;
  46221. }
  46222. assert( (*ppLast)->pRight==0 );
  46223. }
  46224. /*
  46225. ** Convert a sorted list of elements (connected by pRight) into a binary
  46226. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  46227. ** node taken from the head of *ppList. A depth of 2 means a tree with
  46228. ** three nodes. And so forth.
  46229. **
  46230. ** Use as many entries from the input list as required and update the
  46231. ** *ppList to point to the unused elements of the list. If the input
  46232. ** list contains too few elements, then construct an incomplete tree
  46233. ** and leave *ppList set to NULL.
  46234. **
  46235. ** Return a pointer to the root of the constructed binary tree.
  46236. */
  46237. static struct RowSetEntry *rowSetNDeepTree(
  46238. struct RowSetEntry **ppList,
  46239. int iDepth
  46240. ){
  46241. struct RowSetEntry *p; /* Root of the new tree */
  46242. struct RowSetEntry *pLeft; /* Left subtree */
  46243. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  46244. /* Prevent unnecessary deep recursion when we run out of entries */
  46245. return 0;
  46246. }
  46247. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  46248. /* This branch causes a *balanced* tree to be generated. A valid tree
  46249. ** is still generated without this branch, but the tree is wildly
  46250. ** unbalanced and inefficient. */
  46251. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  46252. p = *ppList;
  46253. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  46254. /* It is safe to always return here, but the resulting tree
  46255. ** would be unbalanced */
  46256. return pLeft;
  46257. }
  46258. p->pLeft = pLeft;
  46259. *ppList = p->pRight;
  46260. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  46261. }else{
  46262. p = *ppList;
  46263. *ppList = p->pRight;
  46264. p->pLeft = p->pRight = 0;
  46265. }
  46266. return p;
  46267. }
  46268. /*
  46269. ** Convert a sorted list of elements into a binary tree. Make the tree
  46270. ** as deep as it needs to be in order to contain the entire list.
  46271. */
  46272. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  46273. int iDepth; /* Depth of the tree so far */
  46274. struct RowSetEntry *p; /* Current tree root */
  46275. struct RowSetEntry *pLeft; /* Left subtree */
  46276. assert( pList!=0 );
  46277. p = pList;
  46278. pList = p->pRight;
  46279. p->pLeft = p->pRight = 0;
  46280. for(iDepth=1; pList; iDepth++){
  46281. pLeft = p;
  46282. p = pList;
  46283. pList = p->pRight;
  46284. p->pLeft = pLeft;
  46285. p->pRight = rowSetNDeepTree(&pList, iDepth);
  46286. }
  46287. return p;
  46288. }
  46289. /*
  46290. ** Extract the smallest element from the RowSet.
  46291. ** Write the element into *pRowid. Return 1 on success. Return
  46292. ** 0 if the RowSet is already empty.
  46293. **
  46294. ** After this routine has been called, the sqlite3RowSetInsert()
  46295. ** routine may not be called again.
  46296. **
  46297. ** This routine may not be called after sqlite3RowSetTest() has
  46298. ** been used. Older versions of RowSet allowed that, but as the
  46299. ** capability was not used by the code generator, it was removed
  46300. ** for code economy.
  46301. */
  46302. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  46303. assert( p!=0 );
  46304. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  46305. /* Merge the forest into a single sorted list on first call */
  46306. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  46307. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  46308. p->pEntry = rowSetEntrySort(p->pEntry);
  46309. }
  46310. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  46311. }
  46312. /* Return the next entry on the list */
  46313. if( p->pEntry ){
  46314. *pRowid = p->pEntry->v;
  46315. p->pEntry = p->pEntry->pRight;
  46316. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  46317. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  46318. sqlite3RowSetClear(p);
  46319. }
  46320. return 1;
  46321. }else{
  46322. return 0;
  46323. }
  46324. }
  46325. /*
  46326. ** Check to see if element iRowid was inserted into the rowset as
  46327. ** part of any insert batch prior to iBatch. Return 1 or 0.
  46328. **
  46329. ** If this is the first test of a new batch and if there exist entries
  46330. ** on pRowSet->pEntry, then sort those entries into the forest at
  46331. ** pRowSet->pForest so that they can be tested.
  46332. */
  46333. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  46334. struct RowSetEntry *p, *pTree;
  46335. /* This routine is never called after sqlite3RowSetNext() */
  46336. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  46337. /* Sort entries into the forest on the first test of a new batch.
  46338. ** To save unnecessary work, only do this when the batch number changes.
  46339. */
  46340. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  46341. p = pRowSet->pEntry;
  46342. if( p ){
  46343. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  46344. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  46345. /* Only sort the current set of entiries if they need it */
  46346. p = rowSetEntrySort(p);
  46347. }
  46348. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  46349. ppPrevTree = &pTree->pRight;
  46350. if( pTree->pLeft==0 ){
  46351. pTree->pLeft = rowSetListToTree(p);
  46352. break;
  46353. }else{
  46354. struct RowSetEntry *pAux, *pTail;
  46355. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  46356. pTree->pLeft = 0;
  46357. p = rowSetEntryMerge(pAux, p);
  46358. }
  46359. }
  46360. if( pTree==0 ){
  46361. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  46362. if( pTree ){
  46363. pTree->v = 0;
  46364. pTree->pRight = 0;
  46365. pTree->pLeft = rowSetListToTree(p);
  46366. }
  46367. }
  46368. pRowSet->pEntry = 0;
  46369. pRowSet->pLast = 0;
  46370. pRowSet->rsFlags |= ROWSET_SORTED;
  46371. }
  46372. pRowSet->iBatch = iBatch;
  46373. }
  46374. /* Test to see if the iRowid value appears anywhere in the forest.
  46375. ** Return 1 if it does and 0 if not.
  46376. */
  46377. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  46378. p = pTree->pLeft;
  46379. while( p ){
  46380. if( p->v<iRowid ){
  46381. p = p->pRight;
  46382. }else if( p->v>iRowid ){
  46383. p = p->pLeft;
  46384. }else{
  46385. return 1;
  46386. }
  46387. }
  46388. }
  46389. return 0;
  46390. }
  46391. /************** End of rowset.c **********************************************/
  46392. /************** Begin file pager.c *******************************************/
  46393. /*
  46394. ** 2001 September 15
  46395. **
  46396. ** The author disclaims copyright to this source code. In place of
  46397. ** a legal notice, here is a blessing:
  46398. **
  46399. ** May you do good and not evil.
  46400. ** May you find forgiveness for yourself and forgive others.
  46401. ** May you share freely, never taking more than you give.
  46402. **
  46403. *************************************************************************
  46404. ** This is the implementation of the page cache subsystem or "pager".
  46405. **
  46406. ** The pager is used to access a database disk file. It implements
  46407. ** atomic commit and rollback through the use of a journal file that
  46408. ** is separate from the database file. The pager also implements file
  46409. ** locking to prevent two processes from writing the same database
  46410. ** file simultaneously, or one process from reading the database while
  46411. ** another is writing.
  46412. */
  46413. #ifndef SQLITE_OMIT_DISKIO
  46414. /* #include "sqliteInt.h" */
  46415. /************** Include wal.h in the middle of pager.c ***********************/
  46416. /************** Begin file wal.h *********************************************/
  46417. /*
  46418. ** 2010 February 1
  46419. **
  46420. ** The author disclaims copyright to this source code. In place of
  46421. ** a legal notice, here is a blessing:
  46422. **
  46423. ** May you do good and not evil.
  46424. ** May you find forgiveness for yourself and forgive others.
  46425. ** May you share freely, never taking more than you give.
  46426. **
  46427. *************************************************************************
  46428. ** This header file defines the interface to the write-ahead logging
  46429. ** system. Refer to the comments below and the header comment attached to
  46430. ** the implementation of each function in log.c for further details.
  46431. */
  46432. #ifndef SQLITE_WAL_H
  46433. #define SQLITE_WAL_H
  46434. /* #include "sqliteInt.h" */
  46435. /* Macros for extracting appropriate sync flags for either transaction
  46436. ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
  46437. */
  46438. #define WAL_SYNC_FLAGS(X) ((X)&0x03)
  46439. #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
  46440. #ifdef SQLITE_OMIT_WAL
  46441. # define sqlite3WalOpen(x,y,z) 0
  46442. # define sqlite3WalLimit(x,y)
  46443. # define sqlite3WalClose(v,w,x,y,z) 0
  46444. # define sqlite3WalBeginReadTransaction(y,z) 0
  46445. # define sqlite3WalEndReadTransaction(z)
  46446. # define sqlite3WalDbsize(y) 0
  46447. # define sqlite3WalBeginWriteTransaction(y) 0
  46448. # define sqlite3WalEndWriteTransaction(x) 0
  46449. # define sqlite3WalUndo(x,y,z) 0
  46450. # define sqlite3WalSavepoint(y,z)
  46451. # define sqlite3WalSavepointUndo(y,z) 0
  46452. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  46453. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  46454. # define sqlite3WalCallback(z) 0
  46455. # define sqlite3WalExclusiveMode(y,z) 0
  46456. # define sqlite3WalHeapMemory(z) 0
  46457. # define sqlite3WalFramesize(z) 0
  46458. # define sqlite3WalFindFrame(x,y,z) 0
  46459. # define sqlite3WalFile(x) 0
  46460. #else
  46461. #define WAL_SAVEPOINT_NDATA 4
  46462. /* Connection to a write-ahead log (WAL) file.
  46463. ** There is one object of this type for each pager.
  46464. */
  46465. typedef struct Wal Wal;
  46466. /* Open and close a connection to a write-ahead log. */
  46467. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  46468. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  46469. /* Set the limiting size of a WAL file. */
  46470. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  46471. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  46472. ** snapshot is like a read-transaction. It is the state of the database
  46473. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  46474. ** preserves the current state even if the other threads or processes
  46475. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  46476. ** transaction and releases the lock.
  46477. */
  46478. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  46479. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  46480. /* Read a page from the write-ahead log, if it is present. */
  46481. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  46482. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  46483. /* If the WAL is not empty, return the size of the database. */
  46484. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  46485. /* Obtain or release the WRITER lock. */
  46486. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  46487. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  46488. /* Undo any frames written (but not committed) to the log */
  46489. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  46490. /* Return an integer that records the current (uncommitted) write
  46491. ** position in the WAL */
  46492. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  46493. /* Move the write position of the WAL back to iFrame. Called in
  46494. ** response to a ROLLBACK TO command. */
  46495. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  46496. /* Write a frame or frames to the log. */
  46497. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  46498. /* Copy pages from the log to the database file */
  46499. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  46500. Wal *pWal, /* Write-ahead log connection */
  46501. sqlite3 *db, /* Check this handle's interrupt flag */
  46502. int eMode, /* One of PASSIVE, FULL and RESTART */
  46503. int (*xBusy)(void*), /* Function to call when busy */
  46504. void *pBusyArg, /* Context argument for xBusyHandler */
  46505. int sync_flags, /* Flags to sync db file with (or 0) */
  46506. int nBuf, /* Size of buffer nBuf */
  46507. u8 *zBuf, /* Temporary buffer to use */
  46508. int *pnLog, /* OUT: Number of frames in WAL */
  46509. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  46510. );
  46511. /* Return the value to pass to a sqlite3_wal_hook callback, the
  46512. ** number of frames in the WAL at the point of the last commit since
  46513. ** sqlite3WalCallback() was called. If no commits have occurred since
  46514. ** the last call, then return 0.
  46515. */
  46516. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  46517. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  46518. ** by the pager layer on the database file.
  46519. */
  46520. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  46521. /* Return true if the argument is non-NULL and the WAL module is using
  46522. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  46523. ** WAL module is using shared-memory, return false.
  46524. */
  46525. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  46526. #ifdef SQLITE_ENABLE_SNAPSHOT
  46527. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  46528. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  46529. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  46530. #endif
  46531. #ifdef SQLITE_ENABLE_ZIPVFS
  46532. /* If the WAL file is not empty, return the number of bytes of content
  46533. ** stored in each frame (i.e. the db page-size when the WAL was created).
  46534. */
  46535. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  46536. #endif
  46537. /* Return the sqlite3_file object for the WAL file */
  46538. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  46539. #endif /* ifndef SQLITE_OMIT_WAL */
  46540. #endif /* SQLITE_WAL_H */
  46541. /************** End of wal.h *************************************************/
  46542. /************** Continuing where we left off in pager.c **********************/
  46543. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  46544. **
  46545. ** This comment block describes invariants that hold when using a rollback
  46546. ** journal. These invariants do not apply for journal_mode=WAL,
  46547. ** journal_mode=MEMORY, or journal_mode=OFF.
  46548. **
  46549. ** Within this comment block, a page is deemed to have been synced
  46550. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  46551. ** Otherwise, the page is not synced until the xSync method of the VFS
  46552. ** is called successfully on the file containing the page.
  46553. **
  46554. ** Definition: A page of the database file is said to be "overwriteable" if
  46555. ** one or more of the following are true about the page:
  46556. **
  46557. ** (a) The original content of the page as it was at the beginning of
  46558. ** the transaction has been written into the rollback journal and
  46559. ** synced.
  46560. **
  46561. ** (b) The page was a freelist leaf page at the start of the transaction.
  46562. **
  46563. ** (c) The page number is greater than the largest page that existed in
  46564. ** the database file at the start of the transaction.
  46565. **
  46566. ** (1) A page of the database file is never overwritten unless one of the
  46567. ** following are true:
  46568. **
  46569. ** (a) The page and all other pages on the same sector are overwriteable.
  46570. **
  46571. ** (b) The atomic page write optimization is enabled, and the entire
  46572. ** transaction other than the update of the transaction sequence
  46573. ** number consists of a single page change.
  46574. **
  46575. ** (2) The content of a page written into the rollback journal exactly matches
  46576. ** both the content in the database when the rollback journal was written
  46577. ** and the content in the database at the beginning of the current
  46578. ** transaction.
  46579. **
  46580. ** (3) Writes to the database file are an integer multiple of the page size
  46581. ** in length and are aligned on a page boundary.
  46582. **
  46583. ** (4) Reads from the database file are either aligned on a page boundary and
  46584. ** an integer multiple of the page size in length or are taken from the
  46585. ** first 100 bytes of the database file.
  46586. **
  46587. ** (5) All writes to the database file are synced prior to the rollback journal
  46588. ** being deleted, truncated, or zeroed.
  46589. **
  46590. ** (6) If a master journal file is used, then all writes to the database file
  46591. ** are synced prior to the master journal being deleted.
  46592. **
  46593. ** Definition: Two databases (or the same database at two points it time)
  46594. ** are said to be "logically equivalent" if they give the same answer to
  46595. ** all queries. Note in particular the content of freelist leaf
  46596. ** pages can be changed arbitrarily without affecting the logical equivalence
  46597. ** of the database.
  46598. **
  46599. ** (7) At any time, if any subset, including the empty set and the total set,
  46600. ** of the unsynced changes to a rollback journal are removed and the
  46601. ** journal is rolled back, the resulting database file will be logically
  46602. ** equivalent to the database file at the beginning of the transaction.
  46603. **
  46604. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  46605. ** is called to restore the database file to the same size it was at
  46606. ** the beginning of the transaction. (In some VFSes, the xTruncate
  46607. ** method is a no-op, but that does not change the fact the SQLite will
  46608. ** invoke it.)
  46609. **
  46610. ** (9) Whenever the database file is modified, at least one bit in the range
  46611. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  46612. ** the EXCLUSIVE lock, thus signaling other connections on the same
  46613. ** database to flush their caches.
  46614. **
  46615. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  46616. ** than one billion transactions.
  46617. **
  46618. ** (11) A database file is well-formed at the beginning and at the conclusion
  46619. ** of every transaction.
  46620. **
  46621. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  46622. ** the database file.
  46623. **
  46624. ** (13) A SHARED lock is held on the database file while reading any
  46625. ** content out of the database file.
  46626. **
  46627. ******************************************************************************/
  46628. /*
  46629. ** Macros for troubleshooting. Normally turned off
  46630. */
  46631. #if 0
  46632. int sqlite3PagerTrace=1; /* True to enable tracing */
  46633. #define sqlite3DebugPrintf printf
  46634. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  46635. #else
  46636. #define PAGERTRACE(X)
  46637. #endif
  46638. /*
  46639. ** The following two macros are used within the PAGERTRACE() macros above
  46640. ** to print out file-descriptors.
  46641. **
  46642. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  46643. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  46644. ** struct as its argument.
  46645. */
  46646. #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
  46647. #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
  46648. /*
  46649. ** The Pager.eState variable stores the current 'state' of a pager. A
  46650. ** pager may be in any one of the seven states shown in the following
  46651. ** state diagram.
  46652. **
  46653. ** OPEN <------+------+
  46654. ** | | |
  46655. ** V | |
  46656. ** +---------> READER-------+ |
  46657. ** | | |
  46658. ** | V |
  46659. ** |<-------WRITER_LOCKED------> ERROR
  46660. ** | | ^
  46661. ** | V |
  46662. ** |<------WRITER_CACHEMOD-------->|
  46663. ** | | |
  46664. ** | V |
  46665. ** |<-------WRITER_DBMOD---------->|
  46666. ** | | |
  46667. ** | V |
  46668. ** +<------WRITER_FINISHED-------->+
  46669. **
  46670. **
  46671. ** List of state transitions and the C [function] that performs each:
  46672. **
  46673. ** OPEN -> READER [sqlite3PagerSharedLock]
  46674. ** READER -> OPEN [pager_unlock]
  46675. **
  46676. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  46677. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  46678. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  46679. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  46680. ** WRITER_*** -> READER [pager_end_transaction]
  46681. **
  46682. ** WRITER_*** -> ERROR [pager_error]
  46683. ** ERROR -> OPEN [pager_unlock]
  46684. **
  46685. **
  46686. ** OPEN:
  46687. **
  46688. ** The pager starts up in this state. Nothing is guaranteed in this
  46689. ** state - the file may or may not be locked and the database size is
  46690. ** unknown. The database may not be read or written.
  46691. **
  46692. ** * No read or write transaction is active.
  46693. ** * Any lock, or no lock at all, may be held on the database file.
  46694. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  46695. **
  46696. ** READER:
  46697. **
  46698. ** In this state all the requirements for reading the database in
  46699. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  46700. ** was) in exclusive-locking mode, a user-level read transaction is
  46701. ** open. The database size is known in this state.
  46702. **
  46703. ** A connection running with locking_mode=normal enters this state when
  46704. ** it opens a read-transaction on the database and returns to state
  46705. ** OPEN after the read-transaction is completed. However a connection
  46706. ** running in locking_mode=exclusive (including temp databases) remains in
  46707. ** this state even after the read-transaction is closed. The only way
  46708. ** a locking_mode=exclusive connection can transition from READER to OPEN
  46709. ** is via the ERROR state (see below).
  46710. **
  46711. ** * A read transaction may be active (but a write-transaction cannot).
  46712. ** * A SHARED or greater lock is held on the database file.
  46713. ** * The dbSize variable may be trusted (even if a user-level read
  46714. ** transaction is not active). The dbOrigSize and dbFileSize variables
  46715. ** may not be trusted at this point.
  46716. ** * If the database is a WAL database, then the WAL connection is open.
  46717. ** * Even if a read-transaction is not open, it is guaranteed that
  46718. ** there is no hot-journal in the file-system.
  46719. **
  46720. ** WRITER_LOCKED:
  46721. **
  46722. ** The pager moves to this state from READER when a write-transaction
  46723. ** is first opened on the database. In WRITER_LOCKED state, all locks
  46724. ** required to start a write-transaction are held, but no actual
  46725. ** modifications to the cache or database have taken place.
  46726. **
  46727. ** In rollback mode, a RESERVED or (if the transaction was opened with
  46728. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  46729. ** moving to this state, but the journal file is not written to or opened
  46730. ** to in this state. If the transaction is committed or rolled back while
  46731. ** in WRITER_LOCKED state, all that is required is to unlock the database
  46732. ** file.
  46733. **
  46734. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  46735. ** If the connection is running with locking_mode=exclusive, an attempt
  46736. ** is made to obtain an EXCLUSIVE lock on the database file.
  46737. **
  46738. ** * A write transaction is active.
  46739. ** * If the connection is open in rollback-mode, a RESERVED or greater
  46740. ** lock is held on the database file.
  46741. ** * If the connection is open in WAL-mode, a WAL write transaction
  46742. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  46743. ** called).
  46744. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  46745. ** * The contents of the pager cache have not been modified.
  46746. ** * The journal file may or may not be open.
  46747. ** * Nothing (not even the first header) has been written to the journal.
  46748. **
  46749. ** WRITER_CACHEMOD:
  46750. **
  46751. ** A pager moves from WRITER_LOCKED state to this state when a page is
  46752. ** first modified by the upper layer. In rollback mode the journal file
  46753. ** is opened (if it is not already open) and a header written to the
  46754. ** start of it. The database file on disk has not been modified.
  46755. **
  46756. ** * A write transaction is active.
  46757. ** * A RESERVED or greater lock is held on the database file.
  46758. ** * The journal file is open and the first header has been written
  46759. ** to it, but the header has not been synced to disk.
  46760. ** * The contents of the page cache have been modified.
  46761. **
  46762. ** WRITER_DBMOD:
  46763. **
  46764. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  46765. ** when it modifies the contents of the database file. WAL connections
  46766. ** never enter this state (since they do not modify the database file,
  46767. ** just the log file).
  46768. **
  46769. ** * A write transaction is active.
  46770. ** * An EXCLUSIVE or greater lock is held on the database file.
  46771. ** * The journal file is open and the first header has been written
  46772. ** and synced to disk.
  46773. ** * The contents of the page cache have been modified (and possibly
  46774. ** written to disk).
  46775. **
  46776. ** WRITER_FINISHED:
  46777. **
  46778. ** It is not possible for a WAL connection to enter this state.
  46779. **
  46780. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  46781. ** state after the entire transaction has been successfully written into the
  46782. ** database file. In this state the transaction may be committed simply
  46783. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  46784. ** not possible to modify the database further. At this point, the upper
  46785. ** layer must either commit or rollback the transaction.
  46786. **
  46787. ** * A write transaction is active.
  46788. ** * An EXCLUSIVE or greater lock is held on the database file.
  46789. ** * All writing and syncing of journal and database data has finished.
  46790. ** If no error occurred, all that remains is to finalize the journal to
  46791. ** commit the transaction. If an error did occur, the caller will need
  46792. ** to rollback the transaction.
  46793. **
  46794. ** ERROR:
  46795. **
  46796. ** The ERROR state is entered when an IO or disk-full error (including
  46797. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  46798. ** difficult to be sure that the in-memory pager state (cache contents,
  46799. ** db size etc.) are consistent with the contents of the file-system.
  46800. **
  46801. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  46802. ** cannot.
  46803. **
  46804. ** For example, if an IO error occurs while performing a rollback,
  46805. ** the contents of the page-cache may be left in an inconsistent state.
  46806. ** At this point it would be dangerous to change back to READER state
  46807. ** (as usually happens after a rollback). Any subsequent readers might
  46808. ** report database corruption (due to the inconsistent cache), and if
  46809. ** they upgrade to writers, they may inadvertently corrupt the database
  46810. ** file. To avoid this hazard, the pager switches into the ERROR state
  46811. ** instead of READER following such an error.
  46812. **
  46813. ** Once it has entered the ERROR state, any attempt to use the pager
  46814. ** to read or write data returns an error. Eventually, once all
  46815. ** outstanding transactions have been abandoned, the pager is able to
  46816. ** transition back to OPEN state, discarding the contents of the
  46817. ** page-cache and any other in-memory state at the same time. Everything
  46818. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  46819. ** when a read-transaction is next opened on the pager (transitioning
  46820. ** the pager into READER state). At that point the system has recovered
  46821. ** from the error.
  46822. **
  46823. ** Specifically, the pager jumps into the ERROR state if:
  46824. **
  46825. ** 1. An error occurs while attempting a rollback. This happens in
  46826. ** function sqlite3PagerRollback().
  46827. **
  46828. ** 2. An error occurs while attempting to finalize a journal file
  46829. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  46830. **
  46831. ** 3. An error occurs while attempting to write to the journal or
  46832. ** database file in function pagerStress() in order to free up
  46833. ** memory.
  46834. **
  46835. ** In other cases, the error is returned to the b-tree layer. The b-tree
  46836. ** layer then attempts a rollback operation. If the error condition
  46837. ** persists, the pager enters the ERROR state via condition (1) above.
  46838. **
  46839. ** Condition (3) is necessary because it can be triggered by a read-only
  46840. ** statement executed within a transaction. In this case, if the error
  46841. ** code were simply returned to the user, the b-tree layer would not
  46842. ** automatically attempt a rollback, as it assumes that an error in a
  46843. ** read-only statement cannot leave the pager in an internally inconsistent
  46844. ** state.
  46845. **
  46846. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  46847. ** * There are one or more outstanding references to pages (after the
  46848. ** last reference is dropped the pager should move back to OPEN state).
  46849. ** * The pager is not an in-memory pager.
  46850. **
  46851. **
  46852. ** Notes:
  46853. **
  46854. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  46855. ** connection is open in WAL mode. A WAL connection is always in one
  46856. ** of the first four states.
  46857. **
  46858. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  46859. ** state. There are two exceptions: immediately after exclusive-mode has
  46860. ** been turned on (and before any read or write transactions are
  46861. ** executed), and when the pager is leaving the "error state".
  46862. **
  46863. ** * See also: assert_pager_state().
  46864. */
  46865. #define PAGER_OPEN 0
  46866. #define PAGER_READER 1
  46867. #define PAGER_WRITER_LOCKED 2
  46868. #define PAGER_WRITER_CACHEMOD 3
  46869. #define PAGER_WRITER_DBMOD 4
  46870. #define PAGER_WRITER_FINISHED 5
  46871. #define PAGER_ERROR 6
  46872. /*
  46873. ** The Pager.eLock variable is almost always set to one of the
  46874. ** following locking-states, according to the lock currently held on
  46875. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  46876. ** This variable is kept up to date as locks are taken and released by
  46877. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  46878. **
  46879. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  46880. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  46881. ** the operation was successful. In these circumstances pagerLockDb() and
  46882. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  46883. ** when unlocking the file, and only updated when locking the file if the
  46884. ** VFS call is successful. This way, the Pager.eLock variable may be set
  46885. ** to a less exclusive (lower) value than the lock that is actually held
  46886. ** at the system level, but it is never set to a more exclusive value.
  46887. **
  46888. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  46889. ** be a few redundant xLock() calls or a lock may be held for longer than
  46890. ** required, but nothing really goes wrong.
  46891. **
  46892. ** The exception is when the database file is unlocked as the pager moves
  46893. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  46894. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  46895. ** transition, by the same pager or any other). If the call to xUnlock()
  46896. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  46897. ** can confuse the call to xCheckReservedLock() call made later as part
  46898. ** of hot-journal detection.
  46899. **
  46900. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  46901. ** lock held by this process or any others". So xCheckReservedLock may
  46902. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  46903. ** doesn't know it because of a previous error in xUnlock). If this happens
  46904. ** a hot-journal may be mistaken for a journal being created by an active
  46905. ** transaction in another process, causing SQLite to read from the database
  46906. ** without rolling it back.
  46907. **
  46908. ** To work around this, if a call to xUnlock() fails when unlocking the
  46909. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  46910. ** is only changed back to a real locking state after a successful call
  46911. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  46912. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  46913. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  46914. ** lock on the database file before attempting to roll it back. See function
  46915. ** PagerSharedLock() for more detail.
  46916. **
  46917. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  46918. ** PAGER_OPEN state.
  46919. */
  46920. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  46921. /*
  46922. ** A macro used for invoking the codec if there is one
  46923. */
  46924. #ifdef SQLITE_HAS_CODEC
  46925. # define CODEC1(P,D,N,X,E) \
  46926. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  46927. # define CODEC2(P,D,N,X,E,O) \
  46928. if( P->xCodec==0 ){ O=(char*)D; }else \
  46929. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  46930. #else
  46931. # define CODEC1(P,D,N,X,E) /* NO-OP */
  46932. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  46933. #endif
  46934. /*
  46935. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  46936. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  46937. ** This could conceivably cause corruption following a power failure on
  46938. ** such a system. This is currently an undocumented limit.
  46939. */
  46940. #define MAX_SECTOR_SIZE 0x10000
  46941. /*
  46942. ** An instance of the following structure is allocated for each active
  46943. ** savepoint and statement transaction in the system. All such structures
  46944. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  46945. ** resized using sqlite3Realloc().
  46946. **
  46947. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  46948. ** set to 0. If a journal-header is written into the main journal while
  46949. ** the savepoint is active, then iHdrOffset is set to the byte offset
  46950. ** immediately following the last journal record written into the main
  46951. ** journal before the journal-header. This is required during savepoint
  46952. ** rollback (see pagerPlaybackSavepoint()).
  46953. */
  46954. typedef struct PagerSavepoint PagerSavepoint;
  46955. struct PagerSavepoint {
  46956. i64 iOffset; /* Starting offset in main journal */
  46957. i64 iHdrOffset; /* See above */
  46958. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  46959. Pgno nOrig; /* Original number of pages in file */
  46960. Pgno iSubRec; /* Index of first record in sub-journal */
  46961. #ifndef SQLITE_OMIT_WAL
  46962. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  46963. #endif
  46964. };
  46965. /*
  46966. ** Bits of the Pager.doNotSpill flag. See further description below.
  46967. */
  46968. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  46969. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  46970. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  46971. /*
  46972. ** An open page cache is an instance of struct Pager. A description of
  46973. ** some of the more important member variables follows:
  46974. **
  46975. ** eState
  46976. **
  46977. ** The current 'state' of the pager object. See the comment and state
  46978. ** diagram above for a description of the pager state.
  46979. **
  46980. ** eLock
  46981. **
  46982. ** For a real on-disk database, the current lock held on the database file -
  46983. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  46984. **
  46985. ** For a temporary or in-memory database (neither of which require any
  46986. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  46987. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  46988. ** logic into thinking that it already has all the locks it will ever
  46989. ** need (and no reason to release them).
  46990. **
  46991. ** In some (obscure) circumstances, this variable may also be set to
  46992. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  46993. ** details.
  46994. **
  46995. ** changeCountDone
  46996. **
  46997. ** This boolean variable is used to make sure that the change-counter
  46998. ** (the 4-byte header field at byte offset 24 of the database file) is
  46999. ** not updated more often than necessary.
  47000. **
  47001. ** It is set to true when the change-counter field is updated, which
  47002. ** can only happen if an exclusive lock is held on the database file.
  47003. ** It is cleared (set to false) whenever an exclusive lock is
  47004. ** relinquished on the database file. Each time a transaction is committed,
  47005. ** The changeCountDone flag is inspected. If it is true, the work of
  47006. ** updating the change-counter is omitted for the current transaction.
  47007. **
  47008. ** This mechanism means that when running in exclusive mode, a connection
  47009. ** need only update the change-counter once, for the first transaction
  47010. ** committed.
  47011. **
  47012. ** setMaster
  47013. **
  47014. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  47015. ** (or may not) specify a master-journal name to be written into the
  47016. ** journal file before it is synced to disk.
  47017. **
  47018. ** Whether or not a journal file contains a master-journal pointer affects
  47019. ** the way in which the journal file is finalized after the transaction is
  47020. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  47021. ** If a journal file does not contain a master-journal pointer, it is
  47022. ** finalized by overwriting the first journal header with zeroes. If
  47023. ** it does contain a master-journal pointer the journal file is finalized
  47024. ** by truncating it to zero bytes, just as if the connection were
  47025. ** running in "journal_mode=truncate" mode.
  47026. **
  47027. ** Journal files that contain master journal pointers cannot be finalized
  47028. ** simply by overwriting the first journal-header with zeroes, as the
  47029. ** master journal pointer could interfere with hot-journal rollback of any
  47030. ** subsequently interrupted transaction that reuses the journal file.
  47031. **
  47032. ** The flag is cleared as soon as the journal file is finalized (either
  47033. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  47034. ** journal file from being successfully finalized, the setMaster flag
  47035. ** is cleared anyway (and the pager will move to ERROR state).
  47036. **
  47037. ** doNotSpill
  47038. **
  47039. ** This variables control the behavior of cache-spills (calls made by
  47040. ** the pcache module to the pagerStress() routine to write cached data
  47041. ** to the file-system in order to free up memory).
  47042. **
  47043. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  47044. ** writing to the database from pagerStress() is disabled altogether.
  47045. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  47046. ** comes up during savepoint rollback that requires the pcache module
  47047. ** to allocate a new page to prevent the journal file from being written
  47048. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  47049. ** case is a user preference.
  47050. **
  47051. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  47052. ** pagerStress() is permitted, but syncing the journal file is not.
  47053. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  47054. ** is larger than the database page-size in order to prevent a journal sync
  47055. ** from happening in between the journalling of two pages on the same sector.
  47056. **
  47057. ** subjInMemory
  47058. **
  47059. ** This is a boolean variable. If true, then any required sub-journal
  47060. ** is opened as an in-memory journal file. If false, then in-memory
  47061. ** sub-journals are only used for in-memory pager files.
  47062. **
  47063. ** This variable is updated by the upper layer each time a new
  47064. ** write-transaction is opened.
  47065. **
  47066. ** dbSize, dbOrigSize, dbFileSize
  47067. **
  47068. ** Variable dbSize is set to the number of pages in the database file.
  47069. ** It is valid in PAGER_READER and higher states (all states except for
  47070. ** OPEN and ERROR).
  47071. **
  47072. ** dbSize is set based on the size of the database file, which may be
  47073. ** larger than the size of the database (the value stored at offset
  47074. ** 28 of the database header by the btree). If the size of the file
  47075. ** is not an integer multiple of the page-size, the value stored in
  47076. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  47077. ** Except, any file that is greater than 0 bytes in size is considered
  47078. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  47079. ** to dbSize==1).
  47080. **
  47081. ** During a write-transaction, if pages with page-numbers greater than
  47082. ** dbSize are modified in the cache, dbSize is updated accordingly.
  47083. ** Similarly, if the database is truncated using PagerTruncateImage(),
  47084. ** dbSize is updated.
  47085. **
  47086. ** Variables dbOrigSize and dbFileSize are valid in states
  47087. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  47088. ** variable at the start of the transaction. It is used during rollback,
  47089. ** and to determine whether or not pages need to be journalled before
  47090. ** being modified.
  47091. **
  47092. ** Throughout a write-transaction, dbFileSize contains the size of
  47093. ** the file on disk in pages. It is set to a copy of dbSize when the
  47094. ** write-transaction is first opened, and updated when VFS calls are made
  47095. ** to write or truncate the database file on disk.
  47096. **
  47097. ** The only reason the dbFileSize variable is required is to suppress
  47098. ** unnecessary calls to xTruncate() after committing a transaction. If,
  47099. ** when a transaction is committed, the dbFileSize variable indicates
  47100. ** that the database file is larger than the database image (Pager.dbSize),
  47101. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  47102. ** to measure the database file on disk, and then truncates it if required.
  47103. ** dbFileSize is not used when rolling back a transaction. In this case
  47104. ** pager_truncate() is called unconditionally (which means there may be
  47105. ** a call to xFilesize() that is not strictly required). In either case,
  47106. ** pager_truncate() may cause the file to become smaller or larger.
  47107. **
  47108. ** dbHintSize
  47109. **
  47110. ** The dbHintSize variable is used to limit the number of calls made to
  47111. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  47112. **
  47113. ** dbHintSize is set to a copy of the dbSize variable when a
  47114. ** write-transaction is opened (at the same time as dbFileSize and
  47115. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  47116. ** dbHintSize is increased to the number of pages that correspond to the
  47117. ** size-hint passed to the method call. See pager_write_pagelist() for
  47118. ** details.
  47119. **
  47120. ** errCode
  47121. **
  47122. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  47123. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  47124. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  47125. ** sub-codes.
  47126. **
  47127. ** syncFlags, walSyncFlags
  47128. **
  47129. ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
  47130. ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
  47131. ** and contains the flags used to sync the checkpoint operations in the
  47132. ** lower two bits, and sync flags used for transaction commits in the WAL
  47133. ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
  47134. ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
  47135. ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
  47136. ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
  47137. ** meaning that the 0x04 and 0x08 bits are both zero.
  47138. */
  47139. struct Pager {
  47140. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  47141. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  47142. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  47143. u8 useJournal; /* Use a rollback journal on this file */
  47144. u8 noSync; /* Do not sync the journal if true */
  47145. u8 fullSync; /* Do extra syncs of the journal for robustness */
  47146. u8 extraSync; /* sync directory after journal delete */
  47147. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  47148. u8 walSyncFlags; /* See description above */
  47149. u8 tempFile; /* zFilename is a temporary or immutable file */
  47150. u8 noLock; /* Do not lock (except in WAL mode) */
  47151. u8 readOnly; /* True for a read-only database */
  47152. u8 memDb; /* True to inhibit all file I/O */
  47153. /**************************************************************************
  47154. ** The following block contains those class members that change during
  47155. ** routine operation. Class members not in this block are either fixed
  47156. ** when the pager is first created or else only change when there is a
  47157. ** significant mode change (such as changing the page_size, locking_mode,
  47158. ** or the journal_mode). From another view, these class members describe
  47159. ** the "state" of the pager, while other class members describe the
  47160. ** "configuration" of the pager.
  47161. */
  47162. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  47163. u8 eLock; /* Current lock held on database file */
  47164. u8 changeCountDone; /* Set after incrementing the change-counter */
  47165. u8 setMaster; /* True if a m-j name has been written to jrnl */
  47166. u8 doNotSpill; /* Do not spill the cache when non-zero */
  47167. u8 subjInMemory; /* True to use in-memory sub-journals */
  47168. u8 bUseFetch; /* True to use xFetch() */
  47169. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  47170. Pgno dbSize; /* Number of pages in the database */
  47171. Pgno dbOrigSize; /* dbSize before the current transaction */
  47172. Pgno dbFileSize; /* Number of pages in the database file */
  47173. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  47174. int errCode; /* One of several kinds of errors */
  47175. int nRec; /* Pages journalled since last j-header written */
  47176. u32 cksumInit; /* Quasi-random value added to every checksum */
  47177. u32 nSubRec; /* Number of records written to sub-journal */
  47178. Bitvec *pInJournal; /* One bit for each page in the database file */
  47179. sqlite3_file *fd; /* File descriptor for database */
  47180. sqlite3_file *jfd; /* File descriptor for main journal */
  47181. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  47182. i64 journalOff; /* Current write offset in the journal file */
  47183. i64 journalHdr; /* Byte offset to previous journal header */
  47184. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  47185. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  47186. int nSavepoint; /* Number of elements in aSavepoint[] */
  47187. u32 iDataVersion; /* Changes whenever database content changes */
  47188. char dbFileVers[16]; /* Changes whenever database file changes */
  47189. int nMmapOut; /* Number of mmap pages currently outstanding */
  47190. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  47191. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  47192. /*
  47193. ** End of the routinely-changing class members
  47194. ***************************************************************************/
  47195. u16 nExtra; /* Add this many bytes to each in-memory page */
  47196. i16 nReserve; /* Number of unused bytes at end of each page */
  47197. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  47198. u32 sectorSize; /* Assumed sector size during rollback */
  47199. int pageSize; /* Number of bytes in a page */
  47200. Pgno mxPgno; /* Maximum allowed size of the database */
  47201. i64 journalSizeLimit; /* Size limit for persistent journal files */
  47202. char *zFilename; /* Name of the database file */
  47203. char *zJournal; /* Name of the journal file */
  47204. int (*xBusyHandler)(void*); /* Function to call when busy */
  47205. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  47206. int aStat[4]; /* Total cache hits, misses, writes, spills */
  47207. #ifdef SQLITE_TEST
  47208. int nRead; /* Database pages read */
  47209. #endif
  47210. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  47211. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  47212. #ifdef SQLITE_HAS_CODEC
  47213. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  47214. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  47215. void (*xCodecFree)(void*); /* Destructor for the codec */
  47216. void *pCodec; /* First argument to xCodec... methods */
  47217. #endif
  47218. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  47219. PCache *pPCache; /* Pointer to page cache object */
  47220. #ifndef SQLITE_OMIT_WAL
  47221. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  47222. char *zWal; /* File name for write-ahead log */
  47223. #endif
  47224. };
  47225. /*
  47226. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  47227. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  47228. ** or CACHE_WRITE to sqlite3_db_status().
  47229. */
  47230. #define PAGER_STAT_HIT 0
  47231. #define PAGER_STAT_MISS 1
  47232. #define PAGER_STAT_WRITE 2
  47233. #define PAGER_STAT_SPILL 3
  47234. /*
  47235. ** The following global variables hold counters used for
  47236. ** testing purposes only. These variables do not exist in
  47237. ** a non-testing build. These variables are not thread-safe.
  47238. */
  47239. #ifdef SQLITE_TEST
  47240. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  47241. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  47242. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  47243. # define PAGER_INCR(v) v++
  47244. #else
  47245. # define PAGER_INCR(v)
  47246. #endif
  47247. /*
  47248. ** Journal files begin with the following magic string. The data
  47249. ** was obtained from /dev/random. It is used only as a sanity check.
  47250. **
  47251. ** Since version 2.8.0, the journal format contains additional sanity
  47252. ** checking information. If the power fails while the journal is being
  47253. ** written, semi-random garbage data might appear in the journal
  47254. ** file after power is restored. If an attempt is then made
  47255. ** to roll the journal back, the database could be corrupted. The additional
  47256. ** sanity checking data is an attempt to discover the garbage in the
  47257. ** journal and ignore it.
  47258. **
  47259. ** The sanity checking information for the new journal format consists
  47260. ** of a 32-bit checksum on each page of data. The checksum covers both
  47261. ** the page number and the pPager->pageSize bytes of data for the page.
  47262. ** This cksum is initialized to a 32-bit random value that appears in the
  47263. ** journal file right after the header. The random initializer is important,
  47264. ** because garbage data that appears at the end of a journal is likely
  47265. ** data that was once in other files that have now been deleted. If the
  47266. ** garbage data came from an obsolete journal file, the checksums might
  47267. ** be correct. But by initializing the checksum to random value which
  47268. ** is different for every journal, we minimize that risk.
  47269. */
  47270. static const unsigned char aJournalMagic[] = {
  47271. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  47272. };
  47273. /*
  47274. ** The size of the of each page record in the journal is given by
  47275. ** the following macro.
  47276. */
  47277. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  47278. /*
  47279. ** The journal header size for this pager. This is usually the same
  47280. ** size as a single disk sector. See also setSectorSize().
  47281. */
  47282. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  47283. /*
  47284. ** The macro MEMDB is true if we are dealing with an in-memory database.
  47285. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  47286. ** the value of MEMDB will be a constant and the compiler will optimize
  47287. ** out code that would never execute.
  47288. */
  47289. #ifdef SQLITE_OMIT_MEMORYDB
  47290. # define MEMDB 0
  47291. #else
  47292. # define MEMDB pPager->memDb
  47293. #endif
  47294. /*
  47295. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  47296. ** interfaces to access the database using memory-mapped I/O.
  47297. */
  47298. #if SQLITE_MAX_MMAP_SIZE>0
  47299. # define USEFETCH(x) ((x)->bUseFetch)
  47300. #else
  47301. # define USEFETCH(x) 0
  47302. #endif
  47303. /*
  47304. ** The maximum legal page number is (2^31 - 1).
  47305. */
  47306. #define PAGER_MAX_PGNO 2147483647
  47307. /*
  47308. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  47309. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  47310. **
  47311. ** This is so that expressions can be written as:
  47312. **
  47313. ** if( isOpen(pPager->jfd) ){ ...
  47314. **
  47315. ** instead of
  47316. **
  47317. ** if( pPager->jfd->pMethods ){ ...
  47318. */
  47319. #define isOpen(pFd) ((pFd)->pMethods!=0)
  47320. /*
  47321. ** Return true if this pager uses a write-ahead log to read page pgno.
  47322. ** Return false if the pager reads pgno directly from the database.
  47323. */
  47324. #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
  47325. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
  47326. u32 iRead = 0;
  47327. int rc;
  47328. if( pPager->pWal==0 ) return 0;
  47329. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  47330. return rc || iRead;
  47331. }
  47332. #endif
  47333. #ifndef SQLITE_OMIT_WAL
  47334. # define pagerUseWal(x) ((x)->pWal!=0)
  47335. #else
  47336. # define pagerUseWal(x) 0
  47337. # define pagerRollbackWal(x) 0
  47338. # define pagerWalFrames(v,w,x,y) 0
  47339. # define pagerOpenWalIfPresent(z) SQLITE_OK
  47340. # define pagerBeginReadTransaction(z) SQLITE_OK
  47341. #endif
  47342. #ifndef NDEBUG
  47343. /*
  47344. ** Usage:
  47345. **
  47346. ** assert( assert_pager_state(pPager) );
  47347. **
  47348. ** This function runs many asserts to try to find inconsistencies in
  47349. ** the internal state of the Pager object.
  47350. */
  47351. static int assert_pager_state(Pager *p){
  47352. Pager *pPager = p;
  47353. /* State must be valid. */
  47354. assert( p->eState==PAGER_OPEN
  47355. || p->eState==PAGER_READER
  47356. || p->eState==PAGER_WRITER_LOCKED
  47357. || p->eState==PAGER_WRITER_CACHEMOD
  47358. || p->eState==PAGER_WRITER_DBMOD
  47359. || p->eState==PAGER_WRITER_FINISHED
  47360. || p->eState==PAGER_ERROR
  47361. );
  47362. /* Regardless of the current state, a temp-file connection always behaves
  47363. ** as if it has an exclusive lock on the database file. It never updates
  47364. ** the change-counter field, so the changeCountDone flag is always set.
  47365. */
  47366. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  47367. assert( p->tempFile==0 || pPager->changeCountDone );
  47368. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  47369. ** And if the journal-mode is "OFF", the journal file must not be open.
  47370. */
  47371. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  47372. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  47373. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  47374. ** this means an in-memory pager performs no IO at all, it cannot encounter
  47375. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  47376. ** a journal file. (although the in-memory journal implementation may
  47377. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  47378. ** is therefore not possible for an in-memory pager to enter the ERROR
  47379. ** state.
  47380. */
  47381. if( MEMDB ){
  47382. assert( !isOpen(p->fd) );
  47383. assert( p->noSync );
  47384. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  47385. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  47386. );
  47387. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  47388. assert( pagerUseWal(p)==0 );
  47389. }
  47390. /* If changeCountDone is set, a RESERVED lock or greater must be held
  47391. ** on the file.
  47392. */
  47393. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  47394. assert( p->eLock!=PENDING_LOCK );
  47395. switch( p->eState ){
  47396. case PAGER_OPEN:
  47397. assert( !MEMDB );
  47398. assert( pPager->errCode==SQLITE_OK );
  47399. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  47400. break;
  47401. case PAGER_READER:
  47402. assert( pPager->errCode==SQLITE_OK );
  47403. assert( p->eLock!=UNKNOWN_LOCK );
  47404. assert( p->eLock>=SHARED_LOCK );
  47405. break;
  47406. case PAGER_WRITER_LOCKED:
  47407. assert( p->eLock!=UNKNOWN_LOCK );
  47408. assert( pPager->errCode==SQLITE_OK );
  47409. if( !pagerUseWal(pPager) ){
  47410. assert( p->eLock>=RESERVED_LOCK );
  47411. }
  47412. assert( pPager->dbSize==pPager->dbOrigSize );
  47413. assert( pPager->dbOrigSize==pPager->dbFileSize );
  47414. assert( pPager->dbOrigSize==pPager->dbHintSize );
  47415. assert( pPager->setMaster==0 );
  47416. break;
  47417. case PAGER_WRITER_CACHEMOD:
  47418. assert( p->eLock!=UNKNOWN_LOCK );
  47419. assert( pPager->errCode==SQLITE_OK );
  47420. if( !pagerUseWal(pPager) ){
  47421. /* It is possible that if journal_mode=wal here that neither the
  47422. ** journal file nor the WAL file are open. This happens during
  47423. ** a rollback transaction that switches from journal_mode=off
  47424. ** to journal_mode=wal.
  47425. */
  47426. assert( p->eLock>=RESERVED_LOCK );
  47427. assert( isOpen(p->jfd)
  47428. || p->journalMode==PAGER_JOURNALMODE_OFF
  47429. || p->journalMode==PAGER_JOURNALMODE_WAL
  47430. );
  47431. }
  47432. assert( pPager->dbOrigSize==pPager->dbFileSize );
  47433. assert( pPager->dbOrigSize==pPager->dbHintSize );
  47434. break;
  47435. case PAGER_WRITER_DBMOD:
  47436. assert( p->eLock==EXCLUSIVE_LOCK );
  47437. assert( pPager->errCode==SQLITE_OK );
  47438. assert( !pagerUseWal(pPager) );
  47439. assert( p->eLock>=EXCLUSIVE_LOCK );
  47440. assert( isOpen(p->jfd)
  47441. || p->journalMode==PAGER_JOURNALMODE_OFF
  47442. || p->journalMode==PAGER_JOURNALMODE_WAL
  47443. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  47444. );
  47445. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  47446. break;
  47447. case PAGER_WRITER_FINISHED:
  47448. assert( p->eLock==EXCLUSIVE_LOCK );
  47449. assert( pPager->errCode==SQLITE_OK );
  47450. assert( !pagerUseWal(pPager) );
  47451. assert( isOpen(p->jfd)
  47452. || p->journalMode==PAGER_JOURNALMODE_OFF
  47453. || p->journalMode==PAGER_JOURNALMODE_WAL
  47454. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  47455. );
  47456. break;
  47457. case PAGER_ERROR:
  47458. /* There must be at least one outstanding reference to the pager if
  47459. ** in ERROR state. Otherwise the pager should have already dropped
  47460. ** back to OPEN state.
  47461. */
  47462. assert( pPager->errCode!=SQLITE_OK );
  47463. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  47464. break;
  47465. }
  47466. return 1;
  47467. }
  47468. #endif /* ifndef NDEBUG */
  47469. #ifdef SQLITE_DEBUG
  47470. /*
  47471. ** Return a pointer to a human readable string in a static buffer
  47472. ** containing the state of the Pager object passed as an argument. This
  47473. ** is intended to be used within debuggers. For example, as an alternative
  47474. ** to "print *pPager" in gdb:
  47475. **
  47476. ** (gdb) printf "%s", print_pager_state(pPager)
  47477. */
  47478. static char *print_pager_state(Pager *p){
  47479. static char zRet[1024];
  47480. sqlite3_snprintf(1024, zRet,
  47481. "Filename: %s\n"
  47482. "State: %s errCode=%d\n"
  47483. "Lock: %s\n"
  47484. "Locking mode: locking_mode=%s\n"
  47485. "Journal mode: journal_mode=%s\n"
  47486. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  47487. "Journal: journalOff=%lld journalHdr=%lld\n"
  47488. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  47489. , p->zFilename
  47490. , p->eState==PAGER_OPEN ? "OPEN" :
  47491. p->eState==PAGER_READER ? "READER" :
  47492. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  47493. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  47494. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  47495. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  47496. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  47497. , (int)p->errCode
  47498. , p->eLock==NO_LOCK ? "NO_LOCK" :
  47499. p->eLock==RESERVED_LOCK ? "RESERVED" :
  47500. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  47501. p->eLock==SHARED_LOCK ? "SHARED" :
  47502. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  47503. , p->exclusiveMode ? "exclusive" : "normal"
  47504. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  47505. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  47506. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  47507. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  47508. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  47509. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  47510. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  47511. , p->journalOff, p->journalHdr
  47512. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  47513. );
  47514. return zRet;
  47515. }
  47516. #endif
  47517. /* Forward references to the various page getters */
  47518. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  47519. static int getPageError(Pager*,Pgno,DbPage**,int);
  47520. #if SQLITE_MAX_MMAP_SIZE>0
  47521. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  47522. #endif
  47523. /*
  47524. ** Set the Pager.xGet method for the appropriate routine used to fetch
  47525. ** content from the pager.
  47526. */
  47527. static void setGetterMethod(Pager *pPager){
  47528. if( pPager->errCode ){
  47529. pPager->xGet = getPageError;
  47530. #if SQLITE_MAX_MMAP_SIZE>0
  47531. }else if( USEFETCH(pPager)
  47532. #ifdef SQLITE_HAS_CODEC
  47533. && pPager->xCodec==0
  47534. #endif
  47535. ){
  47536. pPager->xGet = getPageMMap;
  47537. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  47538. }else{
  47539. pPager->xGet = getPageNormal;
  47540. }
  47541. }
  47542. /*
  47543. ** Return true if it is necessary to write page *pPg into the sub-journal.
  47544. ** A page needs to be written into the sub-journal if there exists one
  47545. ** or more open savepoints for which:
  47546. **
  47547. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  47548. ** * The bit corresponding to the page-number is not set in
  47549. ** PagerSavepoint.pInSavepoint.
  47550. */
  47551. static int subjRequiresPage(PgHdr *pPg){
  47552. Pager *pPager = pPg->pPager;
  47553. PagerSavepoint *p;
  47554. Pgno pgno = pPg->pgno;
  47555. int i;
  47556. for(i=0; i<pPager->nSavepoint; i++){
  47557. p = &pPager->aSavepoint[i];
  47558. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  47559. return 1;
  47560. }
  47561. }
  47562. return 0;
  47563. }
  47564. #ifdef SQLITE_DEBUG
  47565. /*
  47566. ** Return true if the page is already in the journal file.
  47567. */
  47568. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  47569. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  47570. }
  47571. #endif
  47572. /*
  47573. ** Read a 32-bit integer from the given file descriptor. Store the integer
  47574. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  47575. ** error code is something goes wrong.
  47576. **
  47577. ** All values are stored on disk as big-endian.
  47578. */
  47579. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  47580. unsigned char ac[4];
  47581. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  47582. if( rc==SQLITE_OK ){
  47583. *pRes = sqlite3Get4byte(ac);
  47584. }
  47585. return rc;
  47586. }
  47587. /*
  47588. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  47589. */
  47590. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  47591. /*
  47592. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  47593. ** on success or an error code is something goes wrong.
  47594. */
  47595. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  47596. char ac[4];
  47597. put32bits(ac, val);
  47598. return sqlite3OsWrite(fd, ac, 4, offset);
  47599. }
  47600. /*
  47601. ** Unlock the database file to level eLock, which must be either NO_LOCK
  47602. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  47603. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  47604. **
  47605. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  47606. ** called, do not modify it. See the comment above the #define of
  47607. ** UNKNOWN_LOCK for an explanation of this.
  47608. */
  47609. static int pagerUnlockDb(Pager *pPager, int eLock){
  47610. int rc = SQLITE_OK;
  47611. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  47612. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  47613. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  47614. if( isOpen(pPager->fd) ){
  47615. assert( pPager->eLock>=eLock );
  47616. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  47617. if( pPager->eLock!=UNKNOWN_LOCK ){
  47618. pPager->eLock = (u8)eLock;
  47619. }
  47620. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  47621. }
  47622. return rc;
  47623. }
  47624. /*
  47625. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  47626. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  47627. ** Pager.eLock variable to the new locking state.
  47628. **
  47629. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  47630. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  47631. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  47632. ** of this.
  47633. */
  47634. static int pagerLockDb(Pager *pPager, int eLock){
  47635. int rc = SQLITE_OK;
  47636. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  47637. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  47638. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  47639. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  47640. pPager->eLock = (u8)eLock;
  47641. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  47642. }
  47643. }
  47644. return rc;
  47645. }
  47646. /*
  47647. ** This function determines whether or not the atomic-write or
  47648. ** atomic-batch-write optimizations can be used with this pager. The
  47649. ** atomic-write optimization can be used if:
  47650. **
  47651. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  47652. ** a database page may be written atomically, and
  47653. ** (b) the value returned by OsSectorSize() is less than or equal
  47654. ** to the page size.
  47655. **
  47656. ** If it can be used, then the value returned is the size of the journal
  47657. ** file when it contains rollback data for exactly one page.
  47658. **
  47659. ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
  47660. ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
  47661. ** returned in this case.
  47662. **
  47663. ** If neither optimization can be used, 0 is returned.
  47664. */
  47665. static int jrnlBufferSize(Pager *pPager){
  47666. assert( !MEMDB );
  47667. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  47668. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  47669. int dc; /* Device characteristics */
  47670. assert( isOpen(pPager->fd) );
  47671. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  47672. #else
  47673. UNUSED_PARAMETER(pPager);
  47674. #endif
  47675. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  47676. if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
  47677. return -1;
  47678. }
  47679. #endif
  47680. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  47681. {
  47682. int nSector = pPager->sectorSize;
  47683. int szPage = pPager->pageSize;
  47684. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  47685. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  47686. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  47687. return 0;
  47688. }
  47689. }
  47690. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  47691. #endif
  47692. return 0;
  47693. }
  47694. /*
  47695. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  47696. ** on the cache using a hash function. This is used for testing
  47697. ** and debugging only.
  47698. */
  47699. #ifdef SQLITE_CHECK_PAGES
  47700. /*
  47701. ** Return a 32-bit hash of the page data for pPage.
  47702. */
  47703. static u32 pager_datahash(int nByte, unsigned char *pData){
  47704. u32 hash = 0;
  47705. int i;
  47706. for(i=0; i<nByte; i++){
  47707. hash = (hash*1039) + pData[i];
  47708. }
  47709. return hash;
  47710. }
  47711. static u32 pager_pagehash(PgHdr *pPage){
  47712. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  47713. }
  47714. static void pager_set_pagehash(PgHdr *pPage){
  47715. pPage->pageHash = pager_pagehash(pPage);
  47716. }
  47717. /*
  47718. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  47719. ** is defined, and NDEBUG is not defined, an assert() statement checks
  47720. ** that the page is either dirty or still matches the calculated page-hash.
  47721. */
  47722. #define CHECK_PAGE(x) checkPage(x)
  47723. static void checkPage(PgHdr *pPg){
  47724. Pager *pPager = pPg->pPager;
  47725. assert( pPager->eState!=PAGER_ERROR );
  47726. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  47727. }
  47728. #else
  47729. #define pager_datahash(X,Y) 0
  47730. #define pager_pagehash(X) 0
  47731. #define pager_set_pagehash(X)
  47732. #define CHECK_PAGE(x)
  47733. #endif /* SQLITE_CHECK_PAGES */
  47734. /*
  47735. ** When this is called the journal file for pager pPager must be open.
  47736. ** This function attempts to read a master journal file name from the
  47737. ** end of the file and, if successful, copies it into memory supplied
  47738. ** by the caller. See comments above writeMasterJournal() for the format
  47739. ** used to store a master journal file name at the end of a journal file.
  47740. **
  47741. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  47742. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  47743. ** enough space to write the master journal name). If the master journal
  47744. ** name in the journal is longer than nMaster bytes (including a
  47745. ** nul-terminator), then this is handled as if no master journal name
  47746. ** were present in the journal.
  47747. **
  47748. ** If a master journal file name is present at the end of the journal
  47749. ** file, then it is copied into the buffer pointed to by zMaster. A
  47750. ** nul-terminator byte is appended to the buffer following the master
  47751. ** journal file name.
  47752. **
  47753. ** If it is determined that no master journal file name is present
  47754. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  47755. **
  47756. ** If an error occurs while reading from the journal file, an SQLite
  47757. ** error code is returned.
  47758. */
  47759. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  47760. int rc; /* Return code */
  47761. u32 len; /* Length in bytes of master journal name */
  47762. i64 szJ; /* Total size in bytes of journal file pJrnl */
  47763. u32 cksum; /* MJ checksum value read from journal */
  47764. u32 u; /* Unsigned loop counter */
  47765. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  47766. zMaster[0] = '\0';
  47767. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  47768. || szJ<16
  47769. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  47770. || len>=nMaster
  47771. || len>szJ-16
  47772. || len==0
  47773. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  47774. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  47775. || memcmp(aMagic, aJournalMagic, 8)
  47776. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  47777. ){
  47778. return rc;
  47779. }
  47780. /* See if the checksum matches the master journal name */
  47781. for(u=0; u<len; u++){
  47782. cksum -= zMaster[u];
  47783. }
  47784. if( cksum ){
  47785. /* If the checksum doesn't add up, then one or more of the disk sectors
  47786. ** containing the master journal filename is corrupted. This means
  47787. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  47788. ** master-journal filename.
  47789. */
  47790. len = 0;
  47791. }
  47792. zMaster[len] = '\0';
  47793. return SQLITE_OK;
  47794. }
  47795. /*
  47796. ** Return the offset of the sector boundary at or immediately
  47797. ** following the value in pPager->journalOff, assuming a sector
  47798. ** size of pPager->sectorSize bytes.
  47799. **
  47800. ** i.e for a sector size of 512:
  47801. **
  47802. ** Pager.journalOff Return value
  47803. ** ---------------------------------------
  47804. ** 0 0
  47805. ** 512 512
  47806. ** 100 512
  47807. ** 2000 2048
  47808. **
  47809. */
  47810. static i64 journalHdrOffset(Pager *pPager){
  47811. i64 offset = 0;
  47812. i64 c = pPager->journalOff;
  47813. if( c ){
  47814. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  47815. }
  47816. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  47817. assert( offset>=c );
  47818. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  47819. return offset;
  47820. }
  47821. /*
  47822. ** The journal file must be open when this function is called.
  47823. **
  47824. ** This function is a no-op if the journal file has not been written to
  47825. ** within the current transaction (i.e. if Pager.journalOff==0).
  47826. **
  47827. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  47828. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  47829. ** zero the 28-byte header at the start of the journal file. In either case,
  47830. ** if the pager is not in no-sync mode, sync the journal file immediately
  47831. ** after writing or truncating it.
  47832. **
  47833. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  47834. ** following the truncation or zeroing described above the size of the
  47835. ** journal file in bytes is larger than this value, then truncate the
  47836. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  47837. ** not need to be synced following this operation.
  47838. **
  47839. ** If an IO error occurs, abandon processing and return the IO error code.
  47840. ** Otherwise, return SQLITE_OK.
  47841. */
  47842. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  47843. int rc = SQLITE_OK; /* Return code */
  47844. assert( isOpen(pPager->jfd) );
  47845. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  47846. if( pPager->journalOff ){
  47847. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  47848. IOTRACE(("JZEROHDR %p\n", pPager))
  47849. if( doTruncate || iLimit==0 ){
  47850. rc = sqlite3OsTruncate(pPager->jfd, 0);
  47851. }else{
  47852. static const char zeroHdr[28] = {0};
  47853. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  47854. }
  47855. if( rc==SQLITE_OK && !pPager->noSync ){
  47856. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  47857. }
  47858. /* At this point the transaction is committed but the write lock
  47859. ** is still held on the file. If there is a size limit configured for
  47860. ** the persistent journal and the journal file currently consumes more
  47861. ** space than that limit allows for, truncate it now. There is no need
  47862. ** to sync the file following this operation.
  47863. */
  47864. if( rc==SQLITE_OK && iLimit>0 ){
  47865. i64 sz;
  47866. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  47867. if( rc==SQLITE_OK && sz>iLimit ){
  47868. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  47869. }
  47870. }
  47871. }
  47872. return rc;
  47873. }
  47874. /*
  47875. ** The journal file must be open when this routine is called. A journal
  47876. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  47877. ** current location.
  47878. **
  47879. ** The format for the journal header is as follows:
  47880. ** - 8 bytes: Magic identifying journal format.
  47881. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  47882. ** - 4 bytes: Random number used for page hash.
  47883. ** - 4 bytes: Initial database page count.
  47884. ** - 4 bytes: Sector size used by the process that wrote this journal.
  47885. ** - 4 bytes: Database page size.
  47886. **
  47887. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  47888. */
  47889. static int writeJournalHdr(Pager *pPager){
  47890. int rc = SQLITE_OK; /* Return code */
  47891. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  47892. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  47893. u32 nWrite; /* Bytes of header sector written */
  47894. int ii; /* Loop counter */
  47895. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  47896. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  47897. nHeader = JOURNAL_HDR_SZ(pPager);
  47898. }
  47899. /* If there are active savepoints and any of them were created
  47900. ** since the most recent journal header was written, update the
  47901. ** PagerSavepoint.iHdrOffset fields now.
  47902. */
  47903. for(ii=0; ii<pPager->nSavepoint; ii++){
  47904. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  47905. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  47906. }
  47907. }
  47908. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  47909. /*
  47910. ** Write the nRec Field - the number of page records that follow this
  47911. ** journal header. Normally, zero is written to this value at this time.
  47912. ** After the records are added to the journal (and the journal synced,
  47913. ** if in full-sync mode), the zero is overwritten with the true number
  47914. ** of records (see syncJournal()).
  47915. **
  47916. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  47917. ** reading the journal this value tells SQLite to assume that the
  47918. ** rest of the journal file contains valid page records. This assumption
  47919. ** is dangerous, as if a failure occurred whilst writing to the journal
  47920. ** file it may contain some garbage data. There are two scenarios
  47921. ** where this risk can be ignored:
  47922. **
  47923. ** * When the pager is in no-sync mode. Corruption can follow a
  47924. ** power failure in this case anyway.
  47925. **
  47926. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  47927. ** that garbage data is never appended to the journal file.
  47928. */
  47929. assert( isOpen(pPager->fd) || pPager->noSync );
  47930. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  47931. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  47932. ){
  47933. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  47934. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  47935. }else{
  47936. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  47937. }
  47938. /* The random check-hash initializer */
  47939. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  47940. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  47941. /* The initial database size */
  47942. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  47943. /* The assumed sector size for this process */
  47944. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  47945. /* The page size */
  47946. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  47947. /* Initializing the tail of the buffer is not necessary. Everything
  47948. ** works find if the following memset() is omitted. But initializing
  47949. ** the memory prevents valgrind from complaining, so we are willing to
  47950. ** take the performance hit.
  47951. */
  47952. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  47953. nHeader-(sizeof(aJournalMagic)+20));
  47954. /* In theory, it is only necessary to write the 28 bytes that the
  47955. ** journal header consumes to the journal file here. Then increment the
  47956. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  47957. ** record is written to the following sector (leaving a gap in the file
  47958. ** that will be implicitly filled in by the OS).
  47959. **
  47960. ** However it has been discovered that on some systems this pattern can
  47961. ** be significantly slower than contiguously writing data to the file,
  47962. ** even if that means explicitly writing data to the block of
  47963. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  47964. ** is done.
  47965. **
  47966. ** The loop is required here in case the sector-size is larger than the
  47967. ** database page size. Since the zHeader buffer is only Pager.pageSize
  47968. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  47969. ** to populate the entire journal header sector.
  47970. */
  47971. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  47972. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  47973. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  47974. assert( pPager->journalHdr <= pPager->journalOff );
  47975. pPager->journalOff += nHeader;
  47976. }
  47977. return rc;
  47978. }
  47979. /*
  47980. ** The journal file must be open when this is called. A journal header file
  47981. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  47982. ** file. The current location in the journal file is given by
  47983. ** pPager->journalOff. See comments above function writeJournalHdr() for
  47984. ** a description of the journal header format.
  47985. **
  47986. ** If the header is read successfully, *pNRec is set to the number of
  47987. ** page records following this header and *pDbSize is set to the size of the
  47988. ** database before the transaction began, in pages. Also, pPager->cksumInit
  47989. ** is set to the value read from the journal header. SQLITE_OK is returned
  47990. ** in this case.
  47991. **
  47992. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  47993. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  47994. ** cannot be read from the journal file an error code is returned.
  47995. */
  47996. static int readJournalHdr(
  47997. Pager *pPager, /* Pager object */
  47998. int isHot,
  47999. i64 journalSize, /* Size of the open journal file in bytes */
  48000. u32 *pNRec, /* OUT: Value read from the nRec field */
  48001. u32 *pDbSize /* OUT: Value of original database size field */
  48002. ){
  48003. int rc; /* Return code */
  48004. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  48005. i64 iHdrOff; /* Offset of journal header being read */
  48006. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  48007. /* Advance Pager.journalOff to the start of the next sector. If the
  48008. ** journal file is too small for there to be a header stored at this
  48009. ** point, return SQLITE_DONE.
  48010. */
  48011. pPager->journalOff = journalHdrOffset(pPager);
  48012. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  48013. return SQLITE_DONE;
  48014. }
  48015. iHdrOff = pPager->journalOff;
  48016. /* Read in the first 8 bytes of the journal header. If they do not match
  48017. ** the magic string found at the start of each journal header, return
  48018. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  48019. ** proceed.
  48020. */
  48021. if( isHot || iHdrOff!=pPager->journalHdr ){
  48022. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  48023. if( rc ){
  48024. return rc;
  48025. }
  48026. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  48027. return SQLITE_DONE;
  48028. }
  48029. }
  48030. /* Read the first three 32-bit fields of the journal header: The nRec
  48031. ** field, the checksum-initializer and the database size at the start
  48032. ** of the transaction. Return an error code if anything goes wrong.
  48033. */
  48034. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  48035. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  48036. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  48037. ){
  48038. return rc;
  48039. }
  48040. if( pPager->journalOff==0 ){
  48041. u32 iPageSize; /* Page-size field of journal header */
  48042. u32 iSectorSize; /* Sector-size field of journal header */
  48043. /* Read the page-size and sector-size journal header fields. */
  48044. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  48045. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  48046. ){
  48047. return rc;
  48048. }
  48049. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  48050. ** journal header to zero. In this case, assume that the Pager.pageSize
  48051. ** variable is already set to the correct page size.
  48052. */
  48053. if( iPageSize==0 ){
  48054. iPageSize = pPager->pageSize;
  48055. }
  48056. /* Check that the values read from the page-size and sector-size fields
  48057. ** are within range. To be 'in range', both values need to be a power
  48058. ** of two greater than or equal to 512 or 32, and not greater than their
  48059. ** respective compile time maximum limits.
  48060. */
  48061. if( iPageSize<512 || iSectorSize<32
  48062. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  48063. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  48064. ){
  48065. /* If the either the page-size or sector-size in the journal-header is
  48066. ** invalid, then the process that wrote the journal-header must have
  48067. ** crashed before the header was synced. In this case stop reading
  48068. ** the journal file here.
  48069. */
  48070. return SQLITE_DONE;
  48071. }
  48072. /* Update the page-size to match the value read from the journal.
  48073. ** Use a testcase() macro to make sure that malloc failure within
  48074. ** PagerSetPagesize() is tested.
  48075. */
  48076. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  48077. testcase( rc!=SQLITE_OK );
  48078. /* Update the assumed sector-size to match the value used by
  48079. ** the process that created this journal. If this journal was
  48080. ** created by a process other than this one, then this routine
  48081. ** is being called from within pager_playback(). The local value
  48082. ** of Pager.sectorSize is restored at the end of that routine.
  48083. */
  48084. pPager->sectorSize = iSectorSize;
  48085. }
  48086. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  48087. return rc;
  48088. }
  48089. /*
  48090. ** Write the supplied master journal name into the journal file for pager
  48091. ** pPager at the current location. The master journal name must be the last
  48092. ** thing written to a journal file. If the pager is in full-sync mode, the
  48093. ** journal file descriptor is advanced to the next sector boundary before
  48094. ** anything is written. The format is:
  48095. **
  48096. ** + 4 bytes: PAGER_MJ_PGNO.
  48097. ** + N bytes: Master journal filename in utf-8.
  48098. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  48099. ** + 4 bytes: Master journal name checksum.
  48100. ** + 8 bytes: aJournalMagic[].
  48101. **
  48102. ** The master journal page checksum is the sum of the bytes in the master
  48103. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  48104. **
  48105. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  48106. ** this call is a no-op.
  48107. */
  48108. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  48109. int rc; /* Return code */
  48110. int nMaster; /* Length of string zMaster */
  48111. i64 iHdrOff; /* Offset of header in journal file */
  48112. i64 jrnlSize; /* Size of journal file on disk */
  48113. u32 cksum = 0; /* Checksum of string zMaster */
  48114. assert( pPager->setMaster==0 );
  48115. assert( !pagerUseWal(pPager) );
  48116. if( !zMaster
  48117. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  48118. || !isOpen(pPager->jfd)
  48119. ){
  48120. return SQLITE_OK;
  48121. }
  48122. pPager->setMaster = 1;
  48123. assert( pPager->journalHdr <= pPager->journalOff );
  48124. /* Calculate the length in bytes and the checksum of zMaster */
  48125. for(nMaster=0; zMaster[nMaster]; nMaster++){
  48126. cksum += zMaster[nMaster];
  48127. }
  48128. /* If in full-sync mode, advance to the next disk sector before writing
  48129. ** the master journal name. This is in case the previous page written to
  48130. ** the journal has already been synced.
  48131. */
  48132. if( pPager->fullSync ){
  48133. pPager->journalOff = journalHdrOffset(pPager);
  48134. }
  48135. iHdrOff = pPager->journalOff;
  48136. /* Write the master journal data to the end of the journal file. If
  48137. ** an error occurs, return the error code to the caller.
  48138. */
  48139. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  48140. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  48141. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  48142. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  48143. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  48144. iHdrOff+4+nMaster+8)))
  48145. ){
  48146. return rc;
  48147. }
  48148. pPager->journalOff += (nMaster+20);
  48149. /* If the pager is in peristent-journal mode, then the physical
  48150. ** journal-file may extend past the end of the master-journal name
  48151. ** and 8 bytes of magic data just written to the file. This is
  48152. ** dangerous because the code to rollback a hot-journal file
  48153. ** will not be able to find the master-journal name to determine
  48154. ** whether or not the journal is hot.
  48155. **
  48156. ** Easiest thing to do in this scenario is to truncate the journal
  48157. ** file to the required size.
  48158. */
  48159. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  48160. && jrnlSize>pPager->journalOff
  48161. ){
  48162. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  48163. }
  48164. return rc;
  48165. }
  48166. /*
  48167. ** Discard the entire contents of the in-memory page-cache.
  48168. */
  48169. static void pager_reset(Pager *pPager){
  48170. pPager->iDataVersion++;
  48171. sqlite3BackupRestart(pPager->pBackup);
  48172. sqlite3PcacheClear(pPager->pPCache);
  48173. }
  48174. /*
  48175. ** Return the pPager->iDataVersion value
  48176. */
  48177. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  48178. assert( pPager->eState>PAGER_OPEN );
  48179. return pPager->iDataVersion;
  48180. }
  48181. /*
  48182. ** Free all structures in the Pager.aSavepoint[] array and set both
  48183. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  48184. ** if it is open and the pager is not in exclusive mode.
  48185. */
  48186. static void releaseAllSavepoints(Pager *pPager){
  48187. int ii; /* Iterator for looping through Pager.aSavepoint */
  48188. for(ii=0; ii<pPager->nSavepoint; ii++){
  48189. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  48190. }
  48191. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  48192. sqlite3OsClose(pPager->sjfd);
  48193. }
  48194. sqlite3_free(pPager->aSavepoint);
  48195. pPager->aSavepoint = 0;
  48196. pPager->nSavepoint = 0;
  48197. pPager->nSubRec = 0;
  48198. }
  48199. /*
  48200. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  48201. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  48202. ** or SQLITE_NOMEM if a malloc failure occurs.
  48203. */
  48204. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  48205. int ii; /* Loop counter */
  48206. int rc = SQLITE_OK; /* Result code */
  48207. for(ii=0; ii<pPager->nSavepoint; ii++){
  48208. PagerSavepoint *p = &pPager->aSavepoint[ii];
  48209. if( pgno<=p->nOrig ){
  48210. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  48211. testcase( rc==SQLITE_NOMEM );
  48212. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  48213. }
  48214. }
  48215. return rc;
  48216. }
  48217. /*
  48218. ** This function is a no-op if the pager is in exclusive mode and not
  48219. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  48220. ** state.
  48221. **
  48222. ** If the pager is not in exclusive-access mode, the database file is
  48223. ** completely unlocked. If the file is unlocked and the file-system does
  48224. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  48225. ** closed (if it is open).
  48226. **
  48227. ** If the pager is in ERROR state when this function is called, the
  48228. ** contents of the pager cache are discarded before switching back to
  48229. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  48230. ** or not, any journal file left in the file-system will be treated
  48231. ** as a hot-journal and rolled back the next time a read-transaction
  48232. ** is opened (by this or by any other connection).
  48233. */
  48234. static void pager_unlock(Pager *pPager){
  48235. assert( pPager->eState==PAGER_READER
  48236. || pPager->eState==PAGER_OPEN
  48237. || pPager->eState==PAGER_ERROR
  48238. );
  48239. sqlite3BitvecDestroy(pPager->pInJournal);
  48240. pPager->pInJournal = 0;
  48241. releaseAllSavepoints(pPager);
  48242. if( pagerUseWal(pPager) ){
  48243. assert( !isOpen(pPager->jfd) );
  48244. sqlite3WalEndReadTransaction(pPager->pWal);
  48245. pPager->eState = PAGER_OPEN;
  48246. }else if( !pPager->exclusiveMode ){
  48247. int rc; /* Error code returned by pagerUnlockDb() */
  48248. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  48249. /* If the operating system support deletion of open files, then
  48250. ** close the journal file when dropping the database lock. Otherwise
  48251. ** another connection with journal_mode=delete might delete the file
  48252. ** out from under us.
  48253. */
  48254. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  48255. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  48256. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  48257. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  48258. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  48259. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  48260. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  48261. || 1!=(pPager->journalMode & 5)
  48262. ){
  48263. sqlite3OsClose(pPager->jfd);
  48264. }
  48265. /* If the pager is in the ERROR state and the call to unlock the database
  48266. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  48267. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  48268. ** is necessary.
  48269. */
  48270. rc = pagerUnlockDb(pPager, NO_LOCK);
  48271. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  48272. pPager->eLock = UNKNOWN_LOCK;
  48273. }
  48274. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  48275. ** without clearing the error code. This is intentional - the error
  48276. ** code is cleared and the cache reset in the block below.
  48277. */
  48278. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  48279. pPager->changeCountDone = 0;
  48280. pPager->eState = PAGER_OPEN;
  48281. }
  48282. /* If Pager.errCode is set, the contents of the pager cache cannot be
  48283. ** trusted. Now that there are no outstanding references to the pager,
  48284. ** it can safely move back to PAGER_OPEN state. This happens in both
  48285. ** normal and exclusive-locking mode.
  48286. */
  48287. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  48288. if( pPager->errCode ){
  48289. if( pPager->tempFile==0 ){
  48290. pager_reset(pPager);
  48291. pPager->changeCountDone = 0;
  48292. pPager->eState = PAGER_OPEN;
  48293. }else{
  48294. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  48295. }
  48296. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  48297. pPager->errCode = SQLITE_OK;
  48298. setGetterMethod(pPager);
  48299. }
  48300. pPager->journalOff = 0;
  48301. pPager->journalHdr = 0;
  48302. pPager->setMaster = 0;
  48303. }
  48304. /*
  48305. ** This function is called whenever an IOERR or FULL error that requires
  48306. ** the pager to transition into the ERROR state may ahve occurred.
  48307. ** The first argument is a pointer to the pager structure, the second
  48308. ** the error-code about to be returned by a pager API function. The
  48309. ** value returned is a copy of the second argument to this function.
  48310. **
  48311. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  48312. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  48313. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  48314. ** all major API calls on the Pager will immediately return Pager.errCode.
  48315. **
  48316. ** The ERROR state indicates that the contents of the pager-cache
  48317. ** cannot be trusted. This state can be cleared by completely discarding
  48318. ** the contents of the pager-cache. If a transaction was active when
  48319. ** the persistent error occurred, then the rollback journal may need
  48320. ** to be replayed to restore the contents of the database file (as if
  48321. ** it were a hot-journal).
  48322. */
  48323. static int pager_error(Pager *pPager, int rc){
  48324. int rc2 = rc & 0xff;
  48325. assert( rc==SQLITE_OK || !MEMDB );
  48326. assert(
  48327. pPager->errCode==SQLITE_FULL ||
  48328. pPager->errCode==SQLITE_OK ||
  48329. (pPager->errCode & 0xff)==SQLITE_IOERR
  48330. );
  48331. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  48332. pPager->errCode = rc;
  48333. pPager->eState = PAGER_ERROR;
  48334. setGetterMethod(pPager);
  48335. }
  48336. return rc;
  48337. }
  48338. static int pager_truncate(Pager *pPager, Pgno nPage);
  48339. /*
  48340. ** The write transaction open on pPager is being committed (bCommit==1)
  48341. ** or rolled back (bCommit==0).
  48342. **
  48343. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  48344. **
  48345. ** Rules:
  48346. **
  48347. ** * For non-TEMP databases, always sync to disk. This is necessary
  48348. ** for transactions to be durable.
  48349. **
  48350. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  48351. ** file has been created already (via a spill on pagerStress()) and
  48352. ** when the number of dirty pages in memory exceeds 25% of the total
  48353. ** cache size.
  48354. */
  48355. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  48356. if( pPager->tempFile==0 ) return 1;
  48357. if( !bCommit ) return 0;
  48358. if( !isOpen(pPager->fd) ) return 0;
  48359. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  48360. }
  48361. /*
  48362. ** This routine ends a transaction. A transaction is usually ended by
  48363. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  48364. ** after rollback of a hot-journal, or if an error occurs while opening
  48365. ** the journal file or writing the very first journal-header of a
  48366. ** database transaction.
  48367. **
  48368. ** This routine is never called in PAGER_ERROR state. If it is called
  48369. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  48370. ** exclusive than a RESERVED lock, it is a no-op.
  48371. **
  48372. ** Otherwise, any active savepoints are released.
  48373. **
  48374. ** If the journal file is open, then it is "finalized". Once a journal
  48375. ** file has been finalized it is not possible to use it to roll back a
  48376. ** transaction. Nor will it be considered to be a hot-journal by this
  48377. ** or any other database connection. Exactly how a journal is finalized
  48378. ** depends on whether or not the pager is running in exclusive mode and
  48379. ** the current journal-mode (Pager.journalMode value), as follows:
  48380. **
  48381. ** journalMode==MEMORY
  48382. ** Journal file descriptor is simply closed. This destroys an
  48383. ** in-memory journal.
  48384. **
  48385. ** journalMode==TRUNCATE
  48386. ** Journal file is truncated to zero bytes in size.
  48387. **
  48388. ** journalMode==PERSIST
  48389. ** The first 28 bytes of the journal file are zeroed. This invalidates
  48390. ** the first journal header in the file, and hence the entire journal
  48391. ** file. An invalid journal file cannot be rolled back.
  48392. **
  48393. ** journalMode==DELETE
  48394. ** The journal file is closed and deleted using sqlite3OsDelete().
  48395. **
  48396. ** If the pager is running in exclusive mode, this method of finalizing
  48397. ** the journal file is never used. Instead, if the journalMode is
  48398. ** DELETE and the pager is in exclusive mode, the method described under
  48399. ** journalMode==PERSIST is used instead.
  48400. **
  48401. ** After the journal is finalized, the pager moves to PAGER_READER state.
  48402. ** If running in non-exclusive rollback mode, the lock on the file is
  48403. ** downgraded to a SHARED_LOCK.
  48404. **
  48405. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  48406. ** any of the IO operations to finalize the journal file or unlock the
  48407. ** database then the IO error code is returned to the user. If the
  48408. ** operation to finalize the journal file fails, then the code still
  48409. ** tries to unlock the database file if not in exclusive mode. If the
  48410. ** unlock operation fails as well, then the first error code related
  48411. ** to the first error encountered (the journal finalization one) is
  48412. ** returned.
  48413. */
  48414. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  48415. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  48416. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  48417. /* Do nothing if the pager does not have an open write transaction
  48418. ** or at least a RESERVED lock. This function may be called when there
  48419. ** is no write-transaction active but a RESERVED or greater lock is
  48420. ** held under two circumstances:
  48421. **
  48422. ** 1. After a successful hot-journal rollback, it is called with
  48423. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  48424. **
  48425. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  48426. ** lock switches back to locking_mode=normal and then executes a
  48427. ** read-transaction, this function is called with eState==PAGER_READER
  48428. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  48429. */
  48430. assert( assert_pager_state(pPager) );
  48431. assert( pPager->eState!=PAGER_ERROR );
  48432. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  48433. return SQLITE_OK;
  48434. }
  48435. releaseAllSavepoints(pPager);
  48436. assert( isOpen(pPager->jfd) || pPager->pInJournal==0
  48437. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48438. );
  48439. if( isOpen(pPager->jfd) ){
  48440. assert( !pagerUseWal(pPager) );
  48441. /* Finalize the journal file. */
  48442. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  48443. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  48444. sqlite3OsClose(pPager->jfd);
  48445. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  48446. if( pPager->journalOff==0 ){
  48447. rc = SQLITE_OK;
  48448. }else{
  48449. rc = sqlite3OsTruncate(pPager->jfd, 0);
  48450. if( rc==SQLITE_OK && pPager->fullSync ){
  48451. /* Make sure the new file size is written into the inode right away.
  48452. ** Otherwise the journal might resurrect following a power loss and
  48453. ** cause the last transaction to roll back. See
  48454. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  48455. */
  48456. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  48457. }
  48458. }
  48459. pPager->journalOff = 0;
  48460. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  48461. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  48462. ){
  48463. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  48464. pPager->journalOff = 0;
  48465. }else{
  48466. /* This branch may be executed with Pager.journalMode==MEMORY if
  48467. ** a hot-journal was just rolled back. In this case the journal
  48468. ** file should be closed and deleted. If this connection writes to
  48469. ** the database file, it will do so using an in-memory journal.
  48470. */
  48471. int bDelete = !pPager->tempFile;
  48472. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  48473. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  48474. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  48475. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  48476. );
  48477. sqlite3OsClose(pPager->jfd);
  48478. if( bDelete ){
  48479. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  48480. }
  48481. }
  48482. }
  48483. #ifdef SQLITE_CHECK_PAGES
  48484. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  48485. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  48486. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  48487. if( p ){
  48488. p->pageHash = 0;
  48489. sqlite3PagerUnrefNotNull(p);
  48490. }
  48491. }
  48492. #endif
  48493. sqlite3BitvecDestroy(pPager->pInJournal);
  48494. pPager->pInJournal = 0;
  48495. pPager->nRec = 0;
  48496. if( rc==SQLITE_OK ){
  48497. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  48498. sqlite3PcacheCleanAll(pPager->pPCache);
  48499. }else{
  48500. sqlite3PcacheClearWritable(pPager->pPCache);
  48501. }
  48502. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  48503. }
  48504. if( pagerUseWal(pPager) ){
  48505. /* Drop the WAL write-lock, if any. Also, if the connection was in
  48506. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  48507. ** lock held on the database file.
  48508. */
  48509. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  48510. assert( rc2==SQLITE_OK );
  48511. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  48512. /* This branch is taken when committing a transaction in rollback-journal
  48513. ** mode if the database file on disk is larger than the database image.
  48514. ** At this point the journal has been finalized and the transaction
  48515. ** successfully committed, but the EXCLUSIVE lock is still held on the
  48516. ** file. So it is safe to truncate the database file to its minimum
  48517. ** required size. */
  48518. assert( pPager->eLock==EXCLUSIVE_LOCK );
  48519. rc = pager_truncate(pPager, pPager->dbSize);
  48520. }
  48521. if( rc==SQLITE_OK && bCommit ){
  48522. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  48523. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  48524. }
  48525. if( !pPager->exclusiveMode
  48526. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  48527. ){
  48528. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  48529. pPager->changeCountDone = 0;
  48530. }
  48531. pPager->eState = PAGER_READER;
  48532. pPager->setMaster = 0;
  48533. return (rc==SQLITE_OK?rc2:rc);
  48534. }
  48535. /*
  48536. ** Execute a rollback if a transaction is active and unlock the
  48537. ** database file.
  48538. **
  48539. ** If the pager has already entered the ERROR state, do not attempt
  48540. ** the rollback at this time. Instead, pager_unlock() is called. The
  48541. ** call to pager_unlock() will discard all in-memory pages, unlock
  48542. ** the database file and move the pager back to OPEN state. If this
  48543. ** means that there is a hot-journal left in the file-system, the next
  48544. ** connection to obtain a shared lock on the pager (which may be this one)
  48545. ** will roll it back.
  48546. **
  48547. ** If the pager has not already entered the ERROR state, but an IO or
  48548. ** malloc error occurs during a rollback, then this will itself cause
  48549. ** the pager to enter the ERROR state. Which will be cleared by the
  48550. ** call to pager_unlock(), as described above.
  48551. */
  48552. static void pagerUnlockAndRollback(Pager *pPager){
  48553. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  48554. assert( assert_pager_state(pPager) );
  48555. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  48556. sqlite3BeginBenignMalloc();
  48557. sqlite3PagerRollback(pPager);
  48558. sqlite3EndBenignMalloc();
  48559. }else if( !pPager->exclusiveMode ){
  48560. assert( pPager->eState==PAGER_READER );
  48561. pager_end_transaction(pPager, 0, 0);
  48562. }
  48563. }
  48564. pager_unlock(pPager);
  48565. }
  48566. /*
  48567. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  48568. ** of data. Compute and return a checksum based ont the contents of the
  48569. ** page of data and the current value of pPager->cksumInit.
  48570. **
  48571. ** This is not a real checksum. It is really just the sum of the
  48572. ** random initial value (pPager->cksumInit) and every 200th byte
  48573. ** of the page data, starting with byte offset (pPager->pageSize%200).
  48574. ** Each byte is interpreted as an 8-bit unsigned integer.
  48575. **
  48576. ** Changing the formula used to compute this checksum results in an
  48577. ** incompatible journal file format.
  48578. **
  48579. ** If journal corruption occurs due to a power failure, the most likely
  48580. ** scenario is that one end or the other of the record will be changed.
  48581. ** It is much less likely that the two ends of the journal record will be
  48582. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  48583. ** though fast and simple, catches the mostly likely kind of corruption.
  48584. */
  48585. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  48586. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  48587. int i = pPager->pageSize-200; /* Loop counter */
  48588. while( i>0 ){
  48589. cksum += aData[i];
  48590. i -= 200;
  48591. }
  48592. return cksum;
  48593. }
  48594. /*
  48595. ** Report the current page size and number of reserved bytes back
  48596. ** to the codec.
  48597. */
  48598. #ifdef SQLITE_HAS_CODEC
  48599. static void pagerReportSize(Pager *pPager){
  48600. if( pPager->xCodecSizeChng ){
  48601. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  48602. (int)pPager->nReserve);
  48603. }
  48604. }
  48605. #else
  48606. # define pagerReportSize(X) /* No-op if we do not support a codec */
  48607. #endif
  48608. #ifdef SQLITE_HAS_CODEC
  48609. /*
  48610. ** Make sure the number of reserved bits is the same in the destination
  48611. ** pager as it is in the source. This comes up when a VACUUM changes the
  48612. ** number of reserved bits to the "optimal" amount.
  48613. */
  48614. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  48615. if( pDest->nReserve!=pSrc->nReserve ){
  48616. pDest->nReserve = pSrc->nReserve;
  48617. pagerReportSize(pDest);
  48618. }
  48619. }
  48620. #endif
  48621. /*
  48622. ** Read a single page from either the journal file (if isMainJrnl==1) or
  48623. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  48624. ** The page begins at offset *pOffset into the file. The *pOffset
  48625. ** value is increased to the start of the next page in the journal.
  48626. **
  48627. ** The main rollback journal uses checksums - the statement journal does
  48628. ** not.
  48629. **
  48630. ** If the page number of the page record read from the (sub-)journal file
  48631. ** is greater than the current value of Pager.dbSize, then playback is
  48632. ** skipped and SQLITE_OK is returned.
  48633. **
  48634. ** If pDone is not NULL, then it is a record of pages that have already
  48635. ** been played back. If the page at *pOffset has already been played back
  48636. ** (if the corresponding pDone bit is set) then skip the playback.
  48637. ** Make sure the pDone bit corresponding to the *pOffset page is set
  48638. ** prior to returning.
  48639. **
  48640. ** If the page record is successfully read from the (sub-)journal file
  48641. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  48642. ** while reading the record from the (sub-)journal file or while writing
  48643. ** to the database file, then the IO error code is returned. If data
  48644. ** is successfully read from the (sub-)journal file but appears to be
  48645. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  48646. ** two circumstances:
  48647. **
  48648. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  48649. ** * If the record is being rolled back from the main journal file
  48650. ** and the checksum field does not match the record content.
  48651. **
  48652. ** Neither of these two scenarios are possible during a savepoint rollback.
  48653. **
  48654. ** If this is a savepoint rollback, then memory may have to be dynamically
  48655. ** allocated by this function. If this is the case and an allocation fails,
  48656. ** SQLITE_NOMEM is returned.
  48657. */
  48658. static int pager_playback_one_page(
  48659. Pager *pPager, /* The pager being played back */
  48660. i64 *pOffset, /* Offset of record to playback */
  48661. Bitvec *pDone, /* Bitvec of pages already played back */
  48662. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  48663. int isSavepnt /* True for a savepoint rollback */
  48664. ){
  48665. int rc;
  48666. PgHdr *pPg; /* An existing page in the cache */
  48667. Pgno pgno; /* The page number of a page in journal */
  48668. u32 cksum; /* Checksum used for sanity checking */
  48669. char *aData; /* Temporary storage for the page */
  48670. sqlite3_file *jfd; /* The file descriptor for the journal file */
  48671. int isSynced; /* True if journal page is synced */
  48672. #ifdef SQLITE_HAS_CODEC
  48673. /* The jrnlEnc flag is true if Journal pages should be passed through
  48674. ** the codec. It is false for pure in-memory journals. */
  48675. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  48676. #endif
  48677. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  48678. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  48679. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  48680. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  48681. aData = pPager->pTmpSpace;
  48682. assert( aData ); /* Temp storage must have already been allocated */
  48683. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  48684. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  48685. ** or savepoint rollback done at the request of the caller) or this is
  48686. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  48687. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  48688. ** only reads from the main journal, not the sub-journal.
  48689. */
  48690. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  48691. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  48692. );
  48693. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  48694. /* Read the page number and page data from the journal or sub-journal
  48695. ** file. Return an error code to the caller if an IO error occurs.
  48696. */
  48697. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  48698. rc = read32bits(jfd, *pOffset, &pgno);
  48699. if( rc!=SQLITE_OK ) return rc;
  48700. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  48701. if( rc!=SQLITE_OK ) return rc;
  48702. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  48703. /* Sanity checking on the page. This is more important that I originally
  48704. ** thought. If a power failure occurs while the journal is being written,
  48705. ** it could cause invalid data to be written into the journal. We need to
  48706. ** detect this invalid data (with high probability) and ignore it.
  48707. */
  48708. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  48709. assert( !isSavepnt );
  48710. return SQLITE_DONE;
  48711. }
  48712. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  48713. return SQLITE_OK;
  48714. }
  48715. if( isMainJrnl ){
  48716. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  48717. if( rc ) return rc;
  48718. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  48719. return SQLITE_DONE;
  48720. }
  48721. }
  48722. /* If this page has already been played back before during the current
  48723. ** rollback, then don't bother to play it back again.
  48724. */
  48725. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  48726. return rc;
  48727. }
  48728. /* When playing back page 1, restore the nReserve setting
  48729. */
  48730. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  48731. pPager->nReserve = ((u8*)aData)[20];
  48732. pagerReportSize(pPager);
  48733. }
  48734. /* If the pager is in CACHEMOD state, then there must be a copy of this
  48735. ** page in the pager cache. In this case just update the pager cache,
  48736. ** not the database file. The page is left marked dirty in this case.
  48737. **
  48738. ** An exception to the above rule: If the database is in no-sync mode
  48739. ** and a page is moved during an incremental vacuum then the page may
  48740. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  48741. ** during a Movepage() call, then the page may not be in the cache
  48742. ** either. So the condition described in the above paragraph is not
  48743. ** assert()able.
  48744. **
  48745. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  48746. ** pager cache if it exists and the main file. The page is then marked
  48747. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  48748. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  48749. ** if the pager is in OPEN state.
  48750. **
  48751. ** Ticket #1171: The statement journal might contain page content that is
  48752. ** different from the page content at the start of the transaction.
  48753. ** This occurs when a page is changed prior to the start of a statement
  48754. ** then changed again within the statement. When rolling back such a
  48755. ** statement we must not write to the original database unless we know
  48756. ** for certain that original page contents are synced into the main rollback
  48757. ** journal. Otherwise, a power loss might leave modified data in the
  48758. ** database file without an entry in the rollback journal that can
  48759. ** restore the database to its original form. Two conditions must be
  48760. ** met before writing to the database files. (1) the database must be
  48761. ** locked. (2) we know that the original page content is fully synced
  48762. ** in the main journal either because the page is not in cache or else
  48763. ** the page is marked as needSync==0.
  48764. **
  48765. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  48766. ** is possible to fail a statement on a database that does not yet exist.
  48767. ** Do not attempt to write if database file has never been opened.
  48768. */
  48769. if( pagerUseWal(pPager) ){
  48770. pPg = 0;
  48771. }else{
  48772. pPg = sqlite3PagerLookup(pPager, pgno);
  48773. }
  48774. assert( pPg || !MEMDB );
  48775. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  48776. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  48777. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  48778. (isMainJrnl?"main-journal":"sub-journal")
  48779. ));
  48780. if( isMainJrnl ){
  48781. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  48782. }else{
  48783. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  48784. }
  48785. if( isOpen(pPager->fd)
  48786. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  48787. && isSynced
  48788. ){
  48789. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  48790. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  48791. assert( !pagerUseWal(pPager) );
  48792. /* Write the data read from the journal back into the database file.
  48793. ** This is usually safe even for an encrypted database - as the data
  48794. ** was encrypted before it was written to the journal file. The exception
  48795. ** is if the data was just read from an in-memory sub-journal. In that
  48796. ** case it must be encrypted here before it is copied into the database
  48797. ** file. */
  48798. #ifdef SQLITE_HAS_CODEC
  48799. if( !jrnlEnc ){
  48800. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  48801. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  48802. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  48803. }else
  48804. #endif
  48805. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  48806. if( pgno>pPager->dbFileSize ){
  48807. pPager->dbFileSize = pgno;
  48808. }
  48809. if( pPager->pBackup ){
  48810. #ifdef SQLITE_HAS_CODEC
  48811. if( jrnlEnc ){
  48812. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  48813. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  48814. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  48815. }else
  48816. #endif
  48817. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  48818. }
  48819. }else if( !isMainJrnl && pPg==0 ){
  48820. /* If this is a rollback of a savepoint and data was not written to
  48821. ** the database and the page is not in-memory, there is a potential
  48822. ** problem. When the page is next fetched by the b-tree layer, it
  48823. ** will be read from the database file, which may or may not be
  48824. ** current.
  48825. **
  48826. ** There are a couple of different ways this can happen. All are quite
  48827. ** obscure. When running in synchronous mode, this can only happen
  48828. ** if the page is on the free-list at the start of the transaction, then
  48829. ** populated, then moved using sqlite3PagerMovepage().
  48830. **
  48831. ** The solution is to add an in-memory page to the cache containing
  48832. ** the data just read from the sub-journal. Mark the page as dirty
  48833. ** and if the pager requires a journal-sync, then mark the page as
  48834. ** requiring a journal-sync before it is written.
  48835. */
  48836. assert( isSavepnt );
  48837. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  48838. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  48839. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  48840. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  48841. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  48842. if( rc!=SQLITE_OK ) return rc;
  48843. sqlite3PcacheMakeDirty(pPg);
  48844. }
  48845. if( pPg ){
  48846. /* No page should ever be explicitly rolled back that is in use, except
  48847. ** for page 1 which is held in use in order to keep the lock on the
  48848. ** database active. However such a page may be rolled back as a result
  48849. ** of an internal error resulting in an automatic call to
  48850. ** sqlite3PagerRollback().
  48851. */
  48852. void *pData;
  48853. pData = pPg->pData;
  48854. memcpy(pData, (u8*)aData, pPager->pageSize);
  48855. pPager->xReiniter(pPg);
  48856. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  48857. ** that call was dangerous and had no detectable benefit since the cache
  48858. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  48859. ** has been removed. */
  48860. pager_set_pagehash(pPg);
  48861. /* If this was page 1, then restore the value of Pager.dbFileVers.
  48862. ** Do this before any decoding. */
  48863. if( pgno==1 ){
  48864. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  48865. }
  48866. /* Decode the page just read from disk */
  48867. #if SQLITE_HAS_CODEC
  48868. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  48869. #endif
  48870. sqlite3PcacheRelease(pPg);
  48871. }
  48872. return rc;
  48873. }
  48874. /*
  48875. ** Parameter zMaster is the name of a master journal file. A single journal
  48876. ** file that referred to the master journal file has just been rolled back.
  48877. ** This routine checks if it is possible to delete the master journal file,
  48878. ** and does so if it is.
  48879. **
  48880. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  48881. ** available for use within this function.
  48882. **
  48883. ** When a master journal file is created, it is populated with the names
  48884. ** of all of its child journals, one after another, formatted as utf-8
  48885. ** encoded text. The end of each child journal file is marked with a
  48886. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  48887. ** file for a transaction involving two databases might be:
  48888. **
  48889. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  48890. **
  48891. ** A master journal file may only be deleted once all of its child
  48892. ** journals have been rolled back.
  48893. **
  48894. ** This function reads the contents of the master-journal file into
  48895. ** memory and loops through each of the child journal names. For
  48896. ** each child journal, it checks if:
  48897. **
  48898. ** * if the child journal exists, and if so
  48899. ** * if the child journal contains a reference to master journal
  48900. ** file zMaster
  48901. **
  48902. ** If a child journal can be found that matches both of the criteria
  48903. ** above, this function returns without doing anything. Otherwise, if
  48904. ** no such child journal can be found, file zMaster is deleted from
  48905. ** the file-system using sqlite3OsDelete().
  48906. **
  48907. ** If an IO error within this function, an error code is returned. This
  48908. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  48909. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  48910. ** occur, SQLITE_OK is returned.
  48911. **
  48912. ** TODO: This function allocates a single block of memory to load
  48913. ** the entire contents of the master journal file. This could be
  48914. ** a couple of kilobytes or so - potentially larger than the page
  48915. ** size.
  48916. */
  48917. static int pager_delmaster(Pager *pPager, const char *zMaster){
  48918. sqlite3_vfs *pVfs = pPager->pVfs;
  48919. int rc; /* Return code */
  48920. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  48921. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  48922. char *zMasterJournal = 0; /* Contents of master journal file */
  48923. i64 nMasterJournal; /* Size of master journal file */
  48924. char *zJournal; /* Pointer to one journal within MJ file */
  48925. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  48926. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  48927. /* Allocate space for both the pJournal and pMaster file descriptors.
  48928. ** If successful, open the master journal file for reading.
  48929. */
  48930. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  48931. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  48932. if( !pMaster ){
  48933. rc = SQLITE_NOMEM_BKPT;
  48934. }else{
  48935. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  48936. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  48937. }
  48938. if( rc!=SQLITE_OK ) goto delmaster_out;
  48939. /* Load the entire master journal file into space obtained from
  48940. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  48941. ** sufficient space (in zMasterPtr) to hold the names of master
  48942. ** journal files extracted from regular rollback-journals.
  48943. */
  48944. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  48945. if( rc!=SQLITE_OK ) goto delmaster_out;
  48946. nMasterPtr = pVfs->mxPathname+1;
  48947. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  48948. if( !zMasterJournal ){
  48949. rc = SQLITE_NOMEM_BKPT;
  48950. goto delmaster_out;
  48951. }
  48952. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  48953. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  48954. if( rc!=SQLITE_OK ) goto delmaster_out;
  48955. zMasterJournal[nMasterJournal] = 0;
  48956. zJournal = zMasterJournal;
  48957. while( (zJournal-zMasterJournal)<nMasterJournal ){
  48958. int exists;
  48959. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  48960. if( rc!=SQLITE_OK ){
  48961. goto delmaster_out;
  48962. }
  48963. if( exists ){
  48964. /* One of the journals pointed to by the master journal exists.
  48965. ** Open it and check if it points at the master journal. If
  48966. ** so, return without deleting the master journal file.
  48967. */
  48968. int c;
  48969. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  48970. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  48971. if( rc!=SQLITE_OK ){
  48972. goto delmaster_out;
  48973. }
  48974. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  48975. sqlite3OsClose(pJournal);
  48976. if( rc!=SQLITE_OK ){
  48977. goto delmaster_out;
  48978. }
  48979. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  48980. if( c ){
  48981. /* We have a match. Do not delete the master journal file. */
  48982. goto delmaster_out;
  48983. }
  48984. }
  48985. zJournal += (sqlite3Strlen30(zJournal)+1);
  48986. }
  48987. sqlite3OsClose(pMaster);
  48988. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  48989. delmaster_out:
  48990. sqlite3_free(zMasterJournal);
  48991. if( pMaster ){
  48992. sqlite3OsClose(pMaster);
  48993. assert( !isOpen(pJournal) );
  48994. sqlite3_free(pMaster);
  48995. }
  48996. return rc;
  48997. }
  48998. /*
  48999. ** This function is used to change the actual size of the database
  49000. ** file in the file-system. This only happens when committing a transaction,
  49001. ** or rolling back a transaction (including rolling back a hot-journal).
  49002. **
  49003. ** If the main database file is not open, or the pager is not in either
  49004. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  49005. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  49006. ** If the file on disk is currently larger than nPage pages, then use the VFS
  49007. ** xTruncate() method to truncate it.
  49008. **
  49009. ** Or, it might be the case that the file on disk is smaller than
  49010. ** nPage pages. Some operating system implementations can get confused if
  49011. ** you try to truncate a file to some size that is larger than it
  49012. ** currently is, so detect this case and write a single zero byte to
  49013. ** the end of the new file instead.
  49014. **
  49015. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  49016. ** the database file, return the error code to the caller.
  49017. */
  49018. static int pager_truncate(Pager *pPager, Pgno nPage){
  49019. int rc = SQLITE_OK;
  49020. assert( pPager->eState!=PAGER_ERROR );
  49021. assert( pPager->eState!=PAGER_READER );
  49022. if( isOpen(pPager->fd)
  49023. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  49024. ){
  49025. i64 currentSize, newSize;
  49026. int szPage = pPager->pageSize;
  49027. assert( pPager->eLock==EXCLUSIVE_LOCK );
  49028. /* TODO: Is it safe to use Pager.dbFileSize here? */
  49029. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  49030. newSize = szPage*(i64)nPage;
  49031. if( rc==SQLITE_OK && currentSize!=newSize ){
  49032. if( currentSize>newSize ){
  49033. rc = sqlite3OsTruncate(pPager->fd, newSize);
  49034. }else if( (currentSize+szPage)<=newSize ){
  49035. char *pTmp = pPager->pTmpSpace;
  49036. memset(pTmp, 0, szPage);
  49037. testcase( (newSize-szPage) == currentSize );
  49038. testcase( (newSize-szPage) > currentSize );
  49039. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  49040. }
  49041. if( rc==SQLITE_OK ){
  49042. pPager->dbFileSize = nPage;
  49043. }
  49044. }
  49045. }
  49046. return rc;
  49047. }
  49048. /*
  49049. ** Return a sanitized version of the sector-size of OS file pFile. The
  49050. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  49051. */
  49052. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  49053. int iRet = sqlite3OsSectorSize(pFile);
  49054. if( iRet<32 ){
  49055. iRet = 512;
  49056. }else if( iRet>MAX_SECTOR_SIZE ){
  49057. assert( MAX_SECTOR_SIZE>=512 );
  49058. iRet = MAX_SECTOR_SIZE;
  49059. }
  49060. return iRet;
  49061. }
  49062. /*
  49063. ** Set the value of the Pager.sectorSize variable for the given
  49064. ** pager based on the value returned by the xSectorSize method
  49065. ** of the open database file. The sector size will be used
  49066. ** to determine the size and alignment of journal header and
  49067. ** master journal pointers within created journal files.
  49068. **
  49069. ** For temporary files the effective sector size is always 512 bytes.
  49070. **
  49071. ** Otherwise, for non-temporary files, the effective sector size is
  49072. ** the value returned by the xSectorSize() method rounded up to 32 if
  49073. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  49074. ** is greater than MAX_SECTOR_SIZE.
  49075. **
  49076. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  49077. ** the effective sector size to its minimum value (512). The purpose of
  49078. ** pPager->sectorSize is to define the "blast radius" of bytes that
  49079. ** might change if a crash occurs while writing to a single byte in
  49080. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  49081. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  49082. ** size. For backwards compatibility of the rollback journal file format,
  49083. ** we cannot reduce the effective sector size below 512.
  49084. */
  49085. static void setSectorSize(Pager *pPager){
  49086. assert( isOpen(pPager->fd) || pPager->tempFile );
  49087. if( pPager->tempFile
  49088. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  49089. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  49090. ){
  49091. /* Sector size doesn't matter for temporary files. Also, the file
  49092. ** may not have been opened yet, in which case the OsSectorSize()
  49093. ** call will segfault. */
  49094. pPager->sectorSize = 512;
  49095. }else{
  49096. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  49097. }
  49098. }
  49099. /*
  49100. ** Playback the journal and thus restore the database file to
  49101. ** the state it was in before we started making changes.
  49102. **
  49103. ** The journal file format is as follows:
  49104. **
  49105. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  49106. ** (2) 4 byte big-endian integer which is the number of valid page records
  49107. ** in the journal. If this value is 0xffffffff, then compute the
  49108. ** number of page records from the journal size.
  49109. ** (3) 4 byte big-endian integer which is the initial value for the
  49110. ** sanity checksum.
  49111. ** (4) 4 byte integer which is the number of pages to truncate the
  49112. ** database to during a rollback.
  49113. ** (5) 4 byte big-endian integer which is the sector size. The header
  49114. ** is this many bytes in size.
  49115. ** (6) 4 byte big-endian integer which is the page size.
  49116. ** (7) zero padding out to the next sector size.
  49117. ** (8) Zero or more pages instances, each as follows:
  49118. ** + 4 byte page number.
  49119. ** + pPager->pageSize bytes of data.
  49120. ** + 4 byte checksum
  49121. **
  49122. ** When we speak of the journal header, we mean the first 7 items above.
  49123. ** Each entry in the journal is an instance of the 8th item.
  49124. **
  49125. ** Call the value from the second bullet "nRec". nRec is the number of
  49126. ** valid page entries in the journal. In most cases, you can compute the
  49127. ** value of nRec from the size of the journal file. But if a power
  49128. ** failure occurred while the journal was being written, it could be the
  49129. ** case that the size of the journal file had already been increased but
  49130. ** the extra entries had not yet made it safely to disk. In such a case,
  49131. ** the value of nRec computed from the file size would be too large. For
  49132. ** that reason, we always use the nRec value in the header.
  49133. **
  49134. ** If the nRec value is 0xffffffff it means that nRec should be computed
  49135. ** from the file size. This value is used when the user selects the
  49136. ** no-sync option for the journal. A power failure could lead to corruption
  49137. ** in this case. But for things like temporary table (which will be
  49138. ** deleted when the power is restored) we don't care.
  49139. **
  49140. ** If the file opened as the journal file is not a well-formed
  49141. ** journal file then all pages up to the first corrupted page are rolled
  49142. ** back (or no pages if the journal header is corrupted). The journal file
  49143. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  49144. ** been encountered.
  49145. **
  49146. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  49147. ** and an error code is returned.
  49148. **
  49149. ** The isHot parameter indicates that we are trying to rollback a journal
  49150. ** that might be a hot journal. Or, it could be that the journal is
  49151. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  49152. ** If the journal really is hot, reset the pager cache prior rolling
  49153. ** back any content. If the journal is merely persistent, no reset is
  49154. ** needed.
  49155. */
  49156. static int pager_playback(Pager *pPager, int isHot){
  49157. sqlite3_vfs *pVfs = pPager->pVfs;
  49158. i64 szJ; /* Size of the journal file in bytes */
  49159. u32 nRec; /* Number of Records in the journal */
  49160. u32 u; /* Unsigned loop counter */
  49161. Pgno mxPg = 0; /* Size of the original file in pages */
  49162. int rc; /* Result code of a subroutine */
  49163. int res = 1; /* Value returned by sqlite3OsAccess() */
  49164. char *zMaster = 0; /* Name of master journal file if any */
  49165. int needPagerReset; /* True to reset page prior to first page rollback */
  49166. int nPlayback = 0; /* Total number of pages restored from journal */
  49167. u32 savedPageSize = pPager->pageSize;
  49168. /* Figure out how many records are in the journal. Abort early if
  49169. ** the journal is empty.
  49170. */
  49171. assert( isOpen(pPager->jfd) );
  49172. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  49173. if( rc!=SQLITE_OK ){
  49174. goto end_playback;
  49175. }
  49176. /* Read the master journal name from the journal, if it is present.
  49177. ** If a master journal file name is specified, but the file is not
  49178. ** present on disk, then the journal is not hot and does not need to be
  49179. ** played back.
  49180. **
  49181. ** TODO: Technically the following is an error because it assumes that
  49182. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  49183. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  49184. ** mxPathname is 512, which is the same as the minimum allowable value
  49185. ** for pageSize.
  49186. */
  49187. zMaster = pPager->pTmpSpace;
  49188. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  49189. if( rc==SQLITE_OK && zMaster[0] ){
  49190. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  49191. }
  49192. zMaster = 0;
  49193. if( rc!=SQLITE_OK || !res ){
  49194. goto end_playback;
  49195. }
  49196. pPager->journalOff = 0;
  49197. needPagerReset = isHot;
  49198. /* This loop terminates either when a readJournalHdr() or
  49199. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  49200. ** occurs.
  49201. */
  49202. while( 1 ){
  49203. /* Read the next journal header from the journal file. If there are
  49204. ** not enough bytes left in the journal file for a complete header, or
  49205. ** it is corrupted, then a process must have failed while writing it.
  49206. ** This indicates nothing more needs to be rolled back.
  49207. */
  49208. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  49209. if( rc!=SQLITE_OK ){
  49210. if( rc==SQLITE_DONE ){
  49211. rc = SQLITE_OK;
  49212. }
  49213. goto end_playback;
  49214. }
  49215. /* If nRec is 0xffffffff, then this journal was created by a process
  49216. ** working in no-sync mode. This means that the rest of the journal
  49217. ** file consists of pages, there are no more journal headers. Compute
  49218. ** the value of nRec based on this assumption.
  49219. */
  49220. if( nRec==0xffffffff ){
  49221. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  49222. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  49223. }
  49224. /* If nRec is 0 and this rollback is of a transaction created by this
  49225. ** process and if this is the final header in the journal, then it means
  49226. ** that this part of the journal was being filled but has not yet been
  49227. ** synced to disk. Compute the number of pages based on the remaining
  49228. ** size of the file.
  49229. **
  49230. ** The third term of the test was added to fix ticket #2565.
  49231. ** When rolling back a hot journal, nRec==0 always means that the next
  49232. ** chunk of the journal contains zero pages to be rolled back. But
  49233. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  49234. ** the journal, it means that the journal might contain additional
  49235. ** pages that need to be rolled back and that the number of pages
  49236. ** should be computed based on the journal file size.
  49237. */
  49238. if( nRec==0 && !isHot &&
  49239. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  49240. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  49241. }
  49242. /* If this is the first header read from the journal, truncate the
  49243. ** database file back to its original size.
  49244. */
  49245. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  49246. rc = pager_truncate(pPager, mxPg);
  49247. if( rc!=SQLITE_OK ){
  49248. goto end_playback;
  49249. }
  49250. pPager->dbSize = mxPg;
  49251. }
  49252. /* Copy original pages out of the journal and back into the
  49253. ** database file and/or page cache.
  49254. */
  49255. for(u=0; u<nRec; u++){
  49256. if( needPagerReset ){
  49257. pager_reset(pPager);
  49258. needPagerReset = 0;
  49259. }
  49260. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  49261. if( rc==SQLITE_OK ){
  49262. nPlayback++;
  49263. }else{
  49264. if( rc==SQLITE_DONE ){
  49265. pPager->journalOff = szJ;
  49266. break;
  49267. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  49268. /* If the journal has been truncated, simply stop reading and
  49269. ** processing the journal. This might happen if the journal was
  49270. ** not completely written and synced prior to a crash. In that
  49271. ** case, the database should have never been written in the
  49272. ** first place so it is OK to simply abandon the rollback. */
  49273. rc = SQLITE_OK;
  49274. goto end_playback;
  49275. }else{
  49276. /* If we are unable to rollback, quit and return the error
  49277. ** code. This will cause the pager to enter the error state
  49278. ** so that no further harm will be done. Perhaps the next
  49279. ** process to come along will be able to rollback the database.
  49280. */
  49281. goto end_playback;
  49282. }
  49283. }
  49284. }
  49285. }
  49286. /*NOTREACHED*/
  49287. assert( 0 );
  49288. end_playback:
  49289. if( rc==SQLITE_OK ){
  49290. rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
  49291. }
  49292. /* Following a rollback, the database file should be back in its original
  49293. ** state prior to the start of the transaction, so invoke the
  49294. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  49295. ** assertion that the transaction counter was modified.
  49296. */
  49297. #ifdef SQLITE_DEBUG
  49298. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  49299. #endif
  49300. /* If this playback is happening automatically as a result of an IO or
  49301. ** malloc error that occurred after the change-counter was updated but
  49302. ** before the transaction was committed, then the change-counter
  49303. ** modification may just have been reverted. If this happens in exclusive
  49304. ** mode, then subsequent transactions performed by the connection will not
  49305. ** update the change-counter at all. This may lead to cache inconsistency
  49306. ** problems for other processes at some point in the future. So, just
  49307. ** in case this has happened, clear the changeCountDone flag now.
  49308. */
  49309. pPager->changeCountDone = pPager->tempFile;
  49310. if( rc==SQLITE_OK ){
  49311. zMaster = pPager->pTmpSpace;
  49312. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  49313. testcase( rc!=SQLITE_OK );
  49314. }
  49315. if( rc==SQLITE_OK
  49316. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  49317. ){
  49318. rc = sqlite3PagerSync(pPager, 0);
  49319. }
  49320. if( rc==SQLITE_OK ){
  49321. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  49322. testcase( rc!=SQLITE_OK );
  49323. }
  49324. if( rc==SQLITE_OK && zMaster[0] && res ){
  49325. /* If there was a master journal and this routine will return success,
  49326. ** see if it is possible to delete the master journal.
  49327. */
  49328. rc = pager_delmaster(pPager, zMaster);
  49329. testcase( rc!=SQLITE_OK );
  49330. }
  49331. if( isHot && nPlayback ){
  49332. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  49333. nPlayback, pPager->zJournal);
  49334. }
  49335. /* The Pager.sectorSize variable may have been updated while rolling
  49336. ** back a journal created by a process with a different sector size
  49337. ** value. Reset it to the correct value for this process.
  49338. */
  49339. setSectorSize(pPager);
  49340. return rc;
  49341. }
  49342. /*
  49343. ** Read the content for page pPg out of the database file (or out of
  49344. ** the WAL if that is where the most recent copy if found) into
  49345. ** pPg->pData. A shared lock or greater must be held on the database
  49346. ** file before this function is called.
  49347. **
  49348. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  49349. ** the value read from the database file.
  49350. **
  49351. ** If an IO error occurs, then the IO error is returned to the caller.
  49352. ** Otherwise, SQLITE_OK is returned.
  49353. */
  49354. static int readDbPage(PgHdr *pPg){
  49355. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  49356. int rc = SQLITE_OK; /* Return code */
  49357. #ifndef SQLITE_OMIT_WAL
  49358. u32 iFrame = 0; /* Frame of WAL containing pgno */
  49359. assert( pPager->eState>=PAGER_READER && !MEMDB );
  49360. assert( isOpen(pPager->fd) );
  49361. if( pagerUseWal(pPager) ){
  49362. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  49363. if( rc ) return rc;
  49364. }
  49365. if( iFrame ){
  49366. rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
  49367. }else
  49368. #endif
  49369. {
  49370. i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
  49371. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  49372. if( rc==SQLITE_IOERR_SHORT_READ ){
  49373. rc = SQLITE_OK;
  49374. }
  49375. }
  49376. if( pPg->pgno==1 ){
  49377. if( rc ){
  49378. /* If the read is unsuccessful, set the dbFileVers[] to something
  49379. ** that will never be a valid file version. dbFileVers[] is a copy
  49380. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  49381. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  49382. ** should be page numbers which are never 0xffffffff. So filling
  49383. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  49384. **
  49385. ** For an encrypted database, the situation is more complex: bytes
  49386. ** 24..39 of the database are white noise. But the probability of
  49387. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  49388. ** we should still be ok.
  49389. */
  49390. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  49391. }else{
  49392. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  49393. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  49394. }
  49395. }
  49396. CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
  49397. PAGER_INCR(sqlite3_pager_readdb_count);
  49398. PAGER_INCR(pPager->nRead);
  49399. IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
  49400. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  49401. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  49402. return rc;
  49403. }
  49404. /*
  49405. ** Update the value of the change-counter at offsets 24 and 92 in
  49406. ** the header and the sqlite version number at offset 96.
  49407. **
  49408. ** This is an unconditional update. See also the pager_incr_changecounter()
  49409. ** routine which only updates the change-counter if the update is actually
  49410. ** needed, as determined by the pPager->changeCountDone state variable.
  49411. */
  49412. static void pager_write_changecounter(PgHdr *pPg){
  49413. u32 change_counter;
  49414. /* Increment the value just read and write it back to byte 24. */
  49415. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  49416. put32bits(((char*)pPg->pData)+24, change_counter);
  49417. /* Also store the SQLite version number in bytes 96..99 and in
  49418. ** bytes 92..95 store the change counter for which the version number
  49419. ** is valid. */
  49420. put32bits(((char*)pPg->pData)+92, change_counter);
  49421. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  49422. }
  49423. #ifndef SQLITE_OMIT_WAL
  49424. /*
  49425. ** This function is invoked once for each page that has already been
  49426. ** written into the log file when a WAL transaction is rolled back.
  49427. ** Parameter iPg is the page number of said page. The pCtx argument
  49428. ** is actually a pointer to the Pager structure.
  49429. **
  49430. ** If page iPg is present in the cache, and has no outstanding references,
  49431. ** it is discarded. Otherwise, if there are one or more outstanding
  49432. ** references, the page content is reloaded from the database. If the
  49433. ** attempt to reload content from the database is required and fails,
  49434. ** return an SQLite error code. Otherwise, SQLITE_OK.
  49435. */
  49436. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  49437. int rc = SQLITE_OK;
  49438. Pager *pPager = (Pager *)pCtx;
  49439. PgHdr *pPg;
  49440. assert( pagerUseWal(pPager) );
  49441. pPg = sqlite3PagerLookup(pPager, iPg);
  49442. if( pPg ){
  49443. if( sqlite3PcachePageRefcount(pPg)==1 ){
  49444. sqlite3PcacheDrop(pPg);
  49445. }else{
  49446. rc = readDbPage(pPg);
  49447. if( rc==SQLITE_OK ){
  49448. pPager->xReiniter(pPg);
  49449. }
  49450. sqlite3PagerUnrefNotNull(pPg);
  49451. }
  49452. }
  49453. /* Normally, if a transaction is rolled back, any backup processes are
  49454. ** updated as data is copied out of the rollback journal and into the
  49455. ** database. This is not generally possible with a WAL database, as
  49456. ** rollback involves simply truncating the log file. Therefore, if one
  49457. ** or more frames have already been written to the log (and therefore
  49458. ** also copied into the backup databases) as part of this transaction,
  49459. ** the backups must be restarted.
  49460. */
  49461. sqlite3BackupRestart(pPager->pBackup);
  49462. return rc;
  49463. }
  49464. /*
  49465. ** This function is called to rollback a transaction on a WAL database.
  49466. */
  49467. static int pagerRollbackWal(Pager *pPager){
  49468. int rc; /* Return Code */
  49469. PgHdr *pList; /* List of dirty pages to revert */
  49470. /* For all pages in the cache that are currently dirty or have already
  49471. ** been written (but not committed) to the log file, do one of the
  49472. ** following:
  49473. **
  49474. ** + Discard the cached page (if refcount==0), or
  49475. ** + Reload page content from the database (if refcount>0).
  49476. */
  49477. pPager->dbSize = pPager->dbOrigSize;
  49478. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  49479. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  49480. while( pList && rc==SQLITE_OK ){
  49481. PgHdr *pNext = pList->pDirty;
  49482. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  49483. pList = pNext;
  49484. }
  49485. return rc;
  49486. }
  49487. /*
  49488. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  49489. ** the contents of the list of pages headed by pList (connected by pDirty),
  49490. ** this function notifies any active backup processes that the pages have
  49491. ** changed.
  49492. **
  49493. ** The list of pages passed into this routine is always sorted by page number.
  49494. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  49495. */
  49496. static int pagerWalFrames(
  49497. Pager *pPager, /* Pager object */
  49498. PgHdr *pList, /* List of frames to log */
  49499. Pgno nTruncate, /* Database size after this commit */
  49500. int isCommit /* True if this is a commit */
  49501. ){
  49502. int rc; /* Return code */
  49503. int nList; /* Number of pages in pList */
  49504. PgHdr *p; /* For looping over pages */
  49505. assert( pPager->pWal );
  49506. assert( pList );
  49507. #ifdef SQLITE_DEBUG
  49508. /* Verify that the page list is in accending order */
  49509. for(p=pList; p && p->pDirty; p=p->pDirty){
  49510. assert( p->pgno < p->pDirty->pgno );
  49511. }
  49512. #endif
  49513. assert( pList->pDirty==0 || isCommit );
  49514. if( isCommit ){
  49515. /* If a WAL transaction is being committed, there is no point in writing
  49516. ** any pages with page numbers greater than nTruncate into the WAL file.
  49517. ** They will never be read by any client. So remove them from the pDirty
  49518. ** list here. */
  49519. PgHdr **ppNext = &pList;
  49520. nList = 0;
  49521. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  49522. if( p->pgno<=nTruncate ){
  49523. ppNext = &p->pDirty;
  49524. nList++;
  49525. }
  49526. }
  49527. assert( pList );
  49528. }else{
  49529. nList = 1;
  49530. }
  49531. pPager->aStat[PAGER_STAT_WRITE] += nList;
  49532. if( pList->pgno==1 ) pager_write_changecounter(pList);
  49533. rc = sqlite3WalFrames(pPager->pWal,
  49534. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  49535. );
  49536. if( rc==SQLITE_OK && pPager->pBackup ){
  49537. for(p=pList; p; p=p->pDirty){
  49538. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  49539. }
  49540. }
  49541. #ifdef SQLITE_CHECK_PAGES
  49542. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  49543. for(p=pList; p; p=p->pDirty){
  49544. pager_set_pagehash(p);
  49545. }
  49546. #endif
  49547. return rc;
  49548. }
  49549. /*
  49550. ** Begin a read transaction on the WAL.
  49551. **
  49552. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  49553. ** makes a snapshot of the database at the current point in time and preserves
  49554. ** that snapshot for use by the reader in spite of concurrently changes by
  49555. ** other writers or checkpointers.
  49556. */
  49557. static int pagerBeginReadTransaction(Pager *pPager){
  49558. int rc; /* Return code */
  49559. int changed = 0; /* True if cache must be reset */
  49560. assert( pagerUseWal(pPager) );
  49561. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  49562. /* sqlite3WalEndReadTransaction() was not called for the previous
  49563. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  49564. ** are in locking_mode=NORMAL and EndRead() was previously called,
  49565. ** the duplicate call is harmless.
  49566. */
  49567. sqlite3WalEndReadTransaction(pPager->pWal);
  49568. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  49569. if( rc!=SQLITE_OK || changed ){
  49570. pager_reset(pPager);
  49571. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  49572. }
  49573. return rc;
  49574. }
  49575. #endif
  49576. /*
  49577. ** This function is called as part of the transition from PAGER_OPEN
  49578. ** to PAGER_READER state to determine the size of the database file
  49579. ** in pages (assuming the page size currently stored in Pager.pageSize).
  49580. **
  49581. ** If no error occurs, SQLITE_OK is returned and the size of the database
  49582. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  49583. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  49584. */
  49585. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  49586. Pgno nPage; /* Value to return via *pnPage */
  49587. /* Query the WAL sub-system for the database size. The WalDbsize()
  49588. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  49589. ** if the database size is not available. The database size is not
  49590. ** available from the WAL sub-system if the log file is empty or
  49591. ** contains no valid committed transactions.
  49592. */
  49593. assert( pPager->eState==PAGER_OPEN );
  49594. assert( pPager->eLock>=SHARED_LOCK );
  49595. assert( isOpen(pPager->fd) );
  49596. assert( pPager->tempFile==0 );
  49597. nPage = sqlite3WalDbsize(pPager->pWal);
  49598. /* If the number of pages in the database is not available from the
  49599. ** WAL sub-system, determine the page count based on the size of
  49600. ** the database file. If the size of the database file is not an
  49601. ** integer multiple of the page-size, round up the result.
  49602. */
  49603. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  49604. i64 n = 0; /* Size of db file in bytes */
  49605. int rc = sqlite3OsFileSize(pPager->fd, &n);
  49606. if( rc!=SQLITE_OK ){
  49607. return rc;
  49608. }
  49609. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  49610. }
  49611. /* If the current number of pages in the file is greater than the
  49612. ** configured maximum pager number, increase the allowed limit so
  49613. ** that the file can be read.
  49614. */
  49615. if( nPage>pPager->mxPgno ){
  49616. pPager->mxPgno = (Pgno)nPage;
  49617. }
  49618. *pnPage = nPage;
  49619. return SQLITE_OK;
  49620. }
  49621. #ifndef SQLITE_OMIT_WAL
  49622. /*
  49623. ** Check if the *-wal file that corresponds to the database opened by pPager
  49624. ** exists if the database is not empy, or verify that the *-wal file does
  49625. ** not exist (by deleting it) if the database file is empty.
  49626. **
  49627. ** If the database is not empty and the *-wal file exists, open the pager
  49628. ** in WAL mode. If the database is empty or if no *-wal file exists and
  49629. ** if no error occurs, make sure Pager.journalMode is not set to
  49630. ** PAGER_JOURNALMODE_WAL.
  49631. **
  49632. ** Return SQLITE_OK or an error code.
  49633. **
  49634. ** The caller must hold a SHARED lock on the database file to call this
  49635. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  49636. ** a WAL on a none-empty database, this ensures there is no race condition
  49637. ** between the xAccess() below and an xDelete() being executed by some
  49638. ** other connection.
  49639. */
  49640. static int pagerOpenWalIfPresent(Pager *pPager){
  49641. int rc = SQLITE_OK;
  49642. assert( pPager->eState==PAGER_OPEN );
  49643. assert( pPager->eLock>=SHARED_LOCK );
  49644. if( !pPager->tempFile ){
  49645. int isWal; /* True if WAL file exists */
  49646. rc = sqlite3OsAccess(
  49647. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  49648. );
  49649. if( rc==SQLITE_OK ){
  49650. if( isWal ){
  49651. Pgno nPage; /* Size of the database file */
  49652. rc = pagerPagecount(pPager, &nPage);
  49653. if( rc ) return rc;
  49654. if( nPage==0 ){
  49655. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  49656. }else{
  49657. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  49658. rc = sqlite3PagerOpenWal(pPager, 0);
  49659. }
  49660. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  49661. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  49662. }
  49663. }
  49664. }
  49665. return rc;
  49666. }
  49667. #endif
  49668. /*
  49669. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  49670. ** the entire master journal file. The case pSavepoint==NULL occurs when
  49671. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  49672. ** savepoint.
  49673. **
  49674. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  49675. ** being rolled back), then the rollback consists of up to three stages,
  49676. ** performed in the order specified:
  49677. **
  49678. ** * Pages are played back from the main journal starting at byte
  49679. ** offset PagerSavepoint.iOffset and continuing to
  49680. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  49681. ** file if PagerSavepoint.iHdrOffset is zero.
  49682. **
  49683. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  49684. ** back starting from the journal header immediately following
  49685. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  49686. **
  49687. ** * Pages are then played back from the sub-journal file, starting
  49688. ** with the PagerSavepoint.iSubRec and continuing to the end of
  49689. ** the journal file.
  49690. **
  49691. ** Throughout the rollback process, each time a page is rolled back, the
  49692. ** corresponding bit is set in a bitvec structure (variable pDone in the
  49693. ** implementation below). This is used to ensure that a page is only
  49694. ** rolled back the first time it is encountered in either journal.
  49695. **
  49696. ** If pSavepoint is NULL, then pages are only played back from the main
  49697. ** journal file. There is no need for a bitvec in this case.
  49698. **
  49699. ** In either case, before playback commences the Pager.dbSize variable
  49700. ** is reset to the value that it held at the start of the savepoint
  49701. ** (or transaction). No page with a page-number greater than this value
  49702. ** is played back. If one is encountered it is simply skipped.
  49703. */
  49704. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  49705. i64 szJ; /* Effective size of the main journal */
  49706. i64 iHdrOff; /* End of first segment of main-journal records */
  49707. int rc = SQLITE_OK; /* Return code */
  49708. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  49709. assert( pPager->eState!=PAGER_ERROR );
  49710. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  49711. /* Allocate a bitvec to use to store the set of pages rolled back */
  49712. if( pSavepoint ){
  49713. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  49714. if( !pDone ){
  49715. return SQLITE_NOMEM_BKPT;
  49716. }
  49717. }
  49718. /* Set the database size back to the value it was before the savepoint
  49719. ** being reverted was opened.
  49720. */
  49721. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  49722. pPager->changeCountDone = pPager->tempFile;
  49723. if( !pSavepoint && pagerUseWal(pPager) ){
  49724. return pagerRollbackWal(pPager);
  49725. }
  49726. /* Use pPager->journalOff as the effective size of the main rollback
  49727. ** journal. The actual file might be larger than this in
  49728. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  49729. ** past pPager->journalOff is off-limits to us.
  49730. */
  49731. szJ = pPager->journalOff;
  49732. assert( pagerUseWal(pPager)==0 || szJ==0 );
  49733. /* Begin by rolling back records from the main journal starting at
  49734. ** PagerSavepoint.iOffset and continuing to the next journal header.
  49735. ** There might be records in the main journal that have a page number
  49736. ** greater than the current database size (pPager->dbSize) but those
  49737. ** will be skipped automatically. Pages are added to pDone as they
  49738. ** are played back.
  49739. */
  49740. if( pSavepoint && !pagerUseWal(pPager) ){
  49741. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  49742. pPager->journalOff = pSavepoint->iOffset;
  49743. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  49744. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  49745. }
  49746. assert( rc!=SQLITE_DONE );
  49747. }else{
  49748. pPager->journalOff = 0;
  49749. }
  49750. /* Continue rolling back records out of the main journal starting at
  49751. ** the first journal header seen and continuing until the effective end
  49752. ** of the main journal file. Continue to skip out-of-range pages and
  49753. ** continue adding pages rolled back to pDone.
  49754. */
  49755. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  49756. u32 ii; /* Loop counter */
  49757. u32 nJRec = 0; /* Number of Journal Records */
  49758. u32 dummy;
  49759. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  49760. assert( rc!=SQLITE_DONE );
  49761. /*
  49762. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  49763. ** test is related to ticket #2565. See the discussion in the
  49764. ** pager_playback() function for additional information.
  49765. */
  49766. if( nJRec==0
  49767. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  49768. ){
  49769. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  49770. }
  49771. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  49772. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  49773. }
  49774. assert( rc!=SQLITE_DONE );
  49775. }
  49776. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  49777. /* Finally, rollback pages from the sub-journal. Page that were
  49778. ** previously rolled back out of the main journal (and are hence in pDone)
  49779. ** will be skipped. Out-of-range pages are also skipped.
  49780. */
  49781. if( pSavepoint ){
  49782. u32 ii; /* Loop counter */
  49783. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  49784. if( pagerUseWal(pPager) ){
  49785. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  49786. }
  49787. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  49788. assert( offset==(i64)ii*(4+pPager->pageSize) );
  49789. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  49790. }
  49791. assert( rc!=SQLITE_DONE );
  49792. }
  49793. sqlite3BitvecDestroy(pDone);
  49794. if( rc==SQLITE_OK ){
  49795. pPager->journalOff = szJ;
  49796. }
  49797. return rc;
  49798. }
  49799. /*
  49800. ** Change the maximum number of in-memory pages that are allowed
  49801. ** before attempting to recycle clean and unused pages.
  49802. */
  49803. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  49804. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  49805. }
  49806. /*
  49807. ** Change the maximum number of in-memory pages that are allowed
  49808. ** before attempting to spill pages to journal.
  49809. */
  49810. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  49811. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  49812. }
  49813. /*
  49814. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  49815. */
  49816. static void pagerFixMaplimit(Pager *pPager){
  49817. #if SQLITE_MAX_MMAP_SIZE>0
  49818. sqlite3_file *fd = pPager->fd;
  49819. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  49820. sqlite3_int64 sz;
  49821. sz = pPager->szMmap;
  49822. pPager->bUseFetch = (sz>0);
  49823. setGetterMethod(pPager);
  49824. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  49825. }
  49826. #endif
  49827. }
  49828. /*
  49829. ** Change the maximum size of any memory mapping made of the database file.
  49830. */
  49831. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  49832. pPager->szMmap = szMmap;
  49833. pagerFixMaplimit(pPager);
  49834. }
  49835. /*
  49836. ** Free as much memory as possible from the pager.
  49837. */
  49838. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  49839. sqlite3PcacheShrink(pPager->pPCache);
  49840. }
  49841. /*
  49842. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  49843. **
  49844. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  49845. ** of the database to damage due to OS crashes or power failures by
  49846. ** changing the number of syncs()s when writing the journals.
  49847. ** There are four levels:
  49848. **
  49849. ** OFF sqlite3OsSync() is never called. This is the default
  49850. ** for temporary and transient files.
  49851. **
  49852. ** NORMAL The journal is synced once before writes begin on the
  49853. ** database. This is normally adequate protection, but
  49854. ** it is theoretically possible, though very unlikely,
  49855. ** that an inopertune power failure could leave the journal
  49856. ** in a state which would cause damage to the database
  49857. ** when it is rolled back.
  49858. **
  49859. ** FULL The journal is synced twice before writes begin on the
  49860. ** database (with some additional information - the nRec field
  49861. ** of the journal header - being written in between the two
  49862. ** syncs). If we assume that writing a
  49863. ** single disk sector is atomic, then this mode provides
  49864. ** assurance that the journal will not be corrupted to the
  49865. ** point of causing damage to the database during rollback.
  49866. **
  49867. ** EXTRA This is like FULL except that is also syncs the directory
  49868. ** that contains the rollback journal after the rollback
  49869. ** journal is unlinked.
  49870. **
  49871. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  49872. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  49873. ** prior to the start of checkpoint and that the database file is synced
  49874. ** at the conclusion of the checkpoint if the entire content of the WAL
  49875. ** was written back into the database. But no sync operations occur for
  49876. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  49877. ** file is synced following each commit operation, in addition to the
  49878. ** syncs associated with NORMAL. There is no difference between FULL
  49879. ** and EXTRA for WAL mode.
  49880. **
  49881. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  49882. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  49883. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  49884. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  49885. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  49886. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  49887. ** the xSync primitive is called and is relevant to all platforms.
  49888. **
  49889. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  49890. ** and FULL=3.
  49891. */
  49892. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  49893. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  49894. Pager *pPager, /* The pager to set safety level for */
  49895. unsigned pgFlags /* Various flags */
  49896. ){
  49897. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  49898. if( pPager->tempFile ){
  49899. pPager->noSync = 1;
  49900. pPager->fullSync = 0;
  49901. pPager->extraSync = 0;
  49902. }else{
  49903. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  49904. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  49905. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  49906. }
  49907. if( pPager->noSync ){
  49908. pPager->syncFlags = 0;
  49909. }else if( pgFlags & PAGER_FULLFSYNC ){
  49910. pPager->syncFlags = SQLITE_SYNC_FULL;
  49911. }else{
  49912. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  49913. }
  49914. pPager->walSyncFlags = (pPager->syncFlags<<2);
  49915. if( pPager->fullSync ){
  49916. pPager->walSyncFlags |= pPager->syncFlags;
  49917. }
  49918. if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
  49919. pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
  49920. }
  49921. if( pgFlags & PAGER_CACHESPILL ){
  49922. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  49923. }else{
  49924. pPager->doNotSpill |= SPILLFLAG_OFF;
  49925. }
  49926. }
  49927. #endif
  49928. /*
  49929. ** The following global variable is incremented whenever the library
  49930. ** attempts to open a temporary file. This information is used for
  49931. ** testing and analysis only.
  49932. */
  49933. #ifdef SQLITE_TEST
  49934. SQLITE_API int sqlite3_opentemp_count = 0;
  49935. #endif
  49936. /*
  49937. ** Open a temporary file.
  49938. **
  49939. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  49940. ** or some other error code if we fail. The OS will automatically
  49941. ** delete the temporary file when it is closed.
  49942. **
  49943. ** The flags passed to the VFS layer xOpen() call are those specified
  49944. ** by parameter vfsFlags ORed with the following:
  49945. **
  49946. ** SQLITE_OPEN_READWRITE
  49947. ** SQLITE_OPEN_CREATE
  49948. ** SQLITE_OPEN_EXCLUSIVE
  49949. ** SQLITE_OPEN_DELETEONCLOSE
  49950. */
  49951. static int pagerOpentemp(
  49952. Pager *pPager, /* The pager object */
  49953. sqlite3_file *pFile, /* Write the file descriptor here */
  49954. int vfsFlags /* Flags passed through to the VFS */
  49955. ){
  49956. int rc; /* Return code */
  49957. #ifdef SQLITE_TEST
  49958. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  49959. #endif
  49960. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  49961. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  49962. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  49963. assert( rc!=SQLITE_OK || isOpen(pFile) );
  49964. return rc;
  49965. }
  49966. /*
  49967. ** Set the busy handler function.
  49968. **
  49969. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  49970. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  49971. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  49972. ** lock. It does *not* invoke the busy handler when upgrading from
  49973. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  49974. ** (which occurs during hot-journal rollback). Summary:
  49975. **
  49976. ** Transition | Invokes xBusyHandler
  49977. ** --------------------------------------------------------
  49978. ** NO_LOCK -> SHARED_LOCK | Yes
  49979. ** SHARED_LOCK -> RESERVED_LOCK | No
  49980. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  49981. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  49982. **
  49983. ** If the busy-handler callback returns non-zero, the lock is
  49984. ** retried. If it returns zero, then the SQLITE_BUSY error is
  49985. ** returned to the caller of the pager API function.
  49986. */
  49987. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
  49988. Pager *pPager, /* Pager object */
  49989. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  49990. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  49991. ){
  49992. void **ap;
  49993. pPager->xBusyHandler = xBusyHandler;
  49994. pPager->pBusyHandlerArg = pBusyHandlerArg;
  49995. ap = (void **)&pPager->xBusyHandler;
  49996. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  49997. assert( ap[1]==pBusyHandlerArg );
  49998. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  49999. }
  50000. /*
  50001. ** Change the page size used by the Pager object. The new page size
  50002. ** is passed in *pPageSize.
  50003. **
  50004. ** If the pager is in the error state when this function is called, it
  50005. ** is a no-op. The value returned is the error state error code (i.e.
  50006. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  50007. **
  50008. ** Otherwise, if all of the following are true:
  50009. **
  50010. ** * the new page size (value of *pPageSize) is valid (a power
  50011. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  50012. **
  50013. ** * there are no outstanding page references, and
  50014. **
  50015. ** * the database is either not an in-memory database or it is
  50016. ** an in-memory database that currently consists of zero pages.
  50017. **
  50018. ** then the pager object page size is set to *pPageSize.
  50019. **
  50020. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  50021. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  50022. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  50023. ** In all other cases, SQLITE_OK is returned.
  50024. **
  50025. ** If the page size is not changed, either because one of the enumerated
  50026. ** conditions above is not true, the pager was in error state when this
  50027. ** function was called, or because the memory allocation attempt failed,
  50028. ** then *pPageSize is set to the old, retained page size before returning.
  50029. */
  50030. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  50031. int rc = SQLITE_OK;
  50032. /* It is not possible to do a full assert_pager_state() here, as this
  50033. ** function may be called from within PagerOpen(), before the state
  50034. ** of the Pager object is internally consistent.
  50035. **
  50036. ** At one point this function returned an error if the pager was in
  50037. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  50038. ** there is at least one outstanding page reference, this function
  50039. ** is a no-op for that case anyhow.
  50040. */
  50041. u32 pageSize = *pPageSize;
  50042. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  50043. if( (pPager->memDb==0 || pPager->dbSize==0)
  50044. && sqlite3PcacheRefCount(pPager->pPCache)==0
  50045. && pageSize && pageSize!=(u32)pPager->pageSize
  50046. ){
  50047. char *pNew = NULL; /* New temp space */
  50048. i64 nByte = 0;
  50049. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  50050. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  50051. }
  50052. if( rc==SQLITE_OK ){
  50053. pNew = (char *)sqlite3PageMalloc(pageSize);
  50054. if( !pNew ) rc = SQLITE_NOMEM_BKPT;
  50055. }
  50056. if( rc==SQLITE_OK ){
  50057. pager_reset(pPager);
  50058. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  50059. }
  50060. if( rc==SQLITE_OK ){
  50061. sqlite3PageFree(pPager->pTmpSpace);
  50062. pPager->pTmpSpace = pNew;
  50063. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  50064. pPager->pageSize = pageSize;
  50065. }else{
  50066. sqlite3PageFree(pNew);
  50067. }
  50068. }
  50069. *pPageSize = pPager->pageSize;
  50070. if( rc==SQLITE_OK ){
  50071. if( nReserve<0 ) nReserve = pPager->nReserve;
  50072. assert( nReserve>=0 && nReserve<1000 );
  50073. pPager->nReserve = (i16)nReserve;
  50074. pagerReportSize(pPager);
  50075. pagerFixMaplimit(pPager);
  50076. }
  50077. return rc;
  50078. }
  50079. /*
  50080. ** Return a pointer to the "temporary page" buffer held internally
  50081. ** by the pager. This is a buffer that is big enough to hold the
  50082. ** entire content of a database page. This buffer is used internally
  50083. ** during rollback and will be overwritten whenever a rollback
  50084. ** occurs. But other modules are free to use it too, as long as
  50085. ** no rollbacks are happening.
  50086. */
  50087. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  50088. return pPager->pTmpSpace;
  50089. }
  50090. /*
  50091. ** Attempt to set the maximum database page count if mxPage is positive.
  50092. ** Make no changes if mxPage is zero or negative. And never reduce the
  50093. ** maximum page count below the current size of the database.
  50094. **
  50095. ** Regardless of mxPage, return the current maximum page count.
  50096. */
  50097. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  50098. if( mxPage>0 ){
  50099. pPager->mxPgno = mxPage;
  50100. }
  50101. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  50102. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  50103. return pPager->mxPgno;
  50104. }
  50105. /*
  50106. ** The following set of routines are used to disable the simulated
  50107. ** I/O error mechanism. These routines are used to avoid simulated
  50108. ** errors in places where we do not care about errors.
  50109. **
  50110. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  50111. ** and generate no code.
  50112. */
  50113. #ifdef SQLITE_TEST
  50114. SQLITE_API extern int sqlite3_io_error_pending;
  50115. SQLITE_API extern int sqlite3_io_error_hit;
  50116. static int saved_cnt;
  50117. void disable_simulated_io_errors(void){
  50118. saved_cnt = sqlite3_io_error_pending;
  50119. sqlite3_io_error_pending = -1;
  50120. }
  50121. void enable_simulated_io_errors(void){
  50122. sqlite3_io_error_pending = saved_cnt;
  50123. }
  50124. #else
  50125. # define disable_simulated_io_errors()
  50126. # define enable_simulated_io_errors()
  50127. #endif
  50128. /*
  50129. ** Read the first N bytes from the beginning of the file into memory
  50130. ** that pDest points to.
  50131. **
  50132. ** If the pager was opened on a transient file (zFilename==""), or
  50133. ** opened on a file less than N bytes in size, the output buffer is
  50134. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  50135. ** function is used to read database headers, and a new transient or
  50136. ** zero sized database has a header than consists entirely of zeroes.
  50137. **
  50138. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  50139. ** the error code is returned to the caller and the contents of the
  50140. ** output buffer undefined.
  50141. */
  50142. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  50143. int rc = SQLITE_OK;
  50144. memset(pDest, 0, N);
  50145. assert( isOpen(pPager->fd) || pPager->tempFile );
  50146. /* This routine is only called by btree immediately after creating
  50147. ** the Pager object. There has not been an opportunity to transition
  50148. ** to WAL mode yet.
  50149. */
  50150. assert( !pagerUseWal(pPager) );
  50151. if( isOpen(pPager->fd) ){
  50152. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  50153. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  50154. if( rc==SQLITE_IOERR_SHORT_READ ){
  50155. rc = SQLITE_OK;
  50156. }
  50157. }
  50158. return rc;
  50159. }
  50160. /*
  50161. ** This function may only be called when a read-transaction is open on
  50162. ** the pager. It returns the total number of pages in the database.
  50163. **
  50164. ** However, if the file is between 1 and <page-size> bytes in size, then
  50165. ** this is considered a 1 page file.
  50166. */
  50167. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  50168. assert( pPager->eState>=PAGER_READER );
  50169. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  50170. *pnPage = (int)pPager->dbSize;
  50171. }
  50172. /*
  50173. ** Try to obtain a lock of type locktype on the database file. If
  50174. ** a similar or greater lock is already held, this function is a no-op
  50175. ** (returning SQLITE_OK immediately).
  50176. **
  50177. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  50178. ** the busy callback if the lock is currently not available. Repeat
  50179. ** until the busy callback returns false or until the attempt to
  50180. ** obtain the lock succeeds.
  50181. **
  50182. ** Return SQLITE_OK on success and an error code if we cannot obtain
  50183. ** the lock. If the lock is obtained successfully, set the Pager.state
  50184. ** variable to locktype before returning.
  50185. */
  50186. static int pager_wait_on_lock(Pager *pPager, int locktype){
  50187. int rc; /* Return code */
  50188. /* Check that this is either a no-op (because the requested lock is
  50189. ** already held), or one of the transitions that the busy-handler
  50190. ** may be invoked during, according to the comment above
  50191. ** sqlite3PagerSetBusyhandler().
  50192. */
  50193. assert( (pPager->eLock>=locktype)
  50194. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  50195. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  50196. );
  50197. do {
  50198. rc = pagerLockDb(pPager, locktype);
  50199. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  50200. return rc;
  50201. }
  50202. /*
  50203. ** Function assertTruncateConstraint(pPager) checks that one of the
  50204. ** following is true for all dirty pages currently in the page-cache:
  50205. **
  50206. ** a) The page number is less than or equal to the size of the
  50207. ** current database image, in pages, OR
  50208. **
  50209. ** b) if the page content were written at this time, it would not
  50210. ** be necessary to write the current content out to the sub-journal
  50211. ** (as determined by function subjRequiresPage()).
  50212. **
  50213. ** If the condition asserted by this function were not true, and the
  50214. ** dirty page were to be discarded from the cache via the pagerStress()
  50215. ** routine, pagerStress() would not write the current page content to
  50216. ** the database file. If a savepoint transaction were rolled back after
  50217. ** this happened, the correct behavior would be to restore the current
  50218. ** content of the page. However, since this content is not present in either
  50219. ** the database file or the portion of the rollback journal and
  50220. ** sub-journal rolled back the content could not be restored and the
  50221. ** database image would become corrupt. It is therefore fortunate that
  50222. ** this circumstance cannot arise.
  50223. */
  50224. #if defined(SQLITE_DEBUG)
  50225. static void assertTruncateConstraintCb(PgHdr *pPg){
  50226. assert( pPg->flags&PGHDR_DIRTY );
  50227. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  50228. }
  50229. static void assertTruncateConstraint(Pager *pPager){
  50230. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  50231. }
  50232. #else
  50233. # define assertTruncateConstraint(pPager)
  50234. #endif
  50235. /*
  50236. ** Truncate the in-memory database file image to nPage pages. This
  50237. ** function does not actually modify the database file on disk. It
  50238. ** just sets the internal state of the pager object so that the
  50239. ** truncation will be done when the current transaction is committed.
  50240. **
  50241. ** This function is only called right before committing a transaction.
  50242. ** Once this function has been called, the transaction must either be
  50243. ** rolled back or committed. It is not safe to call this function and
  50244. ** then continue writing to the database.
  50245. */
  50246. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  50247. assert( pPager->dbSize>=nPage );
  50248. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  50249. pPager->dbSize = nPage;
  50250. /* At one point the code here called assertTruncateConstraint() to
  50251. ** ensure that all pages being truncated away by this operation are,
  50252. ** if one or more savepoints are open, present in the savepoint
  50253. ** journal so that they can be restored if the savepoint is rolled
  50254. ** back. This is no longer necessary as this function is now only
  50255. ** called right before committing a transaction. So although the
  50256. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  50257. ** they cannot be rolled back. So the assertTruncateConstraint() call
  50258. ** is no longer correct. */
  50259. }
  50260. /*
  50261. ** This function is called before attempting a hot-journal rollback. It
  50262. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  50263. ** size of the journal file so that the pager_playback() routine knows
  50264. ** that the entire journal file has been synced.
  50265. **
  50266. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  50267. ** that if a power-failure occurs during the rollback, the process that
  50268. ** attempts rollback following system recovery sees the same journal
  50269. ** content as this process.
  50270. **
  50271. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  50272. ** an SQLite error code.
  50273. */
  50274. static int pagerSyncHotJournal(Pager *pPager){
  50275. int rc = SQLITE_OK;
  50276. if( !pPager->noSync ){
  50277. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  50278. }
  50279. if( rc==SQLITE_OK ){
  50280. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  50281. }
  50282. return rc;
  50283. }
  50284. #if SQLITE_MAX_MMAP_SIZE>0
  50285. /*
  50286. ** Obtain a reference to a memory mapped page object for page number pgno.
  50287. ** The new object will use the pointer pData, obtained from xFetch().
  50288. ** If successful, set *ppPage to point to the new page reference
  50289. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  50290. ** *ppPage to zero.
  50291. **
  50292. ** Page references obtained by calling this function should be released
  50293. ** by calling pagerReleaseMapPage().
  50294. */
  50295. static int pagerAcquireMapPage(
  50296. Pager *pPager, /* Pager object */
  50297. Pgno pgno, /* Page number */
  50298. void *pData, /* xFetch()'d data for this page */
  50299. PgHdr **ppPage /* OUT: Acquired page object */
  50300. ){
  50301. PgHdr *p; /* Memory mapped page to return */
  50302. if( pPager->pMmapFreelist ){
  50303. *ppPage = p = pPager->pMmapFreelist;
  50304. pPager->pMmapFreelist = p->pDirty;
  50305. p->pDirty = 0;
  50306. assert( pPager->nExtra>=8 );
  50307. memset(p->pExtra, 0, 8);
  50308. }else{
  50309. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  50310. if( p==0 ){
  50311. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  50312. return SQLITE_NOMEM_BKPT;
  50313. }
  50314. p->pExtra = (void *)&p[1];
  50315. p->flags = PGHDR_MMAP;
  50316. p->nRef = 1;
  50317. p->pPager = pPager;
  50318. }
  50319. assert( p->pExtra==(void *)&p[1] );
  50320. assert( p->pPage==0 );
  50321. assert( p->flags==PGHDR_MMAP );
  50322. assert( p->pPager==pPager );
  50323. assert( p->nRef==1 );
  50324. p->pgno = pgno;
  50325. p->pData = pData;
  50326. pPager->nMmapOut++;
  50327. return SQLITE_OK;
  50328. }
  50329. #endif
  50330. /*
  50331. ** Release a reference to page pPg. pPg must have been returned by an
  50332. ** earlier call to pagerAcquireMapPage().
  50333. */
  50334. static void pagerReleaseMapPage(PgHdr *pPg){
  50335. Pager *pPager = pPg->pPager;
  50336. pPager->nMmapOut--;
  50337. pPg->pDirty = pPager->pMmapFreelist;
  50338. pPager->pMmapFreelist = pPg;
  50339. assert( pPager->fd->pMethods->iVersion>=3 );
  50340. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  50341. }
  50342. /*
  50343. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  50344. */
  50345. static void pagerFreeMapHdrs(Pager *pPager){
  50346. PgHdr *p;
  50347. PgHdr *pNext;
  50348. for(p=pPager->pMmapFreelist; p; p=pNext){
  50349. pNext = p->pDirty;
  50350. sqlite3_free(p);
  50351. }
  50352. }
  50353. /* Verify that the database file has not be deleted or renamed out from
  50354. ** under the pager. Return SQLITE_OK if the database is still where it ought
  50355. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  50356. ** code from sqlite3OsAccess()) if the database has gone missing.
  50357. */
  50358. static int databaseIsUnmoved(Pager *pPager){
  50359. int bHasMoved = 0;
  50360. int rc;
  50361. if( pPager->tempFile ) return SQLITE_OK;
  50362. if( pPager->dbSize==0 ) return SQLITE_OK;
  50363. assert( pPager->zFilename && pPager->zFilename[0] );
  50364. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  50365. if( rc==SQLITE_NOTFOUND ){
  50366. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  50367. ** has not been moved. That is the historical behavior of SQLite: prior to
  50368. ** version 3.8.3, it never checked */
  50369. rc = SQLITE_OK;
  50370. }else if( rc==SQLITE_OK && bHasMoved ){
  50371. rc = SQLITE_READONLY_DBMOVED;
  50372. }
  50373. return rc;
  50374. }
  50375. /*
  50376. ** Shutdown the page cache. Free all memory and close all files.
  50377. **
  50378. ** If a transaction was in progress when this routine is called, that
  50379. ** transaction is rolled back. All outstanding pages are invalidated
  50380. ** and their memory is freed. Any attempt to use a page associated
  50381. ** with this page cache after this function returns will likely
  50382. ** result in a coredump.
  50383. **
  50384. ** This function always succeeds. If a transaction is active an attempt
  50385. ** is made to roll it back. If an error occurs during the rollback
  50386. ** a hot journal may be left in the filesystem but no error is returned
  50387. ** to the caller.
  50388. */
  50389. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  50390. u8 *pTmp = (u8*)pPager->pTmpSpace;
  50391. assert( db || pagerUseWal(pPager)==0 );
  50392. assert( assert_pager_state(pPager) );
  50393. disable_simulated_io_errors();
  50394. sqlite3BeginBenignMalloc();
  50395. pagerFreeMapHdrs(pPager);
  50396. /* pPager->errCode = 0; */
  50397. pPager->exclusiveMode = 0;
  50398. #ifndef SQLITE_OMIT_WAL
  50399. {
  50400. u8 *a = 0;
  50401. assert( db || pPager->pWal==0 );
  50402. if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
  50403. && SQLITE_OK==databaseIsUnmoved(pPager)
  50404. ){
  50405. a = pTmp;
  50406. }
  50407. sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
  50408. pPager->pWal = 0;
  50409. }
  50410. #endif
  50411. pager_reset(pPager);
  50412. if( MEMDB ){
  50413. pager_unlock(pPager);
  50414. }else{
  50415. /* If it is open, sync the journal file before calling UnlockAndRollback.
  50416. ** If this is not done, then an unsynced portion of the open journal
  50417. ** file may be played back into the database. If a power failure occurs
  50418. ** while this is happening, the database could become corrupt.
  50419. **
  50420. ** If an error occurs while trying to sync the journal, shift the pager
  50421. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  50422. ** database and close the journal file without attempting to roll it
  50423. ** back or finalize it. The next database user will have to do hot-journal
  50424. ** rollback before accessing the database file.
  50425. */
  50426. if( isOpen(pPager->jfd) ){
  50427. pager_error(pPager, pagerSyncHotJournal(pPager));
  50428. }
  50429. pagerUnlockAndRollback(pPager);
  50430. }
  50431. sqlite3EndBenignMalloc();
  50432. enable_simulated_io_errors();
  50433. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  50434. IOTRACE(("CLOSE %p\n", pPager))
  50435. sqlite3OsClose(pPager->jfd);
  50436. sqlite3OsClose(pPager->fd);
  50437. sqlite3PageFree(pTmp);
  50438. sqlite3PcacheClose(pPager->pPCache);
  50439. #ifdef SQLITE_HAS_CODEC
  50440. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  50441. #endif
  50442. assert( !pPager->aSavepoint && !pPager->pInJournal );
  50443. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  50444. sqlite3_free(pPager);
  50445. return SQLITE_OK;
  50446. }
  50447. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  50448. /*
  50449. ** Return the page number for page pPg.
  50450. */
  50451. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  50452. return pPg->pgno;
  50453. }
  50454. #endif
  50455. /*
  50456. ** Increment the reference count for page pPg.
  50457. */
  50458. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  50459. sqlite3PcacheRef(pPg);
  50460. }
  50461. /*
  50462. ** Sync the journal. In other words, make sure all the pages that have
  50463. ** been written to the journal have actually reached the surface of the
  50464. ** disk and can be restored in the event of a hot-journal rollback.
  50465. **
  50466. ** If the Pager.noSync flag is set, then this function is a no-op.
  50467. ** Otherwise, the actions required depend on the journal-mode and the
  50468. ** device characteristics of the file-system, as follows:
  50469. **
  50470. ** * If the journal file is an in-memory journal file, no action need
  50471. ** be taken.
  50472. **
  50473. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  50474. ** then the nRec field of the most recently written journal header
  50475. ** is updated to contain the number of journal records that have
  50476. ** been written following it. If the pager is operating in full-sync
  50477. ** mode, then the journal file is synced before this field is updated.
  50478. **
  50479. ** * If the device does not support the SEQUENTIAL property, then
  50480. ** journal file is synced.
  50481. **
  50482. ** Or, in pseudo-code:
  50483. **
  50484. ** if( NOT <in-memory journal> ){
  50485. ** if( NOT SAFE_APPEND ){
  50486. ** if( <full-sync mode> ) xSync(<journal file>);
  50487. ** <update nRec field>
  50488. ** }
  50489. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  50490. ** }
  50491. **
  50492. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  50493. ** page currently held in memory before returning SQLITE_OK. If an IO
  50494. ** error is encountered, then the IO error code is returned to the caller.
  50495. */
  50496. static int syncJournal(Pager *pPager, int newHdr){
  50497. int rc; /* Return code */
  50498. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  50499. || pPager->eState==PAGER_WRITER_DBMOD
  50500. );
  50501. assert( assert_pager_state(pPager) );
  50502. assert( !pagerUseWal(pPager) );
  50503. rc = sqlite3PagerExclusiveLock(pPager);
  50504. if( rc!=SQLITE_OK ) return rc;
  50505. if( !pPager->noSync ){
  50506. assert( !pPager->tempFile );
  50507. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  50508. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  50509. assert( isOpen(pPager->jfd) );
  50510. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  50511. /* This block deals with an obscure problem. If the last connection
  50512. ** that wrote to this database was operating in persistent-journal
  50513. ** mode, then the journal file may at this point actually be larger
  50514. ** than Pager.journalOff bytes. If the next thing in the journal
  50515. ** file happens to be a journal-header (written as part of the
  50516. ** previous connection's transaction), and a crash or power-failure
  50517. ** occurs after nRec is updated but before this connection writes
  50518. ** anything else to the journal file (or commits/rolls back its
  50519. ** transaction), then SQLite may become confused when doing the
  50520. ** hot-journal rollback following recovery. It may roll back all
  50521. ** of this connections data, then proceed to rolling back the old,
  50522. ** out-of-date data that follows it. Database corruption.
  50523. **
  50524. ** To work around this, if the journal file does appear to contain
  50525. ** a valid header following Pager.journalOff, then write a 0x00
  50526. ** byte to the start of it to prevent it from being recognized.
  50527. **
  50528. ** Variable iNextHdrOffset is set to the offset at which this
  50529. ** problematic header will occur, if it exists. aMagic is used
  50530. ** as a temporary buffer to inspect the first couple of bytes of
  50531. ** the potential journal header.
  50532. */
  50533. i64 iNextHdrOffset;
  50534. u8 aMagic[8];
  50535. u8 zHeader[sizeof(aJournalMagic)+4];
  50536. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  50537. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  50538. iNextHdrOffset = journalHdrOffset(pPager);
  50539. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  50540. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  50541. static const u8 zerobyte = 0;
  50542. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  50543. }
  50544. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  50545. return rc;
  50546. }
  50547. /* Write the nRec value into the journal file header. If in
  50548. ** full-synchronous mode, sync the journal first. This ensures that
  50549. ** all data has really hit the disk before nRec is updated to mark
  50550. ** it as a candidate for rollback.
  50551. **
  50552. ** This is not required if the persistent media supports the
  50553. ** SAFE_APPEND property. Because in this case it is not possible
  50554. ** for garbage data to be appended to the file, the nRec field
  50555. ** is populated with 0xFFFFFFFF when the journal header is written
  50556. ** and never needs to be updated.
  50557. */
  50558. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  50559. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  50560. IOTRACE(("JSYNC %p\n", pPager))
  50561. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  50562. if( rc!=SQLITE_OK ) return rc;
  50563. }
  50564. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  50565. rc = sqlite3OsWrite(
  50566. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  50567. );
  50568. if( rc!=SQLITE_OK ) return rc;
  50569. }
  50570. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  50571. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  50572. IOTRACE(("JSYNC %p\n", pPager))
  50573. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  50574. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  50575. );
  50576. if( rc!=SQLITE_OK ) return rc;
  50577. }
  50578. pPager->journalHdr = pPager->journalOff;
  50579. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  50580. pPager->nRec = 0;
  50581. rc = writeJournalHdr(pPager);
  50582. if( rc!=SQLITE_OK ) return rc;
  50583. }
  50584. }else{
  50585. pPager->journalHdr = pPager->journalOff;
  50586. }
  50587. }
  50588. /* Unless the pager is in noSync mode, the journal file was just
  50589. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  50590. ** all pages.
  50591. */
  50592. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  50593. pPager->eState = PAGER_WRITER_DBMOD;
  50594. assert( assert_pager_state(pPager) );
  50595. return SQLITE_OK;
  50596. }
  50597. /*
  50598. ** The argument is the first in a linked list of dirty pages connected
  50599. ** by the PgHdr.pDirty pointer. This function writes each one of the
  50600. ** in-memory pages in the list to the database file. The argument may
  50601. ** be NULL, representing an empty list. In this case this function is
  50602. ** a no-op.
  50603. **
  50604. ** The pager must hold at least a RESERVED lock when this function
  50605. ** is called. Before writing anything to the database file, this lock
  50606. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  50607. ** SQLITE_BUSY is returned and no data is written to the database file.
  50608. **
  50609. ** If the pager is a temp-file pager and the actual file-system file
  50610. ** is not yet open, it is created and opened before any data is
  50611. ** written out.
  50612. **
  50613. ** Once the lock has been upgraded and, if necessary, the file opened,
  50614. ** the pages are written out to the database file in list order. Writing
  50615. ** a page is skipped if it meets either of the following criteria:
  50616. **
  50617. ** * The page number is greater than Pager.dbSize, or
  50618. ** * The PGHDR_DONT_WRITE flag is set on the page.
  50619. **
  50620. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  50621. ** is updated accordingly. If page 1 is written out, then the value cached
  50622. ** in Pager.dbFileVers[] is updated to match the new value stored in
  50623. ** the database file.
  50624. **
  50625. ** If everything is successful, SQLITE_OK is returned. If an IO error
  50626. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  50627. ** be obtained, SQLITE_BUSY is returned.
  50628. */
  50629. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  50630. int rc = SQLITE_OK; /* Return code */
  50631. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  50632. assert( !pagerUseWal(pPager) );
  50633. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  50634. assert( pPager->eLock==EXCLUSIVE_LOCK );
  50635. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  50636. /* If the file is a temp-file has not yet been opened, open it now. It
  50637. ** is not possible for rc to be other than SQLITE_OK if this branch
  50638. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  50639. */
  50640. if( !isOpen(pPager->fd) ){
  50641. assert( pPager->tempFile && rc==SQLITE_OK );
  50642. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  50643. }
  50644. /* Before the first write, give the VFS a hint of what the final
  50645. ** file size will be.
  50646. */
  50647. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  50648. if( rc==SQLITE_OK
  50649. && pPager->dbHintSize<pPager->dbSize
  50650. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  50651. ){
  50652. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  50653. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  50654. pPager->dbHintSize = pPager->dbSize;
  50655. }
  50656. while( rc==SQLITE_OK && pList ){
  50657. Pgno pgno = pList->pgno;
  50658. /* If there are dirty pages in the page cache with page numbers greater
  50659. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  50660. ** make the file smaller (presumably by auto-vacuum code). Do not write
  50661. ** any such pages to the file.
  50662. **
  50663. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  50664. ** set (set by sqlite3PagerDontWrite()).
  50665. */
  50666. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  50667. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  50668. char *pData; /* Data to write */
  50669. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  50670. if( pList->pgno==1 ) pager_write_changecounter(pList);
  50671. /* Encode the database */
  50672. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  50673. /* Write out the page data. */
  50674. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  50675. /* If page 1 was just written, update Pager.dbFileVers to match
  50676. ** the value now stored in the database file. If writing this
  50677. ** page caused the database file to grow, update dbFileSize.
  50678. */
  50679. if( pgno==1 ){
  50680. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  50681. }
  50682. if( pgno>pPager->dbFileSize ){
  50683. pPager->dbFileSize = pgno;
  50684. }
  50685. pPager->aStat[PAGER_STAT_WRITE]++;
  50686. /* Update any backup objects copying the contents of this pager. */
  50687. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  50688. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  50689. PAGERID(pPager), pgno, pager_pagehash(pList)));
  50690. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  50691. PAGER_INCR(sqlite3_pager_writedb_count);
  50692. }else{
  50693. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  50694. }
  50695. pager_set_pagehash(pList);
  50696. pList = pList->pDirty;
  50697. }
  50698. return rc;
  50699. }
  50700. /*
  50701. ** Ensure that the sub-journal file is open. If it is already open, this
  50702. ** function is a no-op.
  50703. **
  50704. ** SQLITE_OK is returned if everything goes according to plan. An
  50705. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  50706. ** fails.
  50707. */
  50708. static int openSubJournal(Pager *pPager){
  50709. int rc = SQLITE_OK;
  50710. if( !isOpen(pPager->sjfd) ){
  50711. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  50712. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  50713. | SQLITE_OPEN_DELETEONCLOSE;
  50714. int nStmtSpill = sqlite3Config.nStmtSpill;
  50715. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  50716. nStmtSpill = -1;
  50717. }
  50718. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  50719. }
  50720. return rc;
  50721. }
  50722. /*
  50723. ** Append a record of the current state of page pPg to the sub-journal.
  50724. **
  50725. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  50726. ** for all open savepoints before returning.
  50727. **
  50728. ** This function returns SQLITE_OK if everything is successful, an IO
  50729. ** error code if the attempt to write to the sub-journal fails, or
  50730. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  50731. ** bitvec.
  50732. */
  50733. static int subjournalPage(PgHdr *pPg){
  50734. int rc = SQLITE_OK;
  50735. Pager *pPager = pPg->pPager;
  50736. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  50737. /* Open the sub-journal, if it has not already been opened */
  50738. assert( pPager->useJournal );
  50739. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  50740. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  50741. assert( pagerUseWal(pPager)
  50742. || pageInJournal(pPager, pPg)
  50743. || pPg->pgno>pPager->dbOrigSize
  50744. );
  50745. rc = openSubJournal(pPager);
  50746. /* If the sub-journal was opened successfully (or was already open),
  50747. ** write the journal record into the file. */
  50748. if( rc==SQLITE_OK ){
  50749. void *pData = pPg->pData;
  50750. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  50751. char *pData2;
  50752. #if SQLITE_HAS_CODEC
  50753. if( !pPager->subjInMemory ){
  50754. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  50755. }else
  50756. #endif
  50757. pData2 = pData;
  50758. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  50759. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  50760. if( rc==SQLITE_OK ){
  50761. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  50762. }
  50763. }
  50764. }
  50765. if( rc==SQLITE_OK ){
  50766. pPager->nSubRec++;
  50767. assert( pPager->nSavepoint>0 );
  50768. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  50769. }
  50770. return rc;
  50771. }
  50772. static int subjournalPageIfRequired(PgHdr *pPg){
  50773. if( subjRequiresPage(pPg) ){
  50774. return subjournalPage(pPg);
  50775. }else{
  50776. return SQLITE_OK;
  50777. }
  50778. }
  50779. /*
  50780. ** This function is called by the pcache layer when it has reached some
  50781. ** soft memory limit. The first argument is a pointer to a Pager object
  50782. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  50783. ** database). The second argument is a reference to a page that is
  50784. ** currently dirty but has no outstanding references. The page
  50785. ** is always associated with the Pager object passed as the first
  50786. ** argument.
  50787. **
  50788. ** The job of this function is to make pPg clean by writing its contents
  50789. ** out to the database file, if possible. This may involve syncing the
  50790. ** journal file.
  50791. **
  50792. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  50793. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  50794. ** page clean, the IO error code is returned. If the page cannot be
  50795. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  50796. ** is returned by sqlite3PcacheMakeClean() is not called.
  50797. */
  50798. static int pagerStress(void *p, PgHdr *pPg){
  50799. Pager *pPager = (Pager *)p;
  50800. int rc = SQLITE_OK;
  50801. assert( pPg->pPager==pPager );
  50802. assert( pPg->flags&PGHDR_DIRTY );
  50803. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  50804. ** journal (and adding a new header) is not allowed. This occurs
  50805. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  50806. ** pages belonging to the same sector.
  50807. **
  50808. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  50809. ** regardless of whether or not a sync is required. This is set during
  50810. ** a rollback or by user request, respectively.
  50811. **
  50812. ** Spilling is also prohibited when in an error state since that could
  50813. ** lead to database corruption. In the current implementation it
  50814. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  50815. ** while in the error state, hence it is impossible for this routine to
  50816. ** be called in the error state. Nevertheless, we include a NEVER()
  50817. ** test for the error state as a safeguard against future changes.
  50818. */
  50819. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  50820. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  50821. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  50822. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  50823. if( pPager->doNotSpill
  50824. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  50825. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  50826. ){
  50827. return SQLITE_OK;
  50828. }
  50829. pPager->aStat[PAGER_STAT_SPILL]++;
  50830. pPg->pDirty = 0;
  50831. if( pagerUseWal(pPager) ){
  50832. /* Write a single frame for this page to the log. */
  50833. rc = subjournalPageIfRequired(pPg);
  50834. if( rc==SQLITE_OK ){
  50835. rc = pagerWalFrames(pPager, pPg, 0, 0);
  50836. }
  50837. }else{
  50838. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  50839. if( pPager->tempFile==0 ){
  50840. rc = sqlite3JournalCreate(pPager->jfd);
  50841. if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
  50842. }
  50843. #endif
  50844. /* Sync the journal file if required. */
  50845. if( pPg->flags&PGHDR_NEED_SYNC
  50846. || pPager->eState==PAGER_WRITER_CACHEMOD
  50847. ){
  50848. rc = syncJournal(pPager, 1);
  50849. }
  50850. /* Write the contents of the page out to the database file. */
  50851. if( rc==SQLITE_OK ){
  50852. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  50853. rc = pager_write_pagelist(pPager, pPg);
  50854. }
  50855. }
  50856. /* Mark the page as clean. */
  50857. if( rc==SQLITE_OK ){
  50858. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  50859. sqlite3PcacheMakeClean(pPg);
  50860. }
  50861. return pager_error(pPager, rc);
  50862. }
  50863. /*
  50864. ** Flush all unreferenced dirty pages to disk.
  50865. */
  50866. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  50867. int rc = pPager->errCode;
  50868. if( !MEMDB ){
  50869. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50870. assert( assert_pager_state(pPager) );
  50871. while( rc==SQLITE_OK && pList ){
  50872. PgHdr *pNext = pList->pDirty;
  50873. if( pList->nRef==0 ){
  50874. rc = pagerStress((void*)pPager, pList);
  50875. }
  50876. pList = pNext;
  50877. }
  50878. }
  50879. return rc;
  50880. }
  50881. /*
  50882. ** Allocate and initialize a new Pager object and put a pointer to it
  50883. ** in *ppPager. The pager should eventually be freed by passing it
  50884. ** to sqlite3PagerClose().
  50885. **
  50886. ** The zFilename argument is the path to the database file to open.
  50887. ** If zFilename is NULL then a randomly-named temporary file is created
  50888. ** and used as the file to be cached. Temporary files are be deleted
  50889. ** automatically when they are closed. If zFilename is ":memory:" then
  50890. ** all information is held in cache. It is never written to disk.
  50891. ** This can be used to implement an in-memory database.
  50892. **
  50893. ** The nExtra parameter specifies the number of bytes of space allocated
  50894. ** along with each page reference. This space is available to the user
  50895. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  50896. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  50897. ** (The extra space is used by btree as the MemPage object.)
  50898. **
  50899. ** The flags argument is used to specify properties that affect the
  50900. ** operation of the pager. It should be passed some bitwise combination
  50901. ** of the PAGER_* flags.
  50902. **
  50903. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  50904. ** of the xOpen() method of the supplied VFS when opening files.
  50905. **
  50906. ** If the pager object is allocated and the specified file opened
  50907. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  50908. ** the new pager object. If an error occurs, *ppPager is set to NULL
  50909. ** and error code returned. This function may return SQLITE_NOMEM
  50910. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  50911. ** various SQLITE_IO_XXX errors.
  50912. */
  50913. SQLITE_PRIVATE int sqlite3PagerOpen(
  50914. sqlite3_vfs *pVfs, /* The virtual file system to use */
  50915. Pager **ppPager, /* OUT: Return the Pager structure here */
  50916. const char *zFilename, /* Name of the database file to open */
  50917. int nExtra, /* Extra bytes append to each in-memory page */
  50918. int flags, /* flags controlling this file */
  50919. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  50920. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  50921. ){
  50922. u8 *pPtr;
  50923. Pager *pPager = 0; /* Pager object to allocate and return */
  50924. int rc = SQLITE_OK; /* Return code */
  50925. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  50926. int memDb = 0; /* True if this is an in-memory file */
  50927. #ifdef SQLITE_ENABLE_DESERIALIZE
  50928. int memJM = 0; /* Memory journal mode */
  50929. #else
  50930. # define memJM 0
  50931. #endif
  50932. int readOnly = 0; /* True if this is a read-only file */
  50933. int journalFileSize; /* Bytes to allocate for each journal fd */
  50934. char *zPathname = 0; /* Full path to database file */
  50935. int nPathname = 0; /* Number of bytes in zPathname */
  50936. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  50937. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  50938. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  50939. const char *zUri = 0; /* URI args to copy */
  50940. int nUri = 0; /* Number of bytes of URI args at *zUri */
  50941. /* Figure out how much space is required for each journal file-handle
  50942. ** (there are two of them, the main journal and the sub-journal). */
  50943. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  50944. /* Set the output variable to NULL in case an error occurs. */
  50945. *ppPager = 0;
  50946. #ifndef SQLITE_OMIT_MEMORYDB
  50947. if( flags & PAGER_MEMORY ){
  50948. memDb = 1;
  50949. if( zFilename && zFilename[0] ){
  50950. zPathname = sqlite3DbStrDup(0, zFilename);
  50951. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  50952. nPathname = sqlite3Strlen30(zPathname);
  50953. zFilename = 0;
  50954. }
  50955. }
  50956. #endif
  50957. /* Compute and store the full pathname in an allocated buffer pointed
  50958. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  50959. ** leave both nPathname and zPathname set to 0.
  50960. */
  50961. if( zFilename && zFilename[0] ){
  50962. const char *z;
  50963. nPathname = pVfs->mxPathname+1;
  50964. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  50965. if( zPathname==0 ){
  50966. return SQLITE_NOMEM_BKPT;
  50967. }
  50968. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  50969. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  50970. nPathname = sqlite3Strlen30(zPathname);
  50971. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  50972. while( *z ){
  50973. z += sqlite3Strlen30(z)+1;
  50974. z += sqlite3Strlen30(z)+1;
  50975. }
  50976. nUri = (int)(&z[1] - zUri);
  50977. assert( nUri>=0 );
  50978. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  50979. /* This branch is taken when the journal path required by
  50980. ** the database being opened will be more than pVfs->mxPathname
  50981. ** bytes in length. This means the database cannot be opened,
  50982. ** as it will not be possible to open the journal file or even
  50983. ** check for a hot-journal before reading.
  50984. */
  50985. rc = SQLITE_CANTOPEN_BKPT;
  50986. }
  50987. if( rc!=SQLITE_OK ){
  50988. sqlite3DbFree(0, zPathname);
  50989. return rc;
  50990. }
  50991. }
  50992. /* Allocate memory for the Pager structure, PCache object, the
  50993. ** three file descriptors, the database file name and the journal
  50994. ** file name. The layout in memory is as follows:
  50995. **
  50996. ** Pager object (sizeof(Pager) bytes)
  50997. ** PCache object (sqlite3PcacheSize() bytes)
  50998. ** Database file handle (pVfs->szOsFile bytes)
  50999. ** Sub-journal file handle (journalFileSize bytes)
  51000. ** Main journal file handle (journalFileSize bytes)
  51001. ** Database file name (nPathname+1 bytes)
  51002. ** Journal file name (nPathname+8+1 bytes)
  51003. */
  51004. pPtr = (u8 *)sqlite3MallocZero(
  51005. ROUND8(sizeof(*pPager)) + /* Pager structure */
  51006. ROUND8(pcacheSize) + /* PCache object */
  51007. ROUND8(pVfs->szOsFile) + /* The main db file */
  51008. journalFileSize * 2 + /* The two journal files */
  51009. nPathname + 1 + nUri + /* zFilename */
  51010. nPathname + 8 + 2 /* zJournal */
  51011. #ifndef SQLITE_OMIT_WAL
  51012. + nPathname + 4 + 2 /* zWal */
  51013. #endif
  51014. );
  51015. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  51016. if( !pPtr ){
  51017. sqlite3DbFree(0, zPathname);
  51018. return SQLITE_NOMEM_BKPT;
  51019. }
  51020. pPager = (Pager*)(pPtr);
  51021. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  51022. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  51023. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  51024. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  51025. pPager->zFilename = (char*)(pPtr += journalFileSize);
  51026. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  51027. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  51028. if( zPathname ){
  51029. assert( nPathname>0 );
  51030. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  51031. memcpy(pPager->zFilename, zPathname, nPathname);
  51032. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  51033. memcpy(pPager->zJournal, zPathname, nPathname);
  51034. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  51035. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  51036. #ifndef SQLITE_OMIT_WAL
  51037. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  51038. memcpy(pPager->zWal, zPathname, nPathname);
  51039. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  51040. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  51041. #endif
  51042. sqlite3DbFree(0, zPathname);
  51043. }
  51044. pPager->pVfs = pVfs;
  51045. pPager->vfsFlags = vfsFlags;
  51046. /* Open the pager file.
  51047. */
  51048. if( zFilename && zFilename[0] ){
  51049. int fout = 0; /* VFS flags returned by xOpen() */
  51050. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  51051. assert( !memDb );
  51052. #ifdef SQLITE_ENABLE_DESERIALIZE
  51053. memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
  51054. #endif
  51055. readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
  51056. /* If the file was successfully opened for read/write access,
  51057. ** choose a default page size in case we have to create the
  51058. ** database file. The default page size is the maximum of:
  51059. **
  51060. ** + SQLITE_DEFAULT_PAGE_SIZE,
  51061. ** + The value returned by sqlite3OsSectorSize()
  51062. ** + The largest page size that can be written atomically.
  51063. */
  51064. if( rc==SQLITE_OK ){
  51065. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  51066. if( !readOnly ){
  51067. setSectorSize(pPager);
  51068. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  51069. if( szPageDflt<pPager->sectorSize ){
  51070. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  51071. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  51072. }else{
  51073. szPageDflt = (u32)pPager->sectorSize;
  51074. }
  51075. }
  51076. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  51077. {
  51078. int ii;
  51079. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  51080. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  51081. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  51082. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  51083. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  51084. szPageDflt = ii;
  51085. }
  51086. }
  51087. }
  51088. #endif
  51089. }
  51090. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  51091. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  51092. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  51093. vfsFlags |= SQLITE_OPEN_READONLY;
  51094. goto act_like_temp_file;
  51095. }
  51096. }
  51097. }else{
  51098. /* If a temporary file is requested, it is not opened immediately.
  51099. ** In this case we accept the default page size and delay actually
  51100. ** opening the file until the first call to OsWrite().
  51101. **
  51102. ** This branch is also run for an in-memory database. An in-memory
  51103. ** database is the same as a temp-file that is never written out to
  51104. ** disk and uses an in-memory rollback journal.
  51105. **
  51106. ** This branch also runs for files marked as immutable.
  51107. */
  51108. act_like_temp_file:
  51109. tempFile = 1;
  51110. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  51111. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  51112. pPager->noLock = 1; /* Do no locking */
  51113. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  51114. }
  51115. /* The following call to PagerSetPagesize() serves to set the value of
  51116. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  51117. */
  51118. if( rc==SQLITE_OK ){
  51119. assert( pPager->memDb==0 );
  51120. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  51121. testcase( rc!=SQLITE_OK );
  51122. }
  51123. /* Initialize the PCache object. */
  51124. if( rc==SQLITE_OK ){
  51125. nExtra = ROUND8(nExtra);
  51126. assert( nExtra>=8 && nExtra<1000 );
  51127. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  51128. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  51129. }
  51130. /* If an error occurred above, free the Pager structure and close the file.
  51131. */
  51132. if( rc!=SQLITE_OK ){
  51133. sqlite3OsClose(pPager->fd);
  51134. sqlite3PageFree(pPager->pTmpSpace);
  51135. sqlite3_free(pPager);
  51136. return rc;
  51137. }
  51138. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  51139. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  51140. pPager->useJournal = (u8)useJournal;
  51141. /* pPager->stmtOpen = 0; */
  51142. /* pPager->stmtInUse = 0; */
  51143. /* pPager->nRef = 0; */
  51144. /* pPager->stmtSize = 0; */
  51145. /* pPager->stmtJSize = 0; */
  51146. /* pPager->nPage = 0; */
  51147. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  51148. /* pPager->state = PAGER_UNLOCK; */
  51149. /* pPager->errMask = 0; */
  51150. pPager->tempFile = (u8)tempFile;
  51151. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  51152. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  51153. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  51154. pPager->exclusiveMode = (u8)tempFile;
  51155. pPager->changeCountDone = pPager->tempFile;
  51156. pPager->memDb = (u8)memDb;
  51157. pPager->readOnly = (u8)readOnly;
  51158. assert( useJournal || pPager->tempFile );
  51159. pPager->noSync = pPager->tempFile;
  51160. if( pPager->noSync ){
  51161. assert( pPager->fullSync==0 );
  51162. assert( pPager->extraSync==0 );
  51163. assert( pPager->syncFlags==0 );
  51164. assert( pPager->walSyncFlags==0 );
  51165. }else{
  51166. pPager->fullSync = 1;
  51167. pPager->extraSync = 0;
  51168. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  51169. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
  51170. }
  51171. /* pPager->pFirst = 0; */
  51172. /* pPager->pFirstSynced = 0; */
  51173. /* pPager->pLast = 0; */
  51174. pPager->nExtra = (u16)nExtra;
  51175. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  51176. assert( isOpen(pPager->fd) || tempFile );
  51177. setSectorSize(pPager);
  51178. if( !useJournal ){
  51179. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  51180. }else if( memDb || memJM ){
  51181. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  51182. }
  51183. /* pPager->xBusyHandler = 0; */
  51184. /* pPager->pBusyHandlerArg = 0; */
  51185. pPager->xReiniter = xReinit;
  51186. setGetterMethod(pPager);
  51187. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  51188. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  51189. *ppPager = pPager;
  51190. return SQLITE_OK;
  51191. }
  51192. /*
  51193. ** This function is called after transitioning from PAGER_UNLOCK to
  51194. ** PAGER_SHARED state. It tests if there is a hot journal present in
  51195. ** the file-system for the given pager. A hot journal is one that
  51196. ** needs to be played back. According to this function, a hot-journal
  51197. ** file exists if the following criteria are met:
  51198. **
  51199. ** * The journal file exists in the file system, and
  51200. ** * No process holds a RESERVED or greater lock on the database file, and
  51201. ** * The database file itself is greater than 0 bytes in size, and
  51202. ** * The first byte of the journal file exists and is not 0x00.
  51203. **
  51204. ** If the current size of the database file is 0 but a journal file
  51205. ** exists, that is probably an old journal left over from a prior
  51206. ** database with the same name. In this case the journal file is
  51207. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  51208. ** is returned.
  51209. **
  51210. ** This routine does not check if there is a master journal filename
  51211. ** at the end of the file. If there is, and that master journal file
  51212. ** does not exist, then the journal file is not really hot. In this
  51213. ** case this routine will return a false-positive. The pager_playback()
  51214. ** routine will discover that the journal file is not really hot and
  51215. ** will not roll it back.
  51216. **
  51217. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  51218. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  51219. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  51220. ** to determine whether or not a hot-journal file exists, the IO error
  51221. ** code is returned and the value of *pExists is undefined.
  51222. */
  51223. static int hasHotJournal(Pager *pPager, int *pExists){
  51224. sqlite3_vfs * const pVfs = pPager->pVfs;
  51225. int rc = SQLITE_OK; /* Return code */
  51226. int exists = 1; /* True if a journal file is present */
  51227. int jrnlOpen = !!isOpen(pPager->jfd);
  51228. assert( pPager->useJournal );
  51229. assert( isOpen(pPager->fd) );
  51230. assert( pPager->eState==PAGER_OPEN );
  51231. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  51232. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  51233. ));
  51234. *pExists = 0;
  51235. if( !jrnlOpen ){
  51236. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  51237. }
  51238. if( rc==SQLITE_OK && exists ){
  51239. int locked = 0; /* True if some process holds a RESERVED lock */
  51240. /* Race condition here: Another process might have been holding the
  51241. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  51242. ** call above, but then delete the journal and drop the lock before
  51243. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  51244. ** is the case, this routine might think there is a hot journal when
  51245. ** in fact there is none. This results in a false-positive which will
  51246. ** be dealt with by the playback routine. Ticket #3883.
  51247. */
  51248. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  51249. if( rc==SQLITE_OK && !locked ){
  51250. Pgno nPage; /* Number of pages in database file */
  51251. assert( pPager->tempFile==0 );
  51252. rc = pagerPagecount(pPager, &nPage);
  51253. if( rc==SQLITE_OK ){
  51254. /* If the database is zero pages in size, that means that either (1) the
  51255. ** journal is a remnant from a prior database with the same name where
  51256. ** the database file but not the journal was deleted, or (2) the initial
  51257. ** transaction that populates a new database is being rolled back.
  51258. ** In either case, the journal file can be deleted. However, take care
  51259. ** not to delete the journal file if it is already open due to
  51260. ** journal_mode=PERSIST.
  51261. */
  51262. if( nPage==0 && !jrnlOpen ){
  51263. sqlite3BeginBenignMalloc();
  51264. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  51265. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  51266. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  51267. }
  51268. sqlite3EndBenignMalloc();
  51269. }else{
  51270. /* The journal file exists and no other connection has a reserved
  51271. ** or greater lock on the database file. Now check that there is
  51272. ** at least one non-zero bytes at the start of the journal file.
  51273. ** If there is, then we consider this journal to be hot. If not,
  51274. ** it can be ignored.
  51275. */
  51276. if( !jrnlOpen ){
  51277. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  51278. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  51279. }
  51280. if( rc==SQLITE_OK ){
  51281. u8 first = 0;
  51282. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  51283. if( rc==SQLITE_IOERR_SHORT_READ ){
  51284. rc = SQLITE_OK;
  51285. }
  51286. if( !jrnlOpen ){
  51287. sqlite3OsClose(pPager->jfd);
  51288. }
  51289. *pExists = (first!=0);
  51290. }else if( rc==SQLITE_CANTOPEN ){
  51291. /* If we cannot open the rollback journal file in order to see if
  51292. ** it has a zero header, that might be due to an I/O error, or
  51293. ** it might be due to the race condition described above and in
  51294. ** ticket #3883. Either way, assume that the journal is hot.
  51295. ** This might be a false positive. But if it is, then the
  51296. ** automatic journal playback and recovery mechanism will deal
  51297. ** with it under an EXCLUSIVE lock where we do not need to
  51298. ** worry so much with race conditions.
  51299. */
  51300. *pExists = 1;
  51301. rc = SQLITE_OK;
  51302. }
  51303. }
  51304. }
  51305. }
  51306. }
  51307. return rc;
  51308. }
  51309. /*
  51310. ** This function is called to obtain a shared lock on the database file.
  51311. ** It is illegal to call sqlite3PagerGet() until after this function
  51312. ** has been successfully called. If a shared-lock is already held when
  51313. ** this function is called, it is a no-op.
  51314. **
  51315. ** The following operations are also performed by this function.
  51316. **
  51317. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  51318. ** on the database file), then an attempt is made to obtain a
  51319. ** SHARED lock on the database file. Immediately after obtaining
  51320. ** the SHARED lock, the file-system is checked for a hot-journal,
  51321. ** which is played back if present. Following any hot-journal
  51322. ** rollback, the contents of the cache are validated by checking
  51323. ** the 'change-counter' field of the database file header and
  51324. ** discarded if they are found to be invalid.
  51325. **
  51326. ** 2) If the pager is running in exclusive-mode, and there are currently
  51327. ** no outstanding references to any pages, and is in the error state,
  51328. ** then an attempt is made to clear the error state by discarding
  51329. ** the contents of the page cache and rolling back any open journal
  51330. ** file.
  51331. **
  51332. ** If everything is successful, SQLITE_OK is returned. If an IO error
  51333. ** occurs while locking the database, checking for a hot-journal file or
  51334. ** rolling back a journal file, the IO error code is returned.
  51335. */
  51336. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  51337. int rc = SQLITE_OK; /* Return code */
  51338. /* This routine is only called from b-tree and only when there are no
  51339. ** outstanding pages. This implies that the pager state should either
  51340. ** be OPEN or READER. READER is only possible if the pager is or was in
  51341. ** exclusive access mode. */
  51342. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  51343. assert( assert_pager_state(pPager) );
  51344. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  51345. assert( pPager->errCode==SQLITE_OK );
  51346. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  51347. int bHotJournal = 1; /* True if there exists a hot journal-file */
  51348. assert( !MEMDB );
  51349. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  51350. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  51351. if( rc!=SQLITE_OK ){
  51352. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  51353. goto failed;
  51354. }
  51355. /* If a journal file exists, and there is no RESERVED lock on the
  51356. ** database file, then it either needs to be played back or deleted.
  51357. */
  51358. if( pPager->eLock<=SHARED_LOCK ){
  51359. rc = hasHotJournal(pPager, &bHotJournal);
  51360. }
  51361. if( rc!=SQLITE_OK ){
  51362. goto failed;
  51363. }
  51364. if( bHotJournal ){
  51365. if( pPager->readOnly ){
  51366. rc = SQLITE_READONLY_ROLLBACK;
  51367. goto failed;
  51368. }
  51369. /* Get an EXCLUSIVE lock on the database file. At this point it is
  51370. ** important that a RESERVED lock is not obtained on the way to the
  51371. ** EXCLUSIVE lock. If it were, another process might open the
  51372. ** database file, detect the RESERVED lock, and conclude that the
  51373. ** database is safe to read while this process is still rolling the
  51374. ** hot-journal back.
  51375. **
  51376. ** Because the intermediate RESERVED lock is not requested, any
  51377. ** other process attempting to access the database file will get to
  51378. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  51379. ** on the database file.
  51380. **
  51381. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  51382. ** downgraded to SHARED_LOCK before this function returns.
  51383. */
  51384. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  51385. if( rc!=SQLITE_OK ){
  51386. goto failed;
  51387. }
  51388. /* If it is not already open and the file exists on disk, open the
  51389. ** journal for read/write access. Write access is required because
  51390. ** in exclusive-access mode the file descriptor will be kept open
  51391. ** and possibly used for a transaction later on. Also, write-access
  51392. ** is usually required to finalize the journal in journal_mode=persist
  51393. ** mode (and also for journal_mode=truncate on some systems).
  51394. **
  51395. ** If the journal does not exist, it usually means that some
  51396. ** other connection managed to get in and roll it back before
  51397. ** this connection obtained the exclusive lock above. Or, it
  51398. ** may mean that the pager was in the error-state when this
  51399. ** function was called and the journal file does not exist.
  51400. */
  51401. if( !isOpen(pPager->jfd) ){
  51402. sqlite3_vfs * const pVfs = pPager->pVfs;
  51403. int bExists; /* True if journal file exists */
  51404. rc = sqlite3OsAccess(
  51405. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  51406. if( rc==SQLITE_OK && bExists ){
  51407. int fout = 0;
  51408. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  51409. assert( !pPager->tempFile );
  51410. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  51411. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  51412. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  51413. rc = SQLITE_CANTOPEN_BKPT;
  51414. sqlite3OsClose(pPager->jfd);
  51415. }
  51416. }
  51417. }
  51418. /* Playback and delete the journal. Drop the database write
  51419. ** lock and reacquire the read lock. Purge the cache before
  51420. ** playing back the hot-journal so that we don't end up with
  51421. ** an inconsistent cache. Sync the hot journal before playing
  51422. ** it back since the process that crashed and left the hot journal
  51423. ** probably did not sync it and we are required to always sync
  51424. ** the journal before playing it back.
  51425. */
  51426. if( isOpen(pPager->jfd) ){
  51427. assert( rc==SQLITE_OK );
  51428. rc = pagerSyncHotJournal(pPager);
  51429. if( rc==SQLITE_OK ){
  51430. rc = pager_playback(pPager, !pPager->tempFile);
  51431. pPager->eState = PAGER_OPEN;
  51432. }
  51433. }else if( !pPager->exclusiveMode ){
  51434. pagerUnlockDb(pPager, SHARED_LOCK);
  51435. }
  51436. if( rc!=SQLITE_OK ){
  51437. /* This branch is taken if an error occurs while trying to open
  51438. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  51439. ** pager_unlock() routine will be called before returning to unlock
  51440. ** the file. If the unlock attempt fails, then Pager.eLock must be
  51441. ** set to UNKNOWN_LOCK (see the comment above the #define for
  51442. ** UNKNOWN_LOCK above for an explanation).
  51443. **
  51444. ** In order to get pager_unlock() to do this, set Pager.eState to
  51445. ** PAGER_ERROR now. This is not actually counted as a transition
  51446. ** to ERROR state in the state diagram at the top of this file,
  51447. ** since we know that the same call to pager_unlock() will very
  51448. ** shortly transition the pager object to the OPEN state. Calling
  51449. ** assert_pager_state() would fail now, as it should not be possible
  51450. ** to be in ERROR state when there are zero outstanding page
  51451. ** references.
  51452. */
  51453. pager_error(pPager, rc);
  51454. goto failed;
  51455. }
  51456. assert( pPager->eState==PAGER_OPEN );
  51457. assert( (pPager->eLock==SHARED_LOCK)
  51458. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  51459. );
  51460. }
  51461. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  51462. /* The shared-lock has just been acquired then check to
  51463. ** see if the database has been modified. If the database has changed,
  51464. ** flush the cache. The hasHeldSharedLock flag prevents this from
  51465. ** occurring on the very first access to a file, in order to save a
  51466. ** single unnecessary sqlite3OsRead() call at the start-up.
  51467. **
  51468. ** Database changes are detected by looking at 15 bytes beginning
  51469. ** at offset 24 into the file. The first 4 of these 16 bytes are
  51470. ** a 32-bit counter that is incremented with each change. The
  51471. ** other bytes change randomly with each file change when
  51472. ** a codec is in use.
  51473. **
  51474. ** There is a vanishingly small chance that a change will not be
  51475. ** detected. The chance of an undetected change is so small that
  51476. ** it can be neglected.
  51477. */
  51478. char dbFileVers[sizeof(pPager->dbFileVers)];
  51479. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  51480. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  51481. if( rc!=SQLITE_OK ){
  51482. if( rc!=SQLITE_IOERR_SHORT_READ ){
  51483. goto failed;
  51484. }
  51485. memset(dbFileVers, 0, sizeof(dbFileVers));
  51486. }
  51487. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  51488. pager_reset(pPager);
  51489. /* Unmap the database file. It is possible that external processes
  51490. ** may have truncated the database file and then extended it back
  51491. ** to its original size while this process was not holding a lock.
  51492. ** In this case there may exist a Pager.pMap mapping that appears
  51493. ** to be the right size but is not actually valid. Avoid this
  51494. ** possibility by unmapping the db here. */
  51495. if( USEFETCH(pPager) ){
  51496. sqlite3OsUnfetch(pPager->fd, 0, 0);
  51497. }
  51498. }
  51499. }
  51500. /* If there is a WAL file in the file-system, open this database in WAL
  51501. ** mode. Otherwise, the following function call is a no-op.
  51502. */
  51503. rc = pagerOpenWalIfPresent(pPager);
  51504. #ifndef SQLITE_OMIT_WAL
  51505. assert( pPager->pWal==0 || rc==SQLITE_OK );
  51506. #endif
  51507. }
  51508. if( pagerUseWal(pPager) ){
  51509. assert( rc==SQLITE_OK );
  51510. rc = pagerBeginReadTransaction(pPager);
  51511. }
  51512. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  51513. rc = pagerPagecount(pPager, &pPager->dbSize);
  51514. }
  51515. failed:
  51516. if( rc!=SQLITE_OK ){
  51517. assert( !MEMDB );
  51518. pager_unlock(pPager);
  51519. assert( pPager->eState==PAGER_OPEN );
  51520. }else{
  51521. pPager->eState = PAGER_READER;
  51522. pPager->hasHeldSharedLock = 1;
  51523. }
  51524. return rc;
  51525. }
  51526. /*
  51527. ** If the reference count has reached zero, rollback any active
  51528. ** transaction and unlock the pager.
  51529. **
  51530. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  51531. ** the rollback journal, the unlock is not performed and there is
  51532. ** nothing to rollback, so this routine is a no-op.
  51533. */
  51534. static void pagerUnlockIfUnused(Pager *pPager){
  51535. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  51536. assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
  51537. pagerUnlockAndRollback(pPager);
  51538. }
  51539. }
  51540. /*
  51541. ** The page getter methods each try to acquire a reference to a
  51542. ** page with page number pgno. If the requested reference is
  51543. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  51544. **
  51545. ** There are different implementations of the getter method depending
  51546. ** on the current state of the pager.
  51547. **
  51548. ** getPageNormal() -- The normal getter
  51549. ** getPageError() -- Used if the pager is in an error state
  51550. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  51551. **
  51552. ** If the requested page is already in the cache, it is returned.
  51553. ** Otherwise, a new page object is allocated and populated with data
  51554. ** read from the database file. In some cases, the pcache module may
  51555. ** choose not to allocate a new page object and may reuse an existing
  51556. ** object with no outstanding references.
  51557. **
  51558. ** The extra data appended to a page is always initialized to zeros the
  51559. ** first time a page is loaded into memory. If the page requested is
  51560. ** already in the cache when this function is called, then the extra
  51561. ** data is left as it was when the page object was last used.
  51562. **
  51563. ** If the database image is smaller than the requested page or if
  51564. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  51565. ** requested page is not already stored in the cache, then no
  51566. ** actual disk read occurs. In this case the memory image of the
  51567. ** page is initialized to all zeros.
  51568. **
  51569. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  51570. ** the contents of the page. This occurs in two scenarios:
  51571. **
  51572. ** a) When reading a free-list leaf page from the database, and
  51573. **
  51574. ** b) When a savepoint is being rolled back and we need to load
  51575. ** a new page into the cache to be filled with the data read
  51576. ** from the savepoint journal.
  51577. **
  51578. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  51579. ** of being read from the database. Additionally, the bits corresponding
  51580. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  51581. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  51582. ** savepoints are set. This means if the page is made writable at any
  51583. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  51584. ** will not be journaled. This saves IO.
  51585. **
  51586. ** The acquisition might fail for several reasons. In all cases,
  51587. ** an appropriate error code is returned and *ppPage is set to NULL.
  51588. **
  51589. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  51590. ** to find a page in the in-memory cache first. If the page is not already
  51591. ** in memory, this routine goes to disk to read it in whereas Lookup()
  51592. ** just returns 0. This routine acquires a read-lock the first time it
  51593. ** has to go to disk, and could also playback an old journal if necessary.
  51594. ** Since Lookup() never goes to disk, it never has to deal with locks
  51595. ** or journal files.
  51596. */
  51597. static int getPageNormal(
  51598. Pager *pPager, /* The pager open on the database file */
  51599. Pgno pgno, /* Page number to fetch */
  51600. DbPage **ppPage, /* Write a pointer to the page here */
  51601. int flags /* PAGER_GET_XXX flags */
  51602. ){
  51603. int rc = SQLITE_OK;
  51604. PgHdr *pPg;
  51605. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  51606. sqlite3_pcache_page *pBase;
  51607. assert( pPager->errCode==SQLITE_OK );
  51608. assert( pPager->eState>=PAGER_READER );
  51609. assert( assert_pager_state(pPager) );
  51610. assert( pPager->hasHeldSharedLock==1 );
  51611. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  51612. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  51613. if( pBase==0 ){
  51614. pPg = 0;
  51615. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  51616. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  51617. if( pBase==0 ){
  51618. rc = SQLITE_NOMEM_BKPT;
  51619. goto pager_acquire_err;
  51620. }
  51621. }
  51622. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  51623. assert( pPg==(*ppPage) );
  51624. assert( pPg->pgno==pgno );
  51625. assert( pPg->pPager==pPager || pPg->pPager==0 );
  51626. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  51627. if( pPg->pPager && !noContent ){
  51628. /* In this case the pcache already contains an initialized copy of
  51629. ** the page. Return without further ado. */
  51630. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  51631. pPager->aStat[PAGER_STAT_HIT]++;
  51632. return SQLITE_OK;
  51633. }else{
  51634. /* The pager cache has created a new page. Its content needs to
  51635. ** be initialized. But first some error checks:
  51636. **
  51637. ** (1) The maximum page number is 2^31
  51638. ** (2) Never try to fetch the locking page
  51639. */
  51640. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  51641. rc = SQLITE_CORRUPT_BKPT;
  51642. goto pager_acquire_err;
  51643. }
  51644. pPg->pPager = pPager;
  51645. assert( !isOpen(pPager->fd) || !MEMDB );
  51646. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  51647. if( pgno>pPager->mxPgno ){
  51648. rc = SQLITE_FULL;
  51649. goto pager_acquire_err;
  51650. }
  51651. if( noContent ){
  51652. /* Failure to set the bits in the InJournal bit-vectors is benign.
  51653. ** It merely means that we might do some extra work to journal a
  51654. ** page that does not need to be journaled. Nevertheless, be sure
  51655. ** to test the case where a malloc error occurs while trying to set
  51656. ** a bit in a bit vector.
  51657. */
  51658. sqlite3BeginBenignMalloc();
  51659. if( pgno<=pPager->dbOrigSize ){
  51660. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  51661. testcase( rc==SQLITE_NOMEM );
  51662. }
  51663. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  51664. testcase( rc==SQLITE_NOMEM );
  51665. sqlite3EndBenignMalloc();
  51666. }
  51667. memset(pPg->pData, 0, pPager->pageSize);
  51668. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  51669. }else{
  51670. assert( pPg->pPager==pPager );
  51671. pPager->aStat[PAGER_STAT_MISS]++;
  51672. rc = readDbPage(pPg);
  51673. if( rc!=SQLITE_OK ){
  51674. goto pager_acquire_err;
  51675. }
  51676. }
  51677. pager_set_pagehash(pPg);
  51678. }
  51679. return SQLITE_OK;
  51680. pager_acquire_err:
  51681. assert( rc!=SQLITE_OK );
  51682. if( pPg ){
  51683. sqlite3PcacheDrop(pPg);
  51684. }
  51685. pagerUnlockIfUnused(pPager);
  51686. *ppPage = 0;
  51687. return rc;
  51688. }
  51689. #if SQLITE_MAX_MMAP_SIZE>0
  51690. /* The page getter for when memory-mapped I/O is enabled */
  51691. static int getPageMMap(
  51692. Pager *pPager, /* The pager open on the database file */
  51693. Pgno pgno, /* Page number to fetch */
  51694. DbPage **ppPage, /* Write a pointer to the page here */
  51695. int flags /* PAGER_GET_XXX flags */
  51696. ){
  51697. int rc = SQLITE_OK;
  51698. PgHdr *pPg = 0;
  51699. u32 iFrame = 0; /* Frame to read from WAL file */
  51700. /* It is acceptable to use a read-only (mmap) page for any page except
  51701. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  51702. ** flag was specified by the caller. And so long as the db is not a
  51703. ** temporary or in-memory database. */
  51704. const int bMmapOk = (pgno>1
  51705. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  51706. );
  51707. assert( USEFETCH(pPager) );
  51708. #ifdef SQLITE_HAS_CODEC
  51709. assert( pPager->xCodec==0 );
  51710. #endif
  51711. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  51712. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  51713. ** test in the previous statement, and avoid testing pgno==0 in the
  51714. ** common case where pgno is large. */
  51715. if( pgno<=1 && pgno==0 ){
  51716. return SQLITE_CORRUPT_BKPT;
  51717. }
  51718. assert( pPager->eState>=PAGER_READER );
  51719. assert( assert_pager_state(pPager) );
  51720. assert( pPager->hasHeldSharedLock==1 );
  51721. assert( pPager->errCode==SQLITE_OK );
  51722. if( bMmapOk && pagerUseWal(pPager) ){
  51723. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  51724. if( rc!=SQLITE_OK ){
  51725. *ppPage = 0;
  51726. return rc;
  51727. }
  51728. }
  51729. if( bMmapOk && iFrame==0 ){
  51730. void *pData = 0;
  51731. rc = sqlite3OsFetch(pPager->fd,
  51732. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  51733. );
  51734. if( rc==SQLITE_OK && pData ){
  51735. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  51736. pPg = sqlite3PagerLookup(pPager, pgno);
  51737. }
  51738. if( pPg==0 ){
  51739. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  51740. }else{
  51741. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  51742. }
  51743. if( pPg ){
  51744. assert( rc==SQLITE_OK );
  51745. *ppPage = pPg;
  51746. return SQLITE_OK;
  51747. }
  51748. }
  51749. if( rc!=SQLITE_OK ){
  51750. *ppPage = 0;
  51751. return rc;
  51752. }
  51753. }
  51754. return getPageNormal(pPager, pgno, ppPage, flags);
  51755. }
  51756. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  51757. /* The page getter method for when the pager is an error state */
  51758. static int getPageError(
  51759. Pager *pPager, /* The pager open on the database file */
  51760. Pgno pgno, /* Page number to fetch */
  51761. DbPage **ppPage, /* Write a pointer to the page here */
  51762. int flags /* PAGER_GET_XXX flags */
  51763. ){
  51764. UNUSED_PARAMETER(pgno);
  51765. UNUSED_PARAMETER(flags);
  51766. assert( pPager->errCode!=SQLITE_OK );
  51767. *ppPage = 0;
  51768. return pPager->errCode;
  51769. }
  51770. /* Dispatch all page fetch requests to the appropriate getter method.
  51771. */
  51772. SQLITE_PRIVATE int sqlite3PagerGet(
  51773. Pager *pPager, /* The pager open on the database file */
  51774. Pgno pgno, /* Page number to fetch */
  51775. DbPage **ppPage, /* Write a pointer to the page here */
  51776. int flags /* PAGER_GET_XXX flags */
  51777. ){
  51778. return pPager->xGet(pPager, pgno, ppPage, flags);
  51779. }
  51780. /*
  51781. ** Acquire a page if it is already in the in-memory cache. Do
  51782. ** not read the page from disk. Return a pointer to the page,
  51783. ** or 0 if the page is not in cache.
  51784. **
  51785. ** See also sqlite3PagerGet(). The difference between this routine
  51786. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  51787. ** in the page if the page is not already in cache. This routine
  51788. ** returns NULL if the page is not in cache or if a disk I/O error
  51789. ** has ever happened.
  51790. */
  51791. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  51792. sqlite3_pcache_page *pPage;
  51793. assert( pPager!=0 );
  51794. assert( pgno!=0 );
  51795. assert( pPager->pPCache!=0 );
  51796. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  51797. assert( pPage==0 || pPager->hasHeldSharedLock );
  51798. if( pPage==0 ) return 0;
  51799. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  51800. }
  51801. /*
  51802. ** Release a page reference.
  51803. **
  51804. ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
  51805. ** used if we know that the page being released is not the last page.
  51806. ** The btree layer always holds page1 open until the end, so these first
  51807. ** to routines can be used to release any page other than BtShared.pPage1.
  51808. **
  51809. ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
  51810. ** checks the total number of outstanding pages and if the number of
  51811. ** pages reaches zero it drops the database lock.
  51812. */
  51813. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  51814. TESTONLY( Pager *pPager = pPg->pPager; )
  51815. assert( pPg!=0 );
  51816. if( pPg->flags & PGHDR_MMAP ){
  51817. assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
  51818. pagerReleaseMapPage(pPg);
  51819. }else{
  51820. sqlite3PcacheRelease(pPg);
  51821. }
  51822. /* Do not use this routine to release the last reference to page1 */
  51823. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  51824. }
  51825. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  51826. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  51827. }
  51828. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  51829. Pager *pPager;
  51830. assert( pPg!=0 );
  51831. assert( pPg->pgno==1 );
  51832. assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
  51833. pPager = pPg->pPager;
  51834. sqlite3PagerResetLockTimeout(pPager);
  51835. sqlite3PcacheRelease(pPg);
  51836. pagerUnlockIfUnused(pPager);
  51837. }
  51838. /*
  51839. ** This function is called at the start of every write transaction.
  51840. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  51841. ** file when this routine is called.
  51842. **
  51843. ** Open the journal file for pager pPager and write a journal header
  51844. ** to the start of it. If there are active savepoints, open the sub-journal
  51845. ** as well. This function is only used when the journal file is being
  51846. ** opened to write a rollback log for a transaction. It is not used
  51847. ** when opening a hot journal file to roll it back.
  51848. **
  51849. ** If the journal file is already open (as it may be in exclusive mode),
  51850. ** then this function just writes a journal header to the start of the
  51851. ** already open file.
  51852. **
  51853. ** Whether or not the journal file is opened by this function, the
  51854. ** Pager.pInJournal bitvec structure is allocated.
  51855. **
  51856. ** Return SQLITE_OK if everything is successful. Otherwise, return
  51857. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  51858. ** an IO error code if opening or writing the journal file fails.
  51859. */
  51860. static int pager_open_journal(Pager *pPager){
  51861. int rc = SQLITE_OK; /* Return code */
  51862. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  51863. assert( pPager->eState==PAGER_WRITER_LOCKED );
  51864. assert( assert_pager_state(pPager) );
  51865. assert( pPager->pInJournal==0 );
  51866. /* If already in the error state, this function is a no-op. But on
  51867. ** the other hand, this routine is never called if we are already in
  51868. ** an error state. */
  51869. if( NEVER(pPager->errCode) ) return pPager->errCode;
  51870. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  51871. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  51872. if( pPager->pInJournal==0 ){
  51873. return SQLITE_NOMEM_BKPT;
  51874. }
  51875. /* Open the journal file if it is not already open. */
  51876. if( !isOpen(pPager->jfd) ){
  51877. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  51878. sqlite3MemJournalOpen(pPager->jfd);
  51879. }else{
  51880. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  51881. int nSpill;
  51882. if( pPager->tempFile ){
  51883. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  51884. nSpill = sqlite3Config.nStmtSpill;
  51885. }else{
  51886. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  51887. nSpill = jrnlBufferSize(pPager);
  51888. }
  51889. /* Verify that the database still has the same name as it did when
  51890. ** it was originally opened. */
  51891. rc = databaseIsUnmoved(pPager);
  51892. if( rc==SQLITE_OK ){
  51893. rc = sqlite3JournalOpen (
  51894. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  51895. );
  51896. }
  51897. }
  51898. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  51899. }
  51900. /* Write the first journal header to the journal file and open
  51901. ** the sub-journal if necessary.
  51902. */
  51903. if( rc==SQLITE_OK ){
  51904. /* TODO: Check if all of these are really required. */
  51905. pPager->nRec = 0;
  51906. pPager->journalOff = 0;
  51907. pPager->setMaster = 0;
  51908. pPager->journalHdr = 0;
  51909. rc = writeJournalHdr(pPager);
  51910. }
  51911. }
  51912. if( rc!=SQLITE_OK ){
  51913. sqlite3BitvecDestroy(pPager->pInJournal);
  51914. pPager->pInJournal = 0;
  51915. }else{
  51916. assert( pPager->eState==PAGER_WRITER_LOCKED );
  51917. pPager->eState = PAGER_WRITER_CACHEMOD;
  51918. }
  51919. return rc;
  51920. }
  51921. /*
  51922. ** Begin a write-transaction on the specified pager object. If a
  51923. ** write-transaction has already been opened, this function is a no-op.
  51924. **
  51925. ** If the exFlag argument is false, then acquire at least a RESERVED
  51926. ** lock on the database file. If exFlag is true, then acquire at least
  51927. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  51928. ** functions need be called.
  51929. **
  51930. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  51931. ** within this transaction will be opened as an in-memory file. This
  51932. ** has no effect if the sub-journal is already opened (as it may be when
  51933. ** running in exclusive mode) or if the transaction does not require a
  51934. ** sub-journal. If the subjInMemory argument is zero, then any required
  51935. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  51936. ** or using a temporary file otherwise.
  51937. */
  51938. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  51939. int rc = SQLITE_OK;
  51940. if( pPager->errCode ) return pPager->errCode;
  51941. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  51942. pPager->subjInMemory = (u8)subjInMemory;
  51943. if( ALWAYS(pPager->eState==PAGER_READER) ){
  51944. assert( pPager->pInJournal==0 );
  51945. if( pagerUseWal(pPager) ){
  51946. /* If the pager is configured to use locking_mode=exclusive, and an
  51947. ** exclusive lock on the database is not already held, obtain it now.
  51948. */
  51949. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  51950. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  51951. if( rc!=SQLITE_OK ){
  51952. return rc;
  51953. }
  51954. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  51955. }
  51956. /* Grab the write lock on the log file. If successful, upgrade to
  51957. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  51958. ** The busy-handler is not invoked if another connection already
  51959. ** holds the write-lock. If possible, the upper layer will call it.
  51960. */
  51961. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  51962. }else{
  51963. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  51964. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  51965. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  51966. ** lock, but not when obtaining the RESERVED lock.
  51967. */
  51968. rc = pagerLockDb(pPager, RESERVED_LOCK);
  51969. if( rc==SQLITE_OK && exFlag ){
  51970. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  51971. }
  51972. }
  51973. if( rc==SQLITE_OK ){
  51974. /* Change to WRITER_LOCKED state.
  51975. **
  51976. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  51977. ** when it has an open transaction, but never to DBMOD or FINISHED.
  51978. ** This is because in those states the code to roll back savepoint
  51979. ** transactions may copy data from the sub-journal into the database
  51980. ** file as well as into the page cache. Which would be incorrect in
  51981. ** WAL mode.
  51982. */
  51983. pPager->eState = PAGER_WRITER_LOCKED;
  51984. pPager->dbHintSize = pPager->dbSize;
  51985. pPager->dbFileSize = pPager->dbSize;
  51986. pPager->dbOrigSize = pPager->dbSize;
  51987. pPager->journalOff = 0;
  51988. }
  51989. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  51990. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  51991. assert( assert_pager_state(pPager) );
  51992. }
  51993. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  51994. return rc;
  51995. }
  51996. /*
  51997. ** Write page pPg onto the end of the rollback journal.
  51998. */
  51999. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  52000. Pager *pPager = pPg->pPager;
  52001. int rc;
  52002. u32 cksum;
  52003. char *pData2;
  52004. i64 iOff = pPager->journalOff;
  52005. /* We should never write to the journal file the page that
  52006. ** contains the database locks. The following assert verifies
  52007. ** that we do not. */
  52008. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  52009. assert( pPager->journalHdr<=pPager->journalOff );
  52010. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  52011. cksum = pager_cksum(pPager, (u8*)pData2);
  52012. /* Even if an IO or diskfull error occurs while journalling the
  52013. ** page in the block above, set the need-sync flag for the page.
  52014. ** Otherwise, when the transaction is rolled back, the logic in
  52015. ** playback_one_page() will think that the page needs to be restored
  52016. ** in the database file. And if an IO error occurs while doing so,
  52017. ** then corruption may follow.
  52018. */
  52019. pPg->flags |= PGHDR_NEED_SYNC;
  52020. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  52021. if( rc!=SQLITE_OK ) return rc;
  52022. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  52023. if( rc!=SQLITE_OK ) return rc;
  52024. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  52025. if( rc!=SQLITE_OK ) return rc;
  52026. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  52027. pPager->journalOff, pPager->pageSize));
  52028. PAGER_INCR(sqlite3_pager_writej_count);
  52029. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  52030. PAGERID(pPager), pPg->pgno,
  52031. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  52032. pPager->journalOff += 8 + pPager->pageSize;
  52033. pPager->nRec++;
  52034. assert( pPager->pInJournal!=0 );
  52035. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  52036. testcase( rc==SQLITE_NOMEM );
  52037. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  52038. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  52039. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  52040. return rc;
  52041. }
  52042. /*
  52043. ** Mark a single data page as writeable. The page is written into the
  52044. ** main journal or sub-journal as required. If the page is written into
  52045. ** one of the journals, the corresponding bit is set in the
  52046. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  52047. ** of any open savepoints as appropriate.
  52048. */
  52049. static int pager_write(PgHdr *pPg){
  52050. Pager *pPager = pPg->pPager;
  52051. int rc = SQLITE_OK;
  52052. /* This routine is not called unless a write-transaction has already
  52053. ** been started. The journal file may or may not be open at this point.
  52054. ** It is never called in the ERROR state.
  52055. */
  52056. assert( pPager->eState==PAGER_WRITER_LOCKED
  52057. || pPager->eState==PAGER_WRITER_CACHEMOD
  52058. || pPager->eState==PAGER_WRITER_DBMOD
  52059. );
  52060. assert( assert_pager_state(pPager) );
  52061. assert( pPager->errCode==0 );
  52062. assert( pPager->readOnly==0 );
  52063. CHECK_PAGE(pPg);
  52064. /* The journal file needs to be opened. Higher level routines have already
  52065. ** obtained the necessary locks to begin the write-transaction, but the
  52066. ** rollback journal might not yet be open. Open it now if this is the case.
  52067. **
  52068. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  52069. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  52070. ** an error might occur and the pager would end up in WRITER_LOCKED state
  52071. ** with pages marked as dirty in the cache.
  52072. */
  52073. if( pPager->eState==PAGER_WRITER_LOCKED ){
  52074. rc = pager_open_journal(pPager);
  52075. if( rc!=SQLITE_OK ) return rc;
  52076. }
  52077. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  52078. assert( assert_pager_state(pPager) );
  52079. /* Mark the page that is about to be modified as dirty. */
  52080. sqlite3PcacheMakeDirty(pPg);
  52081. /* If a rollback journal is in use, them make sure the page that is about
  52082. ** to change is in the rollback journal, or if the page is a new page off
  52083. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  52084. */
  52085. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  52086. if( pPager->pInJournal!=0
  52087. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  52088. ){
  52089. assert( pagerUseWal(pPager)==0 );
  52090. if( pPg->pgno<=pPager->dbOrigSize ){
  52091. rc = pagerAddPageToRollbackJournal(pPg);
  52092. if( rc!=SQLITE_OK ){
  52093. return rc;
  52094. }
  52095. }else{
  52096. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  52097. pPg->flags |= PGHDR_NEED_SYNC;
  52098. }
  52099. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  52100. PAGERID(pPager), pPg->pgno,
  52101. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  52102. }
  52103. }
  52104. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  52105. ** and before writing the page into the rollback journal. Wait until now,
  52106. ** after the page has been successfully journalled, before setting the
  52107. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  52108. */
  52109. pPg->flags |= PGHDR_WRITEABLE;
  52110. /* If the statement journal is open and the page is not in it,
  52111. ** then write the page into the statement journal.
  52112. */
  52113. if( pPager->nSavepoint>0 ){
  52114. rc = subjournalPageIfRequired(pPg);
  52115. }
  52116. /* Update the database size and return. */
  52117. if( pPager->dbSize<pPg->pgno ){
  52118. pPager->dbSize = pPg->pgno;
  52119. }
  52120. return rc;
  52121. }
  52122. /*
  52123. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  52124. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  52125. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  52126. ** a sector need to be journalled in case of a power loss in the middle of
  52127. ** a write.
  52128. **
  52129. ** Usually, the sector size is less than or equal to the page size, in which
  52130. ** case pages can be individually written. This routine only runs in the
  52131. ** exceptional case where the page size is smaller than the sector size.
  52132. */
  52133. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  52134. int rc = SQLITE_OK; /* Return code */
  52135. Pgno nPageCount; /* Total number of pages in database file */
  52136. Pgno pg1; /* First page of the sector pPg is located on. */
  52137. int nPage = 0; /* Number of pages starting at pg1 to journal */
  52138. int ii; /* Loop counter */
  52139. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  52140. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  52141. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  52142. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  52143. ** a journal header to be written between the pages journaled by
  52144. ** this function.
  52145. */
  52146. assert( !MEMDB );
  52147. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  52148. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  52149. /* This trick assumes that both the page-size and sector-size are
  52150. ** an integer power of 2. It sets variable pg1 to the identifier
  52151. ** of the first page of the sector pPg is located on.
  52152. */
  52153. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  52154. nPageCount = pPager->dbSize;
  52155. if( pPg->pgno>nPageCount ){
  52156. nPage = (pPg->pgno - pg1)+1;
  52157. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  52158. nPage = nPageCount+1-pg1;
  52159. }else{
  52160. nPage = nPagePerSector;
  52161. }
  52162. assert(nPage>0);
  52163. assert(pg1<=pPg->pgno);
  52164. assert((pg1+nPage)>pPg->pgno);
  52165. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  52166. Pgno pg = pg1+ii;
  52167. PgHdr *pPage;
  52168. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  52169. if( pg!=PAGER_MJ_PGNO(pPager) ){
  52170. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  52171. if( rc==SQLITE_OK ){
  52172. rc = pager_write(pPage);
  52173. if( pPage->flags&PGHDR_NEED_SYNC ){
  52174. needSync = 1;
  52175. }
  52176. sqlite3PagerUnrefNotNull(pPage);
  52177. }
  52178. }
  52179. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  52180. if( pPage->flags&PGHDR_NEED_SYNC ){
  52181. needSync = 1;
  52182. }
  52183. sqlite3PagerUnrefNotNull(pPage);
  52184. }
  52185. }
  52186. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  52187. ** starting at pg1, then it needs to be set for all of them. Because
  52188. ** writing to any of these nPage pages may damage the others, the
  52189. ** journal file must contain sync()ed copies of all of them
  52190. ** before any of them can be written out to the database file.
  52191. */
  52192. if( rc==SQLITE_OK && needSync ){
  52193. assert( !MEMDB );
  52194. for(ii=0; ii<nPage; ii++){
  52195. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  52196. if( pPage ){
  52197. pPage->flags |= PGHDR_NEED_SYNC;
  52198. sqlite3PagerUnrefNotNull(pPage);
  52199. }
  52200. }
  52201. }
  52202. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  52203. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  52204. return rc;
  52205. }
  52206. /*
  52207. ** Mark a data page as writeable. This routine must be called before
  52208. ** making changes to a page. The caller must check the return value
  52209. ** of this function and be careful not to change any page data unless
  52210. ** this routine returns SQLITE_OK.
  52211. **
  52212. ** The difference between this function and pager_write() is that this
  52213. ** function also deals with the special case where 2 or more pages
  52214. ** fit on a single disk sector. In this case all co-resident pages
  52215. ** must have been written to the journal file before returning.
  52216. **
  52217. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  52218. ** as appropriate. Otherwise, SQLITE_OK.
  52219. */
  52220. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  52221. Pager *pPager = pPg->pPager;
  52222. assert( (pPg->flags & PGHDR_MMAP)==0 );
  52223. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  52224. assert( assert_pager_state(pPager) );
  52225. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  52226. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  52227. return SQLITE_OK;
  52228. }else if( pPager->errCode ){
  52229. return pPager->errCode;
  52230. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  52231. assert( pPager->tempFile==0 );
  52232. return pagerWriteLargeSector(pPg);
  52233. }else{
  52234. return pager_write(pPg);
  52235. }
  52236. }
  52237. /*
  52238. ** Return TRUE if the page given in the argument was previously passed
  52239. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  52240. ** to change the content of the page.
  52241. */
  52242. #ifndef NDEBUG
  52243. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  52244. return pPg->flags & PGHDR_WRITEABLE;
  52245. }
  52246. #endif
  52247. /*
  52248. ** A call to this routine tells the pager that it is not necessary to
  52249. ** write the information on page pPg back to the disk, even though
  52250. ** that page might be marked as dirty. This happens, for example, when
  52251. ** the page has been added as a leaf of the freelist and so its
  52252. ** content no longer matters.
  52253. **
  52254. ** The overlying software layer calls this routine when all of the data
  52255. ** on the given page is unused. The pager marks the page as clean so
  52256. ** that it does not get written to disk.
  52257. **
  52258. ** Tests show that this optimization can quadruple the speed of large
  52259. ** DELETE operations.
  52260. **
  52261. ** This optimization cannot be used with a temp-file, as the page may
  52262. ** have been dirty at the start of the transaction. In that case, if
  52263. ** memory pressure forces page pPg out of the cache, the data does need
  52264. ** to be written out to disk so that it may be read back in if the
  52265. ** current transaction is rolled back.
  52266. */
  52267. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  52268. Pager *pPager = pPg->pPager;
  52269. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  52270. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  52271. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  52272. pPg->flags |= PGHDR_DONT_WRITE;
  52273. pPg->flags &= ~PGHDR_WRITEABLE;
  52274. testcase( pPg->flags & PGHDR_NEED_SYNC );
  52275. pager_set_pagehash(pPg);
  52276. }
  52277. }
  52278. /*
  52279. ** This routine is called to increment the value of the database file
  52280. ** change-counter, stored as a 4-byte big-endian integer starting at
  52281. ** byte offset 24 of the pager file. The secondary change counter at
  52282. ** 92 is also updated, as is the SQLite version number at offset 96.
  52283. **
  52284. ** But this only happens if the pPager->changeCountDone flag is false.
  52285. ** To avoid excess churning of page 1, the update only happens once.
  52286. ** See also the pager_write_changecounter() routine that does an
  52287. ** unconditional update of the change counters.
  52288. **
  52289. ** If the isDirectMode flag is zero, then this is done by calling
  52290. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  52291. ** page data. In this case the file will be updated when the current
  52292. ** transaction is committed.
  52293. **
  52294. ** The isDirectMode flag may only be non-zero if the library was compiled
  52295. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  52296. ** if isDirect is non-zero, then the database file is updated directly
  52297. ** by writing an updated version of page 1 using a call to the
  52298. ** sqlite3OsWrite() function.
  52299. */
  52300. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  52301. int rc = SQLITE_OK;
  52302. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  52303. || pPager->eState==PAGER_WRITER_DBMOD
  52304. );
  52305. assert( assert_pager_state(pPager) );
  52306. /* Declare and initialize constant integer 'isDirect'. If the
  52307. ** atomic-write optimization is enabled in this build, then isDirect
  52308. ** is initialized to the value passed as the isDirectMode parameter
  52309. ** to this function. Otherwise, it is always set to zero.
  52310. **
  52311. ** The idea is that if the atomic-write optimization is not
  52312. ** enabled at compile time, the compiler can omit the tests of
  52313. ** 'isDirect' below, as well as the block enclosed in the
  52314. ** "if( isDirect )" condition.
  52315. */
  52316. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  52317. # define DIRECT_MODE 0
  52318. assert( isDirectMode==0 );
  52319. UNUSED_PARAMETER(isDirectMode);
  52320. #else
  52321. # define DIRECT_MODE isDirectMode
  52322. #endif
  52323. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  52324. PgHdr *pPgHdr; /* Reference to page 1 */
  52325. assert( !pPager->tempFile && isOpen(pPager->fd) );
  52326. /* Open page 1 of the file for writing. */
  52327. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  52328. assert( pPgHdr==0 || rc==SQLITE_OK );
  52329. /* If page one was fetched successfully, and this function is not
  52330. ** operating in direct-mode, make page 1 writable. When not in
  52331. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  52332. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  52333. */
  52334. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  52335. rc = sqlite3PagerWrite(pPgHdr);
  52336. }
  52337. if( rc==SQLITE_OK ){
  52338. /* Actually do the update of the change counter */
  52339. pager_write_changecounter(pPgHdr);
  52340. /* If running in direct mode, write the contents of page 1 to the file. */
  52341. if( DIRECT_MODE ){
  52342. const void *zBuf;
  52343. assert( pPager->dbFileSize>0 );
  52344. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  52345. if( rc==SQLITE_OK ){
  52346. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  52347. pPager->aStat[PAGER_STAT_WRITE]++;
  52348. }
  52349. if( rc==SQLITE_OK ){
  52350. /* Update the pager's copy of the change-counter. Otherwise, the
  52351. ** next time a read transaction is opened the cache will be
  52352. ** flushed (as the change-counter values will not match). */
  52353. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  52354. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  52355. pPager->changeCountDone = 1;
  52356. }
  52357. }else{
  52358. pPager->changeCountDone = 1;
  52359. }
  52360. }
  52361. /* Release the page reference. */
  52362. sqlite3PagerUnref(pPgHdr);
  52363. }
  52364. return rc;
  52365. }
  52366. /*
  52367. ** Sync the database file to disk. This is a no-op for in-memory databases
  52368. ** or pages with the Pager.noSync flag set.
  52369. **
  52370. ** If successful, or if called on a pager for which it is a no-op, this
  52371. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  52372. */
  52373. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  52374. int rc = SQLITE_OK;
  52375. void *pArg = (void*)zMaster;
  52376. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  52377. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  52378. if( rc==SQLITE_OK && !pPager->noSync ){
  52379. assert( !MEMDB );
  52380. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  52381. }
  52382. return rc;
  52383. }
  52384. /*
  52385. ** This function may only be called while a write-transaction is active in
  52386. ** rollback. If the connection is in WAL mode, this call is a no-op.
  52387. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  52388. ** the database file, an attempt is made to obtain one.
  52389. **
  52390. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  52391. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  52392. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  52393. ** returned.
  52394. */
  52395. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  52396. int rc = pPager->errCode;
  52397. assert( assert_pager_state(pPager) );
  52398. if( rc==SQLITE_OK ){
  52399. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  52400. || pPager->eState==PAGER_WRITER_DBMOD
  52401. || pPager->eState==PAGER_WRITER_LOCKED
  52402. );
  52403. assert( assert_pager_state(pPager) );
  52404. if( 0==pagerUseWal(pPager) ){
  52405. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  52406. }
  52407. }
  52408. return rc;
  52409. }
  52410. /*
  52411. ** Sync the database file for the pager pPager. zMaster points to the name
  52412. ** of a master journal file that should be written into the individual
  52413. ** journal file. zMaster may be NULL, which is interpreted as no master
  52414. ** journal (a single database transaction).
  52415. **
  52416. ** This routine ensures that:
  52417. **
  52418. ** * The database file change-counter is updated,
  52419. ** * the journal is synced (unless the atomic-write optimization is used),
  52420. ** * all dirty pages are written to the database file,
  52421. ** * the database file is truncated (if required), and
  52422. ** * the database file synced.
  52423. **
  52424. ** The only thing that remains to commit the transaction is to finalize
  52425. ** (delete, truncate or zero the first part of) the journal file (or
  52426. ** delete the master journal file if specified).
  52427. **
  52428. ** Note that if zMaster==NULL, this does not overwrite a previous value
  52429. ** passed to an sqlite3PagerCommitPhaseOne() call.
  52430. **
  52431. ** If the final parameter - noSync - is true, then the database file itself
  52432. ** is not synced. The caller must call sqlite3PagerSync() directly to
  52433. ** sync the database file before calling CommitPhaseTwo() to delete the
  52434. ** journal file in this case.
  52435. */
  52436. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  52437. Pager *pPager, /* Pager object */
  52438. const char *zMaster, /* If not NULL, the master journal name */
  52439. int noSync /* True to omit the xSync on the db file */
  52440. ){
  52441. int rc = SQLITE_OK; /* Return code */
  52442. assert( pPager->eState==PAGER_WRITER_LOCKED
  52443. || pPager->eState==PAGER_WRITER_CACHEMOD
  52444. || pPager->eState==PAGER_WRITER_DBMOD
  52445. || pPager->eState==PAGER_ERROR
  52446. );
  52447. assert( assert_pager_state(pPager) );
  52448. /* If a prior error occurred, report that error again. */
  52449. if( NEVER(pPager->errCode) ) return pPager->errCode;
  52450. /* Provide the ability to easily simulate an I/O error during testing */
  52451. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  52452. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  52453. pPager->zFilename, zMaster, pPager->dbSize));
  52454. /* If no database changes have been made, return early. */
  52455. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  52456. assert( MEMDB==0 || pPager->tempFile );
  52457. assert( isOpen(pPager->fd) || pPager->tempFile );
  52458. if( 0==pagerFlushOnCommit(pPager, 1) ){
  52459. /* If this is an in-memory db, or no pages have been written to, or this
  52460. ** function has already been called, it is mostly a no-op. However, any
  52461. ** backup in progress needs to be restarted. */
  52462. sqlite3BackupRestart(pPager->pBackup);
  52463. }else{
  52464. if( pagerUseWal(pPager) ){
  52465. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  52466. PgHdr *pPageOne = 0;
  52467. if( pList==0 ){
  52468. /* Must have at least one page for the WAL commit flag.
  52469. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  52470. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  52471. pList = pPageOne;
  52472. pList->pDirty = 0;
  52473. }
  52474. assert( rc==SQLITE_OK );
  52475. if( ALWAYS(pList) ){
  52476. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  52477. }
  52478. sqlite3PagerUnref(pPageOne);
  52479. if( rc==SQLITE_OK ){
  52480. sqlite3PcacheCleanAll(pPager->pPCache);
  52481. }
  52482. }else{
  52483. /* The bBatch boolean is true if the batch-atomic-write commit method
  52484. ** should be used. No rollback journal is created if batch-atomic-write
  52485. ** is enabled.
  52486. */
  52487. sqlite3_file *fd = pPager->fd;
  52488. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  52489. const int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
  52490. && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
  52491. && !pPager->noSync
  52492. && sqlite3JournalIsInMemory(pPager->jfd);
  52493. #else
  52494. # define bBatch 0
  52495. #endif
  52496. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  52497. /* The following block updates the change-counter. Exactly how it
  52498. ** does this depends on whether or not the atomic-update optimization
  52499. ** was enabled at compile time, and if this transaction meets the
  52500. ** runtime criteria to use the operation:
  52501. **
  52502. ** * The file-system supports the atomic-write property for
  52503. ** blocks of size page-size, and
  52504. ** * This commit is not part of a multi-file transaction, and
  52505. ** * Exactly one page has been modified and store in the journal file.
  52506. **
  52507. ** If the optimization was not enabled at compile time, then the
  52508. ** pager_incr_changecounter() function is called to update the change
  52509. ** counter in 'indirect-mode'. If the optimization is compiled in but
  52510. ** is not applicable to this transaction, call sqlite3JournalCreate()
  52511. ** to make sure the journal file has actually been created, then call
  52512. ** pager_incr_changecounter() to update the change-counter in indirect
  52513. ** mode.
  52514. **
  52515. ** Otherwise, if the optimization is both enabled and applicable,
  52516. ** then call pager_incr_changecounter() to update the change-counter
  52517. ** in 'direct' mode. In this case the journal file will never be
  52518. ** created for this transaction.
  52519. */
  52520. if( bBatch==0 ){
  52521. PgHdr *pPg;
  52522. assert( isOpen(pPager->jfd)
  52523. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  52524. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  52525. );
  52526. if( !zMaster && isOpen(pPager->jfd)
  52527. && pPager->journalOff==jrnlBufferSize(pPager)
  52528. && pPager->dbSize>=pPager->dbOrigSize
  52529. && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  52530. ){
  52531. /* Update the db file change counter via the direct-write method. The
  52532. ** following call will modify the in-memory representation of page 1
  52533. ** to include the updated change counter and then write page 1
  52534. ** directly to the database file. Because of the atomic-write
  52535. ** property of the host file-system, this is safe.
  52536. */
  52537. rc = pager_incr_changecounter(pPager, 1);
  52538. }else{
  52539. rc = sqlite3JournalCreate(pPager->jfd);
  52540. if( rc==SQLITE_OK ){
  52541. rc = pager_incr_changecounter(pPager, 0);
  52542. }
  52543. }
  52544. }
  52545. #else
  52546. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  52547. if( zMaster ){
  52548. rc = sqlite3JournalCreate(pPager->jfd);
  52549. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52550. }
  52551. #endif
  52552. rc = pager_incr_changecounter(pPager, 0);
  52553. #endif
  52554. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52555. /* Write the master journal name into the journal file. If a master
  52556. ** journal file name has already been written to the journal file,
  52557. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  52558. */
  52559. rc = writeMasterJournal(pPager, zMaster);
  52560. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52561. /* Sync the journal file and write all dirty pages to the database.
  52562. ** If the atomic-update optimization is being used, this sync will not
  52563. ** create the journal file or perform any real IO.
  52564. **
  52565. ** Because the change-counter page was just modified, unless the
  52566. ** atomic-update optimization is used it is almost certain that the
  52567. ** journal requires a sync here. However, in locking_mode=exclusive
  52568. ** on a system under memory pressure it is just possible that this is
  52569. ** not the case. In this case it is likely enough that the redundant
  52570. ** xSync() call will be changed to a no-op by the OS anyhow.
  52571. */
  52572. rc = syncJournal(pPager, 0);
  52573. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52574. if( bBatch ){
  52575. /* The pager is now in DBMOD state. But regardless of what happens
  52576. ** next, attempting to play the journal back into the database would
  52577. ** be unsafe. Close it now to make sure that does not happen. */
  52578. sqlite3OsClose(pPager->jfd);
  52579. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
  52580. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52581. }
  52582. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  52583. if( bBatch ){
  52584. if( rc==SQLITE_OK ){
  52585. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
  52586. }
  52587. if( rc!=SQLITE_OK ){
  52588. sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
  52589. }
  52590. }
  52591. if( rc!=SQLITE_OK ){
  52592. assert( rc!=SQLITE_IOERR_BLOCKED );
  52593. goto commit_phase_one_exit;
  52594. }
  52595. sqlite3PcacheCleanAll(pPager->pPCache);
  52596. /* If the file on disk is smaller than the database image, use
  52597. ** pager_truncate to grow the file here. This can happen if the database
  52598. ** image was extended as part of the current transaction and then the
  52599. ** last page in the db image moved to the free-list. In this case the
  52600. ** last page is never written out to disk, leaving the database file
  52601. ** undersized. Fix this now if it is the case. */
  52602. if( pPager->dbSize>pPager->dbFileSize ){
  52603. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  52604. assert( pPager->eState==PAGER_WRITER_DBMOD );
  52605. rc = pager_truncate(pPager, nNew);
  52606. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52607. }
  52608. /* Finally, sync the database file. */
  52609. if( !noSync ){
  52610. rc = sqlite3PagerSync(pPager, zMaster);
  52611. }
  52612. IOTRACE(("DBSYNC %p\n", pPager))
  52613. }
  52614. }
  52615. commit_phase_one_exit:
  52616. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  52617. pPager->eState = PAGER_WRITER_FINISHED;
  52618. }
  52619. return rc;
  52620. }
  52621. /*
  52622. ** When this function is called, the database file has been completely
  52623. ** updated to reflect the changes made by the current transaction and
  52624. ** synced to disk. The journal file still exists in the file-system
  52625. ** though, and if a failure occurs at this point it will eventually
  52626. ** be used as a hot-journal and the current transaction rolled back.
  52627. **
  52628. ** This function finalizes the journal file, either by deleting,
  52629. ** truncating or partially zeroing it, so that it cannot be used
  52630. ** for hot-journal rollback. Once this is done the transaction is
  52631. ** irrevocably committed.
  52632. **
  52633. ** If an error occurs, an IO error code is returned and the pager
  52634. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  52635. */
  52636. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  52637. int rc = SQLITE_OK; /* Return code */
  52638. /* This routine should not be called if a prior error has occurred.
  52639. ** But if (due to a coding error elsewhere in the system) it does get
  52640. ** called, just return the same error code without doing anything. */
  52641. if( NEVER(pPager->errCode) ) return pPager->errCode;
  52642. assert( pPager->eState==PAGER_WRITER_LOCKED
  52643. || pPager->eState==PAGER_WRITER_FINISHED
  52644. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  52645. );
  52646. assert( assert_pager_state(pPager) );
  52647. /* An optimization. If the database was not actually modified during
  52648. ** this transaction, the pager is running in exclusive-mode and is
  52649. ** using persistent journals, then this function is a no-op.
  52650. **
  52651. ** The start of the journal file currently contains a single journal
  52652. ** header with the nRec field set to 0. If such a journal is used as
  52653. ** a hot-journal during hot-journal rollback, 0 changes will be made
  52654. ** to the database file. So there is no need to zero the journal
  52655. ** header. Since the pager is in exclusive mode, there is no need
  52656. ** to drop any locks either.
  52657. */
  52658. if( pPager->eState==PAGER_WRITER_LOCKED
  52659. && pPager->exclusiveMode
  52660. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  52661. ){
  52662. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  52663. pPager->eState = PAGER_READER;
  52664. return SQLITE_OK;
  52665. }
  52666. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  52667. pPager->iDataVersion++;
  52668. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  52669. return pager_error(pPager, rc);
  52670. }
  52671. /*
  52672. ** If a write transaction is open, then all changes made within the
  52673. ** transaction are reverted and the current write-transaction is closed.
  52674. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  52675. ** state if an error occurs.
  52676. **
  52677. ** If the pager is already in PAGER_ERROR state when this function is called,
  52678. ** it returns Pager.errCode immediately. No work is performed in this case.
  52679. **
  52680. ** Otherwise, in rollback mode, this function performs two functions:
  52681. **
  52682. ** 1) It rolls back the journal file, restoring all database file and
  52683. ** in-memory cache pages to the state they were in when the transaction
  52684. ** was opened, and
  52685. **
  52686. ** 2) It finalizes the journal file, so that it is not used for hot
  52687. ** rollback at any point in the future.
  52688. **
  52689. ** Finalization of the journal file (task 2) is only performed if the
  52690. ** rollback is successful.
  52691. **
  52692. ** In WAL mode, all cache-entries containing data modified within the
  52693. ** current transaction are either expelled from the cache or reverted to
  52694. ** their pre-transaction state by re-reading data from the database or
  52695. ** WAL files. The WAL transaction is then closed.
  52696. */
  52697. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  52698. int rc = SQLITE_OK; /* Return code */
  52699. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  52700. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  52701. ** the pager is already in the ERROR state, the rollback is not
  52702. ** attempted here. Instead, the error code is returned to the caller.
  52703. */
  52704. assert( assert_pager_state(pPager) );
  52705. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  52706. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  52707. if( pagerUseWal(pPager) ){
  52708. int rc2;
  52709. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  52710. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  52711. if( rc==SQLITE_OK ) rc = rc2;
  52712. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  52713. int eState = pPager->eState;
  52714. rc = pager_end_transaction(pPager, 0, 0);
  52715. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  52716. /* This can happen using journal_mode=off. Move the pager to the error
  52717. ** state to indicate that the contents of the cache may not be trusted.
  52718. ** Any active readers will get SQLITE_ABORT.
  52719. */
  52720. pPager->errCode = SQLITE_ABORT;
  52721. pPager->eState = PAGER_ERROR;
  52722. setGetterMethod(pPager);
  52723. return rc;
  52724. }
  52725. }else{
  52726. rc = pager_playback(pPager, 0);
  52727. }
  52728. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  52729. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  52730. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  52731. || rc==SQLITE_CANTOPEN
  52732. );
  52733. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  52734. ** cache. So call pager_error() on the way out to make any error persistent.
  52735. */
  52736. return pager_error(pPager, rc);
  52737. }
  52738. /*
  52739. ** Return TRUE if the database file is opened read-only. Return FALSE
  52740. ** if the database is (in theory) writable.
  52741. */
  52742. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  52743. return pPager->readOnly;
  52744. }
  52745. #ifdef SQLITE_DEBUG
  52746. /*
  52747. ** Return the sum of the reference counts for all pages held by pPager.
  52748. */
  52749. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  52750. return sqlite3PcacheRefCount(pPager->pPCache);
  52751. }
  52752. #endif
  52753. /*
  52754. ** Return the approximate number of bytes of memory currently
  52755. ** used by the pager and its associated cache.
  52756. */
  52757. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  52758. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  52759. + 5*sizeof(void*);
  52760. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  52761. + sqlite3MallocSize(pPager)
  52762. + pPager->pageSize;
  52763. }
  52764. /*
  52765. ** Return the number of references to the specified page.
  52766. */
  52767. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  52768. return sqlite3PcachePageRefcount(pPage);
  52769. }
  52770. #ifdef SQLITE_TEST
  52771. /*
  52772. ** This routine is used for testing and analysis only.
  52773. */
  52774. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  52775. static int a[11];
  52776. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  52777. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  52778. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  52779. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  52780. a[4] = pPager->eState;
  52781. a[5] = pPager->errCode;
  52782. a[6] = pPager->aStat[PAGER_STAT_HIT];
  52783. a[7] = pPager->aStat[PAGER_STAT_MISS];
  52784. a[8] = 0; /* Used to be pPager->nOvfl */
  52785. a[9] = pPager->nRead;
  52786. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  52787. return a;
  52788. }
  52789. #endif
  52790. /*
  52791. ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
  52792. ** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
  52793. ** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because
  52794. ** it was added later.
  52795. **
  52796. ** Before returning, *pnVal is incremented by the
  52797. ** current cache hit or miss count, according to the value of eStat. If the
  52798. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  52799. ** returning.
  52800. */
  52801. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  52802. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  52803. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  52804. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  52805. || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
  52806. );
  52807. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  52808. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  52809. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
  52810. && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
  52811. eStat -= SQLITE_DBSTATUS_CACHE_HIT;
  52812. *pnVal += pPager->aStat[eStat];
  52813. if( reset ){
  52814. pPager->aStat[eStat] = 0;
  52815. }
  52816. }
  52817. /*
  52818. ** Return true if this is an in-memory or temp-file backed pager.
  52819. */
  52820. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  52821. return pPager->tempFile;
  52822. }
  52823. /*
  52824. ** Check that there are at least nSavepoint savepoints open. If there are
  52825. ** currently less than nSavepoints open, then open one or more savepoints
  52826. ** to make up the difference. If the number of savepoints is already
  52827. ** equal to nSavepoint, then this function is a no-op.
  52828. **
  52829. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  52830. ** occurs while opening the sub-journal file, then an IO error code is
  52831. ** returned. Otherwise, SQLITE_OK.
  52832. */
  52833. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  52834. int rc = SQLITE_OK; /* Return code */
  52835. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  52836. int ii; /* Iterator variable */
  52837. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  52838. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  52839. assert( assert_pager_state(pPager) );
  52840. assert( nSavepoint>nCurrent && pPager->useJournal );
  52841. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  52842. ** if the allocation fails. Otherwise, zero the new portion in case a
  52843. ** malloc failure occurs while populating it in the for(...) loop below.
  52844. */
  52845. aNew = (PagerSavepoint *)sqlite3Realloc(
  52846. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  52847. );
  52848. if( !aNew ){
  52849. return SQLITE_NOMEM_BKPT;
  52850. }
  52851. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  52852. pPager->aSavepoint = aNew;
  52853. /* Populate the PagerSavepoint structures just allocated. */
  52854. for(ii=nCurrent; ii<nSavepoint; ii++){
  52855. aNew[ii].nOrig = pPager->dbSize;
  52856. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  52857. aNew[ii].iOffset = pPager->journalOff;
  52858. }else{
  52859. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  52860. }
  52861. aNew[ii].iSubRec = pPager->nSubRec;
  52862. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  52863. if( !aNew[ii].pInSavepoint ){
  52864. return SQLITE_NOMEM_BKPT;
  52865. }
  52866. if( pagerUseWal(pPager) ){
  52867. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  52868. }
  52869. pPager->nSavepoint = ii+1;
  52870. }
  52871. assert( pPager->nSavepoint==nSavepoint );
  52872. assertTruncateConstraint(pPager);
  52873. return rc;
  52874. }
  52875. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  52876. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  52877. assert( assert_pager_state(pPager) );
  52878. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  52879. return pagerOpenSavepoint(pPager, nSavepoint);
  52880. }else{
  52881. return SQLITE_OK;
  52882. }
  52883. }
  52884. /*
  52885. ** This function is called to rollback or release (commit) a savepoint.
  52886. ** The savepoint to release or rollback need not be the most recently
  52887. ** created savepoint.
  52888. **
  52889. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  52890. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  52891. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  52892. ** that have occurred since the specified savepoint was created.
  52893. **
  52894. ** The savepoint to rollback or release is identified by parameter
  52895. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  52896. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  52897. ** on the most recently created savepoint. If iSavepoint is greater than
  52898. ** (Pager.nSavepoint-1), then this function is a no-op.
  52899. **
  52900. ** If a negative value is passed to this function, then the current
  52901. ** transaction is rolled back. This is different to calling
  52902. ** sqlite3PagerRollback() because this function does not terminate
  52903. ** the transaction or unlock the database, it just restores the
  52904. ** contents of the database to its original state.
  52905. **
  52906. ** In any case, all savepoints with an index greater than iSavepoint
  52907. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  52908. ** then savepoint iSavepoint is also destroyed.
  52909. **
  52910. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  52911. ** or an IO error code if an IO error occurs while rolling back a
  52912. ** savepoint. If no errors occur, SQLITE_OK is returned.
  52913. */
  52914. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  52915. int rc = pPager->errCode;
  52916. #ifdef SQLITE_ENABLE_ZIPVFS
  52917. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  52918. #endif
  52919. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  52920. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  52921. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  52922. int ii; /* Iterator variable */
  52923. int nNew; /* Number of remaining savepoints after this op. */
  52924. /* Figure out how many savepoints will still be active after this
  52925. ** operation. Store this value in nNew. Then free resources associated
  52926. ** with any savepoints that are destroyed by this operation.
  52927. */
  52928. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  52929. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  52930. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  52931. }
  52932. pPager->nSavepoint = nNew;
  52933. /* If this is a release of the outermost savepoint, truncate
  52934. ** the sub-journal to zero bytes in size. */
  52935. if( op==SAVEPOINT_RELEASE ){
  52936. if( nNew==0 && isOpen(pPager->sjfd) ){
  52937. /* Only truncate if it is an in-memory sub-journal. */
  52938. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  52939. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  52940. assert( rc==SQLITE_OK );
  52941. }
  52942. pPager->nSubRec = 0;
  52943. }
  52944. }
  52945. /* Else this is a rollback operation, playback the specified savepoint.
  52946. ** If this is a temp-file, it is possible that the journal file has
  52947. ** not yet been opened. In this case there have been no changes to
  52948. ** the database file, so the playback operation can be skipped.
  52949. */
  52950. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  52951. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  52952. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  52953. assert(rc!=SQLITE_DONE);
  52954. }
  52955. #ifdef SQLITE_ENABLE_ZIPVFS
  52956. /* If the cache has been modified but the savepoint cannot be rolled
  52957. ** back journal_mode=off, put the pager in the error state. This way,
  52958. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  52959. ** can be rolled back at the ZipVFS level. */
  52960. else if(
  52961. pPager->journalMode==PAGER_JOURNALMODE_OFF
  52962. && pPager->eState>=PAGER_WRITER_CACHEMOD
  52963. ){
  52964. pPager->errCode = SQLITE_ABORT;
  52965. pPager->eState = PAGER_ERROR;
  52966. setGetterMethod(pPager);
  52967. }
  52968. #endif
  52969. }
  52970. return rc;
  52971. }
  52972. /*
  52973. ** Return the full pathname of the database file.
  52974. **
  52975. ** Except, if the pager is in-memory only, then return an empty string if
  52976. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  52977. ** used to report the filename to the user, for compatibility with legacy
  52978. ** behavior. But when the Btree needs to know the filename for matching to
  52979. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  52980. ** participate in shared-cache.
  52981. */
  52982. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  52983. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  52984. }
  52985. /*
  52986. ** Return the VFS structure for the pager.
  52987. */
  52988. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  52989. return pPager->pVfs;
  52990. }
  52991. /*
  52992. ** Return the file handle for the database file associated
  52993. ** with the pager. This might return NULL if the file has
  52994. ** not yet been opened.
  52995. */
  52996. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  52997. return pPager->fd;
  52998. }
  52999. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  53000. /*
  53001. ** Reset the lock timeout for pager.
  53002. */
  53003. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager){
  53004. int x = 0;
  53005. sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x);
  53006. }
  53007. #endif
  53008. /*
  53009. ** Return the file handle for the journal file (if it exists).
  53010. ** This will be either the rollback journal or the WAL file.
  53011. */
  53012. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  53013. #if SQLITE_OMIT_WAL
  53014. return pPager->jfd;
  53015. #else
  53016. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  53017. #endif
  53018. }
  53019. /*
  53020. ** Return the full pathname of the journal file.
  53021. */
  53022. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  53023. return pPager->zJournal;
  53024. }
  53025. #ifdef SQLITE_HAS_CODEC
  53026. /*
  53027. ** Set or retrieve the codec for this pager
  53028. */
  53029. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  53030. Pager *pPager,
  53031. void *(*xCodec)(void*,void*,Pgno,int),
  53032. void (*xCodecSizeChng)(void*,int,int),
  53033. void (*xCodecFree)(void*),
  53034. void *pCodec
  53035. ){
  53036. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  53037. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  53038. pPager->xCodecSizeChng = xCodecSizeChng;
  53039. pPager->xCodecFree = xCodecFree;
  53040. pPager->pCodec = pCodec;
  53041. setGetterMethod(pPager);
  53042. pagerReportSize(pPager);
  53043. }
  53044. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  53045. return pPager->pCodec;
  53046. }
  53047. /*
  53048. ** This function is called by the wal module when writing page content
  53049. ** into the log file.
  53050. **
  53051. ** This function returns a pointer to a buffer containing the encrypted
  53052. ** page content. If a malloc fails, this function may return NULL.
  53053. */
  53054. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  53055. void *aData = 0;
  53056. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  53057. return aData;
  53058. }
  53059. /*
  53060. ** Return the current pager state
  53061. */
  53062. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  53063. return pPager->eState;
  53064. }
  53065. #endif /* SQLITE_HAS_CODEC */
  53066. #ifndef SQLITE_OMIT_AUTOVACUUM
  53067. /*
  53068. ** Move the page pPg to location pgno in the file.
  53069. **
  53070. ** There must be no references to the page previously located at
  53071. ** pgno (which we call pPgOld) though that page is allowed to be
  53072. ** in cache. If the page previously located at pgno is not already
  53073. ** in the rollback journal, it is not put there by by this routine.
  53074. **
  53075. ** References to the page pPg remain valid. Updating any
  53076. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  53077. ** allocated along with the page) is the responsibility of the caller.
  53078. **
  53079. ** A transaction must be active when this routine is called. It used to be
  53080. ** required that a statement transaction was not active, but this restriction
  53081. ** has been removed (CREATE INDEX needs to move a page when a statement
  53082. ** transaction is active).
  53083. **
  53084. ** If the fourth argument, isCommit, is non-zero, then this page is being
  53085. ** moved as part of a database reorganization just before the transaction
  53086. ** is being committed. In this case, it is guaranteed that the database page
  53087. ** pPg refers to will not be written to again within this transaction.
  53088. **
  53089. ** This function may return SQLITE_NOMEM or an IO error code if an error
  53090. ** occurs. Otherwise, it returns SQLITE_OK.
  53091. */
  53092. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  53093. PgHdr *pPgOld; /* The page being overwritten. */
  53094. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  53095. int rc; /* Return code */
  53096. Pgno origPgno; /* The original page number */
  53097. assert( pPg->nRef>0 );
  53098. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53099. || pPager->eState==PAGER_WRITER_DBMOD
  53100. );
  53101. assert( assert_pager_state(pPager) );
  53102. /* In order to be able to rollback, an in-memory database must journal
  53103. ** the page we are moving from.
  53104. */
  53105. assert( pPager->tempFile || !MEMDB );
  53106. if( pPager->tempFile ){
  53107. rc = sqlite3PagerWrite(pPg);
  53108. if( rc ) return rc;
  53109. }
  53110. /* If the page being moved is dirty and has not been saved by the latest
  53111. ** savepoint, then save the current contents of the page into the
  53112. ** sub-journal now. This is required to handle the following scenario:
  53113. **
  53114. ** BEGIN;
  53115. ** <journal page X, then modify it in memory>
  53116. ** SAVEPOINT one;
  53117. ** <Move page X to location Y>
  53118. ** ROLLBACK TO one;
  53119. **
  53120. ** If page X were not written to the sub-journal here, it would not
  53121. ** be possible to restore its contents when the "ROLLBACK TO one"
  53122. ** statement were is processed.
  53123. **
  53124. ** subjournalPage() may need to allocate space to store pPg->pgno into
  53125. ** one or more savepoint bitvecs. This is the reason this function
  53126. ** may return SQLITE_NOMEM.
  53127. */
  53128. if( (pPg->flags & PGHDR_DIRTY)!=0
  53129. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  53130. ){
  53131. return rc;
  53132. }
  53133. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  53134. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  53135. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  53136. /* If the journal needs to be sync()ed before page pPg->pgno can
  53137. ** be written to, store pPg->pgno in local variable needSyncPgno.
  53138. **
  53139. ** If the isCommit flag is set, there is no need to remember that
  53140. ** the journal needs to be sync()ed before database page pPg->pgno
  53141. ** can be written to. The caller has already promised not to write to it.
  53142. */
  53143. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  53144. needSyncPgno = pPg->pgno;
  53145. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  53146. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  53147. assert( pPg->flags&PGHDR_DIRTY );
  53148. }
  53149. /* If the cache contains a page with page-number pgno, remove it
  53150. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  53151. ** page pgno before the 'move' operation, it needs to be retained
  53152. ** for the page moved there.
  53153. */
  53154. pPg->flags &= ~PGHDR_NEED_SYNC;
  53155. pPgOld = sqlite3PagerLookup(pPager, pgno);
  53156. assert( !pPgOld || pPgOld->nRef==1 );
  53157. if( pPgOld ){
  53158. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  53159. if( pPager->tempFile ){
  53160. /* Do not discard pages from an in-memory database since we might
  53161. ** need to rollback later. Just move the page out of the way. */
  53162. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  53163. }else{
  53164. sqlite3PcacheDrop(pPgOld);
  53165. }
  53166. }
  53167. origPgno = pPg->pgno;
  53168. sqlite3PcacheMove(pPg, pgno);
  53169. sqlite3PcacheMakeDirty(pPg);
  53170. /* For an in-memory database, make sure the original page continues
  53171. ** to exist, in case the transaction needs to roll back. Use pPgOld
  53172. ** as the original page since it has already been allocated.
  53173. */
  53174. if( pPager->tempFile && pPgOld ){
  53175. sqlite3PcacheMove(pPgOld, origPgno);
  53176. sqlite3PagerUnrefNotNull(pPgOld);
  53177. }
  53178. if( needSyncPgno ){
  53179. /* If needSyncPgno is non-zero, then the journal file needs to be
  53180. ** sync()ed before any data is written to database file page needSyncPgno.
  53181. ** Currently, no such page exists in the page-cache and the
  53182. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  53183. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  53184. ** flag.
  53185. **
  53186. ** If the attempt to load the page into the page-cache fails, (due
  53187. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  53188. ** array. Otherwise, if the page is loaded and written again in
  53189. ** this transaction, it may be written to the database file before
  53190. ** it is synced into the journal file. This way, it may end up in
  53191. ** the journal file twice, but that is not a problem.
  53192. */
  53193. PgHdr *pPgHdr;
  53194. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  53195. if( rc!=SQLITE_OK ){
  53196. if( needSyncPgno<=pPager->dbOrigSize ){
  53197. assert( pPager->pTmpSpace!=0 );
  53198. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  53199. }
  53200. return rc;
  53201. }
  53202. pPgHdr->flags |= PGHDR_NEED_SYNC;
  53203. sqlite3PcacheMakeDirty(pPgHdr);
  53204. sqlite3PagerUnrefNotNull(pPgHdr);
  53205. }
  53206. return SQLITE_OK;
  53207. }
  53208. #endif
  53209. /*
  53210. ** The page handle passed as the first argument refers to a dirty page
  53211. ** with a page number other than iNew. This function changes the page's
  53212. ** page number to iNew and sets the value of the PgHdr.flags field to
  53213. ** the value passed as the third parameter.
  53214. */
  53215. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  53216. assert( pPg->pgno!=iNew );
  53217. pPg->flags = flags;
  53218. sqlite3PcacheMove(pPg, iNew);
  53219. }
  53220. /*
  53221. ** Return a pointer to the data for the specified page.
  53222. */
  53223. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  53224. assert( pPg->nRef>0 || pPg->pPager->memDb );
  53225. return pPg->pData;
  53226. }
  53227. /*
  53228. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  53229. ** allocated along with the specified page.
  53230. */
  53231. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  53232. return pPg->pExtra;
  53233. }
  53234. /*
  53235. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  53236. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  53237. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  53238. ** the locking-mode is set to the value specified.
  53239. **
  53240. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  53241. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  53242. ** locking-mode.
  53243. */
  53244. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  53245. assert( eMode==PAGER_LOCKINGMODE_QUERY
  53246. || eMode==PAGER_LOCKINGMODE_NORMAL
  53247. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  53248. assert( PAGER_LOCKINGMODE_QUERY<0 );
  53249. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  53250. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  53251. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  53252. pPager->exclusiveMode = (u8)eMode;
  53253. }
  53254. return (int)pPager->exclusiveMode;
  53255. }
  53256. /*
  53257. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  53258. **
  53259. ** PAGER_JOURNALMODE_DELETE
  53260. ** PAGER_JOURNALMODE_TRUNCATE
  53261. ** PAGER_JOURNALMODE_PERSIST
  53262. ** PAGER_JOURNALMODE_OFF
  53263. ** PAGER_JOURNALMODE_MEMORY
  53264. ** PAGER_JOURNALMODE_WAL
  53265. **
  53266. ** The journalmode is set to the value specified if the change is allowed.
  53267. ** The change may be disallowed for the following reasons:
  53268. **
  53269. ** * An in-memory database can only have its journal_mode set to _OFF
  53270. ** or _MEMORY.
  53271. **
  53272. ** * Temporary databases cannot have _WAL journalmode.
  53273. **
  53274. ** The returned indicate the current (possibly updated) journal-mode.
  53275. */
  53276. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  53277. u8 eOld = pPager->journalMode; /* Prior journalmode */
  53278. #ifdef SQLITE_DEBUG
  53279. /* The print_pager_state() routine is intended to be used by the debugger
  53280. ** only. We invoke it once here to suppress a compiler warning. */
  53281. print_pager_state(pPager);
  53282. #endif
  53283. /* The eMode parameter is always valid */
  53284. assert( eMode==PAGER_JOURNALMODE_DELETE
  53285. || eMode==PAGER_JOURNALMODE_TRUNCATE
  53286. || eMode==PAGER_JOURNALMODE_PERSIST
  53287. || eMode==PAGER_JOURNALMODE_OFF
  53288. || eMode==PAGER_JOURNALMODE_WAL
  53289. || eMode==PAGER_JOURNALMODE_MEMORY );
  53290. /* This routine is only called from the OP_JournalMode opcode, and
  53291. ** the logic there will never allow a temporary file to be changed
  53292. ** to WAL mode.
  53293. */
  53294. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  53295. /* Do allow the journalmode of an in-memory database to be set to
  53296. ** anything other than MEMORY or OFF
  53297. */
  53298. if( MEMDB ){
  53299. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  53300. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  53301. eMode = eOld;
  53302. }
  53303. }
  53304. if( eMode!=eOld ){
  53305. /* Change the journal mode. */
  53306. assert( pPager->eState!=PAGER_ERROR );
  53307. pPager->journalMode = (u8)eMode;
  53308. /* When transistioning from TRUNCATE or PERSIST to any other journal
  53309. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  53310. ** delete the journal file.
  53311. */
  53312. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  53313. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  53314. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  53315. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  53316. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  53317. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  53318. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  53319. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  53320. /* In this case we would like to delete the journal file. If it is
  53321. ** not possible, then that is not a problem. Deleting the journal file
  53322. ** here is an optimization only.
  53323. **
  53324. ** Before deleting the journal file, obtain a RESERVED lock on the
  53325. ** database file. This ensures that the journal file is not deleted
  53326. ** while it is in use by some other client.
  53327. */
  53328. sqlite3OsClose(pPager->jfd);
  53329. if( pPager->eLock>=RESERVED_LOCK ){
  53330. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  53331. }else{
  53332. int rc = SQLITE_OK;
  53333. int state = pPager->eState;
  53334. assert( state==PAGER_OPEN || state==PAGER_READER );
  53335. if( state==PAGER_OPEN ){
  53336. rc = sqlite3PagerSharedLock(pPager);
  53337. }
  53338. if( pPager->eState==PAGER_READER ){
  53339. assert( rc==SQLITE_OK );
  53340. rc = pagerLockDb(pPager, RESERVED_LOCK);
  53341. }
  53342. if( rc==SQLITE_OK ){
  53343. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  53344. }
  53345. if( rc==SQLITE_OK && state==PAGER_READER ){
  53346. pagerUnlockDb(pPager, SHARED_LOCK);
  53347. }else if( state==PAGER_OPEN ){
  53348. pager_unlock(pPager);
  53349. }
  53350. assert( state==pPager->eState );
  53351. }
  53352. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  53353. sqlite3OsClose(pPager->jfd);
  53354. }
  53355. }
  53356. /* Return the new journal mode */
  53357. return (int)pPager->journalMode;
  53358. }
  53359. /*
  53360. ** Return the current journal mode.
  53361. */
  53362. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  53363. return (int)pPager->journalMode;
  53364. }
  53365. /*
  53366. ** Return TRUE if the pager is in a state where it is OK to change the
  53367. ** journalmode. Journalmode changes can only happen when the database
  53368. ** is unmodified.
  53369. */
  53370. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  53371. assert( assert_pager_state(pPager) );
  53372. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  53373. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  53374. return 1;
  53375. }
  53376. /*
  53377. ** Get/set the size-limit used for persistent journal files.
  53378. **
  53379. ** Setting the size limit to -1 means no limit is enforced.
  53380. ** An attempt to set a limit smaller than -1 is a no-op.
  53381. */
  53382. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  53383. if( iLimit>=-1 ){
  53384. pPager->journalSizeLimit = iLimit;
  53385. sqlite3WalLimit(pPager->pWal, iLimit);
  53386. }
  53387. return pPager->journalSizeLimit;
  53388. }
  53389. /*
  53390. ** Return a pointer to the pPager->pBackup variable. The backup module
  53391. ** in backup.c maintains the content of this variable. This module
  53392. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  53393. ** sqlite3BackupUpdate() only.
  53394. */
  53395. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  53396. return &pPager->pBackup;
  53397. }
  53398. #ifndef SQLITE_OMIT_VACUUM
  53399. /*
  53400. ** Unless this is an in-memory or temporary database, clear the pager cache.
  53401. */
  53402. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  53403. assert( MEMDB==0 || pPager->tempFile );
  53404. if( pPager->tempFile==0 ) pager_reset(pPager);
  53405. }
  53406. #endif
  53407. #ifndef SQLITE_OMIT_WAL
  53408. /*
  53409. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  53410. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  53411. ** or wal_blocking_checkpoint() API functions.
  53412. **
  53413. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  53414. */
  53415. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  53416. Pager *pPager, /* Checkpoint on this pager */
  53417. sqlite3 *db, /* Db handle used to check for interrupts */
  53418. int eMode, /* Type of checkpoint */
  53419. int *pnLog, /* OUT: Final number of frames in log */
  53420. int *pnCkpt /* OUT: Final number of checkpointed frames */
  53421. ){
  53422. int rc = SQLITE_OK;
  53423. if( pPager->pWal ){
  53424. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  53425. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  53426. pPager->pBusyHandlerArg,
  53427. pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  53428. pnLog, pnCkpt
  53429. );
  53430. sqlite3PagerResetLockTimeout(pPager);
  53431. }
  53432. return rc;
  53433. }
  53434. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  53435. return sqlite3WalCallback(pPager->pWal);
  53436. }
  53437. /*
  53438. ** Return true if the underlying VFS for the given pager supports the
  53439. ** primitives necessary for write-ahead logging.
  53440. */
  53441. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  53442. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  53443. if( pPager->noLock ) return 0;
  53444. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  53445. }
  53446. /*
  53447. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  53448. ** is obtained instead, immediately release it.
  53449. */
  53450. static int pagerExclusiveLock(Pager *pPager){
  53451. int rc; /* Return code */
  53452. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  53453. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  53454. if( rc!=SQLITE_OK ){
  53455. /* If the attempt to grab the exclusive lock failed, release the
  53456. ** pending lock that may have been obtained instead. */
  53457. pagerUnlockDb(pPager, SHARED_LOCK);
  53458. }
  53459. return rc;
  53460. }
  53461. /*
  53462. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  53463. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  53464. ** lock on the database file and use heap-memory to store the wal-index
  53465. ** in. Otherwise, use the normal shared-memory.
  53466. */
  53467. static int pagerOpenWal(Pager *pPager){
  53468. int rc = SQLITE_OK;
  53469. assert( pPager->pWal==0 && pPager->tempFile==0 );
  53470. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  53471. /* If the pager is already in exclusive-mode, the WAL module will use
  53472. ** heap-memory for the wal-index instead of the VFS shared-memory
  53473. ** implementation. Take the exclusive lock now, before opening the WAL
  53474. ** file, to make sure this is safe.
  53475. */
  53476. if( pPager->exclusiveMode ){
  53477. rc = pagerExclusiveLock(pPager);
  53478. }
  53479. /* Open the connection to the log file. If this operation fails,
  53480. ** (e.g. due to malloc() failure), return an error code.
  53481. */
  53482. if( rc==SQLITE_OK ){
  53483. rc = sqlite3WalOpen(pPager->pVfs,
  53484. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  53485. pPager->journalSizeLimit, &pPager->pWal
  53486. );
  53487. }
  53488. pagerFixMaplimit(pPager);
  53489. return rc;
  53490. }
  53491. /*
  53492. ** The caller must be holding a SHARED lock on the database file to call
  53493. ** this function.
  53494. **
  53495. ** If the pager passed as the first argument is open on a real database
  53496. ** file (not a temp file or an in-memory database), and the WAL file
  53497. ** is not already open, make an attempt to open it now. If successful,
  53498. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  53499. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  53500. ** not modified in either case.
  53501. **
  53502. ** If the pager is open on a temp-file (or in-memory database), or if
  53503. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  53504. ** without doing anything.
  53505. */
  53506. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  53507. Pager *pPager, /* Pager object */
  53508. int *pbOpen /* OUT: Set to true if call is a no-op */
  53509. ){
  53510. int rc = SQLITE_OK; /* Return code */
  53511. assert( assert_pager_state(pPager) );
  53512. assert( pPager->eState==PAGER_OPEN || pbOpen );
  53513. assert( pPager->eState==PAGER_READER || !pbOpen );
  53514. assert( pbOpen==0 || *pbOpen==0 );
  53515. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  53516. if( !pPager->tempFile && !pPager->pWal ){
  53517. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  53518. /* Close any rollback journal previously open */
  53519. sqlite3OsClose(pPager->jfd);
  53520. rc = pagerOpenWal(pPager);
  53521. if( rc==SQLITE_OK ){
  53522. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  53523. pPager->eState = PAGER_OPEN;
  53524. }
  53525. }else{
  53526. *pbOpen = 1;
  53527. }
  53528. return rc;
  53529. }
  53530. /*
  53531. ** This function is called to close the connection to the log file prior
  53532. ** to switching from WAL to rollback mode.
  53533. **
  53534. ** Before closing the log file, this function attempts to take an
  53535. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  53536. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  53537. ** If successful, the EXCLUSIVE lock is not released before returning.
  53538. */
  53539. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  53540. int rc = SQLITE_OK;
  53541. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  53542. /* If the log file is not already open, but does exist in the file-system,
  53543. ** it may need to be checkpointed before the connection can switch to
  53544. ** rollback mode. Open it now so this can happen.
  53545. */
  53546. if( !pPager->pWal ){
  53547. int logexists = 0;
  53548. rc = pagerLockDb(pPager, SHARED_LOCK);
  53549. if( rc==SQLITE_OK ){
  53550. rc = sqlite3OsAccess(
  53551. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  53552. );
  53553. }
  53554. if( rc==SQLITE_OK && logexists ){
  53555. rc = pagerOpenWal(pPager);
  53556. }
  53557. }
  53558. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  53559. ** the database file, the log and log-summary files will be deleted.
  53560. */
  53561. if( rc==SQLITE_OK && pPager->pWal ){
  53562. rc = pagerExclusiveLock(pPager);
  53563. if( rc==SQLITE_OK ){
  53564. rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
  53565. pPager->pageSize, (u8*)pPager->pTmpSpace);
  53566. pPager->pWal = 0;
  53567. pagerFixMaplimit(pPager);
  53568. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  53569. }
  53570. }
  53571. return rc;
  53572. }
  53573. #ifdef SQLITE_ENABLE_SNAPSHOT
  53574. /*
  53575. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  53576. ** currently open. Otherwise, return an error.
  53577. */
  53578. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  53579. int rc = SQLITE_ERROR;
  53580. if( pPager->pWal ){
  53581. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  53582. }
  53583. return rc;
  53584. }
  53585. /*
  53586. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  53587. ** read transaction is opened, attempt to read from the snapshot it
  53588. ** identifies. If this is not a WAL database, return an error.
  53589. */
  53590. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  53591. int rc = SQLITE_OK;
  53592. if( pPager->pWal ){
  53593. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  53594. }else{
  53595. rc = SQLITE_ERROR;
  53596. }
  53597. return rc;
  53598. }
  53599. /*
  53600. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  53601. ** is not a WAL database, return an error.
  53602. */
  53603. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  53604. int rc;
  53605. if( pPager->pWal ){
  53606. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  53607. }else{
  53608. rc = SQLITE_ERROR;
  53609. }
  53610. return rc;
  53611. }
  53612. #endif /* SQLITE_ENABLE_SNAPSHOT */
  53613. #endif /* !SQLITE_OMIT_WAL */
  53614. #ifdef SQLITE_ENABLE_ZIPVFS
  53615. /*
  53616. ** A read-lock must be held on the pager when this function is called. If
  53617. ** the pager is in WAL mode and the WAL file currently contains one or more
  53618. ** frames, return the size in bytes of the page images stored within the
  53619. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  53620. ** is empty, return 0.
  53621. */
  53622. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  53623. assert( pPager->eState>=PAGER_READER );
  53624. return sqlite3WalFramesize(pPager->pWal);
  53625. }
  53626. #endif
  53627. #endif /* SQLITE_OMIT_DISKIO */
  53628. /************** End of pager.c ***********************************************/
  53629. /************** Begin file wal.c *********************************************/
  53630. /*
  53631. ** 2010 February 1
  53632. **
  53633. ** The author disclaims copyright to this source code. In place of
  53634. ** a legal notice, here is a blessing:
  53635. **
  53636. ** May you do good and not evil.
  53637. ** May you find forgiveness for yourself and forgive others.
  53638. ** May you share freely, never taking more than you give.
  53639. **
  53640. *************************************************************************
  53641. **
  53642. ** This file contains the implementation of a write-ahead log (WAL) used in
  53643. ** "journal_mode=WAL" mode.
  53644. **
  53645. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  53646. **
  53647. ** A WAL file consists of a header followed by zero or more "frames".
  53648. ** Each frame records the revised content of a single page from the
  53649. ** database file. All changes to the database are recorded by writing
  53650. ** frames into the WAL. Transactions commit when a frame is written that
  53651. ** contains a commit marker. A single WAL can and usually does record
  53652. ** multiple transactions. Periodically, the content of the WAL is
  53653. ** transferred back into the database file in an operation called a
  53654. ** "checkpoint".
  53655. **
  53656. ** A single WAL file can be used multiple times. In other words, the
  53657. ** WAL can fill up with frames and then be checkpointed and then new
  53658. ** frames can overwrite the old ones. A WAL always grows from beginning
  53659. ** toward the end. Checksums and counters attached to each frame are
  53660. ** used to determine which frames within the WAL are valid and which
  53661. ** are leftovers from prior checkpoints.
  53662. **
  53663. ** The WAL header is 32 bytes in size and consists of the following eight
  53664. ** big-endian 32-bit unsigned integer values:
  53665. **
  53666. ** 0: Magic number. 0x377f0682 or 0x377f0683
  53667. ** 4: File format version. Currently 3007000
  53668. ** 8: Database page size. Example: 1024
  53669. ** 12: Checkpoint sequence number
  53670. ** 16: Salt-1, random integer incremented with each checkpoint
  53671. ** 20: Salt-2, a different random integer changing with each ckpt
  53672. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  53673. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  53674. **
  53675. ** Immediately following the wal-header are zero or more frames. Each
  53676. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  53677. ** of page data. The frame-header is six big-endian 32-bit unsigned
  53678. ** integer values, as follows:
  53679. **
  53680. ** 0: Page number.
  53681. ** 4: For commit records, the size of the database image in pages
  53682. ** after the commit. For all other records, zero.
  53683. ** 8: Salt-1 (copied from the header)
  53684. ** 12: Salt-2 (copied from the header)
  53685. ** 16: Checksum-1.
  53686. ** 20: Checksum-2.
  53687. **
  53688. ** A frame is considered valid if and only if the following conditions are
  53689. ** true:
  53690. **
  53691. ** (1) The salt-1 and salt-2 values in the frame-header match
  53692. ** salt values in the wal-header
  53693. **
  53694. ** (2) The checksum values in the final 8 bytes of the frame-header
  53695. ** exactly match the checksum computed consecutively on the
  53696. ** WAL header and the first 8 bytes and the content of all frames
  53697. ** up to and including the current frame.
  53698. **
  53699. ** The checksum is computed using 32-bit big-endian integers if the
  53700. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  53701. ** is computed using little-endian if the magic number is 0x377f0682.
  53702. ** The checksum values are always stored in the frame header in a
  53703. ** big-endian format regardless of which byte order is used to compute
  53704. ** the checksum. The checksum is computed by interpreting the input as
  53705. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  53706. ** algorithm used for the checksum is as follows:
  53707. **
  53708. ** for i from 0 to n-1 step 2:
  53709. ** s0 += x[i] + s1;
  53710. ** s1 += x[i+1] + s0;
  53711. ** endfor
  53712. **
  53713. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  53714. ** in reverse order (the largest fibonacci weight occurs on the first element
  53715. ** of the sequence being summed.) The s1 value spans all 32-bit
  53716. ** terms of the sequence whereas s0 omits the final term.
  53717. **
  53718. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  53719. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  53720. ** The VFS.xSync operations serve as write barriers - all writes launched
  53721. ** before the xSync must complete before any write that launches after the
  53722. ** xSync begins.
  53723. **
  53724. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  53725. ** value is randomized. This prevents old and new frames in the WAL from
  53726. ** being considered valid at the same time and being checkpointing together
  53727. ** following a crash.
  53728. **
  53729. ** READER ALGORITHM
  53730. **
  53731. ** To read a page from the database (call it page number P), a reader
  53732. ** first checks the WAL to see if it contains page P. If so, then the
  53733. ** last valid instance of page P that is a followed by a commit frame
  53734. ** or is a commit frame itself becomes the value read. If the WAL
  53735. ** contains no copies of page P that are valid and which are a commit
  53736. ** frame or are followed by a commit frame, then page P is read from
  53737. ** the database file.
  53738. **
  53739. ** To start a read transaction, the reader records the index of the last
  53740. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  53741. ** for all subsequent read operations. New transactions can be appended
  53742. ** to the WAL, but as long as the reader uses its original mxFrame value
  53743. ** and ignores the newly appended content, it will see a consistent snapshot
  53744. ** of the database from a single point in time. This technique allows
  53745. ** multiple concurrent readers to view different versions of the database
  53746. ** content simultaneously.
  53747. **
  53748. ** The reader algorithm in the previous paragraphs works correctly, but
  53749. ** because frames for page P can appear anywhere within the WAL, the
  53750. ** reader has to scan the entire WAL looking for page P frames. If the
  53751. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  53752. ** and read performance suffers. To overcome this problem, a separate
  53753. ** data structure called the wal-index is maintained to expedite the
  53754. ** search for frames of a particular page.
  53755. **
  53756. ** WAL-INDEX FORMAT
  53757. **
  53758. ** Conceptually, the wal-index is shared memory, though VFS implementations
  53759. ** might choose to implement the wal-index using a mmapped file. Because
  53760. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  53761. ** on a network filesystem. All users of the database must be able to
  53762. ** share memory.
  53763. **
  53764. ** In the default unix and windows implementation, the wal-index is a mmapped
  53765. ** file whose name is the database name with a "-shm" suffix added. For that
  53766. ** reason, the wal-index is sometimes called the "shm" file.
  53767. **
  53768. ** The wal-index is transient. After a crash, the wal-index can (and should
  53769. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  53770. ** to either truncate or zero the header of the wal-index when the last
  53771. ** connection to it closes. Because the wal-index is transient, it can
  53772. ** use an architecture-specific format; it does not have to be cross-platform.
  53773. ** Hence, unlike the database and WAL file formats which store all values
  53774. ** as big endian, the wal-index can store multi-byte values in the native
  53775. ** byte order of the host computer.
  53776. **
  53777. ** The purpose of the wal-index is to answer this question quickly: Given
  53778. ** a page number P and a maximum frame index M, return the index of the
  53779. ** last frame in the wal before frame M for page P in the WAL, or return
  53780. ** NULL if there are no frames for page P in the WAL prior to M.
  53781. **
  53782. ** The wal-index consists of a header region, followed by an one or
  53783. ** more index blocks.
  53784. **
  53785. ** The wal-index header contains the total number of frames within the WAL
  53786. ** in the mxFrame field.
  53787. **
  53788. ** Each index block except for the first contains information on
  53789. ** HASHTABLE_NPAGE frames. The first index block contains information on
  53790. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  53791. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  53792. ** first index block are the same size as all other index blocks in the
  53793. ** wal-index.
  53794. **
  53795. ** Each index block contains two sections, a page-mapping that contains the
  53796. ** database page number associated with each wal frame, and a hash-table
  53797. ** that allows readers to query an index block for a specific page number.
  53798. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  53799. ** for the first index block) 32-bit page numbers. The first entry in the
  53800. ** first index-block contains the database page number corresponding to the
  53801. ** first frame in the WAL file. The first entry in the second index block
  53802. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  53803. ** the log, and so on.
  53804. **
  53805. ** The last index block in a wal-index usually contains less than the full
  53806. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  53807. ** depending on the contents of the WAL file. This does not change the
  53808. ** allocated size of the page-mapping array - the page-mapping array merely
  53809. ** contains unused entries.
  53810. **
  53811. ** Even without using the hash table, the last frame for page P
  53812. ** can be found by scanning the page-mapping sections of each index block
  53813. ** starting with the last index block and moving toward the first, and
  53814. ** within each index block, starting at the end and moving toward the
  53815. ** beginning. The first entry that equals P corresponds to the frame
  53816. ** holding the content for that page.
  53817. **
  53818. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  53819. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  53820. ** hash table for each page number in the mapping section, so the hash
  53821. ** table is never more than half full. The expected number of collisions
  53822. ** prior to finding a match is 1. Each entry of the hash table is an
  53823. ** 1-based index of an entry in the mapping section of the same
  53824. ** index block. Let K be the 1-based index of the largest entry in
  53825. ** the mapping section. (For index blocks other than the last, K will
  53826. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  53827. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  53828. ** contain a value of 0.
  53829. **
  53830. ** To look for page P in the hash table, first compute a hash iKey on
  53831. ** P as follows:
  53832. **
  53833. ** iKey = (P * 383) % HASHTABLE_NSLOT
  53834. **
  53835. ** Then start scanning entries of the hash table, starting with iKey
  53836. ** (wrapping around to the beginning when the end of the hash table is
  53837. ** reached) until an unused hash slot is found. Let the first unused slot
  53838. ** be at index iUnused. (iUnused might be less than iKey if there was
  53839. ** wrap-around.) Because the hash table is never more than half full,
  53840. ** the search is guaranteed to eventually hit an unused entry. Let
  53841. ** iMax be the value between iKey and iUnused, closest to iUnused,
  53842. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  53843. ** no hash slot such that aHash[i]==p) then page P is not in the
  53844. ** current index block. Otherwise the iMax-th mapping entry of the
  53845. ** current index block corresponds to the last entry that references
  53846. ** page P.
  53847. **
  53848. ** A hash search begins with the last index block and moves toward the
  53849. ** first index block, looking for entries corresponding to page P. On
  53850. ** average, only two or three slots in each index block need to be
  53851. ** examined in order to either find the last entry for page P, or to
  53852. ** establish that no such entry exists in the block. Each index block
  53853. ** holds over 4000 entries. So two or three index blocks are sufficient
  53854. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  53855. ** comparisons (on average) suffice to either locate a frame in the
  53856. ** WAL or to establish that the frame does not exist in the WAL. This
  53857. ** is much faster than scanning the entire 10MB WAL.
  53858. **
  53859. ** Note that entries are added in order of increasing K. Hence, one
  53860. ** reader might be using some value K0 and a second reader that started
  53861. ** at a later time (after additional transactions were added to the WAL
  53862. ** and to the wal-index) might be using a different value K1, where K1>K0.
  53863. ** Both readers can use the same hash table and mapping section to get
  53864. ** the correct result. There may be entries in the hash table with
  53865. ** K>K0 but to the first reader, those entries will appear to be unused
  53866. ** slots in the hash table and so the first reader will get an answer as
  53867. ** if no values greater than K0 had ever been inserted into the hash table
  53868. ** in the first place - which is what reader one wants. Meanwhile, the
  53869. ** second reader using K1 will see additional values that were inserted
  53870. ** later, which is exactly what reader two wants.
  53871. **
  53872. ** When a rollback occurs, the value of K is decreased. Hash table entries
  53873. ** that correspond to frames greater than the new K value are removed
  53874. ** from the hash table at this point.
  53875. */
  53876. #ifndef SQLITE_OMIT_WAL
  53877. /* #include "wal.h" */
  53878. /*
  53879. ** Trace output macros
  53880. */
  53881. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  53882. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  53883. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  53884. #else
  53885. # define WALTRACE(X)
  53886. #endif
  53887. /*
  53888. ** The maximum (and only) versions of the wal and wal-index formats
  53889. ** that may be interpreted by this version of SQLite.
  53890. **
  53891. ** If a client begins recovering a WAL file and finds that (a) the checksum
  53892. ** values in the wal-header are correct and (b) the version field is not
  53893. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  53894. **
  53895. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  53896. ** checksum test is successful) and finds that the version field is not
  53897. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  53898. ** returns SQLITE_CANTOPEN.
  53899. */
  53900. #define WAL_MAX_VERSION 3007000
  53901. #define WALINDEX_MAX_VERSION 3007000
  53902. /*
  53903. ** Index numbers for various locking bytes. WAL_NREADER is the number
  53904. ** of available reader locks and should be at least 3. The default
  53905. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  53906. **
  53907. ** Technically, the various VFSes are free to implement these locks however
  53908. ** they see fit. However, compatibility is encouraged so that VFSes can
  53909. ** interoperate. The standard implemention used on both unix and windows
  53910. ** is for the index number to indicate a byte offset into the
  53911. ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
  53912. ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
  53913. ** should be 120) is the location in the shm file for the first locking
  53914. ** byte.
  53915. */
  53916. #define WAL_WRITE_LOCK 0
  53917. #define WAL_ALL_BUT_WRITE 1
  53918. #define WAL_CKPT_LOCK 1
  53919. #define WAL_RECOVER_LOCK 2
  53920. #define WAL_READ_LOCK(I) (3+(I))
  53921. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  53922. /* Object declarations */
  53923. typedef struct WalIndexHdr WalIndexHdr;
  53924. typedef struct WalIterator WalIterator;
  53925. typedef struct WalCkptInfo WalCkptInfo;
  53926. /*
  53927. ** The following object holds a copy of the wal-index header content.
  53928. **
  53929. ** The actual header in the wal-index consists of two copies of this
  53930. ** object followed by one instance of the WalCkptInfo object.
  53931. ** For all versions of SQLite through 3.10.0 and probably beyond,
  53932. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  53933. ** the total header size is 136 bytes.
  53934. **
  53935. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  53936. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  53937. ** added in 3.7.1 when support for 64K pages was added.
  53938. */
  53939. struct WalIndexHdr {
  53940. u32 iVersion; /* Wal-index version */
  53941. u32 unused; /* Unused (padding) field */
  53942. u32 iChange; /* Counter incremented each transaction */
  53943. u8 isInit; /* 1 when initialized */
  53944. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  53945. u16 szPage; /* Database page size in bytes. 1==64K */
  53946. u32 mxFrame; /* Index of last valid frame in the WAL */
  53947. u32 nPage; /* Size of database in pages */
  53948. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  53949. u32 aSalt[2]; /* Two salt values copied from WAL header */
  53950. u32 aCksum[2]; /* Checksum over all prior fields */
  53951. };
  53952. /*
  53953. ** A copy of the following object occurs in the wal-index immediately
  53954. ** following the second copy of the WalIndexHdr. This object stores
  53955. ** information used by checkpoint.
  53956. **
  53957. ** nBackfill is the number of frames in the WAL that have been written
  53958. ** back into the database. (We call the act of moving content from WAL to
  53959. ** database "backfilling".) The nBackfill number is never greater than
  53960. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  53961. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  53962. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  53963. ** mxFrame back to zero when the WAL is reset.
  53964. **
  53965. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  53966. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  53967. ** the nBackfillAttempted is set before any backfilling is done and the
  53968. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  53969. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  53970. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  53971. **
  53972. ** The aLock[] field is a set of bytes used for locking. These bytes should
  53973. ** never be read or written.
  53974. **
  53975. ** There is one entry in aReadMark[] for each reader lock. If a reader
  53976. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  53977. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  53978. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  53979. ** a special case; its value is never used and it exists as a place-holder
  53980. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  53981. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  53982. ** directly from the database.
  53983. **
  53984. ** The value of aReadMark[K] may only be changed by a thread that
  53985. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  53986. ** aReadMark[K] cannot changed while there is a reader is using that mark
  53987. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  53988. **
  53989. ** The checkpointer may only transfer frames from WAL to database where
  53990. ** the frame numbers are less than or equal to every aReadMark[] that is
  53991. ** in use (that is, every aReadMark[j] for which there is a corresponding
  53992. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  53993. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  53994. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  53995. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  53996. ** in the WAL has been backfilled into the database) then new readers
  53997. ** will choose aReadMark[0] which has value 0 and hence such reader will
  53998. ** get all their all content directly from the database file and ignore
  53999. ** the WAL.
  54000. **
  54001. ** Writers normally append new frames to the end of the WAL. However,
  54002. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  54003. ** written back into the database) and if no readers are using the WAL
  54004. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  54005. ** the writer will first "reset" the WAL back to the beginning and start
  54006. ** writing new content beginning at frame 1.
  54007. **
  54008. ** We assume that 32-bit loads are atomic and so no locks are needed in
  54009. ** order to read from any aReadMark[] entries.
  54010. */
  54011. struct WalCkptInfo {
  54012. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  54013. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  54014. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  54015. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  54016. u32 notUsed0; /* Available for future enhancements */
  54017. };
  54018. #define READMARK_NOT_USED 0xffffffff
  54019. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  54020. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  54021. ** only support mandatory file-locks, we do not read or write data
  54022. ** from the region of the file on which locks are applied.
  54023. */
  54024. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  54025. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  54026. /* Size of header before each frame in wal */
  54027. #define WAL_FRAME_HDRSIZE 24
  54028. /* Size of write ahead log header, including checksum. */
  54029. #define WAL_HDRSIZE 32
  54030. /* WAL magic value. Either this value, or the same value with the least
  54031. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  54032. ** big-endian format in the first 4 bytes of a WAL file.
  54033. **
  54034. ** If the LSB is set, then the checksums for each frame within the WAL
  54035. ** file are calculated by treating all data as an array of 32-bit
  54036. ** big-endian words. Otherwise, they are calculated by interpreting
  54037. ** all data as 32-bit little-endian words.
  54038. */
  54039. #define WAL_MAGIC 0x377f0682
  54040. /*
  54041. ** Return the offset of frame iFrame in the write-ahead log file,
  54042. ** assuming a database page size of szPage bytes. The offset returned
  54043. ** is to the start of the write-ahead log frame-header.
  54044. */
  54045. #define walFrameOffset(iFrame, szPage) ( \
  54046. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  54047. )
  54048. /*
  54049. ** An open write-ahead log file is represented by an instance of the
  54050. ** following object.
  54051. */
  54052. struct Wal {
  54053. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  54054. sqlite3_file *pDbFd; /* File handle for the database file */
  54055. sqlite3_file *pWalFd; /* File handle for WAL file */
  54056. u32 iCallback; /* Value to pass to log callback (or 0) */
  54057. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  54058. int nWiData; /* Size of array apWiData */
  54059. int szFirstBlock; /* Size of first block written to WAL file */
  54060. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  54061. u32 szPage; /* Database page size */
  54062. i16 readLock; /* Which read lock is being held. -1 for none */
  54063. u8 syncFlags; /* Flags to use to sync header writes */
  54064. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  54065. u8 writeLock; /* True if in a write transaction */
  54066. u8 ckptLock; /* True if holding a checkpoint lock */
  54067. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  54068. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  54069. u8 syncHeader; /* Fsync the WAL header if true */
  54070. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  54071. u8 bShmUnreliable; /* SHM content is read-only and unreliable */
  54072. WalIndexHdr hdr; /* Wal-index header for current transaction */
  54073. u32 minFrame; /* Ignore wal frames before this one */
  54074. u32 iReCksum; /* On commit, recalculate checksums from here */
  54075. const char *zWalName; /* Name of WAL file */
  54076. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  54077. #ifdef SQLITE_DEBUG
  54078. u8 lockError; /* True if a locking error has occurred */
  54079. #endif
  54080. #ifdef SQLITE_ENABLE_SNAPSHOT
  54081. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  54082. #endif
  54083. };
  54084. /*
  54085. ** Candidate values for Wal.exclusiveMode.
  54086. */
  54087. #define WAL_NORMAL_MODE 0
  54088. #define WAL_EXCLUSIVE_MODE 1
  54089. #define WAL_HEAPMEMORY_MODE 2
  54090. /*
  54091. ** Possible values for WAL.readOnly
  54092. */
  54093. #define WAL_RDWR 0 /* Normal read/write connection */
  54094. #define WAL_RDONLY 1 /* The WAL file is readonly */
  54095. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  54096. /*
  54097. ** Each page of the wal-index mapping contains a hash-table made up of
  54098. ** an array of HASHTABLE_NSLOT elements of the following type.
  54099. */
  54100. typedef u16 ht_slot;
  54101. /*
  54102. ** This structure is used to implement an iterator that loops through
  54103. ** all frames in the WAL in database page order. Where two or more frames
  54104. ** correspond to the same database page, the iterator visits only the
  54105. ** frame most recently written to the WAL (in other words, the frame with
  54106. ** the largest index).
  54107. **
  54108. ** The internals of this structure are only accessed by:
  54109. **
  54110. ** walIteratorInit() - Create a new iterator,
  54111. ** walIteratorNext() - Step an iterator,
  54112. ** walIteratorFree() - Free an iterator.
  54113. **
  54114. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  54115. */
  54116. struct WalIterator {
  54117. int iPrior; /* Last result returned from the iterator */
  54118. int nSegment; /* Number of entries in aSegment[] */
  54119. struct WalSegment {
  54120. int iNext; /* Next slot in aIndex[] not yet returned */
  54121. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  54122. u32 *aPgno; /* Array of page numbers. */
  54123. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  54124. int iZero; /* Frame number associated with aPgno[0] */
  54125. } aSegment[1]; /* One for every 32KB page in the wal-index */
  54126. };
  54127. /*
  54128. ** Define the parameters of the hash tables in the wal-index file. There
  54129. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  54130. ** wal-index.
  54131. **
  54132. ** Changing any of these constants will alter the wal-index format and
  54133. ** create incompatibilities.
  54134. */
  54135. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  54136. #define HASHTABLE_HASH_1 383 /* Should be prime */
  54137. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  54138. /*
  54139. ** The block of page numbers associated with the first hash-table in a
  54140. ** wal-index is smaller than usual. This is so that there is a complete
  54141. ** hash-table on each aligned 32KB page of the wal-index.
  54142. */
  54143. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  54144. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  54145. #define WALINDEX_PGSZ ( \
  54146. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  54147. )
  54148. /*
  54149. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  54150. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  54151. ** numbered from zero.
  54152. **
  54153. ** If the wal-index is currently smaller the iPage pages then the size
  54154. ** of the wal-index might be increased, but only if it is safe to do
  54155. ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
  54156. ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
  54157. **
  54158. ** If this call is successful, *ppPage is set to point to the wal-index
  54159. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  54160. ** then an SQLite error code is returned and *ppPage is set to 0.
  54161. */
  54162. static SQLITE_NOINLINE int walIndexPageRealloc(
  54163. Wal *pWal, /* The WAL context */
  54164. int iPage, /* The page we seek */
  54165. volatile u32 **ppPage /* Write the page pointer here */
  54166. ){
  54167. int rc = SQLITE_OK;
  54168. /* Enlarge the pWal->apWiData[] array if required */
  54169. if( pWal->nWiData<=iPage ){
  54170. int nByte = sizeof(u32*)*(iPage+1);
  54171. volatile u32 **apNew;
  54172. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  54173. if( !apNew ){
  54174. *ppPage = 0;
  54175. return SQLITE_NOMEM_BKPT;
  54176. }
  54177. memset((void*)&apNew[pWal->nWiData], 0,
  54178. sizeof(u32*)*(iPage+1-pWal->nWiData));
  54179. pWal->apWiData = apNew;
  54180. pWal->nWiData = iPage+1;
  54181. }
  54182. /* Request a pointer to the required page from the VFS */
  54183. assert( pWal->apWiData[iPage]==0 );
  54184. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  54185. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  54186. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  54187. }else{
  54188. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  54189. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  54190. );
  54191. assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
  54192. testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
  54193. if( (rc&0xff)==SQLITE_READONLY ){
  54194. pWal->readOnly |= WAL_SHM_RDONLY;
  54195. if( rc==SQLITE_READONLY ){
  54196. rc = SQLITE_OK;
  54197. }
  54198. }
  54199. }
  54200. *ppPage = pWal->apWiData[iPage];
  54201. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  54202. return rc;
  54203. }
  54204. static int walIndexPage(
  54205. Wal *pWal, /* The WAL context */
  54206. int iPage, /* The page we seek */
  54207. volatile u32 **ppPage /* Write the page pointer here */
  54208. ){
  54209. if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
  54210. return walIndexPageRealloc(pWal, iPage, ppPage);
  54211. }
  54212. return SQLITE_OK;
  54213. }
  54214. /*
  54215. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  54216. */
  54217. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  54218. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  54219. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  54220. }
  54221. /*
  54222. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  54223. */
  54224. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  54225. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  54226. return (volatile WalIndexHdr*)pWal->apWiData[0];
  54227. }
  54228. /*
  54229. ** The argument to this macro must be of type u32. On a little-endian
  54230. ** architecture, it returns the u32 value that results from interpreting
  54231. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  54232. ** returns the value that would be produced by interpreting the 4 bytes
  54233. ** of the input value as a little-endian integer.
  54234. */
  54235. #define BYTESWAP32(x) ( \
  54236. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  54237. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  54238. )
  54239. /*
  54240. ** Generate or extend an 8 byte checksum based on the data in
  54241. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  54242. ** initial values of 0 and 0 if aIn==NULL).
  54243. **
  54244. ** The checksum is written back into aOut[] before returning.
  54245. **
  54246. ** nByte must be a positive multiple of 8.
  54247. */
  54248. static void walChecksumBytes(
  54249. int nativeCksum, /* True for native byte-order, false for non-native */
  54250. u8 *a, /* Content to be checksummed */
  54251. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  54252. const u32 *aIn, /* Initial checksum value input */
  54253. u32 *aOut /* OUT: Final checksum value output */
  54254. ){
  54255. u32 s1, s2;
  54256. u32 *aData = (u32 *)a;
  54257. u32 *aEnd = (u32 *)&a[nByte];
  54258. if( aIn ){
  54259. s1 = aIn[0];
  54260. s2 = aIn[1];
  54261. }else{
  54262. s1 = s2 = 0;
  54263. }
  54264. assert( nByte>=8 );
  54265. assert( (nByte&0x00000007)==0 );
  54266. if( nativeCksum ){
  54267. do {
  54268. s1 += *aData++ + s2;
  54269. s2 += *aData++ + s1;
  54270. }while( aData<aEnd );
  54271. }else{
  54272. do {
  54273. s1 += BYTESWAP32(aData[0]) + s2;
  54274. s2 += BYTESWAP32(aData[1]) + s1;
  54275. aData += 2;
  54276. }while( aData<aEnd );
  54277. }
  54278. aOut[0] = s1;
  54279. aOut[1] = s2;
  54280. }
  54281. static void walShmBarrier(Wal *pWal){
  54282. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  54283. sqlite3OsShmBarrier(pWal->pDbFd);
  54284. }
  54285. }
  54286. /*
  54287. ** Write the header information in pWal->hdr into the wal-index.
  54288. **
  54289. ** The checksum on pWal->hdr is updated before it is written.
  54290. */
  54291. static void walIndexWriteHdr(Wal *pWal){
  54292. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  54293. const int nCksum = offsetof(WalIndexHdr, aCksum);
  54294. assert( pWal->writeLock );
  54295. pWal->hdr.isInit = 1;
  54296. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  54297. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  54298. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  54299. walShmBarrier(pWal);
  54300. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  54301. }
  54302. /*
  54303. ** This function encodes a single frame header and writes it to a buffer
  54304. ** supplied by the caller. A frame-header is made up of a series of
  54305. ** 4-byte big-endian integers, as follows:
  54306. **
  54307. ** 0: Page number.
  54308. ** 4: For commit records, the size of the database image in pages
  54309. ** after the commit. For all other records, zero.
  54310. ** 8: Salt-1 (copied from the wal-header)
  54311. ** 12: Salt-2 (copied from the wal-header)
  54312. ** 16: Checksum-1.
  54313. ** 20: Checksum-2.
  54314. */
  54315. static void walEncodeFrame(
  54316. Wal *pWal, /* The write-ahead log */
  54317. u32 iPage, /* Database page number for frame */
  54318. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  54319. u8 *aData, /* Pointer to page data */
  54320. u8 *aFrame /* OUT: Write encoded frame here */
  54321. ){
  54322. int nativeCksum; /* True for native byte-order checksums */
  54323. u32 *aCksum = pWal->hdr.aFrameCksum;
  54324. assert( WAL_FRAME_HDRSIZE==24 );
  54325. sqlite3Put4byte(&aFrame[0], iPage);
  54326. sqlite3Put4byte(&aFrame[4], nTruncate);
  54327. if( pWal->iReCksum==0 ){
  54328. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  54329. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  54330. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  54331. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  54332. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  54333. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  54334. }else{
  54335. memset(&aFrame[8], 0, 16);
  54336. }
  54337. }
  54338. /*
  54339. ** Check to see if the frame with header in aFrame[] and content
  54340. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  54341. ** *pnTruncate and return true. Return if the frame is not valid.
  54342. */
  54343. static int walDecodeFrame(
  54344. Wal *pWal, /* The write-ahead log */
  54345. u32 *piPage, /* OUT: Database page number for frame */
  54346. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  54347. u8 *aData, /* Pointer to page data (for checksum) */
  54348. u8 *aFrame /* Frame data */
  54349. ){
  54350. int nativeCksum; /* True for native byte-order checksums */
  54351. u32 *aCksum = pWal->hdr.aFrameCksum;
  54352. u32 pgno; /* Page number of the frame */
  54353. assert( WAL_FRAME_HDRSIZE==24 );
  54354. /* A frame is only valid if the salt values in the frame-header
  54355. ** match the salt values in the wal-header.
  54356. */
  54357. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  54358. return 0;
  54359. }
  54360. /* A frame is only valid if the page number is creater than zero.
  54361. */
  54362. pgno = sqlite3Get4byte(&aFrame[0]);
  54363. if( pgno==0 ){
  54364. return 0;
  54365. }
  54366. /* A frame is only valid if a checksum of the WAL header,
  54367. ** all prior frams, the first 16 bytes of this frame-header,
  54368. ** and the frame-data matches the checksum in the last 8
  54369. ** bytes of this frame-header.
  54370. */
  54371. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  54372. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  54373. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  54374. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  54375. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  54376. ){
  54377. /* Checksum failed. */
  54378. return 0;
  54379. }
  54380. /* If we reach this point, the frame is valid. Return the page number
  54381. ** and the new database size.
  54382. */
  54383. *piPage = pgno;
  54384. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  54385. return 1;
  54386. }
  54387. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  54388. /*
  54389. ** Names of locks. This routine is used to provide debugging output and is not
  54390. ** a part of an ordinary build.
  54391. */
  54392. static const char *walLockName(int lockIdx){
  54393. if( lockIdx==WAL_WRITE_LOCK ){
  54394. return "WRITE-LOCK";
  54395. }else if( lockIdx==WAL_CKPT_LOCK ){
  54396. return "CKPT-LOCK";
  54397. }else if( lockIdx==WAL_RECOVER_LOCK ){
  54398. return "RECOVER-LOCK";
  54399. }else{
  54400. static char zName[15];
  54401. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  54402. lockIdx-WAL_READ_LOCK(0));
  54403. return zName;
  54404. }
  54405. }
  54406. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  54407. /*
  54408. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  54409. ** A lock cannot be moved directly between shared and exclusive - it must go
  54410. ** through the unlocked state first.
  54411. **
  54412. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  54413. */
  54414. static int walLockShared(Wal *pWal, int lockIdx){
  54415. int rc;
  54416. if( pWal->exclusiveMode ) return SQLITE_OK;
  54417. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  54418. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  54419. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  54420. walLockName(lockIdx), rc ? "failed" : "ok"));
  54421. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  54422. return rc;
  54423. }
  54424. static void walUnlockShared(Wal *pWal, int lockIdx){
  54425. if( pWal->exclusiveMode ) return;
  54426. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  54427. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  54428. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  54429. }
  54430. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  54431. int rc;
  54432. if( pWal->exclusiveMode ) return SQLITE_OK;
  54433. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  54434. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  54435. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  54436. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  54437. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  54438. return rc;
  54439. }
  54440. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  54441. if( pWal->exclusiveMode ) return;
  54442. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  54443. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  54444. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  54445. walLockName(lockIdx), n));
  54446. }
  54447. /*
  54448. ** Compute a hash on a page number. The resulting hash value must land
  54449. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  54450. ** the hash to the next value in the event of a collision.
  54451. */
  54452. static int walHash(u32 iPage){
  54453. assert( iPage>0 );
  54454. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  54455. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  54456. }
  54457. static int walNextHash(int iPriorHash){
  54458. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  54459. }
  54460. /*
  54461. ** Return pointers to the hash table and page number array stored on
  54462. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  54463. ** numbered starting from 0.
  54464. **
  54465. ** Set output variable *paHash to point to the start of the hash table
  54466. ** in the wal-index file. Set *piZero to one less than the frame
  54467. ** number of the first frame indexed by this hash table. If a
  54468. ** slot in the hash table is set to N, it refers to frame number
  54469. ** (*piZero+N) in the log.
  54470. **
  54471. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  54472. ** first frame indexed by the hash table, frame (*piZero+1).
  54473. */
  54474. static int walHashGet(
  54475. Wal *pWal, /* WAL handle */
  54476. int iHash, /* Find the iHash'th table */
  54477. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  54478. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  54479. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  54480. ){
  54481. int rc; /* Return code */
  54482. volatile u32 *aPgno;
  54483. rc = walIndexPage(pWal, iHash, &aPgno);
  54484. assert( rc==SQLITE_OK || iHash>0 );
  54485. if( rc==SQLITE_OK ){
  54486. u32 iZero;
  54487. volatile ht_slot *aHash;
  54488. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  54489. if( iHash==0 ){
  54490. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  54491. iZero = 0;
  54492. }else{
  54493. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  54494. }
  54495. *paPgno = &aPgno[-1];
  54496. *paHash = aHash;
  54497. *piZero = iZero;
  54498. }
  54499. return rc;
  54500. }
  54501. /*
  54502. ** Return the number of the wal-index page that contains the hash-table
  54503. ** and page-number array that contain entries corresponding to WAL frame
  54504. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  54505. ** are numbered starting from 0.
  54506. */
  54507. static int walFramePage(u32 iFrame){
  54508. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  54509. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  54510. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  54511. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  54512. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  54513. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  54514. );
  54515. return iHash;
  54516. }
  54517. /*
  54518. ** Return the page number associated with frame iFrame in this WAL.
  54519. */
  54520. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  54521. int iHash = walFramePage(iFrame);
  54522. if( iHash==0 ){
  54523. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  54524. }
  54525. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  54526. }
  54527. /*
  54528. ** Remove entries from the hash table that point to WAL slots greater
  54529. ** than pWal->hdr.mxFrame.
  54530. **
  54531. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  54532. ** to a rollback or savepoint.
  54533. **
  54534. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  54535. ** updated. Any later hash tables will be automatically cleared when
  54536. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  54537. ** actually needed.
  54538. */
  54539. static void walCleanupHash(Wal *pWal){
  54540. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  54541. volatile u32 *aPgno = 0; /* Page number array for hash table */
  54542. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  54543. int iLimit = 0; /* Zero values greater than this */
  54544. int nByte; /* Number of bytes to zero in aPgno[] */
  54545. int i; /* Used to iterate through aHash[] */
  54546. assert( pWal->writeLock );
  54547. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  54548. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  54549. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  54550. if( pWal->hdr.mxFrame==0 ) return;
  54551. /* Obtain pointers to the hash-table and page-number array containing
  54552. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  54553. ** that the page said hash-table and array reside on is already mapped.
  54554. */
  54555. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  54556. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  54557. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  54558. /* Zero all hash-table entries that correspond to frame numbers greater
  54559. ** than pWal->hdr.mxFrame.
  54560. */
  54561. iLimit = pWal->hdr.mxFrame - iZero;
  54562. assert( iLimit>0 );
  54563. for(i=0; i<HASHTABLE_NSLOT; i++){
  54564. if( aHash[i]>iLimit ){
  54565. aHash[i] = 0;
  54566. }
  54567. }
  54568. /* Zero the entries in the aPgno array that correspond to frames with
  54569. ** frame numbers greater than pWal->hdr.mxFrame.
  54570. */
  54571. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  54572. memset((void *)&aPgno[iLimit+1], 0, nByte);
  54573. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  54574. /* Verify that the every entry in the mapping region is still reachable
  54575. ** via the hash table even after the cleanup.
  54576. */
  54577. if( iLimit ){
  54578. int j; /* Loop counter */
  54579. int iKey; /* Hash key */
  54580. for(j=1; j<=iLimit; j++){
  54581. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  54582. if( aHash[iKey]==j ) break;
  54583. }
  54584. assert( aHash[iKey]==j );
  54585. }
  54586. }
  54587. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  54588. }
  54589. /*
  54590. ** Set an entry in the wal-index that will map database page number
  54591. ** pPage into WAL frame iFrame.
  54592. */
  54593. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  54594. int rc; /* Return code */
  54595. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  54596. volatile u32 *aPgno = 0; /* Page number array */
  54597. volatile ht_slot *aHash = 0; /* Hash table */
  54598. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  54599. /* Assuming the wal-index file was successfully mapped, populate the
  54600. ** page number array and hash table entry.
  54601. */
  54602. if( rc==SQLITE_OK ){
  54603. int iKey; /* Hash table key */
  54604. int idx; /* Value to write to hash-table slot */
  54605. int nCollide; /* Number of hash collisions */
  54606. idx = iFrame - iZero;
  54607. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  54608. /* If this is the first entry to be added to this hash-table, zero the
  54609. ** entire hash table and aPgno[] array before proceeding.
  54610. */
  54611. if( idx==1 ){
  54612. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  54613. memset((void*)&aPgno[1], 0, nByte);
  54614. }
  54615. /* If the entry in aPgno[] is already set, then the previous writer
  54616. ** must have exited unexpectedly in the middle of a transaction (after
  54617. ** writing one or more dirty pages to the WAL to free up memory).
  54618. ** Remove the remnants of that writers uncommitted transaction from
  54619. ** the hash-table before writing any new entries.
  54620. */
  54621. if( aPgno[idx] ){
  54622. walCleanupHash(pWal);
  54623. assert( !aPgno[idx] );
  54624. }
  54625. /* Write the aPgno[] array entry and the hash-table slot. */
  54626. nCollide = idx;
  54627. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  54628. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  54629. }
  54630. aPgno[idx] = iPage;
  54631. aHash[iKey] = (ht_slot)idx;
  54632. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  54633. /* Verify that the number of entries in the hash table exactly equals
  54634. ** the number of entries in the mapping region.
  54635. */
  54636. {
  54637. int i; /* Loop counter */
  54638. int nEntry = 0; /* Number of entries in the hash table */
  54639. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  54640. assert( nEntry==idx );
  54641. }
  54642. /* Verify that the every entry in the mapping region is reachable
  54643. ** via the hash table. This turns out to be a really, really expensive
  54644. ** thing to check, so only do this occasionally - not on every
  54645. ** iteration.
  54646. */
  54647. if( (idx&0x3ff)==0 ){
  54648. int i; /* Loop counter */
  54649. for(i=1; i<=idx; i++){
  54650. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  54651. if( aHash[iKey]==i ) break;
  54652. }
  54653. assert( aHash[iKey]==i );
  54654. }
  54655. }
  54656. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  54657. }
  54658. return rc;
  54659. }
  54660. /*
  54661. ** Recover the wal-index by reading the write-ahead log file.
  54662. **
  54663. ** This routine first tries to establish an exclusive lock on the
  54664. ** wal-index to prevent other threads/processes from doing anything
  54665. ** with the WAL or wal-index while recovery is running. The
  54666. ** WAL_RECOVER_LOCK is also held so that other threads will know
  54667. ** that this thread is running recovery. If unable to establish
  54668. ** the necessary locks, this routine returns SQLITE_BUSY.
  54669. */
  54670. static int walIndexRecover(Wal *pWal){
  54671. int rc; /* Return Code */
  54672. i64 nSize; /* Size of log file */
  54673. u32 aFrameCksum[2] = {0, 0};
  54674. int iLock; /* Lock offset to lock for checkpoint */
  54675. /* Obtain an exclusive lock on all byte in the locking range not already
  54676. ** locked by the caller. The caller is guaranteed to have locked the
  54677. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  54678. ** If successful, the same bytes that are locked here are unlocked before
  54679. ** this function returns.
  54680. */
  54681. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  54682. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  54683. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  54684. assert( pWal->writeLock );
  54685. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  54686. rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  54687. if( rc==SQLITE_OK ){
  54688. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  54689. if( rc!=SQLITE_OK ){
  54690. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  54691. }
  54692. }
  54693. if( rc ){
  54694. return rc;
  54695. }
  54696. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  54697. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  54698. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  54699. if( rc!=SQLITE_OK ){
  54700. goto recovery_error;
  54701. }
  54702. if( nSize>WAL_HDRSIZE ){
  54703. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  54704. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  54705. int szFrame; /* Number of bytes in buffer aFrame[] */
  54706. u8 *aData; /* Pointer to data part of aFrame buffer */
  54707. int iFrame; /* Index of last frame read */
  54708. i64 iOffset; /* Next offset to read from log file */
  54709. int szPage; /* Page size according to the log */
  54710. u32 magic; /* Magic value read from WAL header */
  54711. u32 version; /* Magic value read from WAL header */
  54712. int isValid; /* True if this frame is valid */
  54713. /* Read in the WAL header. */
  54714. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  54715. if( rc!=SQLITE_OK ){
  54716. goto recovery_error;
  54717. }
  54718. /* If the database page size is not a power of two, or is greater than
  54719. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  54720. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  54721. ** WAL file.
  54722. */
  54723. magic = sqlite3Get4byte(&aBuf[0]);
  54724. szPage = sqlite3Get4byte(&aBuf[8]);
  54725. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  54726. || szPage&(szPage-1)
  54727. || szPage>SQLITE_MAX_PAGE_SIZE
  54728. || szPage<512
  54729. ){
  54730. goto finished;
  54731. }
  54732. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  54733. pWal->szPage = szPage;
  54734. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  54735. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  54736. /* Verify that the WAL header checksum is correct */
  54737. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  54738. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  54739. );
  54740. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  54741. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  54742. ){
  54743. goto finished;
  54744. }
  54745. /* Verify that the version number on the WAL format is one that
  54746. ** are able to understand */
  54747. version = sqlite3Get4byte(&aBuf[4]);
  54748. if( version!=WAL_MAX_VERSION ){
  54749. rc = SQLITE_CANTOPEN_BKPT;
  54750. goto finished;
  54751. }
  54752. /* Malloc a buffer to read frames into. */
  54753. szFrame = szPage + WAL_FRAME_HDRSIZE;
  54754. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  54755. if( !aFrame ){
  54756. rc = SQLITE_NOMEM_BKPT;
  54757. goto recovery_error;
  54758. }
  54759. aData = &aFrame[WAL_FRAME_HDRSIZE];
  54760. /* Read all frames from the log file. */
  54761. iFrame = 0;
  54762. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  54763. u32 pgno; /* Database page number for frame */
  54764. u32 nTruncate; /* dbsize field from frame header */
  54765. /* Read and decode the next log frame. */
  54766. iFrame++;
  54767. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  54768. if( rc!=SQLITE_OK ) break;
  54769. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  54770. if( !isValid ) break;
  54771. rc = walIndexAppend(pWal, iFrame, pgno);
  54772. if( rc!=SQLITE_OK ) break;
  54773. /* If nTruncate is non-zero, this is a commit record. */
  54774. if( nTruncate ){
  54775. pWal->hdr.mxFrame = iFrame;
  54776. pWal->hdr.nPage = nTruncate;
  54777. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  54778. testcase( szPage<=32768 );
  54779. testcase( szPage>=65536 );
  54780. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  54781. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  54782. }
  54783. }
  54784. sqlite3_free(aFrame);
  54785. }
  54786. finished:
  54787. if( rc==SQLITE_OK ){
  54788. volatile WalCkptInfo *pInfo;
  54789. int i;
  54790. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  54791. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  54792. walIndexWriteHdr(pWal);
  54793. /* Reset the checkpoint-header. This is safe because this thread is
  54794. ** currently holding locks that exclude all other readers, writers and
  54795. ** checkpointers.
  54796. */
  54797. pInfo = walCkptInfo(pWal);
  54798. pInfo->nBackfill = 0;
  54799. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  54800. pInfo->aReadMark[0] = 0;
  54801. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  54802. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  54803. /* If more than one frame was recovered from the log file, report an
  54804. ** event via sqlite3_log(). This is to help with identifying performance
  54805. ** problems caused by applications routinely shutting down without
  54806. ** checkpointing the log file.
  54807. */
  54808. if( pWal->hdr.nPage ){
  54809. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  54810. "recovered %d frames from WAL file %s",
  54811. pWal->hdr.mxFrame, pWal->zWalName
  54812. );
  54813. }
  54814. }
  54815. recovery_error:
  54816. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  54817. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  54818. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  54819. return rc;
  54820. }
  54821. /*
  54822. ** Close an open wal-index.
  54823. */
  54824. static void walIndexClose(Wal *pWal, int isDelete){
  54825. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
  54826. int i;
  54827. for(i=0; i<pWal->nWiData; i++){
  54828. sqlite3_free((void *)pWal->apWiData[i]);
  54829. pWal->apWiData[i] = 0;
  54830. }
  54831. }
  54832. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  54833. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  54834. }
  54835. }
  54836. /*
  54837. ** Open a connection to the WAL file zWalName. The database file must
  54838. ** already be opened on connection pDbFd. The buffer that zWalName points
  54839. ** to must remain valid for the lifetime of the returned Wal* handle.
  54840. **
  54841. ** A SHARED lock should be held on the database file when this function
  54842. ** is called. The purpose of this SHARED lock is to prevent any other
  54843. ** client from unlinking the WAL or wal-index file. If another process
  54844. ** were to do this just after this client opened one of these files, the
  54845. ** system would be badly broken.
  54846. **
  54847. ** If the log file is successfully opened, SQLITE_OK is returned and
  54848. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  54849. ** an SQLite error code is returned and *ppWal is left unmodified.
  54850. */
  54851. SQLITE_PRIVATE int sqlite3WalOpen(
  54852. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  54853. sqlite3_file *pDbFd, /* The open database file */
  54854. const char *zWalName, /* Name of the WAL file */
  54855. int bNoShm, /* True to run in heap-memory mode */
  54856. i64 mxWalSize, /* Truncate WAL to this size on reset */
  54857. Wal **ppWal /* OUT: Allocated Wal handle */
  54858. ){
  54859. int rc; /* Return Code */
  54860. Wal *pRet; /* Object to allocate and return */
  54861. int flags; /* Flags passed to OsOpen() */
  54862. assert( zWalName && zWalName[0] );
  54863. assert( pDbFd );
  54864. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  54865. ** this source file. Verify that the #defines of the locking byte offsets
  54866. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  54867. ** For that matter, if the lock offset ever changes from its initial design
  54868. ** value of 120, we need to know that so there is an assert() to check it.
  54869. */
  54870. assert( 120==WALINDEX_LOCK_OFFSET );
  54871. assert( 136==WALINDEX_HDR_SIZE );
  54872. #ifdef WIN_SHM_BASE
  54873. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  54874. #endif
  54875. #ifdef UNIX_SHM_BASE
  54876. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  54877. #endif
  54878. /* Allocate an instance of struct Wal to return. */
  54879. *ppWal = 0;
  54880. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  54881. if( !pRet ){
  54882. return SQLITE_NOMEM_BKPT;
  54883. }
  54884. pRet->pVfs = pVfs;
  54885. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  54886. pRet->pDbFd = pDbFd;
  54887. pRet->readLock = -1;
  54888. pRet->mxWalSize = mxWalSize;
  54889. pRet->zWalName = zWalName;
  54890. pRet->syncHeader = 1;
  54891. pRet->padToSectorBoundary = 1;
  54892. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  54893. /* Open file handle on the write-ahead log file. */
  54894. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  54895. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  54896. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  54897. pRet->readOnly = WAL_RDONLY;
  54898. }
  54899. if( rc!=SQLITE_OK ){
  54900. walIndexClose(pRet, 0);
  54901. sqlite3OsClose(pRet->pWalFd);
  54902. sqlite3_free(pRet);
  54903. }else{
  54904. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  54905. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  54906. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  54907. pRet->padToSectorBoundary = 0;
  54908. }
  54909. *ppWal = pRet;
  54910. WALTRACE(("WAL%d: opened\n", pRet));
  54911. }
  54912. return rc;
  54913. }
  54914. /*
  54915. ** Change the size to which the WAL file is trucated on each reset.
  54916. */
  54917. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  54918. if( pWal ) pWal->mxWalSize = iLimit;
  54919. }
  54920. /*
  54921. ** Find the smallest page number out of all pages held in the WAL that
  54922. ** has not been returned by any prior invocation of this method on the
  54923. ** same WalIterator object. Write into *piFrame the frame index where
  54924. ** that page was last written into the WAL. Write into *piPage the page
  54925. ** number.
  54926. **
  54927. ** Return 0 on success. If there are no pages in the WAL with a page
  54928. ** number larger than *piPage, then return 1.
  54929. */
  54930. static int walIteratorNext(
  54931. WalIterator *p, /* Iterator */
  54932. u32 *piPage, /* OUT: The page number of the next page */
  54933. u32 *piFrame /* OUT: Wal frame index of next page */
  54934. ){
  54935. u32 iMin; /* Result pgno must be greater than iMin */
  54936. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  54937. int i; /* For looping through segments */
  54938. iMin = p->iPrior;
  54939. assert( iMin<0xffffffff );
  54940. for(i=p->nSegment-1; i>=0; i--){
  54941. struct WalSegment *pSegment = &p->aSegment[i];
  54942. while( pSegment->iNext<pSegment->nEntry ){
  54943. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  54944. if( iPg>iMin ){
  54945. if( iPg<iRet ){
  54946. iRet = iPg;
  54947. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  54948. }
  54949. break;
  54950. }
  54951. pSegment->iNext++;
  54952. }
  54953. }
  54954. *piPage = p->iPrior = iRet;
  54955. return (iRet==0xFFFFFFFF);
  54956. }
  54957. /*
  54958. ** This function merges two sorted lists into a single sorted list.
  54959. **
  54960. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  54961. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  54962. ** is guaranteed for all J<K:
  54963. **
  54964. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  54965. ** aContent[aRight[J]] < aContent[aRight[K]]
  54966. **
  54967. ** This routine overwrites aRight[] with a new (probably longer) sequence
  54968. ** of indices such that the aRight[] contains every index that appears in
  54969. ** either aLeft[] or the old aRight[] and such that the second condition
  54970. ** above is still met.
  54971. **
  54972. ** The aContent[aLeft[X]] values will be unique for all X. And the
  54973. ** aContent[aRight[X]] values will be unique too. But there might be
  54974. ** one or more combinations of X and Y such that
  54975. **
  54976. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  54977. **
  54978. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  54979. */
  54980. static void walMerge(
  54981. const u32 *aContent, /* Pages in wal - keys for the sort */
  54982. ht_slot *aLeft, /* IN: Left hand input list */
  54983. int nLeft, /* IN: Elements in array *paLeft */
  54984. ht_slot **paRight, /* IN/OUT: Right hand input list */
  54985. int *pnRight, /* IN/OUT: Elements in *paRight */
  54986. ht_slot *aTmp /* Temporary buffer */
  54987. ){
  54988. int iLeft = 0; /* Current index in aLeft */
  54989. int iRight = 0; /* Current index in aRight */
  54990. int iOut = 0; /* Current index in output buffer */
  54991. int nRight = *pnRight;
  54992. ht_slot *aRight = *paRight;
  54993. assert( nLeft>0 && nRight>0 );
  54994. while( iRight<nRight || iLeft<nLeft ){
  54995. ht_slot logpage;
  54996. Pgno dbpage;
  54997. if( (iLeft<nLeft)
  54998. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  54999. ){
  55000. logpage = aLeft[iLeft++];
  55001. }else{
  55002. logpage = aRight[iRight++];
  55003. }
  55004. dbpage = aContent[logpage];
  55005. aTmp[iOut++] = logpage;
  55006. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  55007. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  55008. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  55009. }
  55010. *paRight = aLeft;
  55011. *pnRight = iOut;
  55012. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  55013. }
  55014. /*
  55015. ** Sort the elements in list aList using aContent[] as the sort key.
  55016. ** Remove elements with duplicate keys, preferring to keep the
  55017. ** larger aList[] values.
  55018. **
  55019. ** The aList[] entries are indices into aContent[]. The values in
  55020. ** aList[] are to be sorted so that for all J<K:
  55021. **
  55022. ** aContent[aList[J]] < aContent[aList[K]]
  55023. **
  55024. ** For any X and Y such that
  55025. **
  55026. ** aContent[aList[X]] == aContent[aList[Y]]
  55027. **
  55028. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  55029. ** the smaller.
  55030. */
  55031. static void walMergesort(
  55032. const u32 *aContent, /* Pages in wal */
  55033. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  55034. ht_slot *aList, /* IN/OUT: List to sort */
  55035. int *pnList /* IN/OUT: Number of elements in aList[] */
  55036. ){
  55037. struct Sublist {
  55038. int nList; /* Number of elements in aList */
  55039. ht_slot *aList; /* Pointer to sub-list content */
  55040. };
  55041. const int nList = *pnList; /* Size of input list */
  55042. int nMerge = 0; /* Number of elements in list aMerge */
  55043. ht_slot *aMerge = 0; /* List to be merged */
  55044. int iList; /* Index into input list */
  55045. u32 iSub = 0; /* Index into aSub array */
  55046. struct Sublist aSub[13]; /* Array of sub-lists */
  55047. memset(aSub, 0, sizeof(aSub));
  55048. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  55049. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  55050. for(iList=0; iList<nList; iList++){
  55051. nMerge = 1;
  55052. aMerge = &aList[iList];
  55053. for(iSub=0; iList & (1<<iSub); iSub++){
  55054. struct Sublist *p;
  55055. assert( iSub<ArraySize(aSub) );
  55056. p = &aSub[iSub];
  55057. assert( p->aList && p->nList<=(1<<iSub) );
  55058. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  55059. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  55060. }
  55061. aSub[iSub].aList = aMerge;
  55062. aSub[iSub].nList = nMerge;
  55063. }
  55064. for(iSub++; iSub<ArraySize(aSub); iSub++){
  55065. if( nList & (1<<iSub) ){
  55066. struct Sublist *p;
  55067. assert( iSub<ArraySize(aSub) );
  55068. p = &aSub[iSub];
  55069. assert( p->nList<=(1<<iSub) );
  55070. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  55071. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  55072. }
  55073. }
  55074. assert( aMerge==aList );
  55075. *pnList = nMerge;
  55076. #ifdef SQLITE_DEBUG
  55077. {
  55078. int i;
  55079. for(i=1; i<*pnList; i++){
  55080. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  55081. }
  55082. }
  55083. #endif
  55084. }
  55085. /*
  55086. ** Free an iterator allocated by walIteratorInit().
  55087. */
  55088. static void walIteratorFree(WalIterator *p){
  55089. sqlite3_free(p);
  55090. }
  55091. /*
  55092. ** Construct a WalInterator object that can be used to loop over all
  55093. ** pages in the WAL following frame nBackfill in ascending order. Frames
  55094. ** nBackfill or earlier may be included - excluding them is an optimization
  55095. ** only. The caller must hold the checkpoint lock.
  55096. **
  55097. ** On success, make *pp point to the newly allocated WalInterator object
  55098. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  55099. ** returns an error, the value of *pp is undefined.
  55100. **
  55101. ** The calling routine should invoke walIteratorFree() to destroy the
  55102. ** WalIterator object when it has finished with it.
  55103. */
  55104. static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
  55105. WalIterator *p; /* Return value */
  55106. int nSegment; /* Number of segments to merge */
  55107. u32 iLast; /* Last frame in log */
  55108. int nByte; /* Number of bytes to allocate */
  55109. int i; /* Iterator variable */
  55110. ht_slot *aTmp; /* Temp space used by merge-sort */
  55111. int rc = SQLITE_OK; /* Return Code */
  55112. /* This routine only runs while holding the checkpoint lock. And
  55113. ** it only runs if there is actually content in the log (mxFrame>0).
  55114. */
  55115. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  55116. iLast = pWal->hdr.mxFrame;
  55117. /* Allocate space for the WalIterator object. */
  55118. nSegment = walFramePage(iLast) + 1;
  55119. nByte = sizeof(WalIterator)
  55120. + (nSegment-1)*sizeof(struct WalSegment)
  55121. + iLast*sizeof(ht_slot);
  55122. p = (WalIterator *)sqlite3_malloc64(nByte);
  55123. if( !p ){
  55124. return SQLITE_NOMEM_BKPT;
  55125. }
  55126. memset(p, 0, nByte);
  55127. p->nSegment = nSegment;
  55128. /* Allocate temporary space used by the merge-sort routine. This block
  55129. ** of memory will be freed before this function returns.
  55130. */
  55131. aTmp = (ht_slot *)sqlite3_malloc64(
  55132. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  55133. );
  55134. if( !aTmp ){
  55135. rc = SQLITE_NOMEM_BKPT;
  55136. }
  55137. for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
  55138. volatile ht_slot *aHash;
  55139. u32 iZero;
  55140. volatile u32 *aPgno;
  55141. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  55142. if( rc==SQLITE_OK ){
  55143. int j; /* Counter variable */
  55144. int nEntry; /* Number of entries in this segment */
  55145. ht_slot *aIndex; /* Sorted index for this segment */
  55146. aPgno++;
  55147. if( (i+1)==nSegment ){
  55148. nEntry = (int)(iLast - iZero);
  55149. }else{
  55150. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  55151. }
  55152. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  55153. iZero++;
  55154. for(j=0; j<nEntry; j++){
  55155. aIndex[j] = (ht_slot)j;
  55156. }
  55157. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  55158. p->aSegment[i].iZero = iZero;
  55159. p->aSegment[i].nEntry = nEntry;
  55160. p->aSegment[i].aIndex = aIndex;
  55161. p->aSegment[i].aPgno = (u32 *)aPgno;
  55162. }
  55163. }
  55164. sqlite3_free(aTmp);
  55165. if( rc!=SQLITE_OK ){
  55166. walIteratorFree(p);
  55167. p = 0;
  55168. }
  55169. *pp = p;
  55170. return rc;
  55171. }
  55172. /*
  55173. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  55174. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  55175. ** busy-handler function. Invoke it and retry the lock until either the
  55176. ** lock is successfully obtained or the busy-handler returns 0.
  55177. */
  55178. static int walBusyLock(
  55179. Wal *pWal, /* WAL connection */
  55180. int (*xBusy)(void*), /* Function to call when busy */
  55181. void *pBusyArg, /* Context argument for xBusyHandler */
  55182. int lockIdx, /* Offset of first byte to lock */
  55183. int n /* Number of bytes to lock */
  55184. ){
  55185. int rc;
  55186. do {
  55187. rc = walLockExclusive(pWal, lockIdx, n);
  55188. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  55189. return rc;
  55190. }
  55191. /*
  55192. ** The cache of the wal-index header must be valid to call this function.
  55193. ** Return the page-size in bytes used by the database.
  55194. */
  55195. static int walPagesize(Wal *pWal){
  55196. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  55197. }
  55198. /*
  55199. ** The following is guaranteed when this function is called:
  55200. **
  55201. ** a) the WRITER lock is held,
  55202. ** b) the entire log file has been checkpointed, and
  55203. ** c) any existing readers are reading exclusively from the database
  55204. ** file - there are no readers that may attempt to read a frame from
  55205. ** the log file.
  55206. **
  55207. ** This function updates the shared-memory structures so that the next
  55208. ** client to write to the database (which may be this one) does so by
  55209. ** writing frames into the start of the log file.
  55210. **
  55211. ** The value of parameter salt1 is used as the aSalt[1] value in the
  55212. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  55213. ** one obtained from sqlite3_randomness()).
  55214. */
  55215. static void walRestartHdr(Wal *pWal, u32 salt1){
  55216. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  55217. int i; /* Loop counter */
  55218. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  55219. pWal->nCkpt++;
  55220. pWal->hdr.mxFrame = 0;
  55221. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  55222. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  55223. walIndexWriteHdr(pWal);
  55224. pInfo->nBackfill = 0;
  55225. pInfo->nBackfillAttempted = 0;
  55226. pInfo->aReadMark[1] = 0;
  55227. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  55228. assert( pInfo->aReadMark[0]==0 );
  55229. }
  55230. /*
  55231. ** Copy as much content as we can from the WAL back into the database file
  55232. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  55233. **
  55234. ** The amount of information copies from WAL to database might be limited
  55235. ** by active readers. This routine will never overwrite a database page
  55236. ** that a concurrent reader might be using.
  55237. **
  55238. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  55239. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  55240. ** checkpoints are always run by a background thread or background
  55241. ** process, foreground threads will never block on a lengthy fsync call.
  55242. **
  55243. ** Fsync is called on the WAL before writing content out of the WAL and
  55244. ** into the database. This ensures that if the new content is persistent
  55245. ** in the WAL and can be recovered following a power-loss or hard reset.
  55246. **
  55247. ** Fsync is also called on the database file if (and only if) the entire
  55248. ** WAL content is copied into the database file. This second fsync makes
  55249. ** it safe to delete the WAL since the new content will persist in the
  55250. ** database file.
  55251. **
  55252. ** This routine uses and updates the nBackfill field of the wal-index header.
  55253. ** This is the only routine that will increase the value of nBackfill.
  55254. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  55255. ** its value.)
  55256. **
  55257. ** The caller must be holding sufficient locks to ensure that no other
  55258. ** checkpoint is running (in any other thread or process) at the same
  55259. ** time.
  55260. */
  55261. static int walCheckpoint(
  55262. Wal *pWal, /* Wal connection */
  55263. sqlite3 *db, /* Check for interrupts on this handle */
  55264. int eMode, /* One of PASSIVE, FULL or RESTART */
  55265. int (*xBusy)(void*), /* Function to call when busy */
  55266. void *pBusyArg, /* Context argument for xBusyHandler */
  55267. int sync_flags, /* Flags for OsSync() (or 0) */
  55268. u8 *zBuf /* Temporary buffer to use */
  55269. ){
  55270. int rc = SQLITE_OK; /* Return code */
  55271. int szPage; /* Database page-size */
  55272. WalIterator *pIter = 0; /* Wal iterator context */
  55273. u32 iDbpage = 0; /* Next database page to write */
  55274. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  55275. u32 mxSafeFrame; /* Max frame that can be backfilled */
  55276. u32 mxPage; /* Max database page to write */
  55277. int i; /* Loop counter */
  55278. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  55279. szPage = walPagesize(pWal);
  55280. testcase( szPage<=32768 );
  55281. testcase( szPage>=65536 );
  55282. pInfo = walCkptInfo(pWal);
  55283. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  55284. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  55285. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  55286. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  55287. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  55288. ** safe to write into the database. Frames beyond mxSafeFrame might
  55289. ** overwrite database pages that are in use by active readers and thus
  55290. ** cannot be backfilled from the WAL.
  55291. */
  55292. mxSafeFrame = pWal->hdr.mxFrame;
  55293. mxPage = pWal->hdr.nPage;
  55294. for(i=1; i<WAL_NREADER; i++){
  55295. /* Thread-sanitizer reports that the following is an unsafe read,
  55296. ** as some other thread may be in the process of updating the value
  55297. ** of the aReadMark[] slot. The assumption here is that if that is
  55298. ** happening, the other client may only be increasing the value,
  55299. ** not decreasing it. So assuming either that either the "old" or
  55300. ** "new" version of the value is read, and not some arbitrary value
  55301. ** that would never be written by a real client, things are still
  55302. ** safe. */
  55303. u32 y = pInfo->aReadMark[i];
  55304. if( mxSafeFrame>y ){
  55305. assert( y<=pWal->hdr.mxFrame );
  55306. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  55307. if( rc==SQLITE_OK ){
  55308. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  55309. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  55310. }else if( rc==SQLITE_BUSY ){
  55311. mxSafeFrame = y;
  55312. xBusy = 0;
  55313. }else{
  55314. goto walcheckpoint_out;
  55315. }
  55316. }
  55317. }
  55318. /* Allocate the iterator */
  55319. if( pInfo->nBackfill<mxSafeFrame ){
  55320. rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
  55321. assert( rc==SQLITE_OK || pIter==0 );
  55322. }
  55323. if( pIter
  55324. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  55325. ){
  55326. i64 nSize; /* Current size of database file */
  55327. u32 nBackfill = pInfo->nBackfill;
  55328. pInfo->nBackfillAttempted = mxSafeFrame;
  55329. /* Sync the WAL to disk */
  55330. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  55331. /* If the database may grow as a result of this checkpoint, hint
  55332. ** about the eventual size of the db file to the VFS layer.
  55333. */
  55334. if( rc==SQLITE_OK ){
  55335. i64 nReq = ((i64)mxPage * szPage);
  55336. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  55337. if( rc==SQLITE_OK && nSize<nReq ){
  55338. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  55339. }
  55340. }
  55341. /* Iterate through the contents of the WAL, copying data to the db file */
  55342. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  55343. i64 iOffset;
  55344. assert( walFramePgno(pWal, iFrame)==iDbpage );
  55345. if( db->u1.isInterrupted ){
  55346. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  55347. break;
  55348. }
  55349. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  55350. continue;
  55351. }
  55352. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  55353. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  55354. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  55355. if( rc!=SQLITE_OK ) break;
  55356. iOffset = (iDbpage-1)*(i64)szPage;
  55357. testcase( IS_BIG_INT(iOffset) );
  55358. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  55359. if( rc!=SQLITE_OK ) break;
  55360. }
  55361. /* If work was actually accomplished... */
  55362. if( rc==SQLITE_OK ){
  55363. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  55364. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  55365. testcase( IS_BIG_INT(szDb) );
  55366. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  55367. if( rc==SQLITE_OK ){
  55368. rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
  55369. }
  55370. }
  55371. if( rc==SQLITE_OK ){
  55372. pInfo->nBackfill = mxSafeFrame;
  55373. }
  55374. }
  55375. /* Release the reader lock held while backfilling */
  55376. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  55377. }
  55378. if( rc==SQLITE_BUSY ){
  55379. /* Reset the return code so as not to report a checkpoint failure
  55380. ** just because there are active readers. */
  55381. rc = SQLITE_OK;
  55382. }
  55383. }
  55384. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  55385. ** entire wal file has been copied into the database file, then block
  55386. ** until all readers have finished using the wal file. This ensures that
  55387. ** the next process to write to the database restarts the wal file.
  55388. */
  55389. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  55390. assert( pWal->writeLock );
  55391. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  55392. rc = SQLITE_BUSY;
  55393. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  55394. u32 salt1;
  55395. sqlite3_randomness(4, &salt1);
  55396. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  55397. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  55398. if( rc==SQLITE_OK ){
  55399. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  55400. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  55401. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  55402. ** truncates the log file to zero bytes just prior to a
  55403. ** successful return.
  55404. **
  55405. ** In theory, it might be safe to do this without updating the
  55406. ** wal-index header in shared memory, as all subsequent reader or
  55407. ** writer clients should see that the entire log file has been
  55408. ** checkpointed and behave accordingly. This seems unsafe though,
  55409. ** as it would leave the system in a state where the contents of
  55410. ** the wal-index header do not match the contents of the
  55411. ** file-system. To avoid this, update the wal-index header to
  55412. ** indicate that the log file contains zero valid frames. */
  55413. walRestartHdr(pWal, salt1);
  55414. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  55415. }
  55416. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  55417. }
  55418. }
  55419. }
  55420. walcheckpoint_out:
  55421. walIteratorFree(pIter);
  55422. return rc;
  55423. }
  55424. /*
  55425. ** If the WAL file is currently larger than nMax bytes in size, truncate
  55426. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  55427. */
  55428. static void walLimitSize(Wal *pWal, i64 nMax){
  55429. i64 sz;
  55430. int rx;
  55431. sqlite3BeginBenignMalloc();
  55432. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  55433. if( rx==SQLITE_OK && (sz > nMax ) ){
  55434. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  55435. }
  55436. sqlite3EndBenignMalloc();
  55437. if( rx ){
  55438. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  55439. }
  55440. }
  55441. /*
  55442. ** Close a connection to a log file.
  55443. */
  55444. SQLITE_PRIVATE int sqlite3WalClose(
  55445. Wal *pWal, /* Wal to close */
  55446. sqlite3 *db, /* For interrupt flag */
  55447. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  55448. int nBuf,
  55449. u8 *zBuf /* Buffer of at least nBuf bytes */
  55450. ){
  55451. int rc = SQLITE_OK;
  55452. if( pWal ){
  55453. int isDelete = 0; /* True to unlink wal and wal-index files */
  55454. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  55455. ** ordinary, rollback-mode locking methods, this guarantees that the
  55456. ** connection associated with this log file is the only connection to
  55457. ** the database. In this case checkpoint the database and unlink both
  55458. ** the wal and wal-index files.
  55459. **
  55460. ** The EXCLUSIVE lock is not released before returning.
  55461. */
  55462. if( zBuf!=0
  55463. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  55464. ){
  55465. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  55466. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  55467. }
  55468. rc = sqlite3WalCheckpoint(pWal, db,
  55469. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  55470. );
  55471. if( rc==SQLITE_OK ){
  55472. int bPersist = -1;
  55473. sqlite3OsFileControlHint(
  55474. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  55475. );
  55476. if( bPersist!=1 ){
  55477. /* Try to delete the WAL file if the checkpoint completed and
  55478. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  55479. ** mode (!bPersist) */
  55480. isDelete = 1;
  55481. }else if( pWal->mxWalSize>=0 ){
  55482. /* Try to truncate the WAL file to zero bytes if the checkpoint
  55483. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  55484. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  55485. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  55486. ** to zero bytes as truncating to the journal_size_limit might
  55487. ** leave a corrupt WAL file on disk. */
  55488. walLimitSize(pWal, 0);
  55489. }
  55490. }
  55491. }
  55492. walIndexClose(pWal, isDelete);
  55493. sqlite3OsClose(pWal->pWalFd);
  55494. if( isDelete ){
  55495. sqlite3BeginBenignMalloc();
  55496. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  55497. sqlite3EndBenignMalloc();
  55498. }
  55499. WALTRACE(("WAL%p: closed\n", pWal));
  55500. sqlite3_free((void *)pWal->apWiData);
  55501. sqlite3_free(pWal);
  55502. }
  55503. return rc;
  55504. }
  55505. /*
  55506. ** Try to read the wal-index header. Return 0 on success and 1 if
  55507. ** there is a problem.
  55508. **
  55509. ** The wal-index is in shared memory. Another thread or process might
  55510. ** be writing the header at the same time this procedure is trying to
  55511. ** read it, which might result in inconsistency. A dirty read is detected
  55512. ** by verifying that both copies of the header are the same and also by
  55513. ** a checksum on the header.
  55514. **
  55515. ** If and only if the read is consistent and the header is different from
  55516. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  55517. ** and *pChanged is set to 1.
  55518. **
  55519. ** If the checksum cannot be verified return non-zero. If the header
  55520. ** is read successfully and the checksum verified, return zero.
  55521. */
  55522. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  55523. u32 aCksum[2]; /* Checksum on the header content */
  55524. WalIndexHdr h1, h2; /* Two copies of the header content */
  55525. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  55526. /* The first page of the wal-index must be mapped at this point. */
  55527. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55528. /* Read the header. This might happen concurrently with a write to the
  55529. ** same area of shared memory on a different CPU in a SMP,
  55530. ** meaning it is possible that an inconsistent snapshot is read
  55531. ** from the file. If this happens, return non-zero.
  55532. **
  55533. ** There are two copies of the header at the beginning of the wal-index.
  55534. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  55535. ** Memory barriers are used to prevent the compiler or the hardware from
  55536. ** reordering the reads and writes.
  55537. */
  55538. aHdr = walIndexHdr(pWal);
  55539. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  55540. walShmBarrier(pWal);
  55541. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  55542. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  55543. return 1; /* Dirty read */
  55544. }
  55545. if( h1.isInit==0 ){
  55546. return 1; /* Malformed header - probably all zeros */
  55547. }
  55548. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  55549. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  55550. return 1; /* Checksum does not match */
  55551. }
  55552. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  55553. *pChanged = 1;
  55554. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  55555. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  55556. testcase( pWal->szPage<=32768 );
  55557. testcase( pWal->szPage>=65536 );
  55558. }
  55559. /* The header was successfully read. Return zero. */
  55560. return 0;
  55561. }
  55562. /*
  55563. ** This is the value that walTryBeginRead returns when it needs to
  55564. ** be retried.
  55565. */
  55566. #define WAL_RETRY (-1)
  55567. /*
  55568. ** Read the wal-index header from the wal-index and into pWal->hdr.
  55569. ** If the wal-header appears to be corrupt, try to reconstruct the
  55570. ** wal-index from the WAL before returning.
  55571. **
  55572. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  55573. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  55574. ** to 0.
  55575. **
  55576. ** If the wal-index header is successfully read, return SQLITE_OK.
  55577. ** Otherwise an SQLite error code.
  55578. */
  55579. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  55580. int rc; /* Return code */
  55581. int badHdr; /* True if a header read failed */
  55582. volatile u32 *page0; /* Chunk of wal-index containing header */
  55583. /* Ensure that page 0 of the wal-index (the page that contains the
  55584. ** wal-index header) is mapped. Return early if an error occurs here.
  55585. */
  55586. assert( pChanged );
  55587. rc = walIndexPage(pWal, 0, &page0);
  55588. if( rc!=SQLITE_OK ){
  55589. assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
  55590. if( rc==SQLITE_READONLY_CANTINIT ){
  55591. /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
  55592. ** was openable but is not writable, and this thread is unable to
  55593. ** confirm that another write-capable connection has the shared-memory
  55594. ** open, and hence the content of the shared-memory is unreliable,
  55595. ** since the shared-memory might be inconsistent with the WAL file
  55596. ** and there is no writer on hand to fix it. */
  55597. assert( page0==0 );
  55598. assert( pWal->writeLock==0 );
  55599. assert( pWal->readOnly & WAL_SHM_RDONLY );
  55600. pWal->bShmUnreliable = 1;
  55601. pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
  55602. *pChanged = 1;
  55603. }else{
  55604. return rc; /* Any other non-OK return is just an error */
  55605. }
  55606. }else{
  55607. /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
  55608. ** is zero, which prevents the SHM from growing */
  55609. testcase( page0!=0 );
  55610. }
  55611. assert( page0!=0 || pWal->writeLock==0 );
  55612. /* If the first page of the wal-index has been mapped, try to read the
  55613. ** wal-index header immediately, without holding any lock. This usually
  55614. ** works, but may fail if the wal-index header is corrupt or currently
  55615. ** being modified by another thread or process.
  55616. */
  55617. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  55618. /* If the first attempt failed, it might have been due to a race
  55619. ** with a writer. So get a WRITE lock and try again.
  55620. */
  55621. assert( badHdr==0 || pWal->writeLock==0 );
  55622. if( badHdr ){
  55623. if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
  55624. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  55625. walUnlockShared(pWal, WAL_WRITE_LOCK);
  55626. rc = SQLITE_READONLY_RECOVERY;
  55627. }
  55628. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  55629. pWal->writeLock = 1;
  55630. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  55631. badHdr = walIndexTryHdr(pWal, pChanged);
  55632. if( badHdr ){
  55633. /* If the wal-index header is still malformed even while holding
  55634. ** a WRITE lock, it can only mean that the header is corrupted and
  55635. ** needs to be reconstructed. So run recovery to do exactly that.
  55636. */
  55637. rc = walIndexRecover(pWal);
  55638. *pChanged = 1;
  55639. }
  55640. }
  55641. pWal->writeLock = 0;
  55642. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  55643. }
  55644. }
  55645. /* If the header is read successfully, check the version number to make
  55646. ** sure the wal-index was not constructed with some future format that
  55647. ** this version of SQLite cannot understand.
  55648. */
  55649. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  55650. rc = SQLITE_CANTOPEN_BKPT;
  55651. }
  55652. if( pWal->bShmUnreliable ){
  55653. if( rc!=SQLITE_OK ){
  55654. walIndexClose(pWal, 0);
  55655. pWal->bShmUnreliable = 0;
  55656. assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
  55657. /* walIndexRecover() might have returned SHORT_READ if a concurrent
  55658. ** writer truncated the WAL out from under it. If that happens, it
  55659. ** indicates that a writer has fixed the SHM file for us, so retry */
  55660. if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
  55661. }
  55662. pWal->exclusiveMode = WAL_NORMAL_MODE;
  55663. }
  55664. return rc;
  55665. }
  55666. /*
  55667. ** Open a transaction in a connection where the shared-memory is read-only
  55668. ** and where we cannot verify that there is a separate write-capable connection
  55669. ** on hand to keep the shared-memory up-to-date with the WAL file.
  55670. **
  55671. ** This can happen, for example, when the shared-memory is implemented by
  55672. ** memory-mapping a *-shm file, where a prior writer has shut down and
  55673. ** left the *-shm file on disk, and now the present connection is trying
  55674. ** to use that database but lacks write permission on the *-shm file.
  55675. ** Other scenarios are also possible, depending on the VFS implementation.
  55676. **
  55677. ** Precondition:
  55678. **
  55679. ** The *-wal file has been read and an appropriate wal-index has been
  55680. ** constructed in pWal->apWiData[] using heap memory instead of shared
  55681. ** memory.
  55682. **
  55683. ** If this function returns SQLITE_OK, then the read transaction has
  55684. ** been successfully opened. In this case output variable (*pChanged)
  55685. ** is set to true before returning if the caller should discard the
  55686. ** contents of the page cache before proceeding. Or, if it returns
  55687. ** WAL_RETRY, then the heap memory wal-index has been discarded and
  55688. ** the caller should retry opening the read transaction from the
  55689. ** beginning (including attempting to map the *-shm file).
  55690. **
  55691. ** If an error occurs, an SQLite error code is returned.
  55692. */
  55693. static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
  55694. i64 szWal; /* Size of wal file on disk in bytes */
  55695. i64 iOffset; /* Current offset when reading wal file */
  55696. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  55697. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  55698. int szFrame; /* Number of bytes in buffer aFrame[] */
  55699. u8 *aData; /* Pointer to data part of aFrame buffer */
  55700. volatile void *pDummy; /* Dummy argument for xShmMap */
  55701. int rc; /* Return code */
  55702. u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
  55703. assert( pWal->bShmUnreliable );
  55704. assert( pWal->readOnly & WAL_SHM_RDONLY );
  55705. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55706. /* Take WAL_READ_LOCK(0). This has the effect of preventing any
  55707. ** writers from running a checkpoint, but does not stop them
  55708. ** from running recovery. */
  55709. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  55710. if( rc!=SQLITE_OK ){
  55711. if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
  55712. goto begin_unreliable_shm_out;
  55713. }
  55714. pWal->readLock = 0;
  55715. /* Check to see if a separate writer has attached to the shared-memory area,
  55716. ** thus making the shared-memory "reliable" again. Do this by invoking
  55717. ** the xShmMap() routine of the VFS and looking to see if the return
  55718. ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
  55719. **
  55720. ** If the shared-memory is now "reliable" return WAL_RETRY, which will
  55721. ** cause the heap-memory WAL-index to be discarded and the actual
  55722. ** shared memory to be used in its place.
  55723. **
  55724. ** This step is important because, even though this connection is holding
  55725. ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
  55726. ** have already checkpointed the WAL file and, while the current
  55727. ** is active, wrap the WAL and start overwriting frames that this
  55728. ** process wants to use.
  55729. **
  55730. ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
  55731. ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
  55732. ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
  55733. ** even if some external agent does a "chmod" to make the shared-memory
  55734. ** writable by us, until sqlite3OsShmUnmap() has been called.
  55735. ** This is a requirement on the VFS implementation.
  55736. */
  55737. rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
  55738. assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
  55739. if( rc!=SQLITE_READONLY_CANTINIT ){
  55740. rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
  55741. goto begin_unreliable_shm_out;
  55742. }
  55743. /* We reach this point only if the real shared-memory is still unreliable.
  55744. ** Assume the in-memory WAL-index substitute is correct and load it
  55745. ** into pWal->hdr.
  55746. */
  55747. memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
  55748. /* Make sure some writer hasn't come in and changed the WAL file out
  55749. ** from under us, then disconnected, while we were not looking.
  55750. */
  55751. rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
  55752. if( rc!=SQLITE_OK ){
  55753. goto begin_unreliable_shm_out;
  55754. }
  55755. if( szWal<WAL_HDRSIZE ){
  55756. /* If the wal file is too small to contain a wal-header and the
  55757. ** wal-index header has mxFrame==0, then it must be safe to proceed
  55758. ** reading the database file only. However, the page cache cannot
  55759. ** be trusted, as a read/write connection may have connected, written
  55760. ** the db, run a checkpoint, truncated the wal file and disconnected
  55761. ** since this client's last read transaction. */
  55762. *pChanged = 1;
  55763. rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
  55764. goto begin_unreliable_shm_out;
  55765. }
  55766. /* Check the salt keys at the start of the wal file still match. */
  55767. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  55768. if( rc!=SQLITE_OK ){
  55769. goto begin_unreliable_shm_out;
  55770. }
  55771. if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
  55772. /* Some writer has wrapped the WAL file while we were not looking.
  55773. ** Return WAL_RETRY which will cause the in-memory WAL-index to be
  55774. ** rebuilt. */
  55775. rc = WAL_RETRY;
  55776. goto begin_unreliable_shm_out;
  55777. }
  55778. /* Allocate a buffer to read frames into */
  55779. szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
  55780. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  55781. if( aFrame==0 ){
  55782. rc = SQLITE_NOMEM_BKPT;
  55783. goto begin_unreliable_shm_out;
  55784. }
  55785. aData = &aFrame[WAL_FRAME_HDRSIZE];
  55786. /* Check to see if a complete transaction has been appended to the
  55787. ** wal file since the heap-memory wal-index was created. If so, the
  55788. ** heap-memory wal-index is discarded and WAL_RETRY returned to
  55789. ** the caller. */
  55790. aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
  55791. aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
  55792. for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
  55793. iOffset+szFrame<=szWal;
  55794. iOffset+=szFrame
  55795. ){
  55796. u32 pgno; /* Database page number for frame */
  55797. u32 nTruncate; /* dbsize field from frame header */
  55798. /* Read and decode the next log frame. */
  55799. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  55800. if( rc!=SQLITE_OK ) break;
  55801. if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
  55802. /* If nTruncate is non-zero, then a complete transaction has been
  55803. ** appended to this wal file. Set rc to WAL_RETRY and break out of
  55804. ** the loop. */
  55805. if( nTruncate ){
  55806. rc = WAL_RETRY;
  55807. break;
  55808. }
  55809. }
  55810. pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
  55811. pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
  55812. begin_unreliable_shm_out:
  55813. sqlite3_free(aFrame);
  55814. if( rc!=SQLITE_OK ){
  55815. int i;
  55816. for(i=0; i<pWal->nWiData; i++){
  55817. sqlite3_free((void*)pWal->apWiData[i]);
  55818. pWal->apWiData[i] = 0;
  55819. }
  55820. pWal->bShmUnreliable = 0;
  55821. sqlite3WalEndReadTransaction(pWal);
  55822. *pChanged = 1;
  55823. }
  55824. return rc;
  55825. }
  55826. /*
  55827. ** Attempt to start a read transaction. This might fail due to a race or
  55828. ** other transient condition. When that happens, it returns WAL_RETRY to
  55829. ** indicate to the caller that it is safe to retry immediately.
  55830. **
  55831. ** On success return SQLITE_OK. On a permanent failure (such an
  55832. ** I/O error or an SQLITE_BUSY because another process is running
  55833. ** recovery) return a positive error code.
  55834. **
  55835. ** The useWal parameter is true to force the use of the WAL and disable
  55836. ** the case where the WAL is bypassed because it has been completely
  55837. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  55838. ** to make a copy of the wal-index header into pWal->hdr. If the
  55839. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  55840. ** to the caller that the local page cache is obsolete and needs to be
  55841. ** flushed.) When useWal==1, the wal-index header is assumed to already
  55842. ** be loaded and the pChanged parameter is unused.
  55843. **
  55844. ** The caller must set the cnt parameter to the number of prior calls to
  55845. ** this routine during the current read attempt that returned WAL_RETRY.
  55846. ** This routine will start taking more aggressive measures to clear the
  55847. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  55848. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  55849. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  55850. ** and is not honoring the locking protocol. There is a vanishingly small
  55851. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  55852. ** bad luck when there is lots of contention for the wal-index, but that
  55853. ** possibility is so small that it can be safely neglected, we believe.
  55854. **
  55855. ** On success, this routine obtains a read lock on
  55856. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  55857. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  55858. ** that means the Wal does not hold any read lock. The reader must not
  55859. ** access any database page that is modified by a WAL frame up to and
  55860. ** including frame number aReadMark[pWal->readLock]. The reader will
  55861. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  55862. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  55863. ** completely and get all content directly from the database file.
  55864. ** If the useWal parameter is 1 then the WAL will never be ignored and
  55865. ** this routine will always set pWal->readLock>0 on success.
  55866. ** When the read transaction is completed, the caller must release the
  55867. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  55868. **
  55869. ** This routine uses the nBackfill and aReadMark[] fields of the header
  55870. ** to select a particular WAL_READ_LOCK() that strives to let the
  55871. ** checkpoint process do as much work as possible. This routine might
  55872. ** update values of the aReadMark[] array in the header, but if it does
  55873. ** so it takes care to hold an exclusive lock on the corresponding
  55874. ** WAL_READ_LOCK() while changing values.
  55875. */
  55876. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  55877. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  55878. u32 mxReadMark; /* Largest aReadMark[] value */
  55879. int mxI; /* Index of largest aReadMark[] value */
  55880. int i; /* Loop counter */
  55881. int rc = SQLITE_OK; /* Return code */
  55882. u32 mxFrame; /* Wal frame to lock to */
  55883. assert( pWal->readLock<0 ); /* Not currently locked */
  55884. /* useWal may only be set for read/write connections */
  55885. assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
  55886. /* Take steps to avoid spinning forever if there is a protocol error.
  55887. **
  55888. ** Circumstances that cause a RETRY should only last for the briefest
  55889. ** instances of time. No I/O or other system calls are done while the
  55890. ** locks are held, so the locks should not be held for very long. But
  55891. ** if we are unlucky, another process that is holding a lock might get
  55892. ** paged out or take a page-fault that is time-consuming to resolve,
  55893. ** during the few nanoseconds that it is holding the lock. In that case,
  55894. ** it might take longer than normal for the lock to free.
  55895. **
  55896. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  55897. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  55898. ** is more of a scheduler yield than an actual delay. But on the 10th
  55899. ** an subsequent retries, the delays start becoming longer and longer,
  55900. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  55901. ** The total delay time before giving up is less than 10 seconds.
  55902. */
  55903. if( cnt>5 ){
  55904. int nDelay = 1; /* Pause time in microseconds */
  55905. if( cnt>100 ){
  55906. VVA_ONLY( pWal->lockError = 1; )
  55907. return SQLITE_PROTOCOL;
  55908. }
  55909. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  55910. sqlite3OsSleep(pWal->pVfs, nDelay);
  55911. }
  55912. if( !useWal ){
  55913. assert( rc==SQLITE_OK );
  55914. if( pWal->bShmUnreliable==0 ){
  55915. rc = walIndexReadHdr(pWal, pChanged);
  55916. }
  55917. if( rc==SQLITE_BUSY ){
  55918. /* If there is not a recovery running in another thread or process
  55919. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  55920. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  55921. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  55922. ** would be technically correct. But the race is benign since with
  55923. ** WAL_RETRY this routine will be called again and will probably be
  55924. ** right on the second iteration.
  55925. */
  55926. if( pWal->apWiData[0]==0 ){
  55927. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  55928. ** We assume this is a transient condition, so return WAL_RETRY. The
  55929. ** xShmMap() implementation used by the default unix and win32 VFS
  55930. ** modules may return SQLITE_BUSY due to a race condition in the
  55931. ** code that determines whether or not the shared-memory region
  55932. ** must be zeroed before the requested page is returned.
  55933. */
  55934. rc = WAL_RETRY;
  55935. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  55936. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  55937. rc = WAL_RETRY;
  55938. }else if( rc==SQLITE_BUSY ){
  55939. rc = SQLITE_BUSY_RECOVERY;
  55940. }
  55941. }
  55942. if( rc!=SQLITE_OK ){
  55943. return rc;
  55944. }
  55945. else if( pWal->bShmUnreliable ){
  55946. return walBeginShmUnreliable(pWal, pChanged);
  55947. }
  55948. }
  55949. assert( pWal->nWiData>0 );
  55950. assert( pWal->apWiData[0]!=0 );
  55951. pInfo = walCkptInfo(pWal);
  55952. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  55953. #ifdef SQLITE_ENABLE_SNAPSHOT
  55954. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
  55955. #endif
  55956. ){
  55957. /* The WAL has been completely backfilled (or it is empty).
  55958. ** and can be safely ignored.
  55959. */
  55960. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  55961. walShmBarrier(pWal);
  55962. if( rc==SQLITE_OK ){
  55963. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  55964. /* It is not safe to allow the reader to continue here if frames
  55965. ** may have been appended to the log before READ_LOCK(0) was obtained.
  55966. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  55967. ** which implies that the database file contains a trustworthy
  55968. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  55969. ** happening, this is usually correct.
  55970. **
  55971. ** However, if frames have been appended to the log (or if the log
  55972. ** is wrapped and written for that matter) before the READ_LOCK(0)
  55973. ** is obtained, that is not necessarily true. A checkpointer may
  55974. ** have started to backfill the appended frames but crashed before
  55975. ** it finished. Leaving a corrupt image in the database file.
  55976. */
  55977. walUnlockShared(pWal, WAL_READ_LOCK(0));
  55978. return WAL_RETRY;
  55979. }
  55980. pWal->readLock = 0;
  55981. return SQLITE_OK;
  55982. }else if( rc!=SQLITE_BUSY ){
  55983. return rc;
  55984. }
  55985. }
  55986. /* If we get this far, it means that the reader will want to use
  55987. ** the WAL to get at content from recent commits. The job now is
  55988. ** to select one of the aReadMark[] entries that is closest to
  55989. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  55990. */
  55991. mxReadMark = 0;
  55992. mxI = 0;
  55993. mxFrame = pWal->hdr.mxFrame;
  55994. #ifdef SQLITE_ENABLE_SNAPSHOT
  55995. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  55996. mxFrame = pWal->pSnapshot->mxFrame;
  55997. }
  55998. #endif
  55999. for(i=1; i<WAL_NREADER; i++){
  56000. u32 thisMark = pInfo->aReadMark[i];
  56001. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  56002. assert( thisMark!=READMARK_NOT_USED );
  56003. mxReadMark = thisMark;
  56004. mxI = i;
  56005. }
  56006. }
  56007. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  56008. && (mxReadMark<mxFrame || mxI==0)
  56009. ){
  56010. for(i=1; i<WAL_NREADER; i++){
  56011. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  56012. if( rc==SQLITE_OK ){
  56013. mxReadMark = pInfo->aReadMark[i] = mxFrame;
  56014. mxI = i;
  56015. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  56016. break;
  56017. }else if( rc!=SQLITE_BUSY ){
  56018. return rc;
  56019. }
  56020. }
  56021. }
  56022. if( mxI==0 ){
  56023. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  56024. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
  56025. }
  56026. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  56027. if( rc ){
  56028. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  56029. }
  56030. /* Now that the read-lock has been obtained, check that neither the
  56031. ** value in the aReadMark[] array or the contents of the wal-index
  56032. ** header have changed.
  56033. **
  56034. ** It is necessary to check that the wal-index header did not change
  56035. ** between the time it was read and when the shared-lock was obtained
  56036. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  56037. ** that the log file may have been wrapped by a writer, or that frames
  56038. ** that occur later in the log than pWal->hdr.mxFrame may have been
  56039. ** copied into the database by a checkpointer. If either of these things
  56040. ** happened, then reading the database with the current value of
  56041. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  56042. ** instead.
  56043. **
  56044. ** Before checking that the live wal-index header has not changed
  56045. ** since it was read, set Wal.minFrame to the first frame in the wal
  56046. ** file that has not yet been checkpointed. This client will not need
  56047. ** to read any frames earlier than minFrame from the wal file - they
  56048. ** can be safely read directly from the database file.
  56049. **
  56050. ** Because a ShmBarrier() call is made between taking the copy of
  56051. ** nBackfill and checking that the wal-header in shared-memory still
  56052. ** matches the one cached in pWal->hdr, it is guaranteed that the
  56053. ** checkpointer that set nBackfill was not working with a wal-index
  56054. ** header newer than that cached in pWal->hdr. If it were, that could
  56055. ** cause a problem. The checkpointer could omit to checkpoint
  56056. ** a version of page X that lies before pWal->minFrame (call that version
  56057. ** A) on the basis that there is a newer version (version B) of the same
  56058. ** page later in the wal file. But if version B happens to like past
  56059. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  56060. ** that it can read version A from the database file. However, since
  56061. ** we can guarantee that the checkpointer that set nBackfill could not
  56062. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  56063. */
  56064. pWal->minFrame = pInfo->nBackfill+1;
  56065. walShmBarrier(pWal);
  56066. if( pInfo->aReadMark[mxI]!=mxReadMark
  56067. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  56068. ){
  56069. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  56070. return WAL_RETRY;
  56071. }else{
  56072. assert( mxReadMark<=pWal->hdr.mxFrame );
  56073. pWal->readLock = (i16)mxI;
  56074. }
  56075. return rc;
  56076. }
  56077. #ifdef SQLITE_ENABLE_SNAPSHOT
  56078. /*
  56079. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  56080. ** variable so that older snapshots can be accessed. To do this, loop
  56081. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  56082. ** comparing their content to the corresponding page with the database
  56083. ** file, if any. Set nBackfillAttempted to the frame number of the
  56084. ** first frame for which the wal file content matches the db file.
  56085. **
  56086. ** This is only really safe if the file-system is such that any page
  56087. ** writes made by earlier checkpointers were atomic operations, which
  56088. ** is not always true. It is also possible that nBackfillAttempted
  56089. ** may be left set to a value larger than expected, if a wal frame
  56090. ** contains content that duplicate of an earlier version of the same
  56091. ** page.
  56092. **
  56093. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  56094. ** error occurs. It is not an error if nBackfillAttempted cannot be
  56095. ** decreased at all.
  56096. */
  56097. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  56098. int rc;
  56099. assert( pWal->readLock>=0 );
  56100. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56101. if( rc==SQLITE_OK ){
  56102. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56103. int szPage = (int)pWal->szPage;
  56104. i64 szDb; /* Size of db file in bytes */
  56105. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  56106. if( rc==SQLITE_OK ){
  56107. void *pBuf1 = sqlite3_malloc(szPage);
  56108. void *pBuf2 = sqlite3_malloc(szPage);
  56109. if( pBuf1==0 || pBuf2==0 ){
  56110. rc = SQLITE_NOMEM;
  56111. }else{
  56112. u32 i = pInfo->nBackfillAttempted;
  56113. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  56114. volatile ht_slot *dummy;
  56115. volatile u32 *aPgno; /* Array of page numbers */
  56116. u32 iZero; /* Frame corresponding to aPgno[0] */
  56117. u32 pgno; /* Page number in db file */
  56118. i64 iDbOff; /* Offset of db file entry */
  56119. i64 iWalOff; /* Offset of wal file entry */
  56120. rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
  56121. if( rc!=SQLITE_OK ) break;
  56122. pgno = aPgno[i-iZero];
  56123. iDbOff = (i64)(pgno-1) * szPage;
  56124. if( iDbOff+szPage<=szDb ){
  56125. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  56126. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  56127. if( rc==SQLITE_OK ){
  56128. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  56129. }
  56130. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  56131. break;
  56132. }
  56133. }
  56134. pInfo->nBackfillAttempted = i-1;
  56135. }
  56136. }
  56137. sqlite3_free(pBuf1);
  56138. sqlite3_free(pBuf2);
  56139. }
  56140. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56141. }
  56142. return rc;
  56143. }
  56144. #endif /* SQLITE_ENABLE_SNAPSHOT */
  56145. /*
  56146. ** Begin a read transaction on the database.
  56147. **
  56148. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  56149. ** it takes a snapshot of the state of the WAL and wal-index for the current
  56150. ** instant in time. The current thread will continue to use this snapshot.
  56151. ** Other threads might append new content to the WAL and wal-index but
  56152. ** that extra content is ignored by the current thread.
  56153. **
  56154. ** If the database contents have changes since the previous read
  56155. ** transaction, then *pChanged is set to 1 before returning. The
  56156. ** Pager layer will use this to know that is cache is stale and
  56157. ** needs to be flushed.
  56158. */
  56159. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  56160. int rc; /* Return code */
  56161. int cnt = 0; /* Number of TryBeginRead attempts */
  56162. #ifdef SQLITE_ENABLE_SNAPSHOT
  56163. int bChanged = 0;
  56164. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  56165. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  56166. bChanged = 1;
  56167. }
  56168. #endif
  56169. do{
  56170. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  56171. }while( rc==WAL_RETRY );
  56172. testcase( (rc&0xff)==SQLITE_BUSY );
  56173. testcase( (rc&0xff)==SQLITE_IOERR );
  56174. testcase( rc==SQLITE_PROTOCOL );
  56175. testcase( rc==SQLITE_OK );
  56176. #ifdef SQLITE_ENABLE_SNAPSHOT
  56177. if( rc==SQLITE_OK ){
  56178. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  56179. /* At this point the client has a lock on an aReadMark[] slot holding
  56180. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  56181. ** is populated with the wal-index header corresponding to the head
  56182. ** of the wal file. Verify that pSnapshot is still valid before
  56183. ** continuing. Reasons why pSnapshot might no longer be valid:
  56184. **
  56185. ** (1) The WAL file has been reset since the snapshot was taken.
  56186. ** In this case, the salt will have changed.
  56187. **
  56188. ** (2) A checkpoint as been attempted that wrote frames past
  56189. ** pSnapshot->mxFrame into the database file. Note that the
  56190. ** checkpoint need not have completed for this to cause problems.
  56191. */
  56192. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56193. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  56194. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  56195. /* It is possible that there is a checkpointer thread running
  56196. ** concurrent with this code. If this is the case, it may be that the
  56197. ** checkpointer has already determined that it will checkpoint
  56198. ** snapshot X, where X is later in the wal file than pSnapshot, but
  56199. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  56200. ** its intent. To avoid the race condition this leads to, ensure that
  56201. ** there is no checkpointer process by taking a shared CKPT lock
  56202. ** before checking pInfo->nBackfillAttempted.
  56203. **
  56204. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  56205. ** this already?
  56206. */
  56207. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  56208. if( rc==SQLITE_OK ){
  56209. /* Check that the wal file has not been wrapped. Assuming that it has
  56210. ** not, also check that no checkpointer has attempted to checkpoint any
  56211. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  56212. ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
  56213. ** with *pSnapshot and set *pChanged as appropriate for opening the
  56214. ** snapshot. */
  56215. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  56216. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  56217. ){
  56218. assert( pWal->readLock>0 );
  56219. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  56220. *pChanged = bChanged;
  56221. }else{
  56222. rc = SQLITE_BUSY_SNAPSHOT;
  56223. }
  56224. /* Release the shared CKPT lock obtained above. */
  56225. walUnlockShared(pWal, WAL_CKPT_LOCK);
  56226. }
  56227. if( rc!=SQLITE_OK ){
  56228. sqlite3WalEndReadTransaction(pWal);
  56229. }
  56230. }
  56231. }
  56232. #endif
  56233. return rc;
  56234. }
  56235. /*
  56236. ** Finish with a read transaction. All this does is release the
  56237. ** read-lock.
  56238. */
  56239. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  56240. sqlite3WalEndWriteTransaction(pWal);
  56241. if( pWal->readLock>=0 ){
  56242. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  56243. pWal->readLock = -1;
  56244. }
  56245. }
  56246. /*
  56247. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  56248. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  56249. ** to zero.
  56250. **
  56251. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  56252. ** error does occur, the final value of *piRead is undefined.
  56253. */
  56254. SQLITE_PRIVATE int sqlite3WalFindFrame(
  56255. Wal *pWal, /* WAL handle */
  56256. Pgno pgno, /* Database page number to read data for */
  56257. u32 *piRead /* OUT: Frame number (or zero) */
  56258. ){
  56259. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  56260. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  56261. int iHash; /* Used to loop through N hash tables */
  56262. int iMinHash;
  56263. /* This routine is only be called from within a read transaction. */
  56264. assert( pWal->readLock>=0 || pWal->lockError );
  56265. /* If the "last page" field of the wal-index header snapshot is 0, then
  56266. ** no data will be read from the wal under any circumstances. Return early
  56267. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  56268. ** then the WAL is ignored by the reader so return early, as if the
  56269. ** WAL were empty.
  56270. */
  56271. if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
  56272. *piRead = 0;
  56273. return SQLITE_OK;
  56274. }
  56275. /* Search the hash table or tables for an entry matching page number
  56276. ** pgno. Each iteration of the following for() loop searches one
  56277. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  56278. **
  56279. ** This code might run concurrently to the code in walIndexAppend()
  56280. ** that adds entries to the wal-index (and possibly to this hash
  56281. ** table). This means the value just read from the hash
  56282. ** slot (aHash[iKey]) may have been added before or after the
  56283. ** current read transaction was opened. Values added after the
  56284. ** read transaction was opened may have been written incorrectly -
  56285. ** i.e. these slots may contain garbage data. However, we assume
  56286. ** that any slots written before the current read transaction was
  56287. ** opened remain unmodified.
  56288. **
  56289. ** For the reasons above, the if(...) condition featured in the inner
  56290. ** loop of the following block is more stringent that would be required
  56291. ** if we had exclusive access to the hash-table:
  56292. **
  56293. ** (aPgno[iFrame]==pgno):
  56294. ** This condition filters out normal hash-table collisions.
  56295. **
  56296. ** (iFrame<=iLast):
  56297. ** This condition filters out entries that were added to the hash
  56298. ** table after the current read-transaction had started.
  56299. */
  56300. iMinHash = walFramePage(pWal->minFrame);
  56301. for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
  56302. volatile ht_slot *aHash; /* Pointer to hash table */
  56303. volatile u32 *aPgno; /* Pointer to array of page numbers */
  56304. u32 iZero; /* Frame number corresponding to aPgno[0] */
  56305. int iKey; /* Hash slot index */
  56306. int nCollide; /* Number of hash collisions remaining */
  56307. int rc; /* Error code */
  56308. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  56309. if( rc!=SQLITE_OK ){
  56310. return rc;
  56311. }
  56312. nCollide = HASHTABLE_NSLOT;
  56313. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  56314. u32 iFrame = aHash[iKey] + iZero;
  56315. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  56316. assert( iFrame>iRead || CORRUPT_DB );
  56317. iRead = iFrame;
  56318. }
  56319. if( (nCollide--)==0 ){
  56320. return SQLITE_CORRUPT_BKPT;
  56321. }
  56322. }
  56323. if( iRead ) break;
  56324. }
  56325. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  56326. /* If expensive assert() statements are available, do a linear search
  56327. ** of the wal-index file content. Make sure the results agree with the
  56328. ** result obtained using the hash indexes above. */
  56329. {
  56330. u32 iRead2 = 0;
  56331. u32 iTest;
  56332. assert( pWal->bShmUnreliable || pWal->minFrame>0 );
  56333. for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
  56334. if( walFramePgno(pWal, iTest)==pgno ){
  56335. iRead2 = iTest;
  56336. break;
  56337. }
  56338. }
  56339. assert( iRead==iRead2 );
  56340. }
  56341. #endif
  56342. *piRead = iRead;
  56343. return SQLITE_OK;
  56344. }
  56345. /*
  56346. ** Read the contents of frame iRead from the wal file into buffer pOut
  56347. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  56348. ** error code otherwise.
  56349. */
  56350. SQLITE_PRIVATE int sqlite3WalReadFrame(
  56351. Wal *pWal, /* WAL handle */
  56352. u32 iRead, /* Frame to read */
  56353. int nOut, /* Size of buffer pOut in bytes */
  56354. u8 *pOut /* Buffer to write page data to */
  56355. ){
  56356. int sz;
  56357. i64 iOffset;
  56358. sz = pWal->hdr.szPage;
  56359. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  56360. testcase( sz<=32768 );
  56361. testcase( sz>=65536 );
  56362. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  56363. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  56364. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  56365. }
  56366. /*
  56367. ** Return the size of the database in pages (or zero, if unknown).
  56368. */
  56369. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  56370. if( pWal && ALWAYS(pWal->readLock>=0) ){
  56371. return pWal->hdr.nPage;
  56372. }
  56373. return 0;
  56374. }
  56375. /*
  56376. ** This function starts a write transaction on the WAL.
  56377. **
  56378. ** A read transaction must have already been started by a prior call
  56379. ** to sqlite3WalBeginReadTransaction().
  56380. **
  56381. ** If another thread or process has written into the database since
  56382. ** the read transaction was started, then it is not possible for this
  56383. ** thread to write as doing so would cause a fork. So this routine
  56384. ** returns SQLITE_BUSY in that case and no write transaction is started.
  56385. **
  56386. ** There can only be a single writer active at a time.
  56387. */
  56388. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  56389. int rc;
  56390. /* Cannot start a write transaction without first holding a read
  56391. ** transaction. */
  56392. assert( pWal->readLock>=0 );
  56393. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  56394. if( pWal->readOnly ){
  56395. return SQLITE_READONLY;
  56396. }
  56397. /* Only one writer allowed at a time. Get the write lock. Return
  56398. ** SQLITE_BUSY if unable.
  56399. */
  56400. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  56401. if( rc ){
  56402. return rc;
  56403. }
  56404. pWal->writeLock = 1;
  56405. /* If another connection has written to the database file since the
  56406. ** time the read transaction on this connection was started, then
  56407. ** the write is disallowed.
  56408. */
  56409. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  56410. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  56411. pWal->writeLock = 0;
  56412. rc = SQLITE_BUSY_SNAPSHOT;
  56413. }
  56414. return rc;
  56415. }
  56416. /*
  56417. ** End a write transaction. The commit has already been done. This
  56418. ** routine merely releases the lock.
  56419. */
  56420. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  56421. if( pWal->writeLock ){
  56422. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  56423. pWal->writeLock = 0;
  56424. pWal->iReCksum = 0;
  56425. pWal->truncateOnCommit = 0;
  56426. }
  56427. return SQLITE_OK;
  56428. }
  56429. /*
  56430. ** If any data has been written (but not committed) to the log file, this
  56431. ** function moves the write-pointer back to the start of the transaction.
  56432. **
  56433. ** Additionally, the callback function is invoked for each frame written
  56434. ** to the WAL since the start of the transaction. If the callback returns
  56435. ** other than SQLITE_OK, it is not invoked again and the error code is
  56436. ** returned to the caller.
  56437. **
  56438. ** Otherwise, if the callback function does not return an error, this
  56439. ** function returns SQLITE_OK.
  56440. */
  56441. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  56442. int rc = SQLITE_OK;
  56443. if( ALWAYS(pWal->writeLock) ){
  56444. Pgno iMax = pWal->hdr.mxFrame;
  56445. Pgno iFrame;
  56446. /* Restore the clients cache of the wal-index header to the state it
  56447. ** was in before the client began writing to the database.
  56448. */
  56449. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  56450. for(iFrame=pWal->hdr.mxFrame+1;
  56451. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  56452. iFrame++
  56453. ){
  56454. /* This call cannot fail. Unless the page for which the page number
  56455. ** is passed as the second argument is (a) in the cache and
  56456. ** (b) has an outstanding reference, then xUndo is either a no-op
  56457. ** (if (a) is false) or simply expels the page from the cache (if (b)
  56458. ** is false).
  56459. **
  56460. ** If the upper layer is doing a rollback, it is guaranteed that there
  56461. ** are no outstanding references to any page other than page 1. And
  56462. ** page 1 is never written to the log until the transaction is
  56463. ** committed. As a result, the call to xUndo may not fail.
  56464. */
  56465. assert( walFramePgno(pWal, iFrame)!=1 );
  56466. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  56467. }
  56468. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  56469. }
  56470. return rc;
  56471. }
  56472. /*
  56473. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  56474. ** values. This function populates the array with values required to
  56475. ** "rollback" the write position of the WAL handle back to the current
  56476. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  56477. */
  56478. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  56479. assert( pWal->writeLock );
  56480. aWalData[0] = pWal->hdr.mxFrame;
  56481. aWalData[1] = pWal->hdr.aFrameCksum[0];
  56482. aWalData[2] = pWal->hdr.aFrameCksum[1];
  56483. aWalData[3] = pWal->nCkpt;
  56484. }
  56485. /*
  56486. ** Move the write position of the WAL back to the point identified by
  56487. ** the values in the aWalData[] array. aWalData must point to an array
  56488. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  56489. ** by a call to WalSavepoint().
  56490. */
  56491. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  56492. int rc = SQLITE_OK;
  56493. assert( pWal->writeLock );
  56494. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  56495. if( aWalData[3]!=pWal->nCkpt ){
  56496. /* This savepoint was opened immediately after the write-transaction
  56497. ** was started. Right after that, the writer decided to wrap around
  56498. ** to the start of the log. Update the savepoint values to match.
  56499. */
  56500. aWalData[0] = 0;
  56501. aWalData[3] = pWal->nCkpt;
  56502. }
  56503. if( aWalData[0]<pWal->hdr.mxFrame ){
  56504. pWal->hdr.mxFrame = aWalData[0];
  56505. pWal->hdr.aFrameCksum[0] = aWalData[1];
  56506. pWal->hdr.aFrameCksum[1] = aWalData[2];
  56507. walCleanupHash(pWal);
  56508. }
  56509. return rc;
  56510. }
  56511. /*
  56512. ** This function is called just before writing a set of frames to the log
  56513. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  56514. ** to the current log file, it is possible to overwrite the start of the
  56515. ** existing log file with the new frames (i.e. "reset" the log). If so,
  56516. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  56517. ** unchanged.
  56518. **
  56519. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  56520. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  56521. ** if an error occurs.
  56522. */
  56523. static int walRestartLog(Wal *pWal){
  56524. int rc = SQLITE_OK;
  56525. int cnt;
  56526. if( pWal->readLock==0 ){
  56527. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56528. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  56529. if( pInfo->nBackfill>0 ){
  56530. u32 salt1;
  56531. sqlite3_randomness(4, &salt1);
  56532. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56533. if( rc==SQLITE_OK ){
  56534. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  56535. ** readers are currently using the WAL), then the transactions
  56536. ** frames will overwrite the start of the existing log. Update the
  56537. ** wal-index header to reflect this.
  56538. **
  56539. ** In theory it would be Ok to update the cache of the header only
  56540. ** at this point. But updating the actual wal-index header is also
  56541. ** safe and means there is no special case for sqlite3WalUndo()
  56542. ** to handle if this transaction is rolled back. */
  56543. walRestartHdr(pWal, salt1);
  56544. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56545. }else if( rc!=SQLITE_BUSY ){
  56546. return rc;
  56547. }
  56548. }
  56549. walUnlockShared(pWal, WAL_READ_LOCK(0));
  56550. pWal->readLock = -1;
  56551. cnt = 0;
  56552. do{
  56553. int notUsed;
  56554. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  56555. }while( rc==WAL_RETRY );
  56556. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  56557. testcase( (rc&0xff)==SQLITE_IOERR );
  56558. testcase( rc==SQLITE_PROTOCOL );
  56559. testcase( rc==SQLITE_OK );
  56560. }
  56561. return rc;
  56562. }
  56563. /*
  56564. ** Information about the current state of the WAL file and where
  56565. ** the next fsync should occur - passed from sqlite3WalFrames() into
  56566. ** walWriteToLog().
  56567. */
  56568. typedef struct WalWriter {
  56569. Wal *pWal; /* The complete WAL information */
  56570. sqlite3_file *pFd; /* The WAL file to which we write */
  56571. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  56572. int syncFlags; /* Flags for the fsync */
  56573. int szPage; /* Size of one page */
  56574. } WalWriter;
  56575. /*
  56576. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  56577. ** Do a sync when crossing the p->iSyncPoint boundary.
  56578. **
  56579. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  56580. ** first write the part before iSyncPoint, then sync, then write the
  56581. ** rest.
  56582. */
  56583. static int walWriteToLog(
  56584. WalWriter *p, /* WAL to write to */
  56585. void *pContent, /* Content to be written */
  56586. int iAmt, /* Number of bytes to write */
  56587. sqlite3_int64 iOffset /* Start writing at this offset */
  56588. ){
  56589. int rc;
  56590. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  56591. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  56592. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  56593. if( rc ) return rc;
  56594. iOffset += iFirstAmt;
  56595. iAmt -= iFirstAmt;
  56596. pContent = (void*)(iFirstAmt + (char*)pContent);
  56597. assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
  56598. rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
  56599. if( iAmt==0 || rc ) return rc;
  56600. }
  56601. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  56602. return rc;
  56603. }
  56604. /*
  56605. ** Write out a single frame of the WAL
  56606. */
  56607. static int walWriteOneFrame(
  56608. WalWriter *p, /* Where to write the frame */
  56609. PgHdr *pPage, /* The page of the frame to be written */
  56610. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  56611. sqlite3_int64 iOffset /* Byte offset at which to write */
  56612. ){
  56613. int rc; /* Result code from subfunctions */
  56614. void *pData; /* Data actually written */
  56615. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  56616. #if defined(SQLITE_HAS_CODEC)
  56617. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  56618. #else
  56619. pData = pPage->pData;
  56620. #endif
  56621. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  56622. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  56623. if( rc ) return rc;
  56624. /* Write the page data */
  56625. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  56626. return rc;
  56627. }
  56628. /*
  56629. ** This function is called as part of committing a transaction within which
  56630. ** one or more frames have been overwritten. It updates the checksums for
  56631. ** all frames written to the wal file by the current transaction starting
  56632. ** with the earliest to have been overwritten.
  56633. **
  56634. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  56635. */
  56636. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  56637. const int szPage = pWal->szPage;/* Database page size */
  56638. int rc = SQLITE_OK; /* Return code */
  56639. u8 *aBuf; /* Buffer to load data from wal file into */
  56640. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  56641. u32 iRead; /* Next frame to read from wal file */
  56642. i64 iCksumOff;
  56643. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  56644. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  56645. /* Find the checksum values to use as input for the recalculating the
  56646. ** first checksum. If the first frame is frame 1 (implying that the current
  56647. ** transaction restarted the wal file), these values must be read from the
  56648. ** wal-file header. Otherwise, read them from the frame header of the
  56649. ** previous frame. */
  56650. assert( pWal->iReCksum>0 );
  56651. if( pWal->iReCksum==1 ){
  56652. iCksumOff = 24;
  56653. }else{
  56654. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  56655. }
  56656. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  56657. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  56658. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  56659. iRead = pWal->iReCksum;
  56660. pWal->iReCksum = 0;
  56661. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  56662. i64 iOff = walFrameOffset(iRead, szPage);
  56663. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  56664. if( rc==SQLITE_OK ){
  56665. u32 iPgno, nDbSize;
  56666. iPgno = sqlite3Get4byte(aBuf);
  56667. nDbSize = sqlite3Get4byte(&aBuf[4]);
  56668. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  56669. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  56670. }
  56671. }
  56672. sqlite3_free(aBuf);
  56673. return rc;
  56674. }
  56675. /*
  56676. ** Write a set of frames to the log. The caller must hold the write-lock
  56677. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  56678. */
  56679. SQLITE_PRIVATE int sqlite3WalFrames(
  56680. Wal *pWal, /* Wal handle to write to */
  56681. int szPage, /* Database page-size in bytes */
  56682. PgHdr *pList, /* List of dirty pages to write */
  56683. Pgno nTruncate, /* Database size after this commit */
  56684. int isCommit, /* True if this is a commit */
  56685. int sync_flags /* Flags to pass to OsSync() (or 0) */
  56686. ){
  56687. int rc; /* Used to catch return codes */
  56688. u32 iFrame; /* Next frame address */
  56689. PgHdr *p; /* Iterator to run through pList with. */
  56690. PgHdr *pLast = 0; /* Last frame in list */
  56691. int nExtra = 0; /* Number of extra copies of last page */
  56692. int szFrame; /* The size of a single frame */
  56693. i64 iOffset; /* Next byte to write in WAL file */
  56694. WalWriter w; /* The writer */
  56695. u32 iFirst = 0; /* First frame that may be overwritten */
  56696. WalIndexHdr *pLive; /* Pointer to shared header */
  56697. assert( pList );
  56698. assert( pWal->writeLock );
  56699. /* If this frame set completes a transaction, then nTruncate>0. If
  56700. ** nTruncate==0 then this frame set does not complete the transaction. */
  56701. assert( (isCommit!=0)==(nTruncate!=0) );
  56702. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  56703. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  56704. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  56705. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  56706. }
  56707. #endif
  56708. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  56709. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  56710. iFirst = pLive->mxFrame+1;
  56711. }
  56712. /* See if it is possible to write these frames into the start of the
  56713. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  56714. */
  56715. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  56716. return rc;
  56717. }
  56718. /* If this is the first frame written into the log, write the WAL
  56719. ** header to the start of the WAL file. See comments at the top of
  56720. ** this source file for a description of the WAL header format.
  56721. */
  56722. iFrame = pWal->hdr.mxFrame;
  56723. if( iFrame==0 ){
  56724. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  56725. u32 aCksum[2]; /* Checksum for wal-header */
  56726. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  56727. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  56728. sqlite3Put4byte(&aWalHdr[8], szPage);
  56729. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  56730. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  56731. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  56732. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  56733. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  56734. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  56735. pWal->szPage = szPage;
  56736. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  56737. pWal->hdr.aFrameCksum[0] = aCksum[0];
  56738. pWal->hdr.aFrameCksum[1] = aCksum[1];
  56739. pWal->truncateOnCommit = 1;
  56740. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  56741. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  56742. if( rc!=SQLITE_OK ){
  56743. return rc;
  56744. }
  56745. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  56746. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  56747. ** an out-of-order write following a WAL restart could result in
  56748. ** database corruption. See the ticket:
  56749. **
  56750. ** https://sqlite.org/src/info/ff5be73dee
  56751. */
  56752. if( pWal->syncHeader ){
  56753. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  56754. if( rc ) return rc;
  56755. }
  56756. }
  56757. assert( (int)pWal->szPage==szPage );
  56758. /* Setup information needed to write frames into the WAL */
  56759. w.pWal = pWal;
  56760. w.pFd = pWal->pWalFd;
  56761. w.iSyncPoint = 0;
  56762. w.syncFlags = sync_flags;
  56763. w.szPage = szPage;
  56764. iOffset = walFrameOffset(iFrame+1, szPage);
  56765. szFrame = szPage + WAL_FRAME_HDRSIZE;
  56766. /* Write all frames into the log file exactly once */
  56767. for(p=pList; p; p=p->pDirty){
  56768. int nDbSize; /* 0 normally. Positive == commit flag */
  56769. /* Check if this page has already been written into the wal file by
  56770. ** the current transaction. If so, overwrite the existing frame and
  56771. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  56772. ** checksums must be recomputed when the transaction is committed. */
  56773. if( iFirst && (p->pDirty || isCommit==0) ){
  56774. u32 iWrite = 0;
  56775. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  56776. assert( rc==SQLITE_OK || iWrite==0 );
  56777. if( iWrite>=iFirst ){
  56778. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  56779. void *pData;
  56780. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  56781. pWal->iReCksum = iWrite;
  56782. }
  56783. #if defined(SQLITE_HAS_CODEC)
  56784. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  56785. #else
  56786. pData = p->pData;
  56787. #endif
  56788. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  56789. if( rc ) return rc;
  56790. p->flags &= ~PGHDR_WAL_APPEND;
  56791. continue;
  56792. }
  56793. }
  56794. iFrame++;
  56795. assert( iOffset==walFrameOffset(iFrame, szPage) );
  56796. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  56797. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  56798. if( rc ) return rc;
  56799. pLast = p;
  56800. iOffset += szFrame;
  56801. p->flags |= PGHDR_WAL_APPEND;
  56802. }
  56803. /* Recalculate checksums within the wal file if required. */
  56804. if( isCommit && pWal->iReCksum ){
  56805. rc = walRewriteChecksums(pWal, iFrame);
  56806. if( rc ) return rc;
  56807. }
  56808. /* If this is the end of a transaction, then we might need to pad
  56809. ** the transaction and/or sync the WAL file.
  56810. **
  56811. ** Padding and syncing only occur if this set of frames complete a
  56812. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  56813. ** or synchronous==OFF, then no padding or syncing are needed.
  56814. **
  56815. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  56816. ** needed and only the sync is done. If padding is needed, then the
  56817. ** final frame is repeated (with its commit mark) until the next sector
  56818. ** boundary is crossed. Only the part of the WAL prior to the last
  56819. ** sector boundary is synced; the part of the last frame that extends
  56820. ** past the sector boundary is written after the sync.
  56821. */
  56822. if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
  56823. int bSync = 1;
  56824. if( pWal->padToSectorBoundary ){
  56825. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  56826. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  56827. bSync = (w.iSyncPoint==iOffset);
  56828. testcase( bSync );
  56829. while( iOffset<w.iSyncPoint ){
  56830. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  56831. if( rc ) return rc;
  56832. iOffset += szFrame;
  56833. nExtra++;
  56834. }
  56835. }
  56836. if( bSync ){
  56837. assert( rc==SQLITE_OK );
  56838. rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
  56839. }
  56840. }
  56841. /* If this frame set completes the first transaction in the WAL and
  56842. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  56843. ** journal size limit, if possible.
  56844. */
  56845. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  56846. i64 sz = pWal->mxWalSize;
  56847. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  56848. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  56849. }
  56850. walLimitSize(pWal, sz);
  56851. pWal->truncateOnCommit = 0;
  56852. }
  56853. /* Append data to the wal-index. It is not necessary to lock the
  56854. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  56855. ** guarantees that there are no other writers, and no data that may
  56856. ** be in use by existing readers is being overwritten.
  56857. */
  56858. iFrame = pWal->hdr.mxFrame;
  56859. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  56860. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  56861. iFrame++;
  56862. rc = walIndexAppend(pWal, iFrame, p->pgno);
  56863. }
  56864. while( rc==SQLITE_OK && nExtra>0 ){
  56865. iFrame++;
  56866. nExtra--;
  56867. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  56868. }
  56869. if( rc==SQLITE_OK ){
  56870. /* Update the private copy of the header. */
  56871. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  56872. testcase( szPage<=32768 );
  56873. testcase( szPage>=65536 );
  56874. pWal->hdr.mxFrame = iFrame;
  56875. if( isCommit ){
  56876. pWal->hdr.iChange++;
  56877. pWal->hdr.nPage = nTruncate;
  56878. }
  56879. /* If this is a commit, update the wal-index header too. */
  56880. if( isCommit ){
  56881. walIndexWriteHdr(pWal);
  56882. pWal->iCallback = iFrame;
  56883. }
  56884. }
  56885. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  56886. return rc;
  56887. }
  56888. /*
  56889. ** This routine is called to implement sqlite3_wal_checkpoint() and
  56890. ** related interfaces.
  56891. **
  56892. ** Obtain a CHECKPOINT lock and then backfill as much information as
  56893. ** we can from WAL into the database.
  56894. **
  56895. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  56896. ** callback. In this case this function runs a blocking checkpoint.
  56897. */
  56898. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  56899. Wal *pWal, /* Wal connection */
  56900. sqlite3 *db, /* Check this handle's interrupt flag */
  56901. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  56902. int (*xBusy)(void*), /* Function to call when busy */
  56903. void *pBusyArg, /* Context argument for xBusyHandler */
  56904. int sync_flags, /* Flags to sync db file with (or 0) */
  56905. int nBuf, /* Size of temporary buffer */
  56906. u8 *zBuf, /* Temporary buffer to use */
  56907. int *pnLog, /* OUT: Number of frames in WAL */
  56908. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  56909. ){
  56910. int rc; /* Return code */
  56911. int isChanged = 0; /* True if a new wal-index header is loaded */
  56912. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  56913. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  56914. assert( pWal->ckptLock==0 );
  56915. assert( pWal->writeLock==0 );
  56916. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  56917. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  56918. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  56919. if( pWal->readOnly ) return SQLITE_READONLY;
  56920. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  56921. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  56922. ** "checkpoint" lock on the database file. */
  56923. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56924. if( rc ){
  56925. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  56926. ** checkpoint operation at the same time, the lock cannot be obtained and
  56927. ** SQLITE_BUSY is returned.
  56928. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  56929. ** it will not be invoked in this case.
  56930. */
  56931. testcase( rc==SQLITE_BUSY );
  56932. testcase( xBusy!=0 );
  56933. return rc;
  56934. }
  56935. pWal->ckptLock = 1;
  56936. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  56937. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  56938. ** file.
  56939. **
  56940. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  56941. ** immediately, and a busy-handler is configured, it is invoked and the
  56942. ** writer lock retried until either the busy-handler returns 0 or the
  56943. ** lock is successfully obtained.
  56944. */
  56945. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  56946. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  56947. if( rc==SQLITE_OK ){
  56948. pWal->writeLock = 1;
  56949. }else if( rc==SQLITE_BUSY ){
  56950. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  56951. xBusy2 = 0;
  56952. rc = SQLITE_OK;
  56953. }
  56954. }
  56955. /* Read the wal-index header. */
  56956. if( rc==SQLITE_OK ){
  56957. rc = walIndexReadHdr(pWal, &isChanged);
  56958. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  56959. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  56960. }
  56961. }
  56962. /* Copy data from the log to the database file. */
  56963. if( rc==SQLITE_OK ){
  56964. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  56965. rc = SQLITE_CORRUPT_BKPT;
  56966. }else{
  56967. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  56968. }
  56969. /* If no error occurred, set the output variables. */
  56970. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  56971. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  56972. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  56973. }
  56974. }
  56975. if( isChanged ){
  56976. /* If a new wal-index header was loaded before the checkpoint was
  56977. ** performed, then the pager-cache associated with pWal is now
  56978. ** out of date. So zero the cached wal-index header to ensure that
  56979. ** next time the pager opens a snapshot on this database it knows that
  56980. ** the cache needs to be reset.
  56981. */
  56982. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  56983. }
  56984. /* Release the locks. */
  56985. sqlite3WalEndWriteTransaction(pWal);
  56986. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56987. pWal->ckptLock = 0;
  56988. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  56989. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  56990. }
  56991. /* Return the value to pass to a sqlite3_wal_hook callback, the
  56992. ** number of frames in the WAL at the point of the last commit since
  56993. ** sqlite3WalCallback() was called. If no commits have occurred since
  56994. ** the last call, then return 0.
  56995. */
  56996. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  56997. u32 ret = 0;
  56998. if( pWal ){
  56999. ret = pWal->iCallback;
  57000. pWal->iCallback = 0;
  57001. }
  57002. return (int)ret;
  57003. }
  57004. /*
  57005. ** This function is called to change the WAL subsystem into or out
  57006. ** of locking_mode=EXCLUSIVE.
  57007. **
  57008. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  57009. ** into locking_mode=NORMAL. This means that we must acquire a lock
  57010. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  57011. ** or if the acquisition of the lock fails, then return 0. If the
  57012. ** transition out of exclusive-mode is successful, return 1. This
  57013. ** operation must occur while the pager is still holding the exclusive
  57014. ** lock on the main database file.
  57015. **
  57016. ** If op is one, then change from locking_mode=NORMAL into
  57017. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  57018. ** be released. Return 1 if the transition is made and 0 if the
  57019. ** WAL is already in exclusive-locking mode - meaning that this
  57020. ** routine is a no-op. The pager must already hold the exclusive lock
  57021. ** on the main database file before invoking this operation.
  57022. **
  57023. ** If op is negative, then do a dry-run of the op==1 case but do
  57024. ** not actually change anything. The pager uses this to see if it
  57025. ** should acquire the database exclusive lock prior to invoking
  57026. ** the op==1 case.
  57027. */
  57028. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  57029. int rc;
  57030. assert( pWal->writeLock==0 );
  57031. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  57032. /* pWal->readLock is usually set, but might be -1 if there was a
  57033. ** prior error while attempting to acquire are read-lock. This cannot
  57034. ** happen if the connection is actually in exclusive mode (as no xShmLock
  57035. ** locks are taken in this case). Nor should the pager attempt to
  57036. ** upgrade to exclusive-mode following such an error.
  57037. */
  57038. assert( pWal->readLock>=0 || pWal->lockError );
  57039. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  57040. if( op==0 ){
  57041. if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
  57042. pWal->exclusiveMode = WAL_NORMAL_MODE;
  57043. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  57044. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  57045. }
  57046. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  57047. }else{
  57048. /* Already in locking_mode=NORMAL */
  57049. rc = 0;
  57050. }
  57051. }else if( op>0 ){
  57052. assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
  57053. assert( pWal->readLock>=0 );
  57054. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  57055. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  57056. rc = 1;
  57057. }else{
  57058. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  57059. }
  57060. return rc;
  57061. }
  57062. /*
  57063. ** Return true if the argument is non-NULL and the WAL module is using
  57064. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  57065. ** WAL module is using shared-memory, return false.
  57066. */
  57067. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  57068. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  57069. }
  57070. #ifdef SQLITE_ENABLE_SNAPSHOT
  57071. /* Create a snapshot object. The content of a snapshot is opaque to
  57072. ** every other subsystem, so the WAL module can put whatever it needs
  57073. ** in the object.
  57074. */
  57075. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  57076. int rc = SQLITE_OK;
  57077. WalIndexHdr *pRet;
  57078. static const u32 aZero[4] = { 0, 0, 0, 0 };
  57079. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  57080. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  57081. *ppSnapshot = 0;
  57082. return SQLITE_ERROR;
  57083. }
  57084. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  57085. if( pRet==0 ){
  57086. rc = SQLITE_NOMEM_BKPT;
  57087. }else{
  57088. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  57089. *ppSnapshot = (sqlite3_snapshot*)pRet;
  57090. }
  57091. return rc;
  57092. }
  57093. /* Try to open on pSnapshot when the next read-transaction starts
  57094. */
  57095. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  57096. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  57097. }
  57098. /*
  57099. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  57100. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  57101. */
  57102. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  57103. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  57104. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  57105. /* aSalt[0] is a copy of the value stored in the wal file header. It
  57106. ** is incremented each time the wal file is restarted. */
  57107. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  57108. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  57109. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  57110. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  57111. return 0;
  57112. }
  57113. #endif /* SQLITE_ENABLE_SNAPSHOT */
  57114. #ifdef SQLITE_ENABLE_ZIPVFS
  57115. /*
  57116. ** If the argument is not NULL, it points to a Wal object that holds a
  57117. ** read-lock. This function returns the database page-size if it is known,
  57118. ** or zero if it is not (or if pWal is NULL).
  57119. */
  57120. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  57121. assert( pWal==0 || pWal->readLock>=0 );
  57122. return (pWal ? pWal->szPage : 0);
  57123. }
  57124. #endif
  57125. /* Return the sqlite3_file object for the WAL file
  57126. */
  57127. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  57128. return pWal->pWalFd;
  57129. }
  57130. #endif /* #ifndef SQLITE_OMIT_WAL */
  57131. /************** End of wal.c *************************************************/
  57132. /************** Begin file btmutex.c *****************************************/
  57133. /*
  57134. ** 2007 August 27
  57135. **
  57136. ** The author disclaims copyright to this source code. In place of
  57137. ** a legal notice, here is a blessing:
  57138. **
  57139. ** May you do good and not evil.
  57140. ** May you find forgiveness for yourself and forgive others.
  57141. ** May you share freely, never taking more than you give.
  57142. **
  57143. *************************************************************************
  57144. **
  57145. ** This file contains code used to implement mutexes on Btree objects.
  57146. ** This code really belongs in btree.c. But btree.c is getting too
  57147. ** big and we want to break it down some. This packaged seemed like
  57148. ** a good breakout.
  57149. */
  57150. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  57151. /************** Begin file btreeInt.h ****************************************/
  57152. /*
  57153. ** 2004 April 6
  57154. **
  57155. ** The author disclaims copyright to this source code. In place of
  57156. ** a legal notice, here is a blessing:
  57157. **
  57158. ** May you do good and not evil.
  57159. ** May you find forgiveness for yourself and forgive others.
  57160. ** May you share freely, never taking more than you give.
  57161. **
  57162. *************************************************************************
  57163. ** This file implements an external (disk-based) database using BTrees.
  57164. ** For a detailed discussion of BTrees, refer to
  57165. **
  57166. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  57167. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  57168. ** Publishing Company, Reading, Massachusetts.
  57169. **
  57170. ** The basic idea is that each page of the file contains N database
  57171. ** entries and N+1 pointers to subpages.
  57172. **
  57173. ** ----------------------------------------------------------------
  57174. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  57175. ** ----------------------------------------------------------------
  57176. **
  57177. ** All of the keys on the page that Ptr(0) points to have values less
  57178. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  57179. ** values greater than Key(0) and less than Key(1). All of the keys
  57180. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  57181. ** so forth.
  57182. **
  57183. ** Finding a particular key requires reading O(log(M)) pages from the
  57184. ** disk where M is the number of entries in the tree.
  57185. **
  57186. ** In this implementation, a single file can hold one or more separate
  57187. ** BTrees. Each BTree is identified by the index of its root page. The
  57188. ** key and data for any entry are combined to form the "payload". A
  57189. ** fixed amount of payload can be carried directly on the database
  57190. ** page. If the payload is larger than the preset amount then surplus
  57191. ** bytes are stored on overflow pages. The payload for an entry
  57192. ** and the preceding pointer are combined to form a "Cell". Each
  57193. ** page has a small header which contains the Ptr(N) pointer and other
  57194. ** information such as the size of key and data.
  57195. **
  57196. ** FORMAT DETAILS
  57197. **
  57198. ** The file is divided into pages. The first page is called page 1,
  57199. ** the second is page 2, and so forth. A page number of zero indicates
  57200. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  57201. ** Each page can be either a btree page, a freelist page, an overflow
  57202. ** page, or a pointer-map page.
  57203. **
  57204. ** The first page is always a btree page. The first 100 bytes of the first
  57205. ** page contain a special header (the "file header") that describes the file.
  57206. ** The format of the file header is as follows:
  57207. **
  57208. ** OFFSET SIZE DESCRIPTION
  57209. ** 0 16 Header string: "SQLite format 3\000"
  57210. ** 16 2 Page size in bytes. (1 means 65536)
  57211. ** 18 1 File format write version
  57212. ** 19 1 File format read version
  57213. ** 20 1 Bytes of unused space at the end of each page
  57214. ** 21 1 Max embedded payload fraction (must be 64)
  57215. ** 22 1 Min embedded payload fraction (must be 32)
  57216. ** 23 1 Min leaf payload fraction (must be 32)
  57217. ** 24 4 File change counter
  57218. ** 28 4 Reserved for future use
  57219. ** 32 4 First freelist page
  57220. ** 36 4 Number of freelist pages in the file
  57221. ** 40 60 15 4-byte meta values passed to higher layers
  57222. **
  57223. ** 40 4 Schema cookie
  57224. ** 44 4 File format of schema layer
  57225. ** 48 4 Size of page cache
  57226. ** 52 4 Largest root-page (auto/incr_vacuum)
  57227. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  57228. ** 60 4 User version
  57229. ** 64 4 Incremental vacuum mode
  57230. ** 68 4 Application-ID
  57231. ** 72 20 unused
  57232. ** 92 4 The version-valid-for number
  57233. ** 96 4 SQLITE_VERSION_NUMBER
  57234. **
  57235. ** All of the integer values are big-endian (most significant byte first).
  57236. **
  57237. ** The file change counter is incremented when the database is changed
  57238. ** This counter allows other processes to know when the file has changed
  57239. ** and thus when they need to flush their cache.
  57240. **
  57241. ** The max embedded payload fraction is the amount of the total usable
  57242. ** space in a page that can be consumed by a single cell for standard
  57243. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  57244. ** is to limit the maximum cell size so that at least 4 cells will fit
  57245. ** on one page. Thus the default max embedded payload fraction is 64.
  57246. **
  57247. ** If the payload for a cell is larger than the max payload, then extra
  57248. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  57249. ** as many bytes as possible are moved into the overflow pages without letting
  57250. ** the cell size drop below the min embedded payload fraction.
  57251. **
  57252. ** The min leaf payload fraction is like the min embedded payload fraction
  57253. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  57254. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  57255. ** not specified in the header.
  57256. **
  57257. ** Each btree pages is divided into three sections: The header, the
  57258. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  57259. ** file header that occurs before the page header.
  57260. **
  57261. ** |----------------|
  57262. ** | file header | 100 bytes. Page 1 only.
  57263. ** |----------------|
  57264. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  57265. ** |----------------|
  57266. ** | cell pointer | | 2 bytes per cell. Sorted order.
  57267. ** | array | | Grows downward
  57268. ** | | v
  57269. ** |----------------|
  57270. ** | unallocated |
  57271. ** | space |
  57272. ** |----------------| ^ Grows upwards
  57273. ** | cell content | | Arbitrary order interspersed with freeblocks.
  57274. ** | area | | and free space fragments.
  57275. ** |----------------|
  57276. **
  57277. ** The page headers looks like this:
  57278. **
  57279. ** OFFSET SIZE DESCRIPTION
  57280. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  57281. ** 1 2 byte offset to the first freeblock
  57282. ** 3 2 number of cells on this page
  57283. ** 5 2 first byte of the cell content area
  57284. ** 7 1 number of fragmented free bytes
  57285. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  57286. **
  57287. ** The flags define the format of this btree page. The leaf flag means that
  57288. ** this page has no children. The zerodata flag means that this page carries
  57289. ** only keys and no data. The intkey flag means that the key is an integer
  57290. ** which is stored in the key size entry of the cell header rather than in
  57291. ** the payload area.
  57292. **
  57293. ** The cell pointer array begins on the first byte after the page header.
  57294. ** The cell pointer array contains zero or more 2-byte numbers which are
  57295. ** offsets from the beginning of the page to the cell content in the cell
  57296. ** content area. The cell pointers occur in sorted order. The system strives
  57297. ** to keep free space after the last cell pointer so that new cells can
  57298. ** be easily added without having to defragment the page.
  57299. **
  57300. ** Cell content is stored at the very end of the page and grows toward the
  57301. ** beginning of the page.
  57302. **
  57303. ** Unused space within the cell content area is collected into a linked list of
  57304. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  57305. ** to the first freeblock is given in the header. Freeblocks occur in
  57306. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  57307. ** any group of 3 or fewer unused bytes in the cell content area cannot
  57308. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  57309. ** a fragment. The total number of bytes in all fragments is recorded.
  57310. ** in the page header at offset 7.
  57311. **
  57312. ** SIZE DESCRIPTION
  57313. ** 2 Byte offset of the next freeblock
  57314. ** 2 Bytes in this freeblock
  57315. **
  57316. ** Cells are of variable length. Cells are stored in the cell content area at
  57317. ** the end of the page. Pointers to the cells are in the cell pointer array
  57318. ** that immediately follows the page header. Cells is not necessarily
  57319. ** contiguous or in order, but cell pointers are contiguous and in order.
  57320. **
  57321. ** Cell content makes use of variable length integers. A variable
  57322. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  57323. ** byte are used. The integer consists of all bytes that have bit 8 set and
  57324. ** the first byte with bit 8 clear. The most significant byte of the integer
  57325. ** appears first. A variable-length integer may not be more than 9 bytes long.
  57326. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  57327. ** allows a 64-bit integer to be encoded in 9 bytes.
  57328. **
  57329. ** 0x00 becomes 0x00000000
  57330. ** 0x7f becomes 0x0000007f
  57331. ** 0x81 0x00 becomes 0x00000080
  57332. ** 0x82 0x00 becomes 0x00000100
  57333. ** 0x80 0x7f becomes 0x0000007f
  57334. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  57335. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  57336. **
  57337. ** Variable length integers are used for rowids and to hold the number of
  57338. ** bytes of key and data in a btree cell.
  57339. **
  57340. ** The content of a cell looks like this:
  57341. **
  57342. ** SIZE DESCRIPTION
  57343. ** 4 Page number of the left child. Omitted if leaf flag is set.
  57344. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  57345. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  57346. ** * Payload
  57347. ** 4 First page of the overflow chain. Omitted if no overflow
  57348. **
  57349. ** Overflow pages form a linked list. Each page except the last is completely
  57350. ** filled with data (pagesize - 4 bytes). The last page can have as little
  57351. ** as 1 byte of data.
  57352. **
  57353. ** SIZE DESCRIPTION
  57354. ** 4 Page number of next overflow page
  57355. ** * Data
  57356. **
  57357. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  57358. ** file header points to the first in a linked list of trunk page. Each trunk
  57359. ** page points to multiple leaf pages. The content of a leaf page is
  57360. ** unspecified. A trunk page looks like this:
  57361. **
  57362. ** SIZE DESCRIPTION
  57363. ** 4 Page number of next trunk page
  57364. ** 4 Number of leaf pointers on this page
  57365. ** * zero or more pages numbers of leaves
  57366. */
  57367. /* #include "sqliteInt.h" */
  57368. /* The following value is the maximum cell size assuming a maximum page
  57369. ** size give above.
  57370. */
  57371. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  57372. /* The maximum number of cells on a single page of the database. This
  57373. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  57374. ** plus 2 bytes for the index to the cell in the page header). Such
  57375. ** small cells will be rare, but they are possible.
  57376. */
  57377. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  57378. /* Forward declarations */
  57379. typedef struct MemPage MemPage;
  57380. typedef struct BtLock BtLock;
  57381. typedef struct CellInfo CellInfo;
  57382. /*
  57383. ** This is a magic string that appears at the beginning of every
  57384. ** SQLite database in order to identify the file as a real database.
  57385. **
  57386. ** You can change this value at compile-time by specifying a
  57387. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  57388. ** header must be exactly 16 bytes including the zero-terminator so
  57389. ** the string itself should be 15 characters long. If you change
  57390. ** the header, then your custom library will not be able to read
  57391. ** databases generated by the standard tools and the standard tools
  57392. ** will not be able to read databases created by your custom library.
  57393. */
  57394. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  57395. # define SQLITE_FILE_HEADER "SQLite format 3"
  57396. #endif
  57397. /*
  57398. ** Page type flags. An ORed combination of these flags appear as the
  57399. ** first byte of on-disk image of every BTree page.
  57400. */
  57401. #define PTF_INTKEY 0x01
  57402. #define PTF_ZERODATA 0x02
  57403. #define PTF_LEAFDATA 0x04
  57404. #define PTF_LEAF 0x08
  57405. /*
  57406. ** An instance of this object stores information about each a single database
  57407. ** page that has been loaded into memory. The information in this object
  57408. ** is derived from the raw on-disk page content.
  57409. **
  57410. ** As each database page is loaded into memory, the pager allocats an
  57411. ** instance of this object and zeros the first 8 bytes. (This is the
  57412. ** "extra" information associated with each page of the pager.)
  57413. **
  57414. ** Access to all fields of this structure is controlled by the mutex
  57415. ** stored in MemPage.pBt->mutex.
  57416. */
  57417. struct MemPage {
  57418. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  57419. u8 bBusy; /* Prevent endless loops on corrupt database files */
  57420. u8 intKey; /* True if table b-trees. False for index b-trees */
  57421. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  57422. Pgno pgno; /* Page number for this page */
  57423. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  57424. ** is allocated. All fields that follow must be initialized before use */
  57425. u8 leaf; /* True if a leaf page */
  57426. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  57427. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  57428. u8 max1bytePayload; /* min(maxLocal,127) */
  57429. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  57430. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  57431. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  57432. u16 cellOffset; /* Index in aData of first cell pointer */
  57433. u16 nFree; /* Number of free bytes on the page */
  57434. u16 nCell; /* Number of cells on this page, local and ovfl */
  57435. u16 maskPage; /* Mask for page offset */
  57436. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  57437. ** non-overflow cell */
  57438. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  57439. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  57440. u8 *aData; /* Pointer to disk image of the page data */
  57441. u8 *aDataEnd; /* One byte past the end of usable data */
  57442. u8 *aCellIdx; /* The cell index area */
  57443. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  57444. DbPage *pDbPage; /* Pager page handle */
  57445. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  57446. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  57447. };
  57448. /*
  57449. ** A linked list of the following structures is stored at BtShared.pLock.
  57450. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  57451. ** is opened on the table with root page BtShared.iTable. Locks are removed
  57452. ** from this list when a transaction is committed or rolled back, or when
  57453. ** a btree handle is closed.
  57454. */
  57455. struct BtLock {
  57456. Btree *pBtree; /* Btree handle holding this lock */
  57457. Pgno iTable; /* Root page of table */
  57458. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  57459. BtLock *pNext; /* Next in BtShared.pLock list */
  57460. };
  57461. /* Candidate values for BtLock.eLock */
  57462. #define READ_LOCK 1
  57463. #define WRITE_LOCK 2
  57464. /* A Btree handle
  57465. **
  57466. ** A database connection contains a pointer to an instance of
  57467. ** this object for every database file that it has open. This structure
  57468. ** is opaque to the database connection. The database connection cannot
  57469. ** see the internals of this structure and only deals with pointers to
  57470. ** this structure.
  57471. **
  57472. ** For some database files, the same underlying database cache might be
  57473. ** shared between multiple connections. In that case, each connection
  57474. ** has it own instance of this object. But each instance of this object
  57475. ** points to the same BtShared object. The database cache and the
  57476. ** schema associated with the database file are all contained within
  57477. ** the BtShared object.
  57478. **
  57479. ** All fields in this structure are accessed under sqlite3.mutex.
  57480. ** The pBt pointer itself may not be changed while there exists cursors
  57481. ** in the referenced BtShared that point back to this Btree since those
  57482. ** cursors have to go through this Btree to find their BtShared and
  57483. ** they often do so without holding sqlite3.mutex.
  57484. */
  57485. struct Btree {
  57486. sqlite3 *db; /* The database connection holding this btree */
  57487. BtShared *pBt; /* Sharable content of this btree */
  57488. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  57489. u8 sharable; /* True if we can share pBt with another db */
  57490. u8 locked; /* True if db currently has pBt locked */
  57491. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  57492. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  57493. int nBackup; /* Number of backup operations reading this btree */
  57494. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  57495. Btree *pNext; /* List of other sharable Btrees from the same db */
  57496. Btree *pPrev; /* Back pointer of the same list */
  57497. #ifndef SQLITE_OMIT_SHARED_CACHE
  57498. BtLock lock; /* Object used to lock page 1 */
  57499. #endif
  57500. };
  57501. /*
  57502. ** Btree.inTrans may take one of the following values.
  57503. **
  57504. ** If the shared-data extension is enabled, there may be multiple users
  57505. ** of the Btree structure. At most one of these may open a write transaction,
  57506. ** but any number may have active read transactions.
  57507. */
  57508. #define TRANS_NONE 0
  57509. #define TRANS_READ 1
  57510. #define TRANS_WRITE 2
  57511. /*
  57512. ** An instance of this object represents a single database file.
  57513. **
  57514. ** A single database file can be in use at the same time by two
  57515. ** or more database connections. When two or more connections are
  57516. ** sharing the same database file, each connection has it own
  57517. ** private Btree object for the file and each of those Btrees points
  57518. ** to this one BtShared object. BtShared.nRef is the number of
  57519. ** connections currently sharing this database file.
  57520. **
  57521. ** Fields in this structure are accessed under the BtShared.mutex
  57522. ** mutex, except for nRef and pNext which are accessed under the
  57523. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  57524. ** may not be modified once it is initially set as long as nRef>0.
  57525. ** The pSchema field may be set once under BtShared.mutex and
  57526. ** thereafter is unchanged as long as nRef>0.
  57527. **
  57528. ** isPending:
  57529. **
  57530. ** If a BtShared client fails to obtain a write-lock on a database
  57531. ** table (because there exists one or more read-locks on the table),
  57532. ** the shared-cache enters 'pending-lock' state and isPending is
  57533. ** set to true.
  57534. **
  57535. ** The shared-cache leaves the 'pending lock' state when either of
  57536. ** the following occur:
  57537. **
  57538. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  57539. ** 2) The number of locks held by other connections drops to zero.
  57540. **
  57541. ** while in the 'pending-lock' state, no connection may start a new
  57542. ** transaction.
  57543. **
  57544. ** This feature is included to help prevent writer-starvation.
  57545. */
  57546. struct BtShared {
  57547. Pager *pPager; /* The page cache */
  57548. sqlite3 *db; /* Database connection currently using this Btree */
  57549. BtCursor *pCursor; /* A list of all open cursors */
  57550. MemPage *pPage1; /* First page of the database */
  57551. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  57552. #ifndef SQLITE_OMIT_AUTOVACUUM
  57553. u8 autoVacuum; /* True if auto-vacuum is enabled */
  57554. u8 incrVacuum; /* True if incr-vacuum is enabled */
  57555. u8 bDoTruncate; /* True to truncate db on commit */
  57556. #endif
  57557. u8 inTransaction; /* Transaction state */
  57558. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  57559. #ifdef SQLITE_HAS_CODEC
  57560. u8 optimalReserve; /* Desired amount of reserved space per page */
  57561. #endif
  57562. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  57563. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  57564. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  57565. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  57566. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  57567. u32 pageSize; /* Total number of bytes on a page */
  57568. u32 usableSize; /* Number of usable bytes on each page */
  57569. int nTransaction; /* Number of open transactions (read + write) */
  57570. u32 nPage; /* Number of pages in the database */
  57571. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  57572. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  57573. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  57574. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  57575. #ifndef SQLITE_OMIT_SHARED_CACHE
  57576. int nRef; /* Number of references to this structure */
  57577. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  57578. BtLock *pLock; /* List of locks held on this shared-btree struct */
  57579. Btree *pWriter; /* Btree with currently open write transaction */
  57580. #endif
  57581. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  57582. };
  57583. /*
  57584. ** Allowed values for BtShared.btsFlags
  57585. */
  57586. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  57587. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  57588. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  57589. #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
  57590. #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
  57591. #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
  57592. #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
  57593. #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
  57594. #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
  57595. /*
  57596. ** An instance of the following structure is used to hold information
  57597. ** about a cell. The parseCellPtr() function fills in this structure
  57598. ** based on information extract from the raw disk page.
  57599. */
  57600. struct CellInfo {
  57601. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  57602. u8 *pPayload; /* Pointer to the start of payload */
  57603. u32 nPayload; /* Bytes of payload */
  57604. u16 nLocal; /* Amount of payload held locally, not on overflow */
  57605. u16 nSize; /* Size of the cell content on the main b-tree page */
  57606. };
  57607. /*
  57608. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  57609. ** this will be declared corrupt. This value is calculated based on a
  57610. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  57611. ** root-node and 3 for all other internal nodes.
  57612. **
  57613. ** If a tree that appears to be taller than this is encountered, it is
  57614. ** assumed that the database is corrupt.
  57615. */
  57616. #define BTCURSOR_MAX_DEPTH 20
  57617. /*
  57618. ** A cursor is a pointer to a particular entry within a particular
  57619. ** b-tree within a database file.
  57620. **
  57621. ** The entry is identified by its MemPage and the index in
  57622. ** MemPage.aCell[] of the entry.
  57623. **
  57624. ** A single database file can be shared by two more database connections,
  57625. ** but cursors cannot be shared. Each cursor is associated with a
  57626. ** particular database connection identified BtCursor.pBtree.db.
  57627. **
  57628. ** Fields in this structure are accessed under the BtShared.mutex
  57629. ** found at self->pBt->mutex.
  57630. **
  57631. ** skipNext meaning:
  57632. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  57633. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  57634. ** eState==FAULT: Cursor fault with skipNext as error code.
  57635. */
  57636. struct BtCursor {
  57637. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  57638. u8 curFlags; /* zero or more BTCF_* flags defined below */
  57639. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  57640. u8 hints; /* As configured by CursorSetHints() */
  57641. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  57642. ** Error code if eState==CURSOR_FAULT */
  57643. Btree *pBtree; /* The Btree to which this cursor belongs */
  57644. Pgno *aOverflow; /* Cache of overflow page locations */
  57645. void *pKey; /* Saved key that was cursor last known position */
  57646. /* All fields above are zeroed when the cursor is allocated. See
  57647. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  57648. ** initialized. */
  57649. #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
  57650. BtShared *pBt; /* The BtShared this cursor points to */
  57651. BtCursor *pNext; /* Forms a linked list of all cursors */
  57652. CellInfo info; /* A parse of the cell we are pointing at */
  57653. i64 nKey; /* Size of pKey, or last integer key */
  57654. Pgno pgnoRoot; /* The root page of this tree */
  57655. i8 iPage; /* Index of current page in apPage */
  57656. u8 curIntKey; /* Value of apPage[0]->intKey */
  57657. u16 ix; /* Current index for apPage[iPage] */
  57658. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  57659. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  57660. MemPage *pPage; /* Current page */
  57661. MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
  57662. };
  57663. /*
  57664. ** Legal values for BtCursor.curFlags
  57665. */
  57666. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  57667. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  57668. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  57669. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  57670. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  57671. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  57672. /*
  57673. ** Potential values for BtCursor.eState.
  57674. **
  57675. ** CURSOR_INVALID:
  57676. ** Cursor does not point to a valid entry. This can happen (for example)
  57677. ** because the table is empty or because BtreeCursorFirst() has not been
  57678. ** called.
  57679. **
  57680. ** CURSOR_VALID:
  57681. ** Cursor points to a valid entry. getPayload() etc. may be called.
  57682. **
  57683. ** CURSOR_SKIPNEXT:
  57684. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  57685. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  57686. ** operation should be a no-op.
  57687. **
  57688. ** CURSOR_REQUIRESEEK:
  57689. ** The table that this cursor was opened on still exists, but has been
  57690. ** modified since the cursor was last used. The cursor position is saved
  57691. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  57692. ** this state, restoreCursorPosition() can be called to attempt to
  57693. ** seek the cursor to the saved position.
  57694. **
  57695. ** CURSOR_FAULT:
  57696. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  57697. ** on a different connection that shares the BtShared cache with this
  57698. ** cursor. The error has left the cache in an inconsistent state.
  57699. ** Do nothing else with this cursor. Any attempt to use the cursor
  57700. ** should return the error code stored in BtCursor.skipNext
  57701. */
  57702. #define CURSOR_VALID 0
  57703. #define CURSOR_INVALID 1
  57704. #define CURSOR_SKIPNEXT 2
  57705. #define CURSOR_REQUIRESEEK 3
  57706. #define CURSOR_FAULT 4
  57707. /*
  57708. ** The database page the PENDING_BYTE occupies. This page is never used.
  57709. */
  57710. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  57711. /*
  57712. ** These macros define the location of the pointer-map entry for a
  57713. ** database page. The first argument to each is the number of usable
  57714. ** bytes on each page of the database (often 1024). The second is the
  57715. ** page number to look up in the pointer map.
  57716. **
  57717. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  57718. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  57719. ** the offset of the requested map entry.
  57720. **
  57721. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  57722. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  57723. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  57724. ** this test.
  57725. */
  57726. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  57727. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  57728. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  57729. /*
  57730. ** The pointer map is a lookup table that identifies the parent page for
  57731. ** each child page in the database file. The parent page is the page that
  57732. ** contains a pointer to the child. Every page in the database contains
  57733. ** 0 or 1 parent pages. (In this context 'database page' refers
  57734. ** to any page that is not part of the pointer map itself.) Each pointer map
  57735. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  57736. ** The PTRMAP_XXX identifiers below are the valid types.
  57737. **
  57738. ** The purpose of the pointer map is to facility moving pages from one
  57739. ** position in the file to another as part of autovacuum. When a page
  57740. ** is moved, the pointer in its parent must be updated to point to the
  57741. ** new location. The pointer map is used to locate the parent page quickly.
  57742. **
  57743. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  57744. ** used in this case.
  57745. **
  57746. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  57747. ** is not used in this case.
  57748. **
  57749. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  57750. ** overflow pages. The page number identifies the page that
  57751. ** contains the cell with a pointer to this overflow page.
  57752. **
  57753. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  57754. ** overflow pages. The page-number identifies the previous
  57755. ** page in the overflow page list.
  57756. **
  57757. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  57758. ** identifies the parent page in the btree.
  57759. */
  57760. #define PTRMAP_ROOTPAGE 1
  57761. #define PTRMAP_FREEPAGE 2
  57762. #define PTRMAP_OVERFLOW1 3
  57763. #define PTRMAP_OVERFLOW2 4
  57764. #define PTRMAP_BTREE 5
  57765. /* A bunch of assert() statements to check the transaction state variables
  57766. ** of handle p (type Btree*) are internally consistent.
  57767. */
  57768. #define btreeIntegrity(p) \
  57769. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  57770. assert( p->pBt->inTransaction>=p->inTrans );
  57771. /*
  57772. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  57773. ** if the database supports auto-vacuum or not. Because it is used
  57774. ** within an expression that is an argument to another macro
  57775. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  57776. ** So, this macro is defined instead.
  57777. */
  57778. #ifndef SQLITE_OMIT_AUTOVACUUM
  57779. #define ISAUTOVACUUM (pBt->autoVacuum)
  57780. #else
  57781. #define ISAUTOVACUUM 0
  57782. #endif
  57783. /*
  57784. ** This structure is passed around through all the sanity checking routines
  57785. ** in order to keep track of some global state information.
  57786. **
  57787. ** The aRef[] array is allocated so that there is 1 bit for each page in
  57788. ** the database. As the integrity-check proceeds, for each page used in
  57789. ** the database the corresponding bit is set. This allows integrity-check to
  57790. ** detect pages that are used twice and orphaned pages (both of which
  57791. ** indicate corruption).
  57792. */
  57793. typedef struct IntegrityCk IntegrityCk;
  57794. struct IntegrityCk {
  57795. BtShared *pBt; /* The tree being checked out */
  57796. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  57797. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  57798. Pgno nPage; /* Number of pages in the database */
  57799. int mxErr; /* Stop accumulating errors when this reaches zero */
  57800. int nErr; /* Number of messages written to zErrMsg so far */
  57801. int mallocFailed; /* A memory allocation error has occurred */
  57802. const char *zPfx; /* Error message prefix */
  57803. int v1, v2; /* Values for up to two %d fields in zPfx */
  57804. StrAccum errMsg; /* Accumulate the error message text here */
  57805. u32 *heap; /* Min-heap used for analyzing cell coverage */
  57806. };
  57807. /*
  57808. ** Routines to read or write a two- and four-byte big-endian integer values.
  57809. */
  57810. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  57811. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  57812. #define get4byte sqlite3Get4byte
  57813. #define put4byte sqlite3Put4byte
  57814. /*
  57815. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  57816. ** two-byte aligned address. get2bytea() is only used for accessing the
  57817. ** cell addresses in a btree header.
  57818. */
  57819. #if SQLITE_BYTEORDER==4321
  57820. # define get2byteAligned(x) (*(u16*)(x))
  57821. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  57822. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  57823. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  57824. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  57825. #else
  57826. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  57827. #endif
  57828. /************** End of btreeInt.h ********************************************/
  57829. /************** Continuing where we left off in btmutex.c ********************/
  57830. #ifndef SQLITE_OMIT_SHARED_CACHE
  57831. #if SQLITE_THREADSAFE
  57832. /*
  57833. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  57834. ** set BtShared.db to the database handle associated with p and the
  57835. ** p->locked boolean to true.
  57836. */
  57837. static void lockBtreeMutex(Btree *p){
  57838. assert( p->locked==0 );
  57839. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  57840. assert( sqlite3_mutex_held(p->db->mutex) );
  57841. sqlite3_mutex_enter(p->pBt->mutex);
  57842. p->pBt->db = p->db;
  57843. p->locked = 1;
  57844. }
  57845. /*
  57846. ** Release the BtShared mutex associated with B-Tree handle p and
  57847. ** clear the p->locked boolean.
  57848. */
  57849. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  57850. BtShared *pBt = p->pBt;
  57851. assert( p->locked==1 );
  57852. assert( sqlite3_mutex_held(pBt->mutex) );
  57853. assert( sqlite3_mutex_held(p->db->mutex) );
  57854. assert( p->db==pBt->db );
  57855. sqlite3_mutex_leave(pBt->mutex);
  57856. p->locked = 0;
  57857. }
  57858. /* Forward reference */
  57859. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  57860. /*
  57861. ** Enter a mutex on the given BTree object.
  57862. **
  57863. ** If the object is not sharable, then no mutex is ever required
  57864. ** and this routine is a no-op. The underlying mutex is non-recursive.
  57865. ** But we keep a reference count in Btree.wantToLock so the behavior
  57866. ** of this interface is recursive.
  57867. **
  57868. ** To avoid deadlocks, multiple Btrees are locked in the same order
  57869. ** by all database connections. The p->pNext is a list of other
  57870. ** Btrees belonging to the same database connection as the p Btree
  57871. ** which need to be locked after p. If we cannot get a lock on
  57872. ** p, then first unlock all of the others on p->pNext, then wait
  57873. ** for the lock to become available on p, then relock all of the
  57874. ** subsequent Btrees that desire a lock.
  57875. */
  57876. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  57877. /* Some basic sanity checking on the Btree. The list of Btrees
  57878. ** connected by pNext and pPrev should be in sorted order by
  57879. ** Btree.pBt value. All elements of the list should belong to
  57880. ** the same connection. Only shared Btrees are on the list. */
  57881. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  57882. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  57883. assert( p->pNext==0 || p->pNext->db==p->db );
  57884. assert( p->pPrev==0 || p->pPrev->db==p->db );
  57885. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  57886. /* Check for locking consistency */
  57887. assert( !p->locked || p->wantToLock>0 );
  57888. assert( p->sharable || p->wantToLock==0 );
  57889. /* We should already hold a lock on the database connection */
  57890. assert( sqlite3_mutex_held(p->db->mutex) );
  57891. /* Unless the database is sharable and unlocked, then BtShared.db
  57892. ** should already be set correctly. */
  57893. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  57894. if( !p->sharable ) return;
  57895. p->wantToLock++;
  57896. if( p->locked ) return;
  57897. btreeLockCarefully(p);
  57898. }
  57899. /* This is a helper function for sqlite3BtreeLock(). By moving
  57900. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  57901. ** into this routine, we avoid unnecessary stack pointer changes
  57902. ** and thus help the sqlite3BtreeLock() routine to run much faster
  57903. ** in the common case.
  57904. */
  57905. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  57906. Btree *pLater;
  57907. /* In most cases, we should be able to acquire the lock we
  57908. ** want without having to go through the ascending lock
  57909. ** procedure that follows. Just be sure not to block.
  57910. */
  57911. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  57912. p->pBt->db = p->db;
  57913. p->locked = 1;
  57914. return;
  57915. }
  57916. /* To avoid deadlock, first release all locks with a larger
  57917. ** BtShared address. Then acquire our lock. Then reacquire
  57918. ** the other BtShared locks that we used to hold in ascending
  57919. ** order.
  57920. */
  57921. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  57922. assert( pLater->sharable );
  57923. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  57924. assert( !pLater->locked || pLater->wantToLock>0 );
  57925. if( pLater->locked ){
  57926. unlockBtreeMutex(pLater);
  57927. }
  57928. }
  57929. lockBtreeMutex(p);
  57930. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  57931. if( pLater->wantToLock ){
  57932. lockBtreeMutex(pLater);
  57933. }
  57934. }
  57935. }
  57936. /*
  57937. ** Exit the recursive mutex on a Btree.
  57938. */
  57939. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  57940. assert( sqlite3_mutex_held(p->db->mutex) );
  57941. if( p->sharable ){
  57942. assert( p->wantToLock>0 );
  57943. p->wantToLock--;
  57944. if( p->wantToLock==0 ){
  57945. unlockBtreeMutex(p);
  57946. }
  57947. }
  57948. }
  57949. #ifndef NDEBUG
  57950. /*
  57951. ** Return true if the BtShared mutex is held on the btree, or if the
  57952. ** B-Tree is not marked as sharable.
  57953. **
  57954. ** This routine is used only from within assert() statements.
  57955. */
  57956. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  57957. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  57958. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  57959. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  57960. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  57961. return (p->sharable==0 || p->locked);
  57962. }
  57963. #endif
  57964. /*
  57965. ** Enter the mutex on every Btree associated with a database
  57966. ** connection. This is needed (for example) prior to parsing
  57967. ** a statement since we will be comparing table and column names
  57968. ** against all schemas and we do not want those schemas being
  57969. ** reset out from under us.
  57970. **
  57971. ** There is a corresponding leave-all procedures.
  57972. **
  57973. ** Enter the mutexes in accending order by BtShared pointer address
  57974. ** to avoid the possibility of deadlock when two threads with
  57975. ** two or more btrees in common both try to lock all their btrees
  57976. ** at the same instant.
  57977. */
  57978. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  57979. int i;
  57980. int skipOk = 1;
  57981. Btree *p;
  57982. assert( sqlite3_mutex_held(db->mutex) );
  57983. for(i=0; i<db->nDb; i++){
  57984. p = db->aDb[i].pBt;
  57985. if( p && p->sharable ){
  57986. sqlite3BtreeEnter(p);
  57987. skipOk = 0;
  57988. }
  57989. }
  57990. db->noSharedCache = skipOk;
  57991. }
  57992. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  57993. if( db->noSharedCache==0 ) btreeEnterAll(db);
  57994. }
  57995. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  57996. int i;
  57997. Btree *p;
  57998. assert( sqlite3_mutex_held(db->mutex) );
  57999. for(i=0; i<db->nDb; i++){
  58000. p = db->aDb[i].pBt;
  58001. if( p ) sqlite3BtreeLeave(p);
  58002. }
  58003. }
  58004. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  58005. if( db->noSharedCache==0 ) btreeLeaveAll(db);
  58006. }
  58007. #ifndef NDEBUG
  58008. /*
  58009. ** Return true if the current thread holds the database connection
  58010. ** mutex and all required BtShared mutexes.
  58011. **
  58012. ** This routine is used inside assert() statements only.
  58013. */
  58014. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  58015. int i;
  58016. if( !sqlite3_mutex_held(db->mutex) ){
  58017. return 0;
  58018. }
  58019. for(i=0; i<db->nDb; i++){
  58020. Btree *p;
  58021. p = db->aDb[i].pBt;
  58022. if( p && p->sharable &&
  58023. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  58024. return 0;
  58025. }
  58026. }
  58027. return 1;
  58028. }
  58029. #endif /* NDEBUG */
  58030. #ifndef NDEBUG
  58031. /*
  58032. ** Return true if the correct mutexes are held for accessing the
  58033. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  58034. ** access are:
  58035. **
  58036. ** (1) The mutex on db
  58037. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  58038. **
  58039. ** If pSchema is not NULL, then iDb is computed from pSchema and
  58040. ** db using sqlite3SchemaToIndex().
  58041. */
  58042. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  58043. Btree *p;
  58044. assert( db!=0 );
  58045. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  58046. assert( iDb>=0 && iDb<db->nDb );
  58047. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  58048. if( iDb==1 ) return 1;
  58049. p = db->aDb[iDb].pBt;
  58050. assert( p!=0 );
  58051. return p->sharable==0 || p->locked==1;
  58052. }
  58053. #endif /* NDEBUG */
  58054. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  58055. /*
  58056. ** The following are special cases for mutex enter routines for use
  58057. ** in single threaded applications that use shared cache. Except for
  58058. ** these two routines, all mutex operations are no-ops in that case and
  58059. ** are null #defines in btree.h.
  58060. **
  58061. ** If shared cache is disabled, then all btree mutex routines, including
  58062. ** the ones below, are no-ops and are null #defines in btree.h.
  58063. */
  58064. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  58065. p->pBt->db = p->db;
  58066. }
  58067. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  58068. int i;
  58069. for(i=0; i<db->nDb; i++){
  58070. Btree *p = db->aDb[i].pBt;
  58071. if( p ){
  58072. p->pBt->db = p->db;
  58073. }
  58074. }
  58075. }
  58076. #endif /* if SQLITE_THREADSAFE */
  58077. #ifndef SQLITE_OMIT_INCRBLOB
  58078. /*
  58079. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  58080. **
  58081. ** These entry points are used by incremental I/O only. Enter() is required
  58082. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  58083. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  58084. */
  58085. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  58086. sqlite3BtreeEnter(pCur->pBtree);
  58087. }
  58088. # if SQLITE_THREADSAFE
  58089. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  58090. sqlite3BtreeLeave(pCur->pBtree);
  58091. }
  58092. # endif
  58093. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  58094. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  58095. /************** End of btmutex.c *********************************************/
  58096. /************** Begin file btree.c *******************************************/
  58097. /*
  58098. ** 2004 April 6
  58099. **
  58100. ** The author disclaims copyright to this source code. In place of
  58101. ** a legal notice, here is a blessing:
  58102. **
  58103. ** May you do good and not evil.
  58104. ** May you find forgiveness for yourself and forgive others.
  58105. ** May you share freely, never taking more than you give.
  58106. **
  58107. *************************************************************************
  58108. ** This file implements an external (disk-based) database using BTrees.
  58109. ** See the header comment on "btreeInt.h" for additional information.
  58110. ** Including a description of file format and an overview of operation.
  58111. */
  58112. /* #include "btreeInt.h" */
  58113. /*
  58114. ** The header string that appears at the beginning of every
  58115. ** SQLite database.
  58116. */
  58117. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  58118. /*
  58119. ** Set this global variable to 1 to enable tracing using the TRACE
  58120. ** macro.
  58121. */
  58122. #if 0
  58123. int sqlite3BtreeTrace=1; /* True to enable tracing */
  58124. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  58125. #else
  58126. # define TRACE(X)
  58127. #endif
  58128. /*
  58129. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  58130. ** But if the value is zero, make it 65536.
  58131. **
  58132. ** This routine is used to extract the "offset to cell content area" value
  58133. ** from the header of a btree page. If the page size is 65536 and the page
  58134. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  58135. ** This routine makes the necessary adjustment to 65536.
  58136. */
  58137. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  58138. /*
  58139. ** Values passed as the 5th argument to allocateBtreePage()
  58140. */
  58141. #define BTALLOC_ANY 0 /* Allocate any page */
  58142. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  58143. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  58144. /*
  58145. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  58146. ** defined, or 0 if it is. For example:
  58147. **
  58148. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  58149. */
  58150. #ifndef SQLITE_OMIT_AUTOVACUUM
  58151. #define IfNotOmitAV(expr) (expr)
  58152. #else
  58153. #define IfNotOmitAV(expr) 0
  58154. #endif
  58155. #ifndef SQLITE_OMIT_SHARED_CACHE
  58156. /*
  58157. ** A list of BtShared objects that are eligible for participation
  58158. ** in shared cache. This variable has file scope during normal builds,
  58159. ** but the test harness needs to access it so we make it global for
  58160. ** test builds.
  58161. **
  58162. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  58163. */
  58164. #ifdef SQLITE_TEST
  58165. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  58166. #else
  58167. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  58168. #endif
  58169. #endif /* SQLITE_OMIT_SHARED_CACHE */
  58170. #ifndef SQLITE_OMIT_SHARED_CACHE
  58171. /*
  58172. ** Enable or disable the shared pager and schema features.
  58173. **
  58174. ** This routine has no effect on existing database connections.
  58175. ** The shared cache setting effects only future calls to
  58176. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  58177. */
  58178. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  58179. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  58180. return SQLITE_OK;
  58181. }
  58182. #endif
  58183. #ifdef SQLITE_OMIT_SHARED_CACHE
  58184. /*
  58185. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  58186. ** and clearAllSharedCacheTableLocks()
  58187. ** manipulate entries in the BtShared.pLock linked list used to store
  58188. ** shared-cache table level locks. If the library is compiled with the
  58189. ** shared-cache feature disabled, then there is only ever one user
  58190. ** of each BtShared structure and so this locking is not necessary.
  58191. ** So define the lock related functions as no-ops.
  58192. */
  58193. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  58194. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  58195. #define clearAllSharedCacheTableLocks(a)
  58196. #define downgradeAllSharedCacheTableLocks(a)
  58197. #define hasSharedCacheTableLock(a,b,c,d) 1
  58198. #define hasReadConflicts(a, b) 0
  58199. #endif
  58200. /*
  58201. ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
  58202. ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
  58203. **
  58204. ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
  58205. ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
  58206. ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
  58207. ** with the page number and filename associated with the (MemPage*).
  58208. */
  58209. #ifdef SQLITE_DEBUG
  58210. int corruptPageError(int lineno, MemPage *p){
  58211. char *zMsg;
  58212. sqlite3BeginBenignMalloc();
  58213. zMsg = sqlite3_mprintf("database corruption page %d of %s",
  58214. (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  58215. );
  58216. sqlite3EndBenignMalloc();
  58217. if( zMsg ){
  58218. sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  58219. }
  58220. sqlite3_free(zMsg);
  58221. return SQLITE_CORRUPT_BKPT;
  58222. }
  58223. # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
  58224. #else
  58225. # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
  58226. #endif
  58227. #ifndef SQLITE_OMIT_SHARED_CACHE
  58228. #ifdef SQLITE_DEBUG
  58229. /*
  58230. **** This function is only used as part of an assert() statement. ***
  58231. **
  58232. ** Check to see if pBtree holds the required locks to read or write to the
  58233. ** table with root page iRoot. Return 1 if it does and 0 if not.
  58234. **
  58235. ** For example, when writing to a table with root-page iRoot via
  58236. ** Btree connection pBtree:
  58237. **
  58238. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  58239. **
  58240. ** When writing to an index that resides in a sharable database, the
  58241. ** caller should have first obtained a lock specifying the root page of
  58242. ** the corresponding table. This makes things a bit more complicated,
  58243. ** as this module treats each table as a separate structure. To determine
  58244. ** the table corresponding to the index being written, this
  58245. ** function has to search through the database schema.
  58246. **
  58247. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  58248. ** hold a write-lock on the schema table (root page 1). This is also
  58249. ** acceptable.
  58250. */
  58251. static int hasSharedCacheTableLock(
  58252. Btree *pBtree, /* Handle that must hold lock */
  58253. Pgno iRoot, /* Root page of b-tree */
  58254. int isIndex, /* True if iRoot is the root of an index b-tree */
  58255. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  58256. ){
  58257. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  58258. Pgno iTab = 0;
  58259. BtLock *pLock;
  58260. /* If this database is not shareable, or if the client is reading
  58261. ** and has the read-uncommitted flag set, then no lock is required.
  58262. ** Return true immediately.
  58263. */
  58264. if( (pBtree->sharable==0)
  58265. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
  58266. ){
  58267. return 1;
  58268. }
  58269. /* If the client is reading or writing an index and the schema is
  58270. ** not loaded, then it is too difficult to actually check to see if
  58271. ** the correct locks are held. So do not bother - just return true.
  58272. ** This case does not come up very often anyhow.
  58273. */
  58274. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  58275. return 1;
  58276. }
  58277. /* Figure out the root-page that the lock should be held on. For table
  58278. ** b-trees, this is just the root page of the b-tree being read or
  58279. ** written. For index b-trees, it is the root page of the associated
  58280. ** table. */
  58281. if( isIndex ){
  58282. HashElem *p;
  58283. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  58284. Index *pIdx = (Index *)sqliteHashData(p);
  58285. if( pIdx->tnum==(int)iRoot ){
  58286. if( iTab ){
  58287. /* Two or more indexes share the same root page. There must
  58288. ** be imposter tables. So just return true. The assert is not
  58289. ** useful in that case. */
  58290. return 1;
  58291. }
  58292. iTab = pIdx->pTable->tnum;
  58293. }
  58294. }
  58295. }else{
  58296. iTab = iRoot;
  58297. }
  58298. /* Search for the required lock. Either a write-lock on root-page iTab, a
  58299. ** write-lock on the schema table, or (if the client is reading) a
  58300. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  58301. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  58302. if( pLock->pBtree==pBtree
  58303. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  58304. && pLock->eLock>=eLockType
  58305. ){
  58306. return 1;
  58307. }
  58308. }
  58309. /* Failed to find the required lock. */
  58310. return 0;
  58311. }
  58312. #endif /* SQLITE_DEBUG */
  58313. #ifdef SQLITE_DEBUG
  58314. /*
  58315. **** This function may be used as part of assert() statements only. ****
  58316. **
  58317. ** Return true if it would be illegal for pBtree to write into the
  58318. ** table or index rooted at iRoot because other shared connections are
  58319. ** simultaneously reading that same table or index.
  58320. **
  58321. ** It is illegal for pBtree to write if some other Btree object that
  58322. ** shares the same BtShared object is currently reading or writing
  58323. ** the iRoot table. Except, if the other Btree object has the
  58324. ** read-uncommitted flag set, then it is OK for the other object to
  58325. ** have a read cursor.
  58326. **
  58327. ** For example, before writing to any part of the table or index
  58328. ** rooted at page iRoot, one should call:
  58329. **
  58330. ** assert( !hasReadConflicts(pBtree, iRoot) );
  58331. */
  58332. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  58333. BtCursor *p;
  58334. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  58335. if( p->pgnoRoot==iRoot
  58336. && p->pBtree!=pBtree
  58337. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
  58338. ){
  58339. return 1;
  58340. }
  58341. }
  58342. return 0;
  58343. }
  58344. #endif /* #ifdef SQLITE_DEBUG */
  58345. /*
  58346. ** Query to see if Btree handle p may obtain a lock of type eLock
  58347. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  58348. ** SQLITE_OK if the lock may be obtained (by calling
  58349. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  58350. */
  58351. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  58352. BtShared *pBt = p->pBt;
  58353. BtLock *pIter;
  58354. assert( sqlite3BtreeHoldsMutex(p) );
  58355. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  58356. assert( p->db!=0 );
  58357. assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
  58358. /* If requesting a write-lock, then the Btree must have an open write
  58359. ** transaction on this file. And, obviously, for this to be so there
  58360. ** must be an open write transaction on the file itself.
  58361. */
  58362. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  58363. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  58364. /* This routine is a no-op if the shared-cache is not enabled */
  58365. if( !p->sharable ){
  58366. return SQLITE_OK;
  58367. }
  58368. /* If some other connection is holding an exclusive lock, the
  58369. ** requested lock may not be obtained.
  58370. */
  58371. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  58372. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  58373. return SQLITE_LOCKED_SHAREDCACHE;
  58374. }
  58375. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  58376. /* The condition (pIter->eLock!=eLock) in the following if(...)
  58377. ** statement is a simplification of:
  58378. **
  58379. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  58380. **
  58381. ** since we know that if eLock==WRITE_LOCK, then no other connection
  58382. ** may hold a WRITE_LOCK on any table in this file (since there can
  58383. ** only be a single writer).
  58384. */
  58385. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  58386. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  58387. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  58388. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  58389. if( eLock==WRITE_LOCK ){
  58390. assert( p==pBt->pWriter );
  58391. pBt->btsFlags |= BTS_PENDING;
  58392. }
  58393. return SQLITE_LOCKED_SHAREDCACHE;
  58394. }
  58395. }
  58396. return SQLITE_OK;
  58397. }
  58398. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  58399. #ifndef SQLITE_OMIT_SHARED_CACHE
  58400. /*
  58401. ** Add a lock on the table with root-page iTable to the shared-btree used
  58402. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  58403. ** WRITE_LOCK.
  58404. **
  58405. ** This function assumes the following:
  58406. **
  58407. ** (a) The specified Btree object p is connected to a sharable
  58408. ** database (one with the BtShared.sharable flag set), and
  58409. **
  58410. ** (b) No other Btree objects hold a lock that conflicts
  58411. ** with the requested lock (i.e. querySharedCacheTableLock() has
  58412. ** already been called and returned SQLITE_OK).
  58413. **
  58414. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  58415. ** is returned if a malloc attempt fails.
  58416. */
  58417. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  58418. BtShared *pBt = p->pBt;
  58419. BtLock *pLock = 0;
  58420. BtLock *pIter;
  58421. assert( sqlite3BtreeHoldsMutex(p) );
  58422. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  58423. assert( p->db!=0 );
  58424. /* A connection with the read-uncommitted flag set will never try to
  58425. ** obtain a read-lock using this function. The only read-lock obtained
  58426. ** by a connection in read-uncommitted mode is on the sqlite_master
  58427. ** table, and that lock is obtained in BtreeBeginTrans(). */
  58428. assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
  58429. /* This function should only be called on a sharable b-tree after it
  58430. ** has been determined that no other b-tree holds a conflicting lock. */
  58431. assert( p->sharable );
  58432. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  58433. /* First search the list for an existing lock on this table. */
  58434. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  58435. if( pIter->iTable==iTable && pIter->pBtree==p ){
  58436. pLock = pIter;
  58437. break;
  58438. }
  58439. }
  58440. /* If the above search did not find a BtLock struct associating Btree p
  58441. ** with table iTable, allocate one and link it into the list.
  58442. */
  58443. if( !pLock ){
  58444. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  58445. if( !pLock ){
  58446. return SQLITE_NOMEM_BKPT;
  58447. }
  58448. pLock->iTable = iTable;
  58449. pLock->pBtree = p;
  58450. pLock->pNext = pBt->pLock;
  58451. pBt->pLock = pLock;
  58452. }
  58453. /* Set the BtLock.eLock variable to the maximum of the current lock
  58454. ** and the requested lock. This means if a write-lock was already held
  58455. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  58456. */
  58457. assert( WRITE_LOCK>READ_LOCK );
  58458. if( eLock>pLock->eLock ){
  58459. pLock->eLock = eLock;
  58460. }
  58461. return SQLITE_OK;
  58462. }
  58463. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  58464. #ifndef SQLITE_OMIT_SHARED_CACHE
  58465. /*
  58466. ** Release all the table locks (locks obtained via calls to
  58467. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  58468. **
  58469. ** This function assumes that Btree p has an open read or write
  58470. ** transaction. If it does not, then the BTS_PENDING flag
  58471. ** may be incorrectly cleared.
  58472. */
  58473. static void clearAllSharedCacheTableLocks(Btree *p){
  58474. BtShared *pBt = p->pBt;
  58475. BtLock **ppIter = &pBt->pLock;
  58476. assert( sqlite3BtreeHoldsMutex(p) );
  58477. assert( p->sharable || 0==*ppIter );
  58478. assert( p->inTrans>0 );
  58479. while( *ppIter ){
  58480. BtLock *pLock = *ppIter;
  58481. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  58482. assert( pLock->pBtree->inTrans>=pLock->eLock );
  58483. if( pLock->pBtree==p ){
  58484. *ppIter = pLock->pNext;
  58485. assert( pLock->iTable!=1 || pLock==&p->lock );
  58486. if( pLock->iTable!=1 ){
  58487. sqlite3_free(pLock);
  58488. }
  58489. }else{
  58490. ppIter = &pLock->pNext;
  58491. }
  58492. }
  58493. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  58494. if( pBt->pWriter==p ){
  58495. pBt->pWriter = 0;
  58496. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  58497. }else if( pBt->nTransaction==2 ){
  58498. /* This function is called when Btree p is concluding its
  58499. ** transaction. If there currently exists a writer, and p is not
  58500. ** that writer, then the number of locks held by connections other
  58501. ** than the writer must be about to drop to zero. In this case
  58502. ** set the BTS_PENDING flag to 0.
  58503. **
  58504. ** If there is not currently a writer, then BTS_PENDING must
  58505. ** be zero already. So this next line is harmless in that case.
  58506. */
  58507. pBt->btsFlags &= ~BTS_PENDING;
  58508. }
  58509. }
  58510. /*
  58511. ** This function changes all write-locks held by Btree p into read-locks.
  58512. */
  58513. static void downgradeAllSharedCacheTableLocks(Btree *p){
  58514. BtShared *pBt = p->pBt;
  58515. if( pBt->pWriter==p ){
  58516. BtLock *pLock;
  58517. pBt->pWriter = 0;
  58518. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  58519. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  58520. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  58521. pLock->eLock = READ_LOCK;
  58522. }
  58523. }
  58524. }
  58525. #endif /* SQLITE_OMIT_SHARED_CACHE */
  58526. static void releasePage(MemPage *pPage); /* Forward reference */
  58527. static void releasePageOne(MemPage *pPage); /* Forward reference */
  58528. static void releasePageNotNull(MemPage *pPage); /* Forward reference */
  58529. /*
  58530. ***** This routine is used inside of assert() only ****
  58531. **
  58532. ** Verify that the cursor holds the mutex on its BtShared
  58533. */
  58534. #ifdef SQLITE_DEBUG
  58535. static int cursorHoldsMutex(BtCursor *p){
  58536. return sqlite3_mutex_held(p->pBt->mutex);
  58537. }
  58538. /* Verify that the cursor and the BtShared agree about what is the current
  58539. ** database connetion. This is important in shared-cache mode. If the database
  58540. ** connection pointers get out-of-sync, it is possible for routines like
  58541. ** btreeInitPage() to reference an stale connection pointer that references a
  58542. ** a connection that has already closed. This routine is used inside assert()
  58543. ** statements only and for the purpose of double-checking that the btree code
  58544. ** does keep the database connection pointers up-to-date.
  58545. */
  58546. static int cursorOwnsBtShared(BtCursor *p){
  58547. assert( cursorHoldsMutex(p) );
  58548. return (p->pBtree->db==p->pBt->db);
  58549. }
  58550. #endif
  58551. /*
  58552. ** Invalidate the overflow cache of the cursor passed as the first argument.
  58553. ** on the shared btree structure pBt.
  58554. */
  58555. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  58556. /*
  58557. ** Invalidate the overflow page-list cache for all cursors opened
  58558. ** on the shared btree structure pBt.
  58559. */
  58560. static void invalidateAllOverflowCache(BtShared *pBt){
  58561. BtCursor *p;
  58562. assert( sqlite3_mutex_held(pBt->mutex) );
  58563. for(p=pBt->pCursor; p; p=p->pNext){
  58564. invalidateOverflowCache(p);
  58565. }
  58566. }
  58567. #ifndef SQLITE_OMIT_INCRBLOB
  58568. /*
  58569. ** This function is called before modifying the contents of a table
  58570. ** to invalidate any incrblob cursors that are open on the
  58571. ** row or one of the rows being modified.
  58572. **
  58573. ** If argument isClearTable is true, then the entire contents of the
  58574. ** table is about to be deleted. In this case invalidate all incrblob
  58575. ** cursors open on any row within the table with root-page pgnoRoot.
  58576. **
  58577. ** Otherwise, if argument isClearTable is false, then the row with
  58578. ** rowid iRow is being replaced or deleted. In this case invalidate
  58579. ** only those incrblob cursors open on that specific row.
  58580. */
  58581. static void invalidateIncrblobCursors(
  58582. Btree *pBtree, /* The database file to check */
  58583. Pgno pgnoRoot, /* The table that might be changing */
  58584. i64 iRow, /* The rowid that might be changing */
  58585. int isClearTable /* True if all rows are being deleted */
  58586. ){
  58587. BtCursor *p;
  58588. if( pBtree->hasIncrblobCur==0 ) return;
  58589. assert( sqlite3BtreeHoldsMutex(pBtree) );
  58590. pBtree->hasIncrblobCur = 0;
  58591. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  58592. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  58593. pBtree->hasIncrblobCur = 1;
  58594. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  58595. p->eState = CURSOR_INVALID;
  58596. }
  58597. }
  58598. }
  58599. }
  58600. #else
  58601. /* Stub function when INCRBLOB is omitted */
  58602. #define invalidateIncrblobCursors(w,x,y,z)
  58603. #endif /* SQLITE_OMIT_INCRBLOB */
  58604. /*
  58605. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  58606. ** when a page that previously contained data becomes a free-list leaf
  58607. ** page.
  58608. **
  58609. ** The BtShared.pHasContent bitvec exists to work around an obscure
  58610. ** bug caused by the interaction of two useful IO optimizations surrounding
  58611. ** free-list leaf pages:
  58612. **
  58613. ** 1) When all data is deleted from a page and the page becomes
  58614. ** a free-list leaf page, the page is not written to the database
  58615. ** (as free-list leaf pages contain no meaningful data). Sometimes
  58616. ** such a page is not even journalled (as it will not be modified,
  58617. ** why bother journalling it?).
  58618. **
  58619. ** 2) When a free-list leaf page is reused, its content is not read
  58620. ** from the database or written to the journal file (why should it
  58621. ** be, if it is not at all meaningful?).
  58622. **
  58623. ** By themselves, these optimizations work fine and provide a handy
  58624. ** performance boost to bulk delete or insert operations. However, if
  58625. ** a page is moved to the free-list and then reused within the same
  58626. ** transaction, a problem comes up. If the page is not journalled when
  58627. ** it is moved to the free-list and it is also not journalled when it
  58628. ** is extracted from the free-list and reused, then the original data
  58629. ** may be lost. In the event of a rollback, it may not be possible
  58630. ** to restore the database to its original configuration.
  58631. **
  58632. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  58633. ** moved to become a free-list leaf page, the corresponding bit is
  58634. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  58635. ** optimization 2 above is omitted if the corresponding bit is already
  58636. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  58637. ** at the end of every transaction.
  58638. */
  58639. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  58640. int rc = SQLITE_OK;
  58641. if( !pBt->pHasContent ){
  58642. assert( pgno<=pBt->nPage );
  58643. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  58644. if( !pBt->pHasContent ){
  58645. rc = SQLITE_NOMEM_BKPT;
  58646. }
  58647. }
  58648. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  58649. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  58650. }
  58651. return rc;
  58652. }
  58653. /*
  58654. ** Query the BtShared.pHasContent vector.
  58655. **
  58656. ** This function is called when a free-list leaf page is removed from the
  58657. ** free-list for reuse. It returns false if it is safe to retrieve the
  58658. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  58659. */
  58660. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  58661. Bitvec *p = pBt->pHasContent;
  58662. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  58663. }
  58664. /*
  58665. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  58666. ** invoked at the conclusion of each write-transaction.
  58667. */
  58668. static void btreeClearHasContent(BtShared *pBt){
  58669. sqlite3BitvecDestroy(pBt->pHasContent);
  58670. pBt->pHasContent = 0;
  58671. }
  58672. /*
  58673. ** Release all of the apPage[] pages for a cursor.
  58674. */
  58675. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  58676. int i;
  58677. if( pCur->iPage>=0 ){
  58678. for(i=0; i<pCur->iPage; i++){
  58679. releasePageNotNull(pCur->apPage[i]);
  58680. }
  58681. releasePageNotNull(pCur->pPage);
  58682. pCur->iPage = -1;
  58683. }
  58684. }
  58685. /*
  58686. ** The cursor passed as the only argument must point to a valid entry
  58687. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  58688. ** function saves the current cursor key in variables pCur->nKey and
  58689. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  58690. ** code otherwise.
  58691. **
  58692. ** If the cursor is open on an intkey table, then the integer key
  58693. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  58694. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  58695. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  58696. ** the key.
  58697. */
  58698. static int saveCursorKey(BtCursor *pCur){
  58699. int rc = SQLITE_OK;
  58700. assert( CURSOR_VALID==pCur->eState );
  58701. assert( 0==pCur->pKey );
  58702. assert( cursorHoldsMutex(pCur) );
  58703. if( pCur->curIntKey ){
  58704. /* Only the rowid is required for a table btree */
  58705. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  58706. }else{
  58707. /* For an index btree, save the complete key content */
  58708. void *pKey;
  58709. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  58710. pKey = sqlite3Malloc( pCur->nKey );
  58711. if( pKey ){
  58712. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  58713. if( rc==SQLITE_OK ){
  58714. pCur->pKey = pKey;
  58715. }else{
  58716. sqlite3_free(pKey);
  58717. }
  58718. }else{
  58719. rc = SQLITE_NOMEM_BKPT;
  58720. }
  58721. }
  58722. assert( !pCur->curIntKey || !pCur->pKey );
  58723. return rc;
  58724. }
  58725. /*
  58726. ** Save the current cursor position in the variables BtCursor.nKey
  58727. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  58728. **
  58729. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  58730. ** prior to calling this routine.
  58731. */
  58732. static int saveCursorPosition(BtCursor *pCur){
  58733. int rc;
  58734. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  58735. assert( 0==pCur->pKey );
  58736. assert( cursorHoldsMutex(pCur) );
  58737. if( pCur->eState==CURSOR_SKIPNEXT ){
  58738. pCur->eState = CURSOR_VALID;
  58739. }else{
  58740. pCur->skipNext = 0;
  58741. }
  58742. rc = saveCursorKey(pCur);
  58743. if( rc==SQLITE_OK ){
  58744. btreeReleaseAllCursorPages(pCur);
  58745. pCur->eState = CURSOR_REQUIRESEEK;
  58746. }
  58747. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  58748. return rc;
  58749. }
  58750. /* Forward reference */
  58751. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  58752. /*
  58753. ** Save the positions of all cursors (except pExcept) that are open on
  58754. ** the table with root-page iRoot. "Saving the cursor position" means that
  58755. ** the location in the btree is remembered in such a way that it can be
  58756. ** moved back to the same spot after the btree has been modified. This
  58757. ** routine is called just before cursor pExcept is used to modify the
  58758. ** table, for example in BtreeDelete() or BtreeInsert().
  58759. **
  58760. ** If there are two or more cursors on the same btree, then all such
  58761. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  58762. ** routine enforces that rule. This routine only needs to be called in
  58763. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  58764. **
  58765. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  58766. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  58767. ** pointless call to this routine.
  58768. **
  58769. ** Implementation note: This routine merely checks to see if any cursors
  58770. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  58771. ** event that cursors are in need to being saved.
  58772. */
  58773. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  58774. BtCursor *p;
  58775. assert( sqlite3_mutex_held(pBt->mutex) );
  58776. assert( pExcept==0 || pExcept->pBt==pBt );
  58777. for(p=pBt->pCursor; p; p=p->pNext){
  58778. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  58779. }
  58780. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  58781. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  58782. return SQLITE_OK;
  58783. }
  58784. /* This helper routine to saveAllCursors does the actual work of saving
  58785. ** the cursors if and when a cursor is found that actually requires saving.
  58786. ** The common case is that no cursors need to be saved, so this routine is
  58787. ** broken out from its caller to avoid unnecessary stack pointer movement.
  58788. */
  58789. static int SQLITE_NOINLINE saveCursorsOnList(
  58790. BtCursor *p, /* The first cursor that needs saving */
  58791. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  58792. BtCursor *pExcept /* Do not save this cursor */
  58793. ){
  58794. do{
  58795. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  58796. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  58797. int rc = saveCursorPosition(p);
  58798. if( SQLITE_OK!=rc ){
  58799. return rc;
  58800. }
  58801. }else{
  58802. testcase( p->iPage>=0 );
  58803. btreeReleaseAllCursorPages(p);
  58804. }
  58805. }
  58806. p = p->pNext;
  58807. }while( p );
  58808. return SQLITE_OK;
  58809. }
  58810. /*
  58811. ** Clear the current cursor position.
  58812. */
  58813. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  58814. assert( cursorHoldsMutex(pCur) );
  58815. sqlite3_free(pCur->pKey);
  58816. pCur->pKey = 0;
  58817. pCur->eState = CURSOR_INVALID;
  58818. }
  58819. /*
  58820. ** In this version of BtreeMoveto, pKey is a packed index record
  58821. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  58822. ** record and then call BtreeMovetoUnpacked() to do the work.
  58823. */
  58824. static int btreeMoveto(
  58825. BtCursor *pCur, /* Cursor open on the btree to be searched */
  58826. const void *pKey, /* Packed key if the btree is an index */
  58827. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  58828. int bias, /* Bias search to the high end */
  58829. int *pRes /* Write search results here */
  58830. ){
  58831. int rc; /* Status code */
  58832. UnpackedRecord *pIdxKey; /* Unpacked index key */
  58833. if( pKey ){
  58834. assert( nKey==(i64)(int)nKey );
  58835. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
  58836. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  58837. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  58838. if( pIdxKey->nField==0 ){
  58839. rc = SQLITE_CORRUPT_BKPT;
  58840. goto moveto_done;
  58841. }
  58842. }else{
  58843. pIdxKey = 0;
  58844. }
  58845. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  58846. moveto_done:
  58847. if( pIdxKey ){
  58848. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  58849. }
  58850. return rc;
  58851. }
  58852. /*
  58853. ** Restore the cursor to the position it was in (or as close to as possible)
  58854. ** when saveCursorPosition() was called. Note that this call deletes the
  58855. ** saved position info stored by saveCursorPosition(), so there can be
  58856. ** at most one effective restoreCursorPosition() call after each
  58857. ** saveCursorPosition().
  58858. */
  58859. static int btreeRestoreCursorPosition(BtCursor *pCur){
  58860. int rc;
  58861. int skipNext;
  58862. assert( cursorOwnsBtShared(pCur) );
  58863. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  58864. if( pCur->eState==CURSOR_FAULT ){
  58865. return pCur->skipNext;
  58866. }
  58867. pCur->eState = CURSOR_INVALID;
  58868. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  58869. if( rc==SQLITE_OK ){
  58870. sqlite3_free(pCur->pKey);
  58871. pCur->pKey = 0;
  58872. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  58873. pCur->skipNext |= skipNext;
  58874. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  58875. pCur->eState = CURSOR_SKIPNEXT;
  58876. }
  58877. }
  58878. return rc;
  58879. }
  58880. #define restoreCursorPosition(p) \
  58881. (p->eState>=CURSOR_REQUIRESEEK ? \
  58882. btreeRestoreCursorPosition(p) : \
  58883. SQLITE_OK)
  58884. /*
  58885. ** Determine whether or not a cursor has moved from the position where
  58886. ** it was last placed, or has been invalidated for any other reason.
  58887. ** Cursors can move when the row they are pointing at is deleted out
  58888. ** from under them, for example. Cursor might also move if a btree
  58889. ** is rebalanced.
  58890. **
  58891. ** Calling this routine with a NULL cursor pointer returns false.
  58892. **
  58893. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  58894. ** back to where it ought to be if this routine returns true.
  58895. */
  58896. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  58897. assert( EIGHT_BYTE_ALIGNMENT(pCur)
  58898. || pCur==sqlite3BtreeFakeValidCursor() );
  58899. assert( offsetof(BtCursor, eState)==0 );
  58900. assert( sizeof(pCur->eState)==1 );
  58901. return CURSOR_VALID != *(u8*)pCur;
  58902. }
  58903. /*
  58904. ** Return a pointer to a fake BtCursor object that will always answer
  58905. ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
  58906. ** cursor returned must not be used with any other Btree interface.
  58907. */
  58908. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
  58909. static u8 fakeCursor = CURSOR_VALID;
  58910. assert( offsetof(BtCursor, eState)==0 );
  58911. return (BtCursor*)&fakeCursor;
  58912. }
  58913. /*
  58914. ** This routine restores a cursor back to its original position after it
  58915. ** has been moved by some outside activity (such as a btree rebalance or
  58916. ** a row having been deleted out from under the cursor).
  58917. **
  58918. ** On success, the *pDifferentRow parameter is false if the cursor is left
  58919. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  58920. ** was pointing to has been deleted, forcing the cursor to point to some
  58921. ** nearby row.
  58922. **
  58923. ** This routine should only be called for a cursor that just returned
  58924. ** TRUE from sqlite3BtreeCursorHasMoved().
  58925. */
  58926. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  58927. int rc;
  58928. assert( pCur!=0 );
  58929. assert( pCur->eState!=CURSOR_VALID );
  58930. rc = restoreCursorPosition(pCur);
  58931. if( rc ){
  58932. *pDifferentRow = 1;
  58933. return rc;
  58934. }
  58935. if( pCur->eState!=CURSOR_VALID ){
  58936. *pDifferentRow = 1;
  58937. }else{
  58938. assert( pCur->skipNext==0 );
  58939. *pDifferentRow = 0;
  58940. }
  58941. return SQLITE_OK;
  58942. }
  58943. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  58944. /*
  58945. ** Provide hints to the cursor. The particular hint given (and the type
  58946. ** and number of the varargs parameters) is determined by the eHintType
  58947. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  58948. */
  58949. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  58950. /* Used only by system that substitute their own storage engine */
  58951. }
  58952. #endif
  58953. /*
  58954. ** Provide flag hints to the cursor.
  58955. */
  58956. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  58957. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  58958. pCur->hints = x;
  58959. }
  58960. #ifndef SQLITE_OMIT_AUTOVACUUM
  58961. /*
  58962. ** Given a page number of a regular database page, return the page
  58963. ** number for the pointer-map page that contains the entry for the
  58964. ** input page number.
  58965. **
  58966. ** Return 0 (not a valid page) for pgno==1 since there is
  58967. ** no pointer map associated with page 1. The integrity_check logic
  58968. ** requires that ptrmapPageno(*,1)!=1.
  58969. */
  58970. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  58971. int nPagesPerMapPage;
  58972. Pgno iPtrMap, ret;
  58973. assert( sqlite3_mutex_held(pBt->mutex) );
  58974. if( pgno<2 ) return 0;
  58975. nPagesPerMapPage = (pBt->usableSize/5)+1;
  58976. iPtrMap = (pgno-2)/nPagesPerMapPage;
  58977. ret = (iPtrMap*nPagesPerMapPage) + 2;
  58978. if( ret==PENDING_BYTE_PAGE(pBt) ){
  58979. ret++;
  58980. }
  58981. return ret;
  58982. }
  58983. /*
  58984. ** Write an entry into the pointer map.
  58985. **
  58986. ** This routine updates the pointer map entry for page number 'key'
  58987. ** so that it maps to type 'eType' and parent page number 'pgno'.
  58988. **
  58989. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  58990. ** a no-op. If an error occurs, the appropriate error code is written
  58991. ** into *pRC.
  58992. */
  58993. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  58994. DbPage *pDbPage; /* The pointer map page */
  58995. u8 *pPtrmap; /* The pointer map data */
  58996. Pgno iPtrmap; /* The pointer map page number */
  58997. int offset; /* Offset in pointer map page */
  58998. int rc; /* Return code from subfunctions */
  58999. if( *pRC ) return;
  59000. assert( sqlite3_mutex_held(pBt->mutex) );
  59001. /* The master-journal page number must never be used as a pointer map page */
  59002. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  59003. assert( pBt->autoVacuum );
  59004. if( key==0 ){
  59005. *pRC = SQLITE_CORRUPT_BKPT;
  59006. return;
  59007. }
  59008. iPtrmap = PTRMAP_PAGENO(pBt, key);
  59009. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  59010. if( rc!=SQLITE_OK ){
  59011. *pRC = rc;
  59012. return;
  59013. }
  59014. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  59015. if( offset<0 ){
  59016. *pRC = SQLITE_CORRUPT_BKPT;
  59017. goto ptrmap_exit;
  59018. }
  59019. assert( offset <= (int)pBt->usableSize-5 );
  59020. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  59021. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  59022. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  59023. *pRC= rc = sqlite3PagerWrite(pDbPage);
  59024. if( rc==SQLITE_OK ){
  59025. pPtrmap[offset] = eType;
  59026. put4byte(&pPtrmap[offset+1], parent);
  59027. }
  59028. }
  59029. ptrmap_exit:
  59030. sqlite3PagerUnref(pDbPage);
  59031. }
  59032. /*
  59033. ** Read an entry from the pointer map.
  59034. **
  59035. ** This routine retrieves the pointer map entry for page 'key', writing
  59036. ** the type and parent page number to *pEType and *pPgno respectively.
  59037. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  59038. */
  59039. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  59040. DbPage *pDbPage; /* The pointer map page */
  59041. int iPtrmap; /* Pointer map page index */
  59042. u8 *pPtrmap; /* Pointer map page data */
  59043. int offset; /* Offset of entry in pointer map */
  59044. int rc;
  59045. assert( sqlite3_mutex_held(pBt->mutex) );
  59046. iPtrmap = PTRMAP_PAGENO(pBt, key);
  59047. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  59048. if( rc!=0 ){
  59049. return rc;
  59050. }
  59051. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  59052. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  59053. if( offset<0 ){
  59054. sqlite3PagerUnref(pDbPage);
  59055. return SQLITE_CORRUPT_BKPT;
  59056. }
  59057. assert( offset <= (int)pBt->usableSize-5 );
  59058. assert( pEType!=0 );
  59059. *pEType = pPtrmap[offset];
  59060. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  59061. sqlite3PagerUnref(pDbPage);
  59062. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
  59063. return SQLITE_OK;
  59064. }
  59065. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  59066. #define ptrmapPut(w,x,y,z,rc)
  59067. #define ptrmapGet(w,x,y,z) SQLITE_OK
  59068. #define ptrmapPutOvflPtr(x, y, rc)
  59069. #endif
  59070. /*
  59071. ** Given a btree page and a cell index (0 means the first cell on
  59072. ** the page, 1 means the second cell, and so forth) return a pointer
  59073. ** to the cell content.
  59074. **
  59075. ** findCellPastPtr() does the same except it skips past the initial
  59076. ** 4-byte child pointer found on interior pages, if there is one.
  59077. **
  59078. ** This routine works only for pages that do not contain overflow cells.
  59079. */
  59080. #define findCell(P,I) \
  59081. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  59082. #define findCellPastPtr(P,I) \
  59083. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  59084. /*
  59085. ** This is common tail processing for btreeParseCellPtr() and
  59086. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  59087. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  59088. ** structure.
  59089. */
  59090. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  59091. MemPage *pPage, /* Page containing the cell */
  59092. u8 *pCell, /* Pointer to the cell text. */
  59093. CellInfo *pInfo /* Fill in this structure */
  59094. ){
  59095. /* If the payload will not fit completely on the local page, we have
  59096. ** to decide how much to store locally and how much to spill onto
  59097. ** overflow pages. The strategy is to minimize the amount of unused
  59098. ** space on overflow pages while keeping the amount of local storage
  59099. ** in between minLocal and maxLocal.
  59100. **
  59101. ** Warning: changing the way overflow payload is distributed in any
  59102. ** way will result in an incompatible file format.
  59103. */
  59104. int minLocal; /* Minimum amount of payload held locally */
  59105. int maxLocal; /* Maximum amount of payload held locally */
  59106. int surplus; /* Overflow payload available for local storage */
  59107. minLocal = pPage->minLocal;
  59108. maxLocal = pPage->maxLocal;
  59109. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  59110. testcase( surplus==maxLocal );
  59111. testcase( surplus==maxLocal+1 );
  59112. if( surplus <= maxLocal ){
  59113. pInfo->nLocal = (u16)surplus;
  59114. }else{
  59115. pInfo->nLocal = (u16)minLocal;
  59116. }
  59117. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  59118. }
  59119. /*
  59120. ** The following routines are implementations of the MemPage.xParseCell()
  59121. ** method.
  59122. **
  59123. ** Parse a cell content block and fill in the CellInfo structure.
  59124. **
  59125. ** btreeParseCellPtr() => table btree leaf nodes
  59126. ** btreeParseCellNoPayload() => table btree internal nodes
  59127. ** btreeParseCellPtrIndex() => index btree nodes
  59128. **
  59129. ** There is also a wrapper function btreeParseCell() that works for
  59130. ** all MemPage types and that references the cell by index rather than
  59131. ** by pointer.
  59132. */
  59133. static void btreeParseCellPtrNoPayload(
  59134. MemPage *pPage, /* Page containing the cell */
  59135. u8 *pCell, /* Pointer to the cell text. */
  59136. CellInfo *pInfo /* Fill in this structure */
  59137. ){
  59138. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59139. assert( pPage->leaf==0 );
  59140. assert( pPage->childPtrSize==4 );
  59141. #ifndef SQLITE_DEBUG
  59142. UNUSED_PARAMETER(pPage);
  59143. #endif
  59144. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  59145. pInfo->nPayload = 0;
  59146. pInfo->nLocal = 0;
  59147. pInfo->pPayload = 0;
  59148. return;
  59149. }
  59150. static void btreeParseCellPtr(
  59151. MemPage *pPage, /* Page containing the cell */
  59152. u8 *pCell, /* Pointer to the cell text. */
  59153. CellInfo *pInfo /* Fill in this structure */
  59154. ){
  59155. u8 *pIter; /* For scanning through pCell */
  59156. u32 nPayload; /* Number of bytes of cell payload */
  59157. u64 iKey; /* Extracted Key value */
  59158. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59159. assert( pPage->leaf==0 || pPage->leaf==1 );
  59160. assert( pPage->intKeyLeaf );
  59161. assert( pPage->childPtrSize==0 );
  59162. pIter = pCell;
  59163. /* The next block of code is equivalent to:
  59164. **
  59165. ** pIter += getVarint32(pIter, nPayload);
  59166. **
  59167. ** The code is inlined to avoid a function call.
  59168. */
  59169. nPayload = *pIter;
  59170. if( nPayload>=0x80 ){
  59171. u8 *pEnd = &pIter[8];
  59172. nPayload &= 0x7f;
  59173. do{
  59174. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  59175. }while( (*pIter)>=0x80 && pIter<pEnd );
  59176. }
  59177. pIter++;
  59178. /* The next block of code is equivalent to:
  59179. **
  59180. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  59181. **
  59182. ** The code is inlined to avoid a function call.
  59183. */
  59184. iKey = *pIter;
  59185. if( iKey>=0x80 ){
  59186. u8 *pEnd = &pIter[7];
  59187. iKey &= 0x7f;
  59188. while(1){
  59189. iKey = (iKey<<7) | (*++pIter & 0x7f);
  59190. if( (*pIter)<0x80 ) break;
  59191. if( pIter>=pEnd ){
  59192. iKey = (iKey<<8) | *++pIter;
  59193. break;
  59194. }
  59195. }
  59196. }
  59197. pIter++;
  59198. pInfo->nKey = *(i64*)&iKey;
  59199. pInfo->nPayload = nPayload;
  59200. pInfo->pPayload = pIter;
  59201. testcase( nPayload==pPage->maxLocal );
  59202. testcase( nPayload==pPage->maxLocal+1 );
  59203. if( nPayload<=pPage->maxLocal ){
  59204. /* This is the (easy) common case where the entire payload fits
  59205. ** on the local page. No overflow is required.
  59206. */
  59207. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  59208. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  59209. pInfo->nLocal = (u16)nPayload;
  59210. }else{
  59211. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  59212. }
  59213. }
  59214. static void btreeParseCellPtrIndex(
  59215. MemPage *pPage, /* Page containing the cell */
  59216. u8 *pCell, /* Pointer to the cell text. */
  59217. CellInfo *pInfo /* Fill in this structure */
  59218. ){
  59219. u8 *pIter; /* For scanning through pCell */
  59220. u32 nPayload; /* Number of bytes of cell payload */
  59221. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59222. assert( pPage->leaf==0 || pPage->leaf==1 );
  59223. assert( pPage->intKeyLeaf==0 );
  59224. pIter = pCell + pPage->childPtrSize;
  59225. nPayload = *pIter;
  59226. if( nPayload>=0x80 ){
  59227. u8 *pEnd = &pIter[8];
  59228. nPayload &= 0x7f;
  59229. do{
  59230. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  59231. }while( *(pIter)>=0x80 && pIter<pEnd );
  59232. }
  59233. pIter++;
  59234. pInfo->nKey = nPayload;
  59235. pInfo->nPayload = nPayload;
  59236. pInfo->pPayload = pIter;
  59237. testcase( nPayload==pPage->maxLocal );
  59238. testcase( nPayload==pPage->maxLocal+1 );
  59239. if( nPayload<=pPage->maxLocal ){
  59240. /* This is the (easy) common case where the entire payload fits
  59241. ** on the local page. No overflow is required.
  59242. */
  59243. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  59244. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  59245. pInfo->nLocal = (u16)nPayload;
  59246. }else{
  59247. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  59248. }
  59249. }
  59250. static void btreeParseCell(
  59251. MemPage *pPage, /* Page containing the cell */
  59252. int iCell, /* The cell index. First cell is 0 */
  59253. CellInfo *pInfo /* Fill in this structure */
  59254. ){
  59255. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  59256. }
  59257. /*
  59258. ** The following routines are implementations of the MemPage.xCellSize
  59259. ** method.
  59260. **
  59261. ** Compute the total number of bytes that a Cell needs in the cell
  59262. ** data area of the btree-page. The return number includes the cell
  59263. ** data header and the local payload, but not any overflow page or
  59264. ** the space used by the cell pointer.
  59265. **
  59266. ** cellSizePtrNoPayload() => table internal nodes
  59267. ** cellSizePtr() => all index nodes & table leaf nodes
  59268. */
  59269. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  59270. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  59271. u8 *pEnd; /* End mark for a varint */
  59272. u32 nSize; /* Size value to return */
  59273. #ifdef SQLITE_DEBUG
  59274. /* The value returned by this function should always be the same as
  59275. ** the (CellInfo.nSize) value found by doing a full parse of the
  59276. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  59277. ** this function verifies that this invariant is not violated. */
  59278. CellInfo debuginfo;
  59279. pPage->xParseCell(pPage, pCell, &debuginfo);
  59280. #endif
  59281. nSize = *pIter;
  59282. if( nSize>=0x80 ){
  59283. pEnd = &pIter[8];
  59284. nSize &= 0x7f;
  59285. do{
  59286. nSize = (nSize<<7) | (*++pIter & 0x7f);
  59287. }while( *(pIter)>=0x80 && pIter<pEnd );
  59288. }
  59289. pIter++;
  59290. if( pPage->intKey ){
  59291. /* pIter now points at the 64-bit integer key value, a variable length
  59292. ** integer. The following block moves pIter to point at the first byte
  59293. ** past the end of the key value. */
  59294. pEnd = &pIter[9];
  59295. while( (*pIter++)&0x80 && pIter<pEnd );
  59296. }
  59297. testcase( nSize==pPage->maxLocal );
  59298. testcase( nSize==pPage->maxLocal+1 );
  59299. if( nSize<=pPage->maxLocal ){
  59300. nSize += (u32)(pIter - pCell);
  59301. if( nSize<4 ) nSize = 4;
  59302. }else{
  59303. int minLocal = pPage->minLocal;
  59304. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  59305. testcase( nSize==pPage->maxLocal );
  59306. testcase( nSize==pPage->maxLocal+1 );
  59307. if( nSize>pPage->maxLocal ){
  59308. nSize = minLocal;
  59309. }
  59310. nSize += 4 + (u16)(pIter - pCell);
  59311. }
  59312. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  59313. return (u16)nSize;
  59314. }
  59315. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  59316. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  59317. u8 *pEnd; /* End mark for a varint */
  59318. #ifdef SQLITE_DEBUG
  59319. /* The value returned by this function should always be the same as
  59320. ** the (CellInfo.nSize) value found by doing a full parse of the
  59321. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  59322. ** this function verifies that this invariant is not violated. */
  59323. CellInfo debuginfo;
  59324. pPage->xParseCell(pPage, pCell, &debuginfo);
  59325. #else
  59326. UNUSED_PARAMETER(pPage);
  59327. #endif
  59328. assert( pPage->childPtrSize==4 );
  59329. pEnd = pIter + 9;
  59330. while( (*pIter++)&0x80 && pIter<pEnd );
  59331. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  59332. return (u16)(pIter - pCell);
  59333. }
  59334. #ifdef SQLITE_DEBUG
  59335. /* This variation on cellSizePtr() is used inside of assert() statements
  59336. ** only. */
  59337. static u16 cellSize(MemPage *pPage, int iCell){
  59338. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  59339. }
  59340. #endif
  59341. #ifndef SQLITE_OMIT_AUTOVACUUM
  59342. /*
  59343. ** If the cell pCell, part of page pPage contains a pointer
  59344. ** to an overflow page, insert an entry into the pointer-map
  59345. ** for the overflow page.
  59346. */
  59347. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  59348. CellInfo info;
  59349. if( *pRC ) return;
  59350. assert( pCell!=0 );
  59351. pPage->xParseCell(pPage, pCell, &info);
  59352. if( info.nLocal<info.nPayload ){
  59353. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  59354. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  59355. }
  59356. }
  59357. #endif
  59358. /*
  59359. ** Defragment the page given. This routine reorganizes cells within the
  59360. ** page so that there are no free-blocks on the free-block list.
  59361. **
  59362. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  59363. ** present in the page after this routine returns.
  59364. **
  59365. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  59366. ** b-tree page so that there are no freeblocks or fragment bytes, all
  59367. ** unused bytes are contained in the unallocated space region, and all
  59368. ** cells are packed tightly at the end of the page.
  59369. */
  59370. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  59371. int i; /* Loop counter */
  59372. int pc; /* Address of the i-th cell */
  59373. int hdr; /* Offset to the page header */
  59374. int size; /* Size of a cell */
  59375. int usableSize; /* Number of usable bytes on a page */
  59376. int cellOffset; /* Offset to the cell pointer array */
  59377. int cbrk; /* Offset to the cell content area */
  59378. int nCell; /* Number of cells on the page */
  59379. unsigned char *data; /* The page data */
  59380. unsigned char *temp; /* Temp area for cell content */
  59381. unsigned char *src; /* Source of content */
  59382. int iCellFirst; /* First allowable cell index */
  59383. int iCellLast; /* Last possible cell index */
  59384. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59385. assert( pPage->pBt!=0 );
  59386. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  59387. assert( pPage->nOverflow==0 );
  59388. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59389. temp = 0;
  59390. src = data = pPage->aData;
  59391. hdr = pPage->hdrOffset;
  59392. cellOffset = pPage->cellOffset;
  59393. nCell = pPage->nCell;
  59394. assert( nCell==get2byte(&data[hdr+3]) );
  59395. iCellFirst = cellOffset + 2*nCell;
  59396. usableSize = pPage->pBt->usableSize;
  59397. /* This block handles pages with two or fewer free blocks and nMaxFrag
  59398. ** or fewer fragmented bytes. In this case it is faster to move the
  59399. ** two (or one) blocks of cells using memmove() and add the required
  59400. ** offsets to each pointer in the cell-pointer array than it is to
  59401. ** reconstruct the entire page. */
  59402. if( (int)data[hdr+7]<=nMaxFrag ){
  59403. int iFree = get2byte(&data[hdr+1]);
  59404. if( iFree ){
  59405. int iFree2 = get2byte(&data[iFree]);
  59406. /* pageFindSlot() has already verified that free blocks are sorted
  59407. ** in order of offset within the page, and that no block extends
  59408. ** past the end of the page. Provided the two free slots do not
  59409. ** overlap, this guarantees that the memmove() calls below will not
  59410. ** overwrite the usableSize byte buffer, even if the database page
  59411. ** is corrupt. */
  59412. assert( iFree2==0 || iFree2>iFree );
  59413. assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
  59414. assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
  59415. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  59416. u8 *pEnd = &data[cellOffset + nCell*2];
  59417. u8 *pAddr;
  59418. int sz2 = 0;
  59419. int sz = get2byte(&data[iFree+2]);
  59420. int top = get2byte(&data[hdr+5]);
  59421. if( top>=iFree ){
  59422. return SQLITE_CORRUPT_PAGE(pPage);
  59423. }
  59424. if( iFree2 ){
  59425. assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
  59426. sz2 = get2byte(&data[iFree2+2]);
  59427. assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
  59428. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  59429. sz += sz2;
  59430. }
  59431. cbrk = top+sz;
  59432. assert( cbrk+(iFree-top) <= usableSize );
  59433. memmove(&data[cbrk], &data[top], iFree-top);
  59434. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  59435. pc = get2byte(pAddr);
  59436. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  59437. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  59438. }
  59439. goto defragment_out;
  59440. }
  59441. }
  59442. }
  59443. cbrk = usableSize;
  59444. iCellLast = usableSize - 4;
  59445. for(i=0; i<nCell; i++){
  59446. u8 *pAddr; /* The i-th cell pointer */
  59447. pAddr = &data[cellOffset + i*2];
  59448. pc = get2byte(pAddr);
  59449. testcase( pc==iCellFirst );
  59450. testcase( pc==iCellLast );
  59451. /* These conditions have already been verified in btreeInitPage()
  59452. ** if PRAGMA cell_size_check=ON.
  59453. */
  59454. if( pc<iCellFirst || pc>iCellLast ){
  59455. return SQLITE_CORRUPT_PAGE(pPage);
  59456. }
  59457. assert( pc>=iCellFirst && pc<=iCellLast );
  59458. size = pPage->xCellSize(pPage, &src[pc]);
  59459. cbrk -= size;
  59460. if( cbrk<iCellFirst || pc+size>usableSize ){
  59461. return SQLITE_CORRUPT_PAGE(pPage);
  59462. }
  59463. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  59464. testcase( cbrk+size==usableSize );
  59465. testcase( pc+size==usableSize );
  59466. put2byte(pAddr, cbrk);
  59467. if( temp==0 ){
  59468. int x;
  59469. if( cbrk==pc ) continue;
  59470. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  59471. x = get2byte(&data[hdr+5]);
  59472. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  59473. src = temp;
  59474. }
  59475. memcpy(&data[cbrk], &src[pc], size);
  59476. }
  59477. data[hdr+7] = 0;
  59478. defragment_out:
  59479. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  59480. return SQLITE_CORRUPT_PAGE(pPage);
  59481. }
  59482. assert( cbrk>=iCellFirst );
  59483. put2byte(&data[hdr+5], cbrk);
  59484. data[hdr+1] = 0;
  59485. data[hdr+2] = 0;
  59486. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  59487. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59488. return SQLITE_OK;
  59489. }
  59490. /*
  59491. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  59492. ** size. If one can be found, return a pointer to the space and remove it
  59493. ** from the free-list.
  59494. **
  59495. ** If no suitable space can be found on the free-list, return NULL.
  59496. **
  59497. ** This function may detect corruption within pPg. If corruption is
  59498. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  59499. **
  59500. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  59501. ** will be ignored if adding the extra space to the fragmentation count
  59502. ** causes the fragmentation count to exceed 60.
  59503. */
  59504. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  59505. const int hdr = pPg->hdrOffset;
  59506. u8 * const aData = pPg->aData;
  59507. int iAddr = hdr + 1;
  59508. int pc = get2byte(&aData[iAddr]);
  59509. int x;
  59510. int usableSize = pPg->pBt->usableSize;
  59511. int size; /* Size of the free slot */
  59512. assert( pc>0 );
  59513. while( pc<=usableSize-4 ){
  59514. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  59515. ** freeblock form a big-endian integer which is the size of the freeblock
  59516. ** in bytes, including the 4-byte header. */
  59517. size = get2byte(&aData[pc+2]);
  59518. if( (x = size - nByte)>=0 ){
  59519. testcase( x==4 );
  59520. testcase( x==3 );
  59521. if( size+pc > usableSize ){
  59522. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  59523. return 0;
  59524. }else if( x<4 ){
  59525. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  59526. ** number of bytes in fragments may not exceed 60. */
  59527. if( aData[hdr+7]>57 ) return 0;
  59528. /* Remove the slot from the free-list. Update the number of
  59529. ** fragmented bytes within the page. */
  59530. memcpy(&aData[iAddr], &aData[pc], 2);
  59531. aData[hdr+7] += (u8)x;
  59532. }else{
  59533. /* The slot remains on the free-list. Reduce its size to account
  59534. ** for the portion used by the new allocation. */
  59535. put2byte(&aData[pc+2], x);
  59536. }
  59537. return &aData[pc + x];
  59538. }
  59539. iAddr = pc;
  59540. pc = get2byte(&aData[pc]);
  59541. if( pc<iAddr+size ) break;
  59542. }
  59543. if( pc ){
  59544. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  59545. }
  59546. return 0;
  59547. }
  59548. /*
  59549. ** Allocate nByte bytes of space from within the B-Tree page passed
  59550. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  59551. ** of the first byte of allocated space. Return either SQLITE_OK or
  59552. ** an error code (usually SQLITE_CORRUPT).
  59553. **
  59554. ** The caller guarantees that there is sufficient space to make the
  59555. ** allocation. This routine might need to defragment in order to bring
  59556. ** all the space together, however. This routine will avoid using
  59557. ** the first two bytes past the cell pointer area since presumably this
  59558. ** allocation is being made in order to insert a new cell, so we will
  59559. ** also end up needing a new cell pointer.
  59560. */
  59561. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  59562. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  59563. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  59564. int top; /* First byte of cell content area */
  59565. int rc = SQLITE_OK; /* Integer return code */
  59566. int gap; /* First byte of gap between cell pointers and cell content */
  59567. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59568. assert( pPage->pBt );
  59569. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59570. assert( nByte>=0 ); /* Minimum cell size is 4 */
  59571. assert( pPage->nFree>=nByte );
  59572. assert( pPage->nOverflow==0 );
  59573. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  59574. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  59575. gap = pPage->cellOffset + 2*pPage->nCell;
  59576. assert( gap<=65536 );
  59577. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  59578. ** and the reserved space is zero (the usual value for reserved space)
  59579. ** then the cell content offset of an empty page wants to be 65536.
  59580. ** However, that integer is too large to be stored in a 2-byte unsigned
  59581. ** integer, so a value of 0 is used in its place. */
  59582. top = get2byte(&data[hdr+5]);
  59583. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  59584. if( gap>top ){
  59585. if( top==0 && pPage->pBt->usableSize==65536 ){
  59586. top = 65536;
  59587. }else{
  59588. return SQLITE_CORRUPT_PAGE(pPage);
  59589. }
  59590. }
  59591. /* If there is enough space between gap and top for one more cell pointer
  59592. ** array entry offset, and if the freelist is not empty, then search the
  59593. ** freelist looking for a free slot big enough to satisfy the request.
  59594. */
  59595. testcase( gap+2==top );
  59596. testcase( gap+1==top );
  59597. testcase( gap==top );
  59598. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  59599. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  59600. if( pSpace ){
  59601. assert( pSpace>=data && (pSpace - data)<65536 );
  59602. *pIdx = (int)(pSpace - data);
  59603. return SQLITE_OK;
  59604. }else if( rc ){
  59605. return rc;
  59606. }
  59607. }
  59608. /* The request could not be fulfilled using a freelist slot. Check
  59609. ** to see if defragmentation is necessary.
  59610. */
  59611. testcase( gap+2+nByte==top );
  59612. if( gap+2+nByte>top ){
  59613. assert( pPage->nCell>0 || CORRUPT_DB );
  59614. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  59615. if( rc ) return rc;
  59616. top = get2byteNotZero(&data[hdr+5]);
  59617. assert( gap+2+nByte<=top );
  59618. }
  59619. /* Allocate memory from the gap in between the cell pointer array
  59620. ** and the cell content area. The btreeInitPage() call has already
  59621. ** validated the freelist. Given that the freelist is valid, there
  59622. ** is no way that the allocation can extend off the end of the page.
  59623. ** The assert() below verifies the previous sentence.
  59624. */
  59625. top -= nByte;
  59626. put2byte(&data[hdr+5], top);
  59627. assert( top+nByte <= (int)pPage->pBt->usableSize );
  59628. *pIdx = top;
  59629. return SQLITE_OK;
  59630. }
  59631. /*
  59632. ** Return a section of the pPage->aData to the freelist.
  59633. ** The first byte of the new free block is pPage->aData[iStart]
  59634. ** and the size of the block is iSize bytes.
  59635. **
  59636. ** Adjacent freeblocks are coalesced.
  59637. **
  59638. ** Note that even though the freeblock list was checked by btreeInitPage(),
  59639. ** that routine will not detect overlap between cells or freeblocks. Nor
  59640. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  59641. ** at the end of the page. So do additional corruption checks inside this
  59642. ** routine and return SQLITE_CORRUPT if any problems are found.
  59643. */
  59644. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  59645. u16 iPtr; /* Address of ptr to next freeblock */
  59646. u16 iFreeBlk; /* Address of the next freeblock */
  59647. u8 hdr; /* Page header size. 0 or 100 */
  59648. u8 nFrag = 0; /* Reduction in fragmentation */
  59649. u16 iOrigSize = iSize; /* Original value of iSize */
  59650. u16 x; /* Offset to cell content area */
  59651. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  59652. unsigned char *data = pPage->aData; /* Page content */
  59653. assert( pPage->pBt!=0 );
  59654. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59655. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  59656. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  59657. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59658. assert( iSize>=4 ); /* Minimum cell size is 4 */
  59659. assert( iStart<=pPage->pBt->usableSize-4 );
  59660. /* The list of freeblocks must be in ascending order. Find the
  59661. ** spot on the list where iStart should be inserted.
  59662. */
  59663. hdr = pPage->hdrOffset;
  59664. iPtr = hdr + 1;
  59665. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  59666. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  59667. }else{
  59668. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  59669. if( iFreeBlk<iPtr+4 ){
  59670. if( iFreeBlk==0 ) break;
  59671. return SQLITE_CORRUPT_PAGE(pPage);
  59672. }
  59673. iPtr = iFreeBlk;
  59674. }
  59675. if( iFreeBlk>pPage->pBt->usableSize-4 ){
  59676. return SQLITE_CORRUPT_PAGE(pPage);
  59677. }
  59678. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  59679. /* At this point:
  59680. ** iFreeBlk: First freeblock after iStart, or zero if none
  59681. ** iPtr: The address of a pointer to iFreeBlk
  59682. **
  59683. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  59684. */
  59685. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  59686. nFrag = iFreeBlk - iEnd;
  59687. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
  59688. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  59689. if( iEnd > pPage->pBt->usableSize ){
  59690. return SQLITE_CORRUPT_PAGE(pPage);
  59691. }
  59692. iSize = iEnd - iStart;
  59693. iFreeBlk = get2byte(&data[iFreeBlk]);
  59694. }
  59695. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  59696. ** pointer in the page header) then check to see if iStart should be
  59697. ** coalesced onto the end of iPtr.
  59698. */
  59699. if( iPtr>hdr+1 ){
  59700. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  59701. if( iPtrEnd+3>=iStart ){
  59702. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
  59703. nFrag += iStart - iPtrEnd;
  59704. iSize = iEnd - iPtr;
  59705. iStart = iPtr;
  59706. }
  59707. }
  59708. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
  59709. data[hdr+7] -= nFrag;
  59710. }
  59711. x = get2byte(&data[hdr+5]);
  59712. if( iStart<=x ){
  59713. /* The new freeblock is at the beginning of the cell content area,
  59714. ** so just extend the cell content area rather than create another
  59715. ** freelist entry */
  59716. if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
  59717. put2byte(&data[hdr+1], iFreeBlk);
  59718. put2byte(&data[hdr+5], iEnd);
  59719. }else{
  59720. /* Insert the new freeblock into the freelist */
  59721. put2byte(&data[iPtr], iStart);
  59722. }
  59723. if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
  59724. /* Overwrite deleted information with zeros when the secure_delete
  59725. ** option is enabled */
  59726. memset(&data[iStart], 0, iSize);
  59727. }
  59728. put2byte(&data[iStart], iFreeBlk);
  59729. put2byte(&data[iStart+2], iSize);
  59730. pPage->nFree += iOrigSize;
  59731. return SQLITE_OK;
  59732. }
  59733. /*
  59734. ** Decode the flags byte (the first byte of the header) for a page
  59735. ** and initialize fields of the MemPage structure accordingly.
  59736. **
  59737. ** Only the following combinations are supported. Anything different
  59738. ** indicates a corrupt database files:
  59739. **
  59740. ** PTF_ZERODATA
  59741. ** PTF_ZERODATA | PTF_LEAF
  59742. ** PTF_LEAFDATA | PTF_INTKEY
  59743. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  59744. */
  59745. static int decodeFlags(MemPage *pPage, int flagByte){
  59746. BtShared *pBt; /* A copy of pPage->pBt */
  59747. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  59748. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59749. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  59750. flagByte &= ~PTF_LEAF;
  59751. pPage->childPtrSize = 4-4*pPage->leaf;
  59752. pPage->xCellSize = cellSizePtr;
  59753. pBt = pPage->pBt;
  59754. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  59755. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  59756. ** interior table b-tree page. */
  59757. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  59758. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  59759. ** leaf table b-tree page. */
  59760. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  59761. pPage->intKey = 1;
  59762. if( pPage->leaf ){
  59763. pPage->intKeyLeaf = 1;
  59764. pPage->xParseCell = btreeParseCellPtr;
  59765. }else{
  59766. pPage->intKeyLeaf = 0;
  59767. pPage->xCellSize = cellSizePtrNoPayload;
  59768. pPage->xParseCell = btreeParseCellPtrNoPayload;
  59769. }
  59770. pPage->maxLocal = pBt->maxLeaf;
  59771. pPage->minLocal = pBt->minLeaf;
  59772. }else if( flagByte==PTF_ZERODATA ){
  59773. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  59774. ** interior index b-tree page. */
  59775. assert( (PTF_ZERODATA)==2 );
  59776. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  59777. ** leaf index b-tree page. */
  59778. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  59779. pPage->intKey = 0;
  59780. pPage->intKeyLeaf = 0;
  59781. pPage->xParseCell = btreeParseCellPtrIndex;
  59782. pPage->maxLocal = pBt->maxLocal;
  59783. pPage->minLocal = pBt->minLocal;
  59784. }else{
  59785. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  59786. ** an error. */
  59787. return SQLITE_CORRUPT_PAGE(pPage);
  59788. }
  59789. pPage->max1bytePayload = pBt->max1bytePayload;
  59790. return SQLITE_OK;
  59791. }
  59792. /*
  59793. ** Initialize the auxiliary information for a disk block.
  59794. **
  59795. ** Return SQLITE_OK on success. If we see that the page does
  59796. ** not contain a well-formed database page, then return
  59797. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  59798. ** guarantee that the page is well-formed. It only shows that
  59799. ** we failed to detect any corruption.
  59800. */
  59801. static int btreeInitPage(MemPage *pPage){
  59802. int pc; /* Address of a freeblock within pPage->aData[] */
  59803. u8 hdr; /* Offset to beginning of page header */
  59804. u8 *data; /* Equal to pPage->aData */
  59805. BtShared *pBt; /* The main btree structure */
  59806. int usableSize; /* Amount of usable space on each page */
  59807. u16 cellOffset; /* Offset from start of page to first cell pointer */
  59808. int nFree; /* Number of unused bytes on the page */
  59809. int top; /* First byte of the cell content area */
  59810. int iCellFirst; /* First allowable cell or freeblock offset */
  59811. int iCellLast; /* Last possible cell or freeblock offset */
  59812. assert( pPage->pBt!=0 );
  59813. assert( pPage->pBt->db!=0 );
  59814. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59815. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  59816. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  59817. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  59818. assert( pPage->isInit==0 );
  59819. pBt = pPage->pBt;
  59820. hdr = pPage->hdrOffset;
  59821. data = pPage->aData;
  59822. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  59823. ** the b-tree page type. */
  59824. if( decodeFlags(pPage, data[hdr]) ){
  59825. return SQLITE_CORRUPT_PAGE(pPage);
  59826. }
  59827. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  59828. pPage->maskPage = (u16)(pBt->pageSize - 1);
  59829. pPage->nOverflow = 0;
  59830. usableSize = pBt->usableSize;
  59831. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  59832. pPage->aDataEnd = &data[usableSize];
  59833. pPage->aCellIdx = &data[cellOffset];
  59834. pPage->aDataOfst = &data[pPage->childPtrSize];
  59835. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  59836. ** the start of the cell content area. A zero value for this integer is
  59837. ** interpreted as 65536. */
  59838. top = get2byteNotZero(&data[hdr+5]);
  59839. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  59840. ** number of cells on the page. */
  59841. pPage->nCell = get2byte(&data[hdr+3]);
  59842. if( pPage->nCell>MX_CELL(pBt) ){
  59843. /* To many cells for a single page. The page must be corrupt */
  59844. return SQLITE_CORRUPT_PAGE(pPage);
  59845. }
  59846. testcase( pPage->nCell==MX_CELL(pBt) );
  59847. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  59848. ** possible for a root page of a table that contains no rows) then the
  59849. ** offset to the cell content area will equal the page size minus the
  59850. ** bytes of reserved space. */
  59851. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  59852. /* A malformed database page might cause us to read past the end
  59853. ** of page when parsing a cell.
  59854. **
  59855. ** The following block of code checks early to see if a cell extends
  59856. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  59857. ** returned if it does.
  59858. */
  59859. iCellFirst = cellOffset + 2*pPage->nCell;
  59860. iCellLast = usableSize - 4;
  59861. if( pBt->db->flags & SQLITE_CellSizeCk ){
  59862. int i; /* Index into the cell pointer array */
  59863. int sz; /* Size of a cell */
  59864. if( !pPage->leaf ) iCellLast--;
  59865. for(i=0; i<pPage->nCell; i++){
  59866. pc = get2byteAligned(&data[cellOffset+i*2]);
  59867. testcase( pc==iCellFirst );
  59868. testcase( pc==iCellLast );
  59869. if( pc<iCellFirst || pc>iCellLast ){
  59870. return SQLITE_CORRUPT_PAGE(pPage);
  59871. }
  59872. sz = pPage->xCellSize(pPage, &data[pc]);
  59873. testcase( pc+sz==usableSize );
  59874. if( pc+sz>usableSize ){
  59875. return SQLITE_CORRUPT_PAGE(pPage);
  59876. }
  59877. }
  59878. if( !pPage->leaf ) iCellLast++;
  59879. }
  59880. /* Compute the total free space on the page
  59881. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  59882. ** start of the first freeblock on the page, or is zero if there are no
  59883. ** freeblocks. */
  59884. pc = get2byte(&data[hdr+1]);
  59885. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  59886. if( pc>0 ){
  59887. u32 next, size;
  59888. if( pc<iCellFirst ){
  59889. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  59890. ** always be at least one cell before the first freeblock.
  59891. */
  59892. return SQLITE_CORRUPT_PAGE(pPage);
  59893. }
  59894. while( 1 ){
  59895. if( pc>iCellLast ){
  59896. /* Freeblock off the end of the page */
  59897. return SQLITE_CORRUPT_PAGE(pPage);
  59898. }
  59899. next = get2byte(&data[pc]);
  59900. size = get2byte(&data[pc+2]);
  59901. nFree = nFree + size;
  59902. if( next<=pc+size+3 ) break;
  59903. pc = next;
  59904. }
  59905. if( next>0 ){
  59906. /* Freeblock not in ascending order */
  59907. return SQLITE_CORRUPT_PAGE(pPage);
  59908. }
  59909. if( pc+size>(unsigned int)usableSize ){
  59910. /* Last freeblock extends past page end */
  59911. return SQLITE_CORRUPT_PAGE(pPage);
  59912. }
  59913. }
  59914. /* At this point, nFree contains the sum of the offset to the start
  59915. ** of the cell-content area plus the number of free bytes within
  59916. ** the cell-content area. If this is greater than the usable-size
  59917. ** of the page, then the page must be corrupted. This check also
  59918. ** serves to verify that the offset to the start of the cell-content
  59919. ** area, according to the page header, lies within the page.
  59920. */
  59921. if( nFree>usableSize ){
  59922. return SQLITE_CORRUPT_PAGE(pPage);
  59923. }
  59924. pPage->nFree = (u16)(nFree - iCellFirst);
  59925. pPage->isInit = 1;
  59926. return SQLITE_OK;
  59927. }
  59928. /*
  59929. ** Set up a raw page so that it looks like a database page holding
  59930. ** no entries.
  59931. */
  59932. static void zeroPage(MemPage *pPage, int flags){
  59933. unsigned char *data = pPage->aData;
  59934. BtShared *pBt = pPage->pBt;
  59935. u8 hdr = pPage->hdrOffset;
  59936. u16 first;
  59937. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  59938. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  59939. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  59940. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59941. assert( sqlite3_mutex_held(pBt->mutex) );
  59942. if( pBt->btsFlags & BTS_FAST_SECURE ){
  59943. memset(&data[hdr], 0, pBt->usableSize - hdr);
  59944. }
  59945. data[hdr] = (char)flags;
  59946. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  59947. memset(&data[hdr+1], 0, 4);
  59948. data[hdr+7] = 0;
  59949. put2byte(&data[hdr+5], pBt->usableSize);
  59950. pPage->nFree = (u16)(pBt->usableSize - first);
  59951. decodeFlags(pPage, flags);
  59952. pPage->cellOffset = first;
  59953. pPage->aDataEnd = &data[pBt->usableSize];
  59954. pPage->aCellIdx = &data[first];
  59955. pPage->aDataOfst = &data[pPage->childPtrSize];
  59956. pPage->nOverflow = 0;
  59957. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  59958. pPage->maskPage = (u16)(pBt->pageSize - 1);
  59959. pPage->nCell = 0;
  59960. pPage->isInit = 1;
  59961. }
  59962. /*
  59963. ** Convert a DbPage obtained from the pager into a MemPage used by
  59964. ** the btree layer.
  59965. */
  59966. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  59967. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  59968. if( pgno!=pPage->pgno ){
  59969. pPage->aData = sqlite3PagerGetData(pDbPage);
  59970. pPage->pDbPage = pDbPage;
  59971. pPage->pBt = pBt;
  59972. pPage->pgno = pgno;
  59973. pPage->hdrOffset = pgno==1 ? 100 : 0;
  59974. }
  59975. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  59976. return pPage;
  59977. }
  59978. /*
  59979. ** Get a page from the pager. Initialize the MemPage.pBt and
  59980. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  59981. **
  59982. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  59983. ** about the content of the page at this time. So do not go to the disk
  59984. ** to fetch the content. Just fill in the content with zeros for now.
  59985. ** If in the future we call sqlite3PagerWrite() on this page, that
  59986. ** means we have started to be concerned about content and the disk
  59987. ** read should occur at that point.
  59988. */
  59989. static int btreeGetPage(
  59990. BtShared *pBt, /* The btree */
  59991. Pgno pgno, /* Number of the page to fetch */
  59992. MemPage **ppPage, /* Return the page in this parameter */
  59993. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  59994. ){
  59995. int rc;
  59996. DbPage *pDbPage;
  59997. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  59998. assert( sqlite3_mutex_held(pBt->mutex) );
  59999. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  60000. if( rc ) return rc;
  60001. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  60002. return SQLITE_OK;
  60003. }
  60004. /*
  60005. ** Retrieve a page from the pager cache. If the requested page is not
  60006. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  60007. ** MemPage.aData elements if needed.
  60008. */
  60009. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  60010. DbPage *pDbPage;
  60011. assert( sqlite3_mutex_held(pBt->mutex) );
  60012. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  60013. if( pDbPage ){
  60014. return btreePageFromDbPage(pDbPage, pgno, pBt);
  60015. }
  60016. return 0;
  60017. }
  60018. /*
  60019. ** Return the size of the database file in pages. If there is any kind of
  60020. ** error, return ((unsigned int)-1).
  60021. */
  60022. static Pgno btreePagecount(BtShared *pBt){
  60023. return pBt->nPage;
  60024. }
  60025. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  60026. assert( sqlite3BtreeHoldsMutex(p) );
  60027. assert( ((p->pBt->nPage)&0x80000000)==0 );
  60028. return btreePagecount(p->pBt);
  60029. }
  60030. /*
  60031. ** Get a page from the pager and initialize it.
  60032. **
  60033. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  60034. ** call. Do additional sanity checking on the page in this case.
  60035. ** And if the fetch fails, this routine must decrement pCur->iPage.
  60036. **
  60037. ** The page is fetched as read-write unless pCur is not NULL and is
  60038. ** a read-only cursor.
  60039. **
  60040. ** If an error occurs, then *ppPage is undefined. It
  60041. ** may remain unchanged, or it may be set to an invalid value.
  60042. */
  60043. static int getAndInitPage(
  60044. BtShared *pBt, /* The database file */
  60045. Pgno pgno, /* Number of the page to get */
  60046. MemPage **ppPage, /* Write the page pointer here */
  60047. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  60048. int bReadOnly /* True for a read-only page */
  60049. ){
  60050. int rc;
  60051. DbPage *pDbPage;
  60052. assert( sqlite3_mutex_held(pBt->mutex) );
  60053. assert( pCur==0 || ppPage==&pCur->pPage );
  60054. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  60055. assert( pCur==0 || pCur->iPage>0 );
  60056. if( pgno>btreePagecount(pBt) ){
  60057. rc = SQLITE_CORRUPT_BKPT;
  60058. goto getAndInitPage_error;
  60059. }
  60060. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  60061. if( rc ){
  60062. goto getAndInitPage_error;
  60063. }
  60064. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  60065. if( (*ppPage)->isInit==0 ){
  60066. btreePageFromDbPage(pDbPage, pgno, pBt);
  60067. rc = btreeInitPage(*ppPage);
  60068. if( rc!=SQLITE_OK ){
  60069. releasePage(*ppPage);
  60070. goto getAndInitPage_error;
  60071. }
  60072. }
  60073. assert( (*ppPage)->pgno==pgno );
  60074. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  60075. /* If obtaining a child page for a cursor, we must verify that the page is
  60076. ** compatible with the root page. */
  60077. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  60078. rc = SQLITE_CORRUPT_PGNO(pgno);
  60079. releasePage(*ppPage);
  60080. goto getAndInitPage_error;
  60081. }
  60082. return SQLITE_OK;
  60083. getAndInitPage_error:
  60084. if( pCur ){
  60085. pCur->iPage--;
  60086. pCur->pPage = pCur->apPage[pCur->iPage];
  60087. }
  60088. testcase( pgno==0 );
  60089. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  60090. return rc;
  60091. }
  60092. /*
  60093. ** Release a MemPage. This should be called once for each prior
  60094. ** call to btreeGetPage.
  60095. **
  60096. ** Page1 is a special case and must be released using releasePageOne().
  60097. */
  60098. static void releasePageNotNull(MemPage *pPage){
  60099. assert( pPage->aData );
  60100. assert( pPage->pBt );
  60101. assert( pPage->pDbPage!=0 );
  60102. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  60103. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  60104. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60105. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  60106. }
  60107. static void releasePage(MemPage *pPage){
  60108. if( pPage ) releasePageNotNull(pPage);
  60109. }
  60110. static void releasePageOne(MemPage *pPage){
  60111. assert( pPage!=0 );
  60112. assert( pPage->aData );
  60113. assert( pPage->pBt );
  60114. assert( pPage->pDbPage!=0 );
  60115. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  60116. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  60117. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60118. sqlite3PagerUnrefPageOne(pPage->pDbPage);
  60119. }
  60120. /*
  60121. ** Get an unused page.
  60122. **
  60123. ** This works just like btreeGetPage() with the addition:
  60124. **
  60125. ** * If the page is already in use for some other purpose, immediately
  60126. ** release it and return an SQLITE_CURRUPT error.
  60127. ** * Make sure the isInit flag is clear
  60128. */
  60129. static int btreeGetUnusedPage(
  60130. BtShared *pBt, /* The btree */
  60131. Pgno pgno, /* Number of the page to fetch */
  60132. MemPage **ppPage, /* Return the page in this parameter */
  60133. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  60134. ){
  60135. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  60136. if( rc==SQLITE_OK ){
  60137. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  60138. releasePage(*ppPage);
  60139. *ppPage = 0;
  60140. return SQLITE_CORRUPT_BKPT;
  60141. }
  60142. (*ppPage)->isInit = 0;
  60143. }else{
  60144. *ppPage = 0;
  60145. }
  60146. return rc;
  60147. }
  60148. /*
  60149. ** During a rollback, when the pager reloads information into the cache
  60150. ** so that the cache is restored to its original state at the start of
  60151. ** the transaction, for each page restored this routine is called.
  60152. **
  60153. ** This routine needs to reset the extra data section at the end of the
  60154. ** page to agree with the restored data.
  60155. */
  60156. static void pageReinit(DbPage *pData){
  60157. MemPage *pPage;
  60158. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  60159. assert( sqlite3PagerPageRefcount(pData)>0 );
  60160. if( pPage->isInit ){
  60161. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60162. pPage->isInit = 0;
  60163. if( sqlite3PagerPageRefcount(pData)>1 ){
  60164. /* pPage might not be a btree page; it might be an overflow page
  60165. ** or ptrmap page or a free page. In those cases, the following
  60166. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  60167. ** But no harm is done by this. And it is very important that
  60168. ** btreeInitPage() be called on every btree page so we make
  60169. ** the call for every page that comes in for re-initing. */
  60170. btreeInitPage(pPage);
  60171. }
  60172. }
  60173. }
  60174. /*
  60175. ** Invoke the busy handler for a btree.
  60176. */
  60177. static int btreeInvokeBusyHandler(void *pArg){
  60178. BtShared *pBt = (BtShared*)pArg;
  60179. assert( pBt->db );
  60180. assert( sqlite3_mutex_held(pBt->db->mutex) );
  60181. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
  60182. sqlite3PagerFile(pBt->pPager));
  60183. }
  60184. /*
  60185. ** Open a database file.
  60186. **
  60187. ** zFilename is the name of the database file. If zFilename is NULL
  60188. ** then an ephemeral database is created. The ephemeral database might
  60189. ** be exclusively in memory, or it might use a disk-based memory cache.
  60190. ** Either way, the ephemeral database will be automatically deleted
  60191. ** when sqlite3BtreeClose() is called.
  60192. **
  60193. ** If zFilename is ":memory:" then an in-memory database is created
  60194. ** that is automatically destroyed when it is closed.
  60195. **
  60196. ** The "flags" parameter is a bitmask that might contain bits like
  60197. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  60198. **
  60199. ** If the database is already opened in the same database connection
  60200. ** and we are in shared cache mode, then the open will fail with an
  60201. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  60202. ** objects in the same database connection since doing so will lead
  60203. ** to problems with locking.
  60204. */
  60205. SQLITE_PRIVATE int sqlite3BtreeOpen(
  60206. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  60207. const char *zFilename, /* Name of the file containing the BTree database */
  60208. sqlite3 *db, /* Associated database handle */
  60209. Btree **ppBtree, /* Pointer to new Btree object written here */
  60210. int flags, /* Options */
  60211. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  60212. ){
  60213. BtShared *pBt = 0; /* Shared part of btree structure */
  60214. Btree *p; /* Handle to return */
  60215. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  60216. int rc = SQLITE_OK; /* Result code from this function */
  60217. u8 nReserve; /* Byte of unused space on each page */
  60218. unsigned char zDbHeader[100]; /* Database header content */
  60219. /* True if opening an ephemeral, temporary database */
  60220. const int isTempDb = zFilename==0 || zFilename[0]==0;
  60221. /* Set the variable isMemdb to true for an in-memory database, or
  60222. ** false for a file-based database.
  60223. */
  60224. #ifdef SQLITE_OMIT_MEMORYDB
  60225. const int isMemdb = 0;
  60226. #else
  60227. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  60228. || (isTempDb && sqlite3TempInMemory(db))
  60229. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  60230. #endif
  60231. assert( db!=0 );
  60232. assert( pVfs!=0 );
  60233. assert( sqlite3_mutex_held(db->mutex) );
  60234. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  60235. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  60236. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  60237. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  60238. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  60239. if( isMemdb ){
  60240. flags |= BTREE_MEMORY;
  60241. }
  60242. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  60243. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  60244. }
  60245. p = sqlite3MallocZero(sizeof(Btree));
  60246. if( !p ){
  60247. return SQLITE_NOMEM_BKPT;
  60248. }
  60249. p->inTrans = TRANS_NONE;
  60250. p->db = db;
  60251. #ifndef SQLITE_OMIT_SHARED_CACHE
  60252. p->lock.pBtree = p;
  60253. p->lock.iTable = 1;
  60254. #endif
  60255. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  60256. /*
  60257. ** If this Btree is a candidate for shared cache, try to find an
  60258. ** existing BtShared object that we can share with
  60259. */
  60260. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  60261. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  60262. int nFilename = sqlite3Strlen30(zFilename)+1;
  60263. int nFullPathname = pVfs->mxPathname+1;
  60264. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  60265. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  60266. p->sharable = 1;
  60267. if( !zFullPathname ){
  60268. sqlite3_free(p);
  60269. return SQLITE_NOMEM_BKPT;
  60270. }
  60271. if( isMemdb ){
  60272. memcpy(zFullPathname, zFilename, nFilename);
  60273. }else{
  60274. rc = sqlite3OsFullPathname(pVfs, zFilename,
  60275. nFullPathname, zFullPathname);
  60276. if( rc ){
  60277. sqlite3_free(zFullPathname);
  60278. sqlite3_free(p);
  60279. return rc;
  60280. }
  60281. }
  60282. #if SQLITE_THREADSAFE
  60283. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  60284. sqlite3_mutex_enter(mutexOpen);
  60285. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  60286. sqlite3_mutex_enter(mutexShared);
  60287. #endif
  60288. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  60289. assert( pBt->nRef>0 );
  60290. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  60291. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  60292. int iDb;
  60293. for(iDb=db->nDb-1; iDb>=0; iDb--){
  60294. Btree *pExisting = db->aDb[iDb].pBt;
  60295. if( pExisting && pExisting->pBt==pBt ){
  60296. sqlite3_mutex_leave(mutexShared);
  60297. sqlite3_mutex_leave(mutexOpen);
  60298. sqlite3_free(zFullPathname);
  60299. sqlite3_free(p);
  60300. return SQLITE_CONSTRAINT;
  60301. }
  60302. }
  60303. p->pBt = pBt;
  60304. pBt->nRef++;
  60305. break;
  60306. }
  60307. }
  60308. sqlite3_mutex_leave(mutexShared);
  60309. sqlite3_free(zFullPathname);
  60310. }
  60311. #ifdef SQLITE_DEBUG
  60312. else{
  60313. /* In debug mode, we mark all persistent databases as sharable
  60314. ** even when they are not. This exercises the locking code and
  60315. ** gives more opportunity for asserts(sqlite3_mutex_held())
  60316. ** statements to find locking problems.
  60317. */
  60318. p->sharable = 1;
  60319. }
  60320. #endif
  60321. }
  60322. #endif
  60323. if( pBt==0 ){
  60324. /*
  60325. ** The following asserts make sure that structures used by the btree are
  60326. ** the right size. This is to guard against size changes that result
  60327. ** when compiling on a different architecture.
  60328. */
  60329. assert( sizeof(i64)==8 );
  60330. assert( sizeof(u64)==8 );
  60331. assert( sizeof(u32)==4 );
  60332. assert( sizeof(u16)==2 );
  60333. assert( sizeof(Pgno)==4 );
  60334. pBt = sqlite3MallocZero( sizeof(*pBt) );
  60335. if( pBt==0 ){
  60336. rc = SQLITE_NOMEM_BKPT;
  60337. goto btree_open_out;
  60338. }
  60339. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  60340. sizeof(MemPage), flags, vfsFlags, pageReinit);
  60341. if( rc==SQLITE_OK ){
  60342. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  60343. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  60344. }
  60345. if( rc!=SQLITE_OK ){
  60346. goto btree_open_out;
  60347. }
  60348. pBt->openFlags = (u8)flags;
  60349. pBt->db = db;
  60350. sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  60351. p->pBt = pBt;
  60352. pBt->pCursor = 0;
  60353. pBt->pPage1 = 0;
  60354. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  60355. #if defined(SQLITE_SECURE_DELETE)
  60356. pBt->btsFlags |= BTS_SECURE_DELETE;
  60357. #elif defined(SQLITE_FAST_SECURE_DELETE)
  60358. pBt->btsFlags |= BTS_OVERWRITE;
  60359. #endif
  60360. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  60361. ** determined by the 2-byte integer located at an offset of 16 bytes from
  60362. ** the beginning of the database file. */
  60363. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  60364. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  60365. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  60366. pBt->pageSize = 0;
  60367. #ifndef SQLITE_OMIT_AUTOVACUUM
  60368. /* If the magic name ":memory:" will create an in-memory database, then
  60369. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  60370. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  60371. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  60372. ** regular file-name. In this case the auto-vacuum applies as per normal.
  60373. */
  60374. if( zFilename && !isMemdb ){
  60375. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  60376. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  60377. }
  60378. #endif
  60379. nReserve = 0;
  60380. }else{
  60381. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  60382. ** determined by the one-byte unsigned integer found at an offset of 20
  60383. ** into the database file header. */
  60384. nReserve = zDbHeader[20];
  60385. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  60386. #ifndef SQLITE_OMIT_AUTOVACUUM
  60387. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  60388. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  60389. #endif
  60390. }
  60391. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  60392. if( rc ) goto btree_open_out;
  60393. pBt->usableSize = pBt->pageSize - nReserve;
  60394. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  60395. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  60396. /* Add the new BtShared object to the linked list sharable BtShareds.
  60397. */
  60398. pBt->nRef = 1;
  60399. if( p->sharable ){
  60400. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  60401. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  60402. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  60403. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  60404. if( pBt->mutex==0 ){
  60405. rc = SQLITE_NOMEM_BKPT;
  60406. goto btree_open_out;
  60407. }
  60408. }
  60409. sqlite3_mutex_enter(mutexShared);
  60410. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  60411. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  60412. sqlite3_mutex_leave(mutexShared);
  60413. }
  60414. #endif
  60415. }
  60416. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  60417. /* If the new Btree uses a sharable pBtShared, then link the new
  60418. ** Btree into the list of all sharable Btrees for the same connection.
  60419. ** The list is kept in ascending order by pBt address.
  60420. */
  60421. if( p->sharable ){
  60422. int i;
  60423. Btree *pSib;
  60424. for(i=0; i<db->nDb; i++){
  60425. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  60426. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  60427. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  60428. p->pNext = pSib;
  60429. p->pPrev = 0;
  60430. pSib->pPrev = p;
  60431. }else{
  60432. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  60433. pSib = pSib->pNext;
  60434. }
  60435. p->pNext = pSib->pNext;
  60436. p->pPrev = pSib;
  60437. if( p->pNext ){
  60438. p->pNext->pPrev = p;
  60439. }
  60440. pSib->pNext = p;
  60441. }
  60442. break;
  60443. }
  60444. }
  60445. }
  60446. #endif
  60447. *ppBtree = p;
  60448. btree_open_out:
  60449. if( rc!=SQLITE_OK ){
  60450. if( pBt && pBt->pPager ){
  60451. sqlite3PagerClose(pBt->pPager, 0);
  60452. }
  60453. sqlite3_free(pBt);
  60454. sqlite3_free(p);
  60455. *ppBtree = 0;
  60456. }else{
  60457. sqlite3_file *pFile;
  60458. /* If the B-Tree was successfully opened, set the pager-cache size to the
  60459. ** default value. Except, when opening on an existing shared pager-cache,
  60460. ** do not change the pager-cache size.
  60461. */
  60462. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  60463. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  60464. }
  60465. pFile = sqlite3PagerFile(pBt->pPager);
  60466. if( pFile->pMethods ){
  60467. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  60468. }
  60469. }
  60470. if( mutexOpen ){
  60471. assert( sqlite3_mutex_held(mutexOpen) );
  60472. sqlite3_mutex_leave(mutexOpen);
  60473. }
  60474. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  60475. return rc;
  60476. }
  60477. /*
  60478. ** Decrement the BtShared.nRef counter. When it reaches zero,
  60479. ** remove the BtShared structure from the sharing list. Return
  60480. ** true if the BtShared.nRef counter reaches zero and return
  60481. ** false if it is still positive.
  60482. */
  60483. static int removeFromSharingList(BtShared *pBt){
  60484. #ifndef SQLITE_OMIT_SHARED_CACHE
  60485. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  60486. BtShared *pList;
  60487. int removed = 0;
  60488. assert( sqlite3_mutex_notheld(pBt->mutex) );
  60489. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  60490. sqlite3_mutex_enter(pMaster);
  60491. pBt->nRef--;
  60492. if( pBt->nRef<=0 ){
  60493. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  60494. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  60495. }else{
  60496. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  60497. while( ALWAYS(pList) && pList->pNext!=pBt ){
  60498. pList=pList->pNext;
  60499. }
  60500. if( ALWAYS(pList) ){
  60501. pList->pNext = pBt->pNext;
  60502. }
  60503. }
  60504. if( SQLITE_THREADSAFE ){
  60505. sqlite3_mutex_free(pBt->mutex);
  60506. }
  60507. removed = 1;
  60508. }
  60509. sqlite3_mutex_leave(pMaster);
  60510. return removed;
  60511. #else
  60512. return 1;
  60513. #endif
  60514. }
  60515. /*
  60516. ** Make sure pBt->pTmpSpace points to an allocation of
  60517. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  60518. ** pointer.
  60519. */
  60520. static void allocateTempSpace(BtShared *pBt){
  60521. if( !pBt->pTmpSpace ){
  60522. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  60523. /* One of the uses of pBt->pTmpSpace is to format cells before
  60524. ** inserting them into a leaf page (function fillInCell()). If
  60525. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  60526. ** by the various routines that manipulate binary cells. Which
  60527. ** can mean that fillInCell() only initializes the first 2 or 3
  60528. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  60529. ** it into a database page. This is not actually a problem, but it
  60530. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  60531. ** data is passed to system call write(). So to avoid this error,
  60532. ** zero the first 4 bytes of temp space here.
  60533. **
  60534. ** Also: Provide four bytes of initialized space before the
  60535. ** beginning of pTmpSpace as an area available to prepend the
  60536. ** left-child pointer to the beginning of a cell.
  60537. */
  60538. if( pBt->pTmpSpace ){
  60539. memset(pBt->pTmpSpace, 0, 8);
  60540. pBt->pTmpSpace += 4;
  60541. }
  60542. }
  60543. }
  60544. /*
  60545. ** Free the pBt->pTmpSpace allocation
  60546. */
  60547. static void freeTempSpace(BtShared *pBt){
  60548. if( pBt->pTmpSpace ){
  60549. pBt->pTmpSpace -= 4;
  60550. sqlite3PageFree(pBt->pTmpSpace);
  60551. pBt->pTmpSpace = 0;
  60552. }
  60553. }
  60554. /*
  60555. ** Close an open database and invalidate all cursors.
  60556. */
  60557. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  60558. BtShared *pBt = p->pBt;
  60559. BtCursor *pCur;
  60560. /* Close all cursors opened via this handle. */
  60561. assert( sqlite3_mutex_held(p->db->mutex) );
  60562. sqlite3BtreeEnter(p);
  60563. pCur = pBt->pCursor;
  60564. while( pCur ){
  60565. BtCursor *pTmp = pCur;
  60566. pCur = pCur->pNext;
  60567. if( pTmp->pBtree==p ){
  60568. sqlite3BtreeCloseCursor(pTmp);
  60569. }
  60570. }
  60571. /* Rollback any active transaction and free the handle structure.
  60572. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  60573. ** this handle.
  60574. */
  60575. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  60576. sqlite3BtreeLeave(p);
  60577. /* If there are still other outstanding references to the shared-btree
  60578. ** structure, return now. The remainder of this procedure cleans
  60579. ** up the shared-btree.
  60580. */
  60581. assert( p->wantToLock==0 && p->locked==0 );
  60582. if( !p->sharable || removeFromSharingList(pBt) ){
  60583. /* The pBt is no longer on the sharing list, so we can access
  60584. ** it without having to hold the mutex.
  60585. **
  60586. ** Clean out and delete the BtShared object.
  60587. */
  60588. assert( !pBt->pCursor );
  60589. sqlite3PagerClose(pBt->pPager, p->db);
  60590. if( pBt->xFreeSchema && pBt->pSchema ){
  60591. pBt->xFreeSchema(pBt->pSchema);
  60592. }
  60593. sqlite3DbFree(0, pBt->pSchema);
  60594. freeTempSpace(pBt);
  60595. sqlite3_free(pBt);
  60596. }
  60597. #ifndef SQLITE_OMIT_SHARED_CACHE
  60598. assert( p->wantToLock==0 );
  60599. assert( p->locked==0 );
  60600. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  60601. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  60602. #endif
  60603. sqlite3_free(p);
  60604. return SQLITE_OK;
  60605. }
  60606. /*
  60607. ** Change the "soft" limit on the number of pages in the cache.
  60608. ** Unused and unmodified pages will be recycled when the number of
  60609. ** pages in the cache exceeds this soft limit. But the size of the
  60610. ** cache is allowed to grow larger than this limit if it contains
  60611. ** dirty pages or pages still in active use.
  60612. */
  60613. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  60614. BtShared *pBt = p->pBt;
  60615. assert( sqlite3_mutex_held(p->db->mutex) );
  60616. sqlite3BtreeEnter(p);
  60617. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  60618. sqlite3BtreeLeave(p);
  60619. return SQLITE_OK;
  60620. }
  60621. /*
  60622. ** Change the "spill" limit on the number of pages in the cache.
  60623. ** If the number of pages exceeds this limit during a write transaction,
  60624. ** the pager might attempt to "spill" pages to the journal early in
  60625. ** order to free up memory.
  60626. **
  60627. ** The value returned is the current spill size. If zero is passed
  60628. ** as an argument, no changes are made to the spill size setting, so
  60629. ** using mxPage of 0 is a way to query the current spill size.
  60630. */
  60631. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  60632. BtShared *pBt = p->pBt;
  60633. int res;
  60634. assert( sqlite3_mutex_held(p->db->mutex) );
  60635. sqlite3BtreeEnter(p);
  60636. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  60637. sqlite3BtreeLeave(p);
  60638. return res;
  60639. }
  60640. #if SQLITE_MAX_MMAP_SIZE>0
  60641. /*
  60642. ** Change the limit on the amount of the database file that may be
  60643. ** memory mapped.
  60644. */
  60645. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  60646. BtShared *pBt = p->pBt;
  60647. assert( sqlite3_mutex_held(p->db->mutex) );
  60648. sqlite3BtreeEnter(p);
  60649. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  60650. sqlite3BtreeLeave(p);
  60651. return SQLITE_OK;
  60652. }
  60653. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  60654. /*
  60655. ** Change the way data is synced to disk in order to increase or decrease
  60656. ** how well the database resists damage due to OS crashes and power
  60657. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  60658. ** there is a high probability of damage) Level 2 is the default. There
  60659. ** is a very low but non-zero probability of damage. Level 3 reduces the
  60660. ** probability of damage to near zero but with a write performance reduction.
  60661. */
  60662. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  60663. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  60664. Btree *p, /* The btree to set the safety level on */
  60665. unsigned pgFlags /* Various PAGER_* flags */
  60666. ){
  60667. BtShared *pBt = p->pBt;
  60668. assert( sqlite3_mutex_held(p->db->mutex) );
  60669. sqlite3BtreeEnter(p);
  60670. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  60671. sqlite3BtreeLeave(p);
  60672. return SQLITE_OK;
  60673. }
  60674. #endif
  60675. /*
  60676. ** Change the default pages size and the number of reserved bytes per page.
  60677. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  60678. ** without changing anything.
  60679. **
  60680. ** The page size must be a power of 2 between 512 and 65536. If the page
  60681. ** size supplied does not meet this constraint then the page size is not
  60682. ** changed.
  60683. **
  60684. ** Page sizes are constrained to be a power of two so that the region
  60685. ** of the database file used for locking (beginning at PENDING_BYTE,
  60686. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  60687. ** at the beginning of a page.
  60688. **
  60689. ** If parameter nReserve is less than zero, then the number of reserved
  60690. ** bytes per page is left unchanged.
  60691. **
  60692. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  60693. ** and autovacuum mode can no longer be changed.
  60694. */
  60695. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  60696. int rc = SQLITE_OK;
  60697. BtShared *pBt = p->pBt;
  60698. assert( nReserve>=-1 && nReserve<=255 );
  60699. sqlite3BtreeEnter(p);
  60700. #if SQLITE_HAS_CODEC
  60701. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  60702. #endif
  60703. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  60704. sqlite3BtreeLeave(p);
  60705. return SQLITE_READONLY;
  60706. }
  60707. if( nReserve<0 ){
  60708. nReserve = pBt->pageSize - pBt->usableSize;
  60709. }
  60710. assert( nReserve>=0 && nReserve<=255 );
  60711. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  60712. ((pageSize-1)&pageSize)==0 ){
  60713. assert( (pageSize & 7)==0 );
  60714. assert( !pBt->pCursor );
  60715. pBt->pageSize = (u32)pageSize;
  60716. freeTempSpace(pBt);
  60717. }
  60718. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  60719. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  60720. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  60721. sqlite3BtreeLeave(p);
  60722. return rc;
  60723. }
  60724. /*
  60725. ** Return the currently defined page size
  60726. */
  60727. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  60728. return p->pBt->pageSize;
  60729. }
  60730. /*
  60731. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  60732. ** may only be called if it is guaranteed that the b-tree mutex is already
  60733. ** held.
  60734. **
  60735. ** This is useful in one special case in the backup API code where it is
  60736. ** known that the shared b-tree mutex is held, but the mutex on the
  60737. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  60738. ** were to be called, it might collide with some other operation on the
  60739. ** database handle that owns *p, causing undefined behavior.
  60740. */
  60741. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  60742. int n;
  60743. assert( sqlite3_mutex_held(p->pBt->mutex) );
  60744. n = p->pBt->pageSize - p->pBt->usableSize;
  60745. return n;
  60746. }
  60747. /*
  60748. ** Return the number of bytes of space at the end of every page that
  60749. ** are intentually left unused. This is the "reserved" space that is
  60750. ** sometimes used by extensions.
  60751. **
  60752. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  60753. ** greater of the current reserved space and the maximum requested
  60754. ** reserve space.
  60755. */
  60756. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  60757. int n;
  60758. sqlite3BtreeEnter(p);
  60759. n = sqlite3BtreeGetReserveNoMutex(p);
  60760. #ifdef SQLITE_HAS_CODEC
  60761. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  60762. #endif
  60763. sqlite3BtreeLeave(p);
  60764. return n;
  60765. }
  60766. /*
  60767. ** Set the maximum page count for a database if mxPage is positive.
  60768. ** No changes are made if mxPage is 0 or negative.
  60769. ** Regardless of the value of mxPage, return the maximum page count.
  60770. */
  60771. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  60772. int n;
  60773. sqlite3BtreeEnter(p);
  60774. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  60775. sqlite3BtreeLeave(p);
  60776. return n;
  60777. }
  60778. /*
  60779. ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
  60780. **
  60781. ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
  60782. ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
  60783. ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
  60784. ** newFlag==(-1) No changes
  60785. **
  60786. ** This routine acts as a query if newFlag is less than zero
  60787. **
  60788. ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
  60789. ** freelist leaf pages are not written back to the database. Thus in-page
  60790. ** deleted content is cleared, but freelist deleted content is not.
  60791. **
  60792. ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
  60793. ** that freelist leaf pages are written back into the database, increasing
  60794. ** the amount of disk I/O.
  60795. */
  60796. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  60797. int b;
  60798. if( p==0 ) return 0;
  60799. sqlite3BtreeEnter(p);
  60800. assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
  60801. assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
  60802. if( newFlag>=0 ){
  60803. p->pBt->btsFlags &= ~BTS_FAST_SECURE;
  60804. p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
  60805. }
  60806. b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
  60807. sqlite3BtreeLeave(p);
  60808. return b;
  60809. }
  60810. /*
  60811. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  60812. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  60813. ** is disabled. The default value for the auto-vacuum property is
  60814. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  60815. */
  60816. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  60817. #ifdef SQLITE_OMIT_AUTOVACUUM
  60818. return SQLITE_READONLY;
  60819. #else
  60820. BtShared *pBt = p->pBt;
  60821. int rc = SQLITE_OK;
  60822. u8 av = (u8)autoVacuum;
  60823. sqlite3BtreeEnter(p);
  60824. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  60825. rc = SQLITE_READONLY;
  60826. }else{
  60827. pBt->autoVacuum = av ?1:0;
  60828. pBt->incrVacuum = av==2 ?1:0;
  60829. }
  60830. sqlite3BtreeLeave(p);
  60831. return rc;
  60832. #endif
  60833. }
  60834. /*
  60835. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  60836. ** enabled 1 is returned. Otherwise 0.
  60837. */
  60838. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  60839. #ifdef SQLITE_OMIT_AUTOVACUUM
  60840. return BTREE_AUTOVACUUM_NONE;
  60841. #else
  60842. int rc;
  60843. sqlite3BtreeEnter(p);
  60844. rc = (
  60845. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  60846. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  60847. BTREE_AUTOVACUUM_INCR
  60848. );
  60849. sqlite3BtreeLeave(p);
  60850. return rc;
  60851. #endif
  60852. }
  60853. /*
  60854. ** If the user has not set the safety-level for this database connection
  60855. ** using "PRAGMA synchronous", and if the safety-level is not already
  60856. ** set to the value passed to this function as the second parameter,
  60857. ** set it so.
  60858. */
  60859. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
  60860. && !defined(SQLITE_OMIT_WAL)
  60861. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  60862. sqlite3 *db;
  60863. Db *pDb;
  60864. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  60865. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  60866. if( pDb->bSyncSet==0
  60867. && pDb->safety_level!=safety_level
  60868. && pDb!=&db->aDb[1]
  60869. ){
  60870. pDb->safety_level = safety_level;
  60871. sqlite3PagerSetFlags(pBt->pPager,
  60872. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  60873. }
  60874. }
  60875. }
  60876. #else
  60877. # define setDefaultSyncFlag(pBt,safety_level)
  60878. #endif
  60879. /* Forward declaration */
  60880. static int newDatabase(BtShared*);
  60881. /*
  60882. ** Get a reference to pPage1 of the database file. This will
  60883. ** also acquire a readlock on that file.
  60884. **
  60885. ** SQLITE_OK is returned on success. If the file is not a
  60886. ** well-formed database file, then SQLITE_CORRUPT is returned.
  60887. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  60888. ** is returned if we run out of memory.
  60889. */
  60890. static int lockBtree(BtShared *pBt){
  60891. int rc; /* Result code from subfunctions */
  60892. MemPage *pPage1; /* Page 1 of the database file */
  60893. int nPage; /* Number of pages in the database */
  60894. int nPageFile = 0; /* Number of pages in the database file */
  60895. int nPageHeader; /* Number of pages in the database according to hdr */
  60896. assert( sqlite3_mutex_held(pBt->mutex) );
  60897. assert( pBt->pPage1==0 );
  60898. rc = sqlite3PagerSharedLock(pBt->pPager);
  60899. if( rc!=SQLITE_OK ) return rc;
  60900. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  60901. if( rc!=SQLITE_OK ) return rc;
  60902. /* Do some checking to help insure the file we opened really is
  60903. ** a valid database file.
  60904. */
  60905. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  60906. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  60907. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  60908. nPage = nPageFile;
  60909. }
  60910. if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
  60911. nPage = 0;
  60912. }
  60913. if( nPage>0 ){
  60914. u32 pageSize;
  60915. u32 usableSize;
  60916. u8 *page1 = pPage1->aData;
  60917. rc = SQLITE_NOTADB;
  60918. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  60919. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  60920. ** 61 74 20 33 00. */
  60921. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  60922. goto page1_init_failed;
  60923. }
  60924. #ifdef SQLITE_OMIT_WAL
  60925. if( page1[18]>1 ){
  60926. pBt->btsFlags |= BTS_READ_ONLY;
  60927. }
  60928. if( page1[19]>1 ){
  60929. goto page1_init_failed;
  60930. }
  60931. #else
  60932. if( page1[18]>2 ){
  60933. pBt->btsFlags |= BTS_READ_ONLY;
  60934. }
  60935. if( page1[19]>2 ){
  60936. goto page1_init_failed;
  60937. }
  60938. /* If the write version is set to 2, this database should be accessed
  60939. ** in WAL mode. If the log is not already open, open it now. Then
  60940. ** return SQLITE_OK and return without populating BtShared.pPage1.
  60941. ** The caller detects this and calls this function again. This is
  60942. ** required as the version of page 1 currently in the page1 buffer
  60943. ** may not be the latest version - there may be a newer one in the log
  60944. ** file.
  60945. */
  60946. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  60947. int isOpen = 0;
  60948. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  60949. if( rc!=SQLITE_OK ){
  60950. goto page1_init_failed;
  60951. }else{
  60952. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  60953. if( isOpen==0 ){
  60954. releasePageOne(pPage1);
  60955. return SQLITE_OK;
  60956. }
  60957. }
  60958. rc = SQLITE_NOTADB;
  60959. }else{
  60960. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  60961. }
  60962. #endif
  60963. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  60964. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  60965. **
  60966. ** The original design allowed these amounts to vary, but as of
  60967. ** version 3.6.0, we require them to be fixed.
  60968. */
  60969. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  60970. goto page1_init_failed;
  60971. }
  60972. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  60973. ** determined by the 2-byte integer located at an offset of 16 bytes from
  60974. ** the beginning of the database file. */
  60975. pageSize = (page1[16]<<8) | (page1[17]<<16);
  60976. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  60977. ** between 512 and 65536 inclusive. */
  60978. if( ((pageSize-1)&pageSize)!=0
  60979. || pageSize>SQLITE_MAX_PAGE_SIZE
  60980. || pageSize<=256
  60981. ){
  60982. goto page1_init_failed;
  60983. }
  60984. assert( (pageSize & 7)==0 );
  60985. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  60986. ** integer at offset 20 is the number of bytes of space at the end of
  60987. ** each page to reserve for extensions.
  60988. **
  60989. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  60990. ** determined by the one-byte unsigned integer found at an offset of 20
  60991. ** into the database file header. */
  60992. usableSize = pageSize - page1[20];
  60993. if( (u32)pageSize!=pBt->pageSize ){
  60994. /* After reading the first page of the database assuming a page size
  60995. ** of BtShared.pageSize, we have discovered that the page-size is
  60996. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  60997. ** zero and return SQLITE_OK. The caller will call this function
  60998. ** again with the correct page-size.
  60999. */
  61000. releasePageOne(pPage1);
  61001. pBt->usableSize = usableSize;
  61002. pBt->pageSize = pageSize;
  61003. freeTempSpace(pBt);
  61004. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  61005. pageSize-usableSize);
  61006. return rc;
  61007. }
  61008. if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
  61009. rc = SQLITE_CORRUPT_BKPT;
  61010. goto page1_init_failed;
  61011. }
  61012. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  61013. ** be less than 480. In other words, if the page size is 512, then the
  61014. ** reserved space size cannot exceed 32. */
  61015. if( usableSize<480 ){
  61016. goto page1_init_failed;
  61017. }
  61018. pBt->pageSize = pageSize;
  61019. pBt->usableSize = usableSize;
  61020. #ifndef SQLITE_OMIT_AUTOVACUUM
  61021. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  61022. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  61023. #endif
  61024. }
  61025. /* maxLocal is the maximum amount of payload to store locally for
  61026. ** a cell. Make sure it is small enough so that at least minFanout
  61027. ** cells can will fit on one page. We assume a 10-byte page header.
  61028. ** Besides the payload, the cell must store:
  61029. ** 2-byte pointer to the cell
  61030. ** 4-byte child pointer
  61031. ** 9-byte nKey value
  61032. ** 4-byte nData value
  61033. ** 4-byte overflow page pointer
  61034. ** So a cell consists of a 2-byte pointer, a header which is as much as
  61035. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  61036. ** page pointer.
  61037. */
  61038. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  61039. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  61040. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  61041. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  61042. if( pBt->maxLocal>127 ){
  61043. pBt->max1bytePayload = 127;
  61044. }else{
  61045. pBt->max1bytePayload = (u8)pBt->maxLocal;
  61046. }
  61047. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  61048. pBt->pPage1 = pPage1;
  61049. pBt->nPage = nPage;
  61050. return SQLITE_OK;
  61051. page1_init_failed:
  61052. releasePageOne(pPage1);
  61053. pBt->pPage1 = 0;
  61054. return rc;
  61055. }
  61056. #ifndef NDEBUG
  61057. /*
  61058. ** Return the number of cursors open on pBt. This is for use
  61059. ** in assert() expressions, so it is only compiled if NDEBUG is not
  61060. ** defined.
  61061. **
  61062. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  61063. ** false then all cursors are counted.
  61064. **
  61065. ** For the purposes of this routine, a cursor is any cursor that
  61066. ** is capable of reading or writing to the database. Cursors that
  61067. ** have been tripped into the CURSOR_FAULT state are not counted.
  61068. */
  61069. static int countValidCursors(BtShared *pBt, int wrOnly){
  61070. BtCursor *pCur;
  61071. int r = 0;
  61072. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  61073. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  61074. && pCur->eState!=CURSOR_FAULT ) r++;
  61075. }
  61076. return r;
  61077. }
  61078. #endif
  61079. /*
  61080. ** If there are no outstanding cursors and we are not in the middle
  61081. ** of a transaction but there is a read lock on the database, then
  61082. ** this routine unrefs the first page of the database file which
  61083. ** has the effect of releasing the read lock.
  61084. **
  61085. ** If there is a transaction in progress, this routine is a no-op.
  61086. */
  61087. static void unlockBtreeIfUnused(BtShared *pBt){
  61088. assert( sqlite3_mutex_held(pBt->mutex) );
  61089. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  61090. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  61091. MemPage *pPage1 = pBt->pPage1;
  61092. assert( pPage1->aData );
  61093. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  61094. pBt->pPage1 = 0;
  61095. releasePageOne(pPage1);
  61096. }
  61097. }
  61098. /*
  61099. ** If pBt points to an empty file then convert that empty file
  61100. ** into a new empty database by initializing the first page of
  61101. ** the database.
  61102. */
  61103. static int newDatabase(BtShared *pBt){
  61104. MemPage *pP1;
  61105. unsigned char *data;
  61106. int rc;
  61107. assert( sqlite3_mutex_held(pBt->mutex) );
  61108. if( pBt->nPage>0 ){
  61109. return SQLITE_OK;
  61110. }
  61111. pP1 = pBt->pPage1;
  61112. assert( pP1!=0 );
  61113. data = pP1->aData;
  61114. rc = sqlite3PagerWrite(pP1->pDbPage);
  61115. if( rc ) return rc;
  61116. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  61117. assert( sizeof(zMagicHeader)==16 );
  61118. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  61119. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  61120. data[18] = 1;
  61121. data[19] = 1;
  61122. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  61123. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  61124. data[21] = 64;
  61125. data[22] = 32;
  61126. data[23] = 32;
  61127. memset(&data[24], 0, 100-24);
  61128. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  61129. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  61130. #ifndef SQLITE_OMIT_AUTOVACUUM
  61131. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  61132. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  61133. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  61134. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  61135. #endif
  61136. pBt->nPage = 1;
  61137. data[31] = 1;
  61138. return SQLITE_OK;
  61139. }
  61140. /*
  61141. ** Initialize the first page of the database file (creating a database
  61142. ** consisting of a single page and no schema objects). Return SQLITE_OK
  61143. ** if successful, or an SQLite error code otherwise.
  61144. */
  61145. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  61146. int rc;
  61147. sqlite3BtreeEnter(p);
  61148. p->pBt->nPage = 0;
  61149. rc = newDatabase(p->pBt);
  61150. sqlite3BtreeLeave(p);
  61151. return rc;
  61152. }
  61153. /*
  61154. ** Attempt to start a new transaction. A write-transaction
  61155. ** is started if the second argument is nonzero, otherwise a read-
  61156. ** transaction. If the second argument is 2 or more and exclusive
  61157. ** transaction is started, meaning that no other process is allowed
  61158. ** to access the database. A preexisting transaction may not be
  61159. ** upgraded to exclusive by calling this routine a second time - the
  61160. ** exclusivity flag only works for a new transaction.
  61161. **
  61162. ** A write-transaction must be started before attempting any
  61163. ** changes to the database. None of the following routines
  61164. ** will work unless a transaction is started first:
  61165. **
  61166. ** sqlite3BtreeCreateTable()
  61167. ** sqlite3BtreeCreateIndex()
  61168. ** sqlite3BtreeClearTable()
  61169. ** sqlite3BtreeDropTable()
  61170. ** sqlite3BtreeInsert()
  61171. ** sqlite3BtreeDelete()
  61172. ** sqlite3BtreeUpdateMeta()
  61173. **
  61174. ** If an initial attempt to acquire the lock fails because of lock contention
  61175. ** and the database was previously unlocked, then invoke the busy handler
  61176. ** if there is one. But if there was previously a read-lock, do not
  61177. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  61178. ** returned when there is already a read-lock in order to avoid a deadlock.
  61179. **
  61180. ** Suppose there are two processes A and B. A has a read lock and B has
  61181. ** a reserved lock. B tries to promote to exclusive but is blocked because
  61182. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  61183. ** One or the other of the two processes must give way or there can be
  61184. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  61185. ** when A already has a read lock, we encourage A to give up and let B
  61186. ** proceed.
  61187. */
  61188. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  61189. BtShared *pBt = p->pBt;
  61190. int rc = SQLITE_OK;
  61191. sqlite3BtreeEnter(p);
  61192. btreeIntegrity(p);
  61193. /* If the btree is already in a write-transaction, or it
  61194. ** is already in a read-transaction and a read-transaction
  61195. ** is requested, this is a no-op.
  61196. */
  61197. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  61198. goto trans_begun;
  61199. }
  61200. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  61201. /* Write transactions are not possible on a read-only database */
  61202. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  61203. rc = SQLITE_READONLY;
  61204. goto trans_begun;
  61205. }
  61206. #ifndef SQLITE_OMIT_SHARED_CACHE
  61207. {
  61208. sqlite3 *pBlock = 0;
  61209. /* If another database handle has already opened a write transaction
  61210. ** on this shared-btree structure and a second write transaction is
  61211. ** requested, return SQLITE_LOCKED.
  61212. */
  61213. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  61214. || (pBt->btsFlags & BTS_PENDING)!=0
  61215. ){
  61216. pBlock = pBt->pWriter->db;
  61217. }else if( wrflag>1 ){
  61218. BtLock *pIter;
  61219. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  61220. if( pIter->pBtree!=p ){
  61221. pBlock = pIter->pBtree->db;
  61222. break;
  61223. }
  61224. }
  61225. }
  61226. if( pBlock ){
  61227. sqlite3ConnectionBlocked(p->db, pBlock);
  61228. rc = SQLITE_LOCKED_SHAREDCACHE;
  61229. goto trans_begun;
  61230. }
  61231. }
  61232. #endif
  61233. /* Any read-only or read-write transaction implies a read-lock on
  61234. ** page 1. So if some other shared-cache client already has a write-lock
  61235. ** on page 1, the transaction cannot be opened. */
  61236. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  61237. if( SQLITE_OK!=rc ) goto trans_begun;
  61238. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  61239. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  61240. do {
  61241. /* Call lockBtree() until either pBt->pPage1 is populated or
  61242. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  61243. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  61244. ** reading page 1 it discovers that the page-size of the database
  61245. ** file is not pBt->pageSize. In this case lockBtree() will update
  61246. ** pBt->pageSize to the page-size of the file on disk.
  61247. */
  61248. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  61249. if( rc==SQLITE_OK && wrflag ){
  61250. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  61251. rc = SQLITE_READONLY;
  61252. }else{
  61253. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  61254. if( rc==SQLITE_OK ){
  61255. rc = newDatabase(pBt);
  61256. }
  61257. }
  61258. }
  61259. if( rc!=SQLITE_OK ){
  61260. unlockBtreeIfUnused(pBt);
  61261. }
  61262. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  61263. btreeInvokeBusyHandler(pBt) );
  61264. sqlite3PagerResetLockTimeout(pBt->pPager);
  61265. if( rc==SQLITE_OK ){
  61266. if( p->inTrans==TRANS_NONE ){
  61267. pBt->nTransaction++;
  61268. #ifndef SQLITE_OMIT_SHARED_CACHE
  61269. if( p->sharable ){
  61270. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  61271. p->lock.eLock = READ_LOCK;
  61272. p->lock.pNext = pBt->pLock;
  61273. pBt->pLock = &p->lock;
  61274. }
  61275. #endif
  61276. }
  61277. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  61278. if( p->inTrans>pBt->inTransaction ){
  61279. pBt->inTransaction = p->inTrans;
  61280. }
  61281. if( wrflag ){
  61282. MemPage *pPage1 = pBt->pPage1;
  61283. #ifndef SQLITE_OMIT_SHARED_CACHE
  61284. assert( !pBt->pWriter );
  61285. pBt->pWriter = p;
  61286. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  61287. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  61288. #endif
  61289. /* If the db-size header field is incorrect (as it may be if an old
  61290. ** client has been writing the database file), update it now. Doing
  61291. ** this sooner rather than later means the database size can safely
  61292. ** re-read the database size from page 1 if a savepoint or transaction
  61293. ** rollback occurs within the transaction.
  61294. */
  61295. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  61296. rc = sqlite3PagerWrite(pPage1->pDbPage);
  61297. if( rc==SQLITE_OK ){
  61298. put4byte(&pPage1->aData[28], pBt->nPage);
  61299. }
  61300. }
  61301. }
  61302. }
  61303. trans_begun:
  61304. if( rc==SQLITE_OK && wrflag ){
  61305. /* This call makes sure that the pager has the correct number of
  61306. ** open savepoints. If the second parameter is greater than 0 and
  61307. ** the sub-journal is not already open, then it will be opened here.
  61308. */
  61309. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  61310. }
  61311. btreeIntegrity(p);
  61312. sqlite3BtreeLeave(p);
  61313. return rc;
  61314. }
  61315. #ifndef SQLITE_OMIT_AUTOVACUUM
  61316. /*
  61317. ** Set the pointer-map entries for all children of page pPage. Also, if
  61318. ** pPage contains cells that point to overflow pages, set the pointer
  61319. ** map entries for the overflow pages as well.
  61320. */
  61321. static int setChildPtrmaps(MemPage *pPage){
  61322. int i; /* Counter variable */
  61323. int nCell; /* Number of cells in page pPage */
  61324. int rc; /* Return code */
  61325. BtShared *pBt = pPage->pBt;
  61326. Pgno pgno = pPage->pgno;
  61327. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61328. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  61329. if( rc!=SQLITE_OK ) return rc;
  61330. nCell = pPage->nCell;
  61331. for(i=0; i<nCell; i++){
  61332. u8 *pCell = findCell(pPage, i);
  61333. ptrmapPutOvflPtr(pPage, pCell, &rc);
  61334. if( !pPage->leaf ){
  61335. Pgno childPgno = get4byte(pCell);
  61336. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  61337. }
  61338. }
  61339. if( !pPage->leaf ){
  61340. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  61341. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  61342. }
  61343. return rc;
  61344. }
  61345. /*
  61346. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  61347. ** that it points to iTo. Parameter eType describes the type of pointer to
  61348. ** be modified, as follows:
  61349. **
  61350. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  61351. ** page of pPage.
  61352. **
  61353. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  61354. ** page pointed to by one of the cells on pPage.
  61355. **
  61356. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  61357. ** overflow page in the list.
  61358. */
  61359. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  61360. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61361. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61362. if( eType==PTRMAP_OVERFLOW2 ){
  61363. /* The pointer is always the first 4 bytes of the page in this case. */
  61364. if( get4byte(pPage->aData)!=iFrom ){
  61365. return SQLITE_CORRUPT_PAGE(pPage);
  61366. }
  61367. put4byte(pPage->aData, iTo);
  61368. }else{
  61369. int i;
  61370. int nCell;
  61371. int rc;
  61372. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  61373. if( rc ) return rc;
  61374. nCell = pPage->nCell;
  61375. for(i=0; i<nCell; i++){
  61376. u8 *pCell = findCell(pPage, i);
  61377. if( eType==PTRMAP_OVERFLOW1 ){
  61378. CellInfo info;
  61379. pPage->xParseCell(pPage, pCell, &info);
  61380. if( info.nLocal<info.nPayload ){
  61381. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  61382. return SQLITE_CORRUPT_PAGE(pPage);
  61383. }
  61384. if( iFrom==get4byte(pCell+info.nSize-4) ){
  61385. put4byte(pCell+info.nSize-4, iTo);
  61386. break;
  61387. }
  61388. }
  61389. }else{
  61390. if( get4byte(pCell)==iFrom ){
  61391. put4byte(pCell, iTo);
  61392. break;
  61393. }
  61394. }
  61395. }
  61396. if( i==nCell ){
  61397. if( eType!=PTRMAP_BTREE ||
  61398. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  61399. return SQLITE_CORRUPT_PAGE(pPage);
  61400. }
  61401. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  61402. }
  61403. }
  61404. return SQLITE_OK;
  61405. }
  61406. /*
  61407. ** Move the open database page pDbPage to location iFreePage in the
  61408. ** database. The pDbPage reference remains valid.
  61409. **
  61410. ** The isCommit flag indicates that there is no need to remember that
  61411. ** the journal needs to be sync()ed before database page pDbPage->pgno
  61412. ** can be written to. The caller has already promised not to write to that
  61413. ** page.
  61414. */
  61415. static int relocatePage(
  61416. BtShared *pBt, /* Btree */
  61417. MemPage *pDbPage, /* Open page to move */
  61418. u8 eType, /* Pointer map 'type' entry for pDbPage */
  61419. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  61420. Pgno iFreePage, /* The location to move pDbPage to */
  61421. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  61422. ){
  61423. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  61424. Pgno iDbPage = pDbPage->pgno;
  61425. Pager *pPager = pBt->pPager;
  61426. int rc;
  61427. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  61428. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  61429. assert( sqlite3_mutex_held(pBt->mutex) );
  61430. assert( pDbPage->pBt==pBt );
  61431. /* Move page iDbPage from its current location to page number iFreePage */
  61432. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  61433. iDbPage, iFreePage, iPtrPage, eType));
  61434. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  61435. if( rc!=SQLITE_OK ){
  61436. return rc;
  61437. }
  61438. pDbPage->pgno = iFreePage;
  61439. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  61440. ** that point to overflow pages. The pointer map entries for all these
  61441. ** pages need to be changed.
  61442. **
  61443. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  61444. ** pointer to a subsequent overflow page. If this is the case, then
  61445. ** the pointer map needs to be updated for the subsequent overflow page.
  61446. */
  61447. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  61448. rc = setChildPtrmaps(pDbPage);
  61449. if( rc!=SQLITE_OK ){
  61450. return rc;
  61451. }
  61452. }else{
  61453. Pgno nextOvfl = get4byte(pDbPage->aData);
  61454. if( nextOvfl!=0 ){
  61455. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  61456. if( rc!=SQLITE_OK ){
  61457. return rc;
  61458. }
  61459. }
  61460. }
  61461. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  61462. ** that it points at iFreePage. Also fix the pointer map entry for
  61463. ** iPtrPage.
  61464. */
  61465. if( eType!=PTRMAP_ROOTPAGE ){
  61466. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  61467. if( rc!=SQLITE_OK ){
  61468. return rc;
  61469. }
  61470. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  61471. if( rc!=SQLITE_OK ){
  61472. releasePage(pPtrPage);
  61473. return rc;
  61474. }
  61475. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  61476. releasePage(pPtrPage);
  61477. if( rc==SQLITE_OK ){
  61478. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  61479. }
  61480. }
  61481. return rc;
  61482. }
  61483. /* Forward declaration required by incrVacuumStep(). */
  61484. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  61485. /*
  61486. ** Perform a single step of an incremental-vacuum. If successful, return
  61487. ** SQLITE_OK. If there is no work to do (and therefore no point in
  61488. ** calling this function again), return SQLITE_DONE. Or, if an error
  61489. ** occurs, return some other error code.
  61490. **
  61491. ** More specifically, this function attempts to re-organize the database so
  61492. ** that the last page of the file currently in use is no longer in use.
  61493. **
  61494. ** Parameter nFin is the number of pages that this database would contain
  61495. ** were this function called until it returns SQLITE_DONE.
  61496. **
  61497. ** If the bCommit parameter is non-zero, this function assumes that the
  61498. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  61499. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  61500. ** operation, or false for an incremental vacuum.
  61501. */
  61502. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  61503. Pgno nFreeList; /* Number of pages still on the free-list */
  61504. int rc;
  61505. assert( sqlite3_mutex_held(pBt->mutex) );
  61506. assert( iLastPg>nFin );
  61507. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  61508. u8 eType;
  61509. Pgno iPtrPage;
  61510. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  61511. if( nFreeList==0 ){
  61512. return SQLITE_DONE;
  61513. }
  61514. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  61515. if( rc!=SQLITE_OK ){
  61516. return rc;
  61517. }
  61518. if( eType==PTRMAP_ROOTPAGE ){
  61519. return SQLITE_CORRUPT_BKPT;
  61520. }
  61521. if( eType==PTRMAP_FREEPAGE ){
  61522. if( bCommit==0 ){
  61523. /* Remove the page from the files free-list. This is not required
  61524. ** if bCommit is non-zero. In that case, the free-list will be
  61525. ** truncated to zero after this function returns, so it doesn't
  61526. ** matter if it still contains some garbage entries.
  61527. */
  61528. Pgno iFreePg;
  61529. MemPage *pFreePg;
  61530. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  61531. if( rc!=SQLITE_OK ){
  61532. return rc;
  61533. }
  61534. assert( iFreePg==iLastPg );
  61535. releasePage(pFreePg);
  61536. }
  61537. } else {
  61538. Pgno iFreePg; /* Index of free page to move pLastPg to */
  61539. MemPage *pLastPg;
  61540. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  61541. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  61542. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  61543. if( rc!=SQLITE_OK ){
  61544. return rc;
  61545. }
  61546. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  61547. ** is swapped with the first free page pulled off the free list.
  61548. **
  61549. ** On the other hand, if bCommit is greater than zero, then keep
  61550. ** looping until a free-page located within the first nFin pages
  61551. ** of the file is found.
  61552. */
  61553. if( bCommit==0 ){
  61554. eMode = BTALLOC_LE;
  61555. iNear = nFin;
  61556. }
  61557. do {
  61558. MemPage *pFreePg;
  61559. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  61560. if( rc!=SQLITE_OK ){
  61561. releasePage(pLastPg);
  61562. return rc;
  61563. }
  61564. releasePage(pFreePg);
  61565. }while( bCommit && iFreePg>nFin );
  61566. assert( iFreePg<iLastPg );
  61567. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  61568. releasePage(pLastPg);
  61569. if( rc!=SQLITE_OK ){
  61570. return rc;
  61571. }
  61572. }
  61573. }
  61574. if( bCommit==0 ){
  61575. do {
  61576. iLastPg--;
  61577. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  61578. pBt->bDoTruncate = 1;
  61579. pBt->nPage = iLastPg;
  61580. }
  61581. return SQLITE_OK;
  61582. }
  61583. /*
  61584. ** The database opened by the first argument is an auto-vacuum database
  61585. ** nOrig pages in size containing nFree free pages. Return the expected
  61586. ** size of the database in pages following an auto-vacuum operation.
  61587. */
  61588. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  61589. int nEntry; /* Number of entries on one ptrmap page */
  61590. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  61591. Pgno nFin; /* Return value */
  61592. nEntry = pBt->usableSize/5;
  61593. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  61594. nFin = nOrig - nFree - nPtrmap;
  61595. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  61596. nFin--;
  61597. }
  61598. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  61599. nFin--;
  61600. }
  61601. return nFin;
  61602. }
  61603. /*
  61604. ** A write-transaction must be opened before calling this function.
  61605. ** It performs a single unit of work towards an incremental vacuum.
  61606. **
  61607. ** If the incremental vacuum is finished after this function has run,
  61608. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  61609. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  61610. */
  61611. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  61612. int rc;
  61613. BtShared *pBt = p->pBt;
  61614. sqlite3BtreeEnter(p);
  61615. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  61616. if( !pBt->autoVacuum ){
  61617. rc = SQLITE_DONE;
  61618. }else{
  61619. Pgno nOrig = btreePagecount(pBt);
  61620. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  61621. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  61622. if( nOrig<nFin ){
  61623. rc = SQLITE_CORRUPT_BKPT;
  61624. }else if( nFree>0 ){
  61625. rc = saveAllCursors(pBt, 0, 0);
  61626. if( rc==SQLITE_OK ){
  61627. invalidateAllOverflowCache(pBt);
  61628. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  61629. }
  61630. if( rc==SQLITE_OK ){
  61631. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  61632. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  61633. }
  61634. }else{
  61635. rc = SQLITE_DONE;
  61636. }
  61637. }
  61638. sqlite3BtreeLeave(p);
  61639. return rc;
  61640. }
  61641. /*
  61642. ** This routine is called prior to sqlite3PagerCommit when a transaction
  61643. ** is committed for an auto-vacuum database.
  61644. **
  61645. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  61646. ** the database file should be truncated to during the commit process.
  61647. ** i.e. the database has been reorganized so that only the first *pnTrunc
  61648. ** pages are in use.
  61649. */
  61650. static int autoVacuumCommit(BtShared *pBt){
  61651. int rc = SQLITE_OK;
  61652. Pager *pPager = pBt->pPager;
  61653. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  61654. assert( sqlite3_mutex_held(pBt->mutex) );
  61655. invalidateAllOverflowCache(pBt);
  61656. assert(pBt->autoVacuum);
  61657. if( !pBt->incrVacuum ){
  61658. Pgno nFin; /* Number of pages in database after autovacuuming */
  61659. Pgno nFree; /* Number of pages on the freelist initially */
  61660. Pgno iFree; /* The next page to be freed */
  61661. Pgno nOrig; /* Database size before freeing */
  61662. nOrig = btreePagecount(pBt);
  61663. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  61664. /* It is not possible to create a database for which the final page
  61665. ** is either a pointer-map page or the pending-byte page. If one
  61666. ** is encountered, this indicates corruption.
  61667. */
  61668. return SQLITE_CORRUPT_BKPT;
  61669. }
  61670. nFree = get4byte(&pBt->pPage1->aData[36]);
  61671. nFin = finalDbSize(pBt, nOrig, nFree);
  61672. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  61673. if( nFin<nOrig ){
  61674. rc = saveAllCursors(pBt, 0, 0);
  61675. }
  61676. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  61677. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  61678. }
  61679. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  61680. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  61681. put4byte(&pBt->pPage1->aData[32], 0);
  61682. put4byte(&pBt->pPage1->aData[36], 0);
  61683. put4byte(&pBt->pPage1->aData[28], nFin);
  61684. pBt->bDoTruncate = 1;
  61685. pBt->nPage = nFin;
  61686. }
  61687. if( rc!=SQLITE_OK ){
  61688. sqlite3PagerRollback(pPager);
  61689. }
  61690. }
  61691. assert( nRef>=sqlite3PagerRefcount(pPager) );
  61692. return rc;
  61693. }
  61694. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  61695. # define setChildPtrmaps(x) SQLITE_OK
  61696. #endif
  61697. /*
  61698. ** This routine does the first phase of a two-phase commit. This routine
  61699. ** causes a rollback journal to be created (if it does not already exist)
  61700. ** and populated with enough information so that if a power loss occurs
  61701. ** the database can be restored to its original state by playing back
  61702. ** the journal. Then the contents of the journal are flushed out to
  61703. ** the disk. After the journal is safely on oxide, the changes to the
  61704. ** database are written into the database file and flushed to oxide.
  61705. ** At the end of this call, the rollback journal still exists on the
  61706. ** disk and we are still holding all locks, so the transaction has not
  61707. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  61708. ** commit process.
  61709. **
  61710. ** This call is a no-op if no write-transaction is currently active on pBt.
  61711. **
  61712. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  61713. ** the name of a master journal file that should be written into the
  61714. ** individual journal file, or is NULL, indicating no master journal file
  61715. ** (single database transaction).
  61716. **
  61717. ** When this is called, the master journal should already have been
  61718. ** created, populated with this journal pointer and synced to disk.
  61719. **
  61720. ** Once this is routine has returned, the only thing required to commit
  61721. ** the write-transaction for this database file is to delete the journal.
  61722. */
  61723. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  61724. int rc = SQLITE_OK;
  61725. if( p->inTrans==TRANS_WRITE ){
  61726. BtShared *pBt = p->pBt;
  61727. sqlite3BtreeEnter(p);
  61728. #ifndef SQLITE_OMIT_AUTOVACUUM
  61729. if( pBt->autoVacuum ){
  61730. rc = autoVacuumCommit(pBt);
  61731. if( rc!=SQLITE_OK ){
  61732. sqlite3BtreeLeave(p);
  61733. return rc;
  61734. }
  61735. }
  61736. if( pBt->bDoTruncate ){
  61737. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  61738. }
  61739. #endif
  61740. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  61741. sqlite3BtreeLeave(p);
  61742. }
  61743. return rc;
  61744. }
  61745. /*
  61746. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  61747. ** at the conclusion of a transaction.
  61748. */
  61749. static void btreeEndTransaction(Btree *p){
  61750. BtShared *pBt = p->pBt;
  61751. sqlite3 *db = p->db;
  61752. assert( sqlite3BtreeHoldsMutex(p) );
  61753. #ifndef SQLITE_OMIT_AUTOVACUUM
  61754. pBt->bDoTruncate = 0;
  61755. #endif
  61756. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  61757. /* If there are other active statements that belong to this database
  61758. ** handle, downgrade to a read-only transaction. The other statements
  61759. ** may still be reading from the database. */
  61760. downgradeAllSharedCacheTableLocks(p);
  61761. p->inTrans = TRANS_READ;
  61762. }else{
  61763. /* If the handle had any kind of transaction open, decrement the
  61764. ** transaction count of the shared btree. If the transaction count
  61765. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  61766. ** call below will unlock the pager. */
  61767. if( p->inTrans!=TRANS_NONE ){
  61768. clearAllSharedCacheTableLocks(p);
  61769. pBt->nTransaction--;
  61770. if( 0==pBt->nTransaction ){
  61771. pBt->inTransaction = TRANS_NONE;
  61772. }
  61773. }
  61774. /* Set the current transaction state to TRANS_NONE and unlock the
  61775. ** pager if this call closed the only read or write transaction. */
  61776. p->inTrans = TRANS_NONE;
  61777. unlockBtreeIfUnused(pBt);
  61778. }
  61779. btreeIntegrity(p);
  61780. }
  61781. /*
  61782. ** Commit the transaction currently in progress.
  61783. **
  61784. ** This routine implements the second phase of a 2-phase commit. The
  61785. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  61786. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  61787. ** routine did all the work of writing information out to disk and flushing the
  61788. ** contents so that they are written onto the disk platter. All this
  61789. ** routine has to do is delete or truncate or zero the header in the
  61790. ** the rollback journal (which causes the transaction to commit) and
  61791. ** drop locks.
  61792. **
  61793. ** Normally, if an error occurs while the pager layer is attempting to
  61794. ** finalize the underlying journal file, this function returns an error and
  61795. ** the upper layer will attempt a rollback. However, if the second argument
  61796. ** is non-zero then this b-tree transaction is part of a multi-file
  61797. ** transaction. In this case, the transaction has already been committed
  61798. ** (by deleting a master journal file) and the caller will ignore this
  61799. ** functions return code. So, even if an error occurs in the pager layer,
  61800. ** reset the b-tree objects internal state to indicate that the write
  61801. ** transaction has been closed. This is quite safe, as the pager will have
  61802. ** transitioned to the error state.
  61803. **
  61804. ** This will release the write lock on the database file. If there
  61805. ** are no active cursors, it also releases the read lock.
  61806. */
  61807. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  61808. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  61809. sqlite3BtreeEnter(p);
  61810. btreeIntegrity(p);
  61811. /* If the handle has a write-transaction open, commit the shared-btrees
  61812. ** transaction and set the shared state to TRANS_READ.
  61813. */
  61814. if( p->inTrans==TRANS_WRITE ){
  61815. int rc;
  61816. BtShared *pBt = p->pBt;
  61817. assert( pBt->inTransaction==TRANS_WRITE );
  61818. assert( pBt->nTransaction>0 );
  61819. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  61820. if( rc!=SQLITE_OK && bCleanup==0 ){
  61821. sqlite3BtreeLeave(p);
  61822. return rc;
  61823. }
  61824. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  61825. pBt->inTransaction = TRANS_READ;
  61826. btreeClearHasContent(pBt);
  61827. }
  61828. btreeEndTransaction(p);
  61829. sqlite3BtreeLeave(p);
  61830. return SQLITE_OK;
  61831. }
  61832. /*
  61833. ** Do both phases of a commit.
  61834. */
  61835. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  61836. int rc;
  61837. sqlite3BtreeEnter(p);
  61838. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  61839. if( rc==SQLITE_OK ){
  61840. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  61841. }
  61842. sqlite3BtreeLeave(p);
  61843. return rc;
  61844. }
  61845. /*
  61846. ** This routine sets the state to CURSOR_FAULT and the error
  61847. ** code to errCode for every cursor on any BtShared that pBtree
  61848. ** references. Or if the writeOnly flag is set to 1, then only
  61849. ** trip write cursors and leave read cursors unchanged.
  61850. **
  61851. ** Every cursor is a candidate to be tripped, including cursors
  61852. ** that belong to other database connections that happen to be
  61853. ** sharing the cache with pBtree.
  61854. **
  61855. ** This routine gets called when a rollback occurs. If the writeOnly
  61856. ** flag is true, then only write-cursors need be tripped - read-only
  61857. ** cursors save their current positions so that they may continue
  61858. ** following the rollback. Or, if writeOnly is false, all cursors are
  61859. ** tripped. In general, writeOnly is false if the transaction being
  61860. ** rolled back modified the database schema. In this case b-tree root
  61861. ** pages may be moved or deleted from the database altogether, making
  61862. ** it unsafe for read cursors to continue.
  61863. **
  61864. ** If the writeOnly flag is true and an error is encountered while
  61865. ** saving the current position of a read-only cursor, all cursors,
  61866. ** including all read-cursors are tripped.
  61867. **
  61868. ** SQLITE_OK is returned if successful, or if an error occurs while
  61869. ** saving a cursor position, an SQLite error code.
  61870. */
  61871. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  61872. BtCursor *p;
  61873. int rc = SQLITE_OK;
  61874. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  61875. if( pBtree ){
  61876. sqlite3BtreeEnter(pBtree);
  61877. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  61878. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  61879. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  61880. rc = saveCursorPosition(p);
  61881. if( rc!=SQLITE_OK ){
  61882. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  61883. break;
  61884. }
  61885. }
  61886. }else{
  61887. sqlite3BtreeClearCursor(p);
  61888. p->eState = CURSOR_FAULT;
  61889. p->skipNext = errCode;
  61890. }
  61891. btreeReleaseAllCursorPages(p);
  61892. }
  61893. sqlite3BtreeLeave(pBtree);
  61894. }
  61895. return rc;
  61896. }
  61897. /*
  61898. ** Rollback the transaction in progress.
  61899. **
  61900. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  61901. ** Only write cursors are tripped if writeOnly is true but all cursors are
  61902. ** tripped if writeOnly is false. Any attempt to use
  61903. ** a tripped cursor will result in an error.
  61904. **
  61905. ** This will release the write lock on the database file. If there
  61906. ** are no active cursors, it also releases the read lock.
  61907. */
  61908. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  61909. int rc;
  61910. BtShared *pBt = p->pBt;
  61911. MemPage *pPage1;
  61912. assert( writeOnly==1 || writeOnly==0 );
  61913. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  61914. sqlite3BtreeEnter(p);
  61915. if( tripCode==SQLITE_OK ){
  61916. rc = tripCode = saveAllCursors(pBt, 0, 0);
  61917. if( rc ) writeOnly = 0;
  61918. }else{
  61919. rc = SQLITE_OK;
  61920. }
  61921. if( tripCode ){
  61922. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  61923. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  61924. if( rc2!=SQLITE_OK ) rc = rc2;
  61925. }
  61926. btreeIntegrity(p);
  61927. if( p->inTrans==TRANS_WRITE ){
  61928. int rc2;
  61929. assert( TRANS_WRITE==pBt->inTransaction );
  61930. rc2 = sqlite3PagerRollback(pBt->pPager);
  61931. if( rc2!=SQLITE_OK ){
  61932. rc = rc2;
  61933. }
  61934. /* The rollback may have destroyed the pPage1->aData value. So
  61935. ** call btreeGetPage() on page 1 again to make
  61936. ** sure pPage1->aData is set correctly. */
  61937. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  61938. int nPage = get4byte(28+(u8*)pPage1->aData);
  61939. testcase( nPage==0 );
  61940. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  61941. testcase( pBt->nPage!=nPage );
  61942. pBt->nPage = nPage;
  61943. releasePageOne(pPage1);
  61944. }
  61945. assert( countValidCursors(pBt, 1)==0 );
  61946. pBt->inTransaction = TRANS_READ;
  61947. btreeClearHasContent(pBt);
  61948. }
  61949. btreeEndTransaction(p);
  61950. sqlite3BtreeLeave(p);
  61951. return rc;
  61952. }
  61953. /*
  61954. ** Start a statement subtransaction. The subtransaction can be rolled
  61955. ** back independently of the main transaction. You must start a transaction
  61956. ** before starting a subtransaction. The subtransaction is ended automatically
  61957. ** if the main transaction commits or rolls back.
  61958. **
  61959. ** Statement subtransactions are used around individual SQL statements
  61960. ** that are contained within a BEGIN...COMMIT block. If a constraint
  61961. ** error occurs within the statement, the effect of that one statement
  61962. ** can be rolled back without having to rollback the entire transaction.
  61963. **
  61964. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  61965. ** value passed as the second parameter is the total number of savepoints,
  61966. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  61967. ** are no active savepoints and no other statement-transactions open,
  61968. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  61969. ** using the sqlite3BtreeSavepoint() function.
  61970. */
  61971. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  61972. int rc;
  61973. BtShared *pBt = p->pBt;
  61974. sqlite3BtreeEnter(p);
  61975. assert( p->inTrans==TRANS_WRITE );
  61976. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  61977. assert( iStatement>0 );
  61978. assert( iStatement>p->db->nSavepoint );
  61979. assert( pBt->inTransaction==TRANS_WRITE );
  61980. /* At the pager level, a statement transaction is a savepoint with
  61981. ** an index greater than all savepoints created explicitly using
  61982. ** SQL statements. It is illegal to open, release or rollback any
  61983. ** such savepoints while the statement transaction savepoint is active.
  61984. */
  61985. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  61986. sqlite3BtreeLeave(p);
  61987. return rc;
  61988. }
  61989. /*
  61990. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  61991. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  61992. ** savepoint identified by parameter iSavepoint, depending on the value
  61993. ** of op.
  61994. **
  61995. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  61996. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  61997. ** contents of the entire transaction are rolled back. This is different
  61998. ** from a normal transaction rollback, as no locks are released and the
  61999. ** transaction remains open.
  62000. */
  62001. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  62002. int rc = SQLITE_OK;
  62003. if( p && p->inTrans==TRANS_WRITE ){
  62004. BtShared *pBt = p->pBt;
  62005. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  62006. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  62007. sqlite3BtreeEnter(p);
  62008. if( op==SAVEPOINT_ROLLBACK ){
  62009. rc = saveAllCursors(pBt, 0, 0);
  62010. }
  62011. if( rc==SQLITE_OK ){
  62012. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  62013. }
  62014. if( rc==SQLITE_OK ){
  62015. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  62016. pBt->nPage = 0;
  62017. }
  62018. rc = newDatabase(pBt);
  62019. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  62020. /* The database size was written into the offset 28 of the header
  62021. ** when the transaction started, so we know that the value at offset
  62022. ** 28 is nonzero. */
  62023. assert( pBt->nPage>0 );
  62024. }
  62025. sqlite3BtreeLeave(p);
  62026. }
  62027. return rc;
  62028. }
  62029. /*
  62030. ** Create a new cursor for the BTree whose root is on the page
  62031. ** iTable. If a read-only cursor is requested, it is assumed that
  62032. ** the caller already has at least a read-only transaction open
  62033. ** on the database already. If a write-cursor is requested, then
  62034. ** the caller is assumed to have an open write transaction.
  62035. **
  62036. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  62037. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  62038. ** can be used for reading or for writing if other conditions for writing
  62039. ** are also met. These are the conditions that must be met in order
  62040. ** for writing to be allowed:
  62041. **
  62042. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  62043. **
  62044. ** 2: Other database connections that share the same pager cache
  62045. ** but which are not in the READ_UNCOMMITTED state may not have
  62046. ** cursors open with wrFlag==0 on the same table. Otherwise
  62047. ** the changes made by this write cursor would be visible to
  62048. ** the read cursors in the other database connection.
  62049. **
  62050. ** 3: The database must be writable (not on read-only media)
  62051. **
  62052. ** 4: There must be an active transaction.
  62053. **
  62054. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  62055. ** is set. If FORDELETE is set, that is a hint to the implementation that
  62056. ** this cursor will only be used to seek to and delete entries of an index
  62057. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  62058. ** this implementation. But in a hypothetical alternative storage engine
  62059. ** in which index entries are automatically deleted when corresponding table
  62060. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  62061. ** operations on this cursor can be no-ops and all READ operations can
  62062. ** return a null row (2-bytes: 0x01 0x00).
  62063. **
  62064. ** No checking is done to make sure that page iTable really is the
  62065. ** root page of a b-tree. If it is not, then the cursor acquired
  62066. ** will not work correctly.
  62067. **
  62068. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  62069. ** on pCur to initialize the memory space prior to invoking this routine.
  62070. */
  62071. static int btreeCursor(
  62072. Btree *p, /* The btree */
  62073. int iTable, /* Root page of table to open */
  62074. int wrFlag, /* 1 to write. 0 read-only */
  62075. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  62076. BtCursor *pCur /* Space for new cursor */
  62077. ){
  62078. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  62079. BtCursor *pX; /* Looping over other all cursors */
  62080. assert( sqlite3BtreeHoldsMutex(p) );
  62081. assert( wrFlag==0
  62082. || wrFlag==BTREE_WRCSR
  62083. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  62084. );
  62085. /* The following assert statements verify that if this is a sharable
  62086. ** b-tree database, the connection is holding the required table locks,
  62087. ** and that no other connection has any open cursor that conflicts with
  62088. ** this lock. */
  62089. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  62090. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  62091. /* Assert that the caller has opened the required transaction. */
  62092. assert( p->inTrans>TRANS_NONE );
  62093. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  62094. assert( pBt->pPage1 && pBt->pPage1->aData );
  62095. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  62096. if( wrFlag ){
  62097. allocateTempSpace(pBt);
  62098. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  62099. }
  62100. if( iTable==1 && btreePagecount(pBt)==0 ){
  62101. assert( wrFlag==0 );
  62102. iTable = 0;
  62103. }
  62104. /* Now that no other errors can occur, finish filling in the BtCursor
  62105. ** variables and link the cursor into the BtShared list. */
  62106. pCur->pgnoRoot = (Pgno)iTable;
  62107. pCur->iPage = -1;
  62108. pCur->pKeyInfo = pKeyInfo;
  62109. pCur->pBtree = p;
  62110. pCur->pBt = pBt;
  62111. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  62112. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  62113. /* If there are two or more cursors on the same btree, then all such
  62114. ** cursors *must* have the BTCF_Multiple flag set. */
  62115. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  62116. if( pX->pgnoRoot==(Pgno)iTable ){
  62117. pX->curFlags |= BTCF_Multiple;
  62118. pCur->curFlags |= BTCF_Multiple;
  62119. }
  62120. }
  62121. pCur->pNext = pBt->pCursor;
  62122. pBt->pCursor = pCur;
  62123. pCur->eState = CURSOR_INVALID;
  62124. return SQLITE_OK;
  62125. }
  62126. SQLITE_PRIVATE int sqlite3BtreeCursor(
  62127. Btree *p, /* The btree */
  62128. int iTable, /* Root page of table to open */
  62129. int wrFlag, /* 1 to write. 0 read-only */
  62130. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  62131. BtCursor *pCur /* Write new cursor here */
  62132. ){
  62133. int rc;
  62134. if( iTable<1 ){
  62135. rc = SQLITE_CORRUPT_BKPT;
  62136. }else{
  62137. sqlite3BtreeEnter(p);
  62138. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  62139. sqlite3BtreeLeave(p);
  62140. }
  62141. return rc;
  62142. }
  62143. /*
  62144. ** Return the size of a BtCursor object in bytes.
  62145. **
  62146. ** This interfaces is needed so that users of cursors can preallocate
  62147. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  62148. ** to users so they cannot do the sizeof() themselves - they must call
  62149. ** this routine.
  62150. */
  62151. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  62152. return ROUND8(sizeof(BtCursor));
  62153. }
  62154. /*
  62155. ** Initialize memory that will be converted into a BtCursor object.
  62156. **
  62157. ** The simple approach here would be to memset() the entire object
  62158. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  62159. ** do not need to be zeroed and they are large, so we can save a lot
  62160. ** of run-time by skipping the initialization of those elements.
  62161. */
  62162. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  62163. memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
  62164. }
  62165. /*
  62166. ** Close a cursor. The read lock on the database file is released
  62167. ** when the last cursor is closed.
  62168. */
  62169. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  62170. Btree *pBtree = pCur->pBtree;
  62171. if( pBtree ){
  62172. BtShared *pBt = pCur->pBt;
  62173. sqlite3BtreeEnter(pBtree);
  62174. assert( pBt->pCursor!=0 );
  62175. if( pBt->pCursor==pCur ){
  62176. pBt->pCursor = pCur->pNext;
  62177. }else{
  62178. BtCursor *pPrev = pBt->pCursor;
  62179. do{
  62180. if( pPrev->pNext==pCur ){
  62181. pPrev->pNext = pCur->pNext;
  62182. break;
  62183. }
  62184. pPrev = pPrev->pNext;
  62185. }while( ALWAYS(pPrev) );
  62186. }
  62187. btreeReleaseAllCursorPages(pCur);
  62188. unlockBtreeIfUnused(pBt);
  62189. sqlite3_free(pCur->aOverflow);
  62190. sqlite3_free(pCur->pKey);
  62191. sqlite3BtreeLeave(pBtree);
  62192. }
  62193. return SQLITE_OK;
  62194. }
  62195. /*
  62196. ** Make sure the BtCursor* given in the argument has a valid
  62197. ** BtCursor.info structure. If it is not already valid, call
  62198. ** btreeParseCell() to fill it in.
  62199. **
  62200. ** BtCursor.info is a cache of the information in the current cell.
  62201. ** Using this cache reduces the number of calls to btreeParseCell().
  62202. */
  62203. #ifndef NDEBUG
  62204. static int cellInfoEqual(CellInfo *a, CellInfo *b){
  62205. if( a->nKey!=b->nKey ) return 0;
  62206. if( a->pPayload!=b->pPayload ) return 0;
  62207. if( a->nPayload!=b->nPayload ) return 0;
  62208. if( a->nLocal!=b->nLocal ) return 0;
  62209. if( a->nSize!=b->nSize ) return 0;
  62210. return 1;
  62211. }
  62212. static void assertCellInfo(BtCursor *pCur){
  62213. CellInfo info;
  62214. memset(&info, 0, sizeof(info));
  62215. btreeParseCell(pCur->pPage, pCur->ix, &info);
  62216. assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
  62217. }
  62218. #else
  62219. #define assertCellInfo(x)
  62220. #endif
  62221. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  62222. if( pCur->info.nSize==0 ){
  62223. pCur->curFlags |= BTCF_ValidNKey;
  62224. btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
  62225. }else{
  62226. assertCellInfo(pCur);
  62227. }
  62228. }
  62229. #ifndef NDEBUG /* The next routine used only within assert() statements */
  62230. /*
  62231. ** Return true if the given BtCursor is valid. A valid cursor is one
  62232. ** that is currently pointing to a row in a (non-empty) table.
  62233. ** This is a verification routine is used only within assert() statements.
  62234. */
  62235. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  62236. return pCur && pCur->eState==CURSOR_VALID;
  62237. }
  62238. #endif /* NDEBUG */
  62239. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  62240. assert( pCur!=0 );
  62241. return pCur->eState==CURSOR_VALID;
  62242. }
  62243. /*
  62244. ** Return the value of the integer key or "rowid" for a table btree.
  62245. ** This routine is only valid for a cursor that is pointing into a
  62246. ** ordinary table btree. If the cursor points to an index btree or
  62247. ** is invalid, the result of this routine is undefined.
  62248. */
  62249. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  62250. assert( cursorHoldsMutex(pCur) );
  62251. assert( pCur->eState==CURSOR_VALID );
  62252. assert( pCur->curIntKey );
  62253. getCellInfo(pCur);
  62254. return pCur->info.nKey;
  62255. }
  62256. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  62257. /*
  62258. ** Return the offset into the database file for the start of the
  62259. ** payload to which the cursor is pointing.
  62260. */
  62261. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
  62262. assert( cursorHoldsMutex(pCur) );
  62263. assert( pCur->eState==CURSOR_VALID );
  62264. getCellInfo(pCur);
  62265. return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
  62266. (i64)(pCur->info.pPayload - pCur->pPage->aData);
  62267. }
  62268. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  62269. /*
  62270. ** Return the number of bytes of payload for the entry that pCur is
  62271. ** currently pointing to. For table btrees, this will be the amount
  62272. ** of data. For index btrees, this will be the size of the key.
  62273. **
  62274. ** The caller must guarantee that the cursor is pointing to a non-NULL
  62275. ** valid entry. In other words, the calling procedure must guarantee
  62276. ** that the cursor has Cursor.eState==CURSOR_VALID.
  62277. */
  62278. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  62279. assert( cursorHoldsMutex(pCur) );
  62280. assert( pCur->eState==CURSOR_VALID );
  62281. getCellInfo(pCur);
  62282. return pCur->info.nPayload;
  62283. }
  62284. /*
  62285. ** Given the page number of an overflow page in the database (parameter
  62286. ** ovfl), this function finds the page number of the next page in the
  62287. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  62288. ** pointer-map data instead of reading the content of page ovfl to do so.
  62289. **
  62290. ** If an error occurs an SQLite error code is returned. Otherwise:
  62291. **
  62292. ** The page number of the next overflow page in the linked list is
  62293. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  62294. ** list, *pPgnoNext is set to zero.
  62295. **
  62296. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  62297. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  62298. ** reference. It is the responsibility of the caller to call releasePage()
  62299. ** on *ppPage to free the reference. In no reference was obtained (because
  62300. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  62301. ** *ppPage is set to zero.
  62302. */
  62303. static int getOverflowPage(
  62304. BtShared *pBt, /* The database file */
  62305. Pgno ovfl, /* Current overflow page number */
  62306. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  62307. Pgno *pPgnoNext /* OUT: Next overflow page number */
  62308. ){
  62309. Pgno next = 0;
  62310. MemPage *pPage = 0;
  62311. int rc = SQLITE_OK;
  62312. assert( sqlite3_mutex_held(pBt->mutex) );
  62313. assert(pPgnoNext);
  62314. #ifndef SQLITE_OMIT_AUTOVACUUM
  62315. /* Try to find the next page in the overflow list using the
  62316. ** autovacuum pointer-map pages. Guess that the next page in
  62317. ** the overflow list is page number (ovfl+1). If that guess turns
  62318. ** out to be wrong, fall back to loading the data of page
  62319. ** number ovfl to determine the next page number.
  62320. */
  62321. if( pBt->autoVacuum ){
  62322. Pgno pgno;
  62323. Pgno iGuess = ovfl+1;
  62324. u8 eType;
  62325. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  62326. iGuess++;
  62327. }
  62328. if( iGuess<=btreePagecount(pBt) ){
  62329. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  62330. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  62331. next = iGuess;
  62332. rc = SQLITE_DONE;
  62333. }
  62334. }
  62335. }
  62336. #endif
  62337. assert( next==0 || rc==SQLITE_DONE );
  62338. if( rc==SQLITE_OK ){
  62339. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  62340. assert( rc==SQLITE_OK || pPage==0 );
  62341. if( rc==SQLITE_OK ){
  62342. next = get4byte(pPage->aData);
  62343. }
  62344. }
  62345. *pPgnoNext = next;
  62346. if( ppPage ){
  62347. *ppPage = pPage;
  62348. }else{
  62349. releasePage(pPage);
  62350. }
  62351. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  62352. }
  62353. /*
  62354. ** Copy data from a buffer to a page, or from a page to a buffer.
  62355. **
  62356. ** pPayload is a pointer to data stored on database page pDbPage.
  62357. ** If argument eOp is false, then nByte bytes of data are copied
  62358. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  62359. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  62360. ** of data are copied from the buffer pBuf to pPayload.
  62361. **
  62362. ** SQLITE_OK is returned on success, otherwise an error code.
  62363. */
  62364. static int copyPayload(
  62365. void *pPayload, /* Pointer to page data */
  62366. void *pBuf, /* Pointer to buffer */
  62367. int nByte, /* Number of bytes to copy */
  62368. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  62369. DbPage *pDbPage /* Page containing pPayload */
  62370. ){
  62371. if( eOp ){
  62372. /* Copy data from buffer to page (a write operation) */
  62373. int rc = sqlite3PagerWrite(pDbPage);
  62374. if( rc!=SQLITE_OK ){
  62375. return rc;
  62376. }
  62377. memcpy(pPayload, pBuf, nByte);
  62378. }else{
  62379. /* Copy data from page to buffer (a read operation) */
  62380. memcpy(pBuf, pPayload, nByte);
  62381. }
  62382. return SQLITE_OK;
  62383. }
  62384. /*
  62385. ** This function is used to read or overwrite payload information
  62386. ** for the entry that the pCur cursor is pointing to. The eOp
  62387. ** argument is interpreted as follows:
  62388. **
  62389. ** 0: The operation is a read. Populate the overflow cache.
  62390. ** 1: The operation is a write. Populate the overflow cache.
  62391. **
  62392. ** A total of "amt" bytes are read or written beginning at "offset".
  62393. ** Data is read to or from the buffer pBuf.
  62394. **
  62395. ** The content being read or written might appear on the main page
  62396. ** or be scattered out on multiple overflow pages.
  62397. **
  62398. ** If the current cursor entry uses one or more overflow pages
  62399. ** this function may allocate space for and lazily populate
  62400. ** the overflow page-list cache array (BtCursor.aOverflow).
  62401. ** Subsequent calls use this cache to make seeking to the supplied offset
  62402. ** more efficient.
  62403. **
  62404. ** Once an overflow page-list cache has been allocated, it must be
  62405. ** invalidated if some other cursor writes to the same table, or if
  62406. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  62407. ** mode, the following events may invalidate an overflow page-list cache.
  62408. **
  62409. ** * An incremental vacuum,
  62410. ** * A commit in auto_vacuum="full" mode,
  62411. ** * Creating a table (may require moving an overflow page).
  62412. */
  62413. static int accessPayload(
  62414. BtCursor *pCur, /* Cursor pointing to entry to read from */
  62415. u32 offset, /* Begin reading this far into payload */
  62416. u32 amt, /* Read this many bytes */
  62417. unsigned char *pBuf, /* Write the bytes into this buffer */
  62418. int eOp /* zero to read. non-zero to write. */
  62419. ){
  62420. unsigned char *aPayload;
  62421. int rc = SQLITE_OK;
  62422. int iIdx = 0;
  62423. MemPage *pPage = pCur->pPage; /* Btree page of current entry */
  62424. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  62425. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  62426. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  62427. #endif
  62428. assert( pPage );
  62429. assert( eOp==0 || eOp==1 );
  62430. assert( pCur->eState==CURSOR_VALID );
  62431. assert( pCur->ix<pPage->nCell );
  62432. assert( cursorHoldsMutex(pCur) );
  62433. getCellInfo(pCur);
  62434. aPayload = pCur->info.pPayload;
  62435. assert( offset+amt <= pCur->info.nPayload );
  62436. assert( aPayload > pPage->aData );
  62437. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  62438. /* Trying to read or write past the end of the data is an error. The
  62439. ** conditional above is really:
  62440. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  62441. ** but is recast into its current form to avoid integer overflow problems
  62442. */
  62443. return SQLITE_CORRUPT_PAGE(pPage);
  62444. }
  62445. /* Check if data must be read/written to/from the btree page itself. */
  62446. if( offset<pCur->info.nLocal ){
  62447. int a = amt;
  62448. if( a+offset>pCur->info.nLocal ){
  62449. a = pCur->info.nLocal - offset;
  62450. }
  62451. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  62452. offset = 0;
  62453. pBuf += a;
  62454. amt -= a;
  62455. }else{
  62456. offset -= pCur->info.nLocal;
  62457. }
  62458. if( rc==SQLITE_OK && amt>0 ){
  62459. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  62460. Pgno nextPage;
  62461. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  62462. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  62463. **
  62464. ** The aOverflow[] array is sized at one entry for each overflow page
  62465. ** in the overflow chain. The page number of the first overflow page is
  62466. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  62467. ** means "not yet known" (the cache is lazily populated).
  62468. */
  62469. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  62470. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  62471. if( pCur->aOverflow==0
  62472. || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
  62473. ){
  62474. Pgno *aNew = (Pgno*)sqlite3Realloc(
  62475. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  62476. );
  62477. if( aNew==0 ){
  62478. return SQLITE_NOMEM_BKPT;
  62479. }else{
  62480. pCur->aOverflow = aNew;
  62481. }
  62482. }
  62483. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  62484. pCur->curFlags |= BTCF_ValidOvfl;
  62485. }else{
  62486. /* If the overflow page-list cache has been allocated and the
  62487. ** entry for the first required overflow page is valid, skip
  62488. ** directly to it.
  62489. */
  62490. if( pCur->aOverflow[offset/ovflSize] ){
  62491. iIdx = (offset/ovflSize);
  62492. nextPage = pCur->aOverflow[iIdx];
  62493. offset = (offset%ovflSize);
  62494. }
  62495. }
  62496. assert( rc==SQLITE_OK && amt>0 );
  62497. while( nextPage ){
  62498. /* If required, populate the overflow page-list cache. */
  62499. assert( pCur->aOverflow[iIdx]==0
  62500. || pCur->aOverflow[iIdx]==nextPage
  62501. || CORRUPT_DB );
  62502. pCur->aOverflow[iIdx] = nextPage;
  62503. if( offset>=ovflSize ){
  62504. /* The only reason to read this page is to obtain the page
  62505. ** number for the next page in the overflow chain. The page
  62506. ** data is not required. So first try to lookup the overflow
  62507. ** page-list cache, if any, then fall back to the getOverflowPage()
  62508. ** function.
  62509. */
  62510. assert( pCur->curFlags & BTCF_ValidOvfl );
  62511. assert( pCur->pBtree->db==pBt->db );
  62512. if( pCur->aOverflow[iIdx+1] ){
  62513. nextPage = pCur->aOverflow[iIdx+1];
  62514. }else{
  62515. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  62516. }
  62517. offset -= ovflSize;
  62518. }else{
  62519. /* Need to read this page properly. It contains some of the
  62520. ** range of data that is being read (eOp==0) or written (eOp!=0).
  62521. */
  62522. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  62523. sqlite3_file *fd; /* File from which to do direct overflow read */
  62524. #endif
  62525. int a = amt;
  62526. if( a + offset > ovflSize ){
  62527. a = ovflSize - offset;
  62528. }
  62529. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  62530. /* If all the following are true:
  62531. **
  62532. ** 1) this is a read operation, and
  62533. ** 2) data is required from the start of this overflow page, and
  62534. ** 3) there is no open write-transaction, and
  62535. ** 4) the database is file-backed, and
  62536. ** 5) the page is not in the WAL file
  62537. ** 6) at least 4 bytes have already been read into the output buffer
  62538. **
  62539. ** then data can be read directly from the database file into the
  62540. ** output buffer, bypassing the page-cache altogether. This speeds
  62541. ** up loading large records that span many overflow pages.
  62542. */
  62543. if( eOp==0 /* (1) */
  62544. && offset==0 /* (2) */
  62545. && pBt->inTransaction==TRANS_READ /* (3) */
  62546. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
  62547. && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
  62548. && &pBuf[-4]>=pBufStart /* (6) */
  62549. ){
  62550. u8 aSave[4];
  62551. u8 *aWrite = &pBuf[-4];
  62552. assert( aWrite>=pBufStart ); /* due to (6) */
  62553. memcpy(aSave, aWrite, 4);
  62554. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  62555. nextPage = get4byte(aWrite);
  62556. memcpy(aWrite, aSave, 4);
  62557. }else
  62558. #endif
  62559. {
  62560. DbPage *pDbPage;
  62561. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  62562. (eOp==0 ? PAGER_GET_READONLY : 0)
  62563. );
  62564. if( rc==SQLITE_OK ){
  62565. aPayload = sqlite3PagerGetData(pDbPage);
  62566. nextPage = get4byte(aPayload);
  62567. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  62568. sqlite3PagerUnref(pDbPage);
  62569. offset = 0;
  62570. }
  62571. }
  62572. amt -= a;
  62573. if( amt==0 ) return rc;
  62574. pBuf += a;
  62575. }
  62576. if( rc ) break;
  62577. iIdx++;
  62578. }
  62579. }
  62580. if( rc==SQLITE_OK && amt>0 ){
  62581. /* Overflow chain ends prematurely */
  62582. return SQLITE_CORRUPT_PAGE(pPage);
  62583. }
  62584. return rc;
  62585. }
  62586. /*
  62587. ** Read part of the payload for the row at which that cursor pCur is currently
  62588. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  62589. ** begins at "offset".
  62590. **
  62591. ** pCur can be pointing to either a table or an index b-tree.
  62592. ** If pointing to a table btree, then the content section is read. If
  62593. ** pCur is pointing to an index b-tree then the key section is read.
  62594. **
  62595. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  62596. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  62597. ** cursor might be invalid or might need to be restored before being read.
  62598. **
  62599. ** Return SQLITE_OK on success or an error code if anything goes
  62600. ** wrong. An error is returned if "offset+amt" is larger than
  62601. ** the available payload.
  62602. */
  62603. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  62604. assert( cursorHoldsMutex(pCur) );
  62605. assert( pCur->eState==CURSOR_VALID );
  62606. assert( pCur->iPage>=0 && pCur->pPage );
  62607. assert( pCur->ix<pCur->pPage->nCell );
  62608. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  62609. }
  62610. /*
  62611. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  62612. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  62613. ** interface.
  62614. */
  62615. #ifndef SQLITE_OMIT_INCRBLOB
  62616. static SQLITE_NOINLINE int accessPayloadChecked(
  62617. BtCursor *pCur,
  62618. u32 offset,
  62619. u32 amt,
  62620. void *pBuf
  62621. ){
  62622. int rc;
  62623. if ( pCur->eState==CURSOR_INVALID ){
  62624. return SQLITE_ABORT;
  62625. }
  62626. assert( cursorOwnsBtShared(pCur) );
  62627. rc = btreeRestoreCursorPosition(pCur);
  62628. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  62629. }
  62630. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  62631. if( pCur->eState==CURSOR_VALID ){
  62632. assert( cursorOwnsBtShared(pCur) );
  62633. return accessPayload(pCur, offset, amt, pBuf, 0);
  62634. }else{
  62635. return accessPayloadChecked(pCur, offset, amt, pBuf);
  62636. }
  62637. }
  62638. #endif /* SQLITE_OMIT_INCRBLOB */
  62639. /*
  62640. ** Return a pointer to payload information from the entry that the
  62641. ** pCur cursor is pointing to. The pointer is to the beginning of
  62642. ** the key if index btrees (pPage->intKey==0) and is the data for
  62643. ** table btrees (pPage->intKey==1). The number of bytes of available
  62644. ** key/data is written into *pAmt. If *pAmt==0, then the value
  62645. ** returned will not be a valid pointer.
  62646. **
  62647. ** This routine is an optimization. It is common for the entire key
  62648. ** and data to fit on the local page and for there to be no overflow
  62649. ** pages. When that is so, this routine can be used to access the
  62650. ** key and data without making a copy. If the key and/or data spills
  62651. ** onto overflow pages, then accessPayload() must be used to reassemble
  62652. ** the key/data and copy it into a preallocated buffer.
  62653. **
  62654. ** The pointer returned by this routine looks directly into the cached
  62655. ** page of the database. The data might change or move the next time
  62656. ** any btree routine is called.
  62657. */
  62658. static const void *fetchPayload(
  62659. BtCursor *pCur, /* Cursor pointing to entry to read from */
  62660. u32 *pAmt /* Write the number of available bytes here */
  62661. ){
  62662. int amt;
  62663. assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
  62664. assert( pCur->eState==CURSOR_VALID );
  62665. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62666. assert( cursorOwnsBtShared(pCur) );
  62667. assert( pCur->ix<pCur->pPage->nCell );
  62668. assert( pCur->info.nSize>0 );
  62669. assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
  62670. assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
  62671. amt = pCur->info.nLocal;
  62672. if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
  62673. /* There is too little space on the page for the expected amount
  62674. ** of local content. Database must be corrupt. */
  62675. assert( CORRUPT_DB );
  62676. amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
  62677. }
  62678. *pAmt = (u32)amt;
  62679. return (void*)pCur->info.pPayload;
  62680. }
  62681. /*
  62682. ** For the entry that cursor pCur is point to, return as
  62683. ** many bytes of the key or data as are available on the local
  62684. ** b-tree page. Write the number of available bytes into *pAmt.
  62685. **
  62686. ** The pointer returned is ephemeral. The key/data may move
  62687. ** or be destroyed on the next call to any Btree routine,
  62688. ** including calls from other threads against the same cache.
  62689. ** Hence, a mutex on the BtShared should be held prior to calling
  62690. ** this routine.
  62691. **
  62692. ** These routines is used to get quick access to key and data
  62693. ** in the common case where no overflow pages are used.
  62694. */
  62695. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  62696. return fetchPayload(pCur, pAmt);
  62697. }
  62698. /*
  62699. ** Move the cursor down to a new child page. The newPgno argument is the
  62700. ** page number of the child page to move to.
  62701. **
  62702. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  62703. ** the new child page does not match the flags field of the parent (i.e.
  62704. ** if an intkey page appears to be the parent of a non-intkey page, or
  62705. ** vice-versa).
  62706. */
  62707. static int moveToChild(BtCursor *pCur, u32 newPgno){
  62708. BtShared *pBt = pCur->pBt;
  62709. assert( cursorOwnsBtShared(pCur) );
  62710. assert( pCur->eState==CURSOR_VALID );
  62711. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  62712. assert( pCur->iPage>=0 );
  62713. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  62714. return SQLITE_CORRUPT_BKPT;
  62715. }
  62716. pCur->info.nSize = 0;
  62717. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  62718. pCur->aiIdx[pCur->iPage] = pCur->ix;
  62719. pCur->apPage[pCur->iPage] = pCur->pPage;
  62720. pCur->ix = 0;
  62721. pCur->iPage++;
  62722. return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
  62723. }
  62724. #ifdef SQLITE_DEBUG
  62725. /*
  62726. ** Page pParent is an internal (non-leaf) tree page. This function
  62727. ** asserts that page number iChild is the left-child if the iIdx'th
  62728. ** cell in page pParent. Or, if iIdx is equal to the total number of
  62729. ** cells in pParent, that page number iChild is the right-child of
  62730. ** the page.
  62731. */
  62732. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  62733. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  62734. ** in a corrupt database */
  62735. assert( iIdx<=pParent->nCell );
  62736. if( iIdx==pParent->nCell ){
  62737. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  62738. }else{
  62739. assert( get4byte(findCell(pParent, iIdx))==iChild );
  62740. }
  62741. }
  62742. #else
  62743. # define assertParentIndex(x,y,z)
  62744. #endif
  62745. /*
  62746. ** Move the cursor up to the parent page.
  62747. **
  62748. ** pCur->idx is set to the cell index that contains the pointer
  62749. ** to the page we are coming from. If we are coming from the
  62750. ** right-most child page then pCur->idx is set to one more than
  62751. ** the largest cell index.
  62752. */
  62753. static void moveToParent(BtCursor *pCur){
  62754. MemPage *pLeaf;
  62755. assert( cursorOwnsBtShared(pCur) );
  62756. assert( pCur->eState==CURSOR_VALID );
  62757. assert( pCur->iPage>0 );
  62758. assert( pCur->pPage );
  62759. assertParentIndex(
  62760. pCur->apPage[pCur->iPage-1],
  62761. pCur->aiIdx[pCur->iPage-1],
  62762. pCur->pPage->pgno
  62763. );
  62764. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  62765. pCur->info.nSize = 0;
  62766. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  62767. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  62768. pLeaf = pCur->pPage;
  62769. pCur->pPage = pCur->apPage[--pCur->iPage];
  62770. releasePageNotNull(pLeaf);
  62771. }
  62772. /*
  62773. ** Move the cursor to point to the root page of its b-tree structure.
  62774. **
  62775. ** If the table has a virtual root page, then the cursor is moved to point
  62776. ** to the virtual root page instead of the actual root page. A table has a
  62777. ** virtual root page when the actual root page contains no cells and a
  62778. ** single child page. This can only happen with the table rooted at page 1.
  62779. **
  62780. ** If the b-tree structure is empty, the cursor state is set to
  62781. ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
  62782. ** the cursor is set to point to the first cell located on the root
  62783. ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
  62784. **
  62785. ** If this function returns successfully, it may be assumed that the
  62786. ** page-header flags indicate that the [virtual] root-page is the expected
  62787. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  62788. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  62789. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  62790. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  62791. ** b-tree).
  62792. */
  62793. static int moveToRoot(BtCursor *pCur){
  62794. MemPage *pRoot;
  62795. int rc = SQLITE_OK;
  62796. assert( cursorOwnsBtShared(pCur) );
  62797. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  62798. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  62799. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  62800. assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
  62801. assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
  62802. if( pCur->iPage>=0 ){
  62803. if( pCur->iPage ){
  62804. releasePageNotNull(pCur->pPage);
  62805. while( --pCur->iPage ){
  62806. releasePageNotNull(pCur->apPage[pCur->iPage]);
  62807. }
  62808. pCur->pPage = pCur->apPage[0];
  62809. goto skip_init;
  62810. }
  62811. }else if( pCur->pgnoRoot==0 ){
  62812. pCur->eState = CURSOR_INVALID;
  62813. return SQLITE_EMPTY;
  62814. }else{
  62815. assert( pCur->iPage==(-1) );
  62816. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  62817. if( pCur->eState==CURSOR_FAULT ){
  62818. assert( pCur->skipNext!=SQLITE_OK );
  62819. return pCur->skipNext;
  62820. }
  62821. sqlite3BtreeClearCursor(pCur);
  62822. }
  62823. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
  62824. 0, pCur->curPagerFlags);
  62825. if( rc!=SQLITE_OK ){
  62826. pCur->eState = CURSOR_INVALID;
  62827. return rc;
  62828. }
  62829. pCur->iPage = 0;
  62830. pCur->curIntKey = pCur->pPage->intKey;
  62831. }
  62832. pRoot = pCur->pPage;
  62833. assert( pRoot->pgno==pCur->pgnoRoot );
  62834. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  62835. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  62836. ** NULL, the caller expects a table b-tree. If this is not the case,
  62837. ** return an SQLITE_CORRUPT error.
  62838. **
  62839. ** Earlier versions of SQLite assumed that this test could not fail
  62840. ** if the root page was already loaded when this function was called (i.e.
  62841. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  62842. ** in such a way that page pRoot is linked into a second b-tree table
  62843. ** (or the freelist). */
  62844. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  62845. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  62846. return SQLITE_CORRUPT_PAGE(pCur->pPage);
  62847. }
  62848. skip_init:
  62849. pCur->ix = 0;
  62850. pCur->info.nSize = 0;
  62851. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  62852. pRoot = pCur->pPage;
  62853. if( pRoot->nCell>0 ){
  62854. pCur->eState = CURSOR_VALID;
  62855. }else if( !pRoot->leaf ){
  62856. Pgno subpage;
  62857. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  62858. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  62859. pCur->eState = CURSOR_VALID;
  62860. rc = moveToChild(pCur, subpage);
  62861. }else{
  62862. pCur->eState = CURSOR_INVALID;
  62863. rc = SQLITE_EMPTY;
  62864. }
  62865. return rc;
  62866. }
  62867. /*
  62868. ** Move the cursor down to the left-most leaf entry beneath the
  62869. ** entry to which it is currently pointing.
  62870. **
  62871. ** The left-most leaf is the one with the smallest key - the first
  62872. ** in ascending order.
  62873. */
  62874. static int moveToLeftmost(BtCursor *pCur){
  62875. Pgno pgno;
  62876. int rc = SQLITE_OK;
  62877. MemPage *pPage;
  62878. assert( cursorOwnsBtShared(pCur) );
  62879. assert( pCur->eState==CURSOR_VALID );
  62880. while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
  62881. assert( pCur->ix<pPage->nCell );
  62882. pgno = get4byte(findCell(pPage, pCur->ix));
  62883. rc = moveToChild(pCur, pgno);
  62884. }
  62885. return rc;
  62886. }
  62887. /*
  62888. ** Move the cursor down to the right-most leaf entry beneath the
  62889. ** page to which it is currently pointing. Notice the difference
  62890. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  62891. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  62892. ** finds the right-most entry beneath the *page*.
  62893. **
  62894. ** The right-most entry is the one with the largest key - the last
  62895. ** key in ascending order.
  62896. */
  62897. static int moveToRightmost(BtCursor *pCur){
  62898. Pgno pgno;
  62899. int rc = SQLITE_OK;
  62900. MemPage *pPage = 0;
  62901. assert( cursorOwnsBtShared(pCur) );
  62902. assert( pCur->eState==CURSOR_VALID );
  62903. while( !(pPage = pCur->pPage)->leaf ){
  62904. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  62905. pCur->ix = pPage->nCell;
  62906. rc = moveToChild(pCur, pgno);
  62907. if( rc ) return rc;
  62908. }
  62909. pCur->ix = pPage->nCell-1;
  62910. assert( pCur->info.nSize==0 );
  62911. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  62912. return SQLITE_OK;
  62913. }
  62914. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  62915. ** on success. Set *pRes to 0 if the cursor actually points to something
  62916. ** or set *pRes to 1 if the table is empty.
  62917. */
  62918. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  62919. int rc;
  62920. assert( cursorOwnsBtShared(pCur) );
  62921. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62922. rc = moveToRoot(pCur);
  62923. if( rc==SQLITE_OK ){
  62924. assert( pCur->pPage->nCell>0 );
  62925. *pRes = 0;
  62926. rc = moveToLeftmost(pCur);
  62927. }else if( rc==SQLITE_EMPTY ){
  62928. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  62929. *pRes = 1;
  62930. rc = SQLITE_OK;
  62931. }
  62932. return rc;
  62933. }
  62934. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  62935. ** on success. Set *pRes to 0 if the cursor actually points to something
  62936. ** or set *pRes to 1 if the table is empty.
  62937. */
  62938. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  62939. int rc;
  62940. assert( cursorOwnsBtShared(pCur) );
  62941. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62942. /* If the cursor already points to the last entry, this is a no-op. */
  62943. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  62944. #ifdef SQLITE_DEBUG
  62945. /* This block serves to assert() that the cursor really does point
  62946. ** to the last entry in the b-tree. */
  62947. int ii;
  62948. for(ii=0; ii<pCur->iPage; ii++){
  62949. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  62950. }
  62951. assert( pCur->ix==pCur->pPage->nCell-1 );
  62952. assert( pCur->pPage->leaf );
  62953. #endif
  62954. return SQLITE_OK;
  62955. }
  62956. rc = moveToRoot(pCur);
  62957. if( rc==SQLITE_OK ){
  62958. assert( pCur->eState==CURSOR_VALID );
  62959. *pRes = 0;
  62960. rc = moveToRightmost(pCur);
  62961. if( rc==SQLITE_OK ){
  62962. pCur->curFlags |= BTCF_AtLast;
  62963. }else{
  62964. pCur->curFlags &= ~BTCF_AtLast;
  62965. }
  62966. }else if( rc==SQLITE_EMPTY ){
  62967. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  62968. *pRes = 1;
  62969. rc = SQLITE_OK;
  62970. }
  62971. return rc;
  62972. }
  62973. /* Move the cursor so that it points to an entry near the key
  62974. ** specified by pIdxKey or intKey. Return a success code.
  62975. **
  62976. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  62977. ** must be NULL. For index tables, pIdxKey is used and intKey
  62978. ** is ignored.
  62979. **
  62980. ** If an exact match is not found, then the cursor is always
  62981. ** left pointing at a leaf page which would hold the entry if it
  62982. ** were present. The cursor might point to an entry that comes
  62983. ** before or after the key.
  62984. **
  62985. ** An integer is written into *pRes which is the result of
  62986. ** comparing the key with the entry to which the cursor is
  62987. ** pointing. The meaning of the integer written into
  62988. ** *pRes is as follows:
  62989. **
  62990. ** *pRes<0 The cursor is left pointing at an entry that
  62991. ** is smaller than intKey/pIdxKey or if the table is empty
  62992. ** and the cursor is therefore left point to nothing.
  62993. **
  62994. ** *pRes==0 The cursor is left pointing at an entry that
  62995. ** exactly matches intKey/pIdxKey.
  62996. **
  62997. ** *pRes>0 The cursor is left pointing at an entry that
  62998. ** is larger than intKey/pIdxKey.
  62999. **
  63000. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  63001. ** exists an entry in the table that exactly matches pIdxKey.
  63002. */
  63003. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  63004. BtCursor *pCur, /* The cursor to be moved */
  63005. UnpackedRecord *pIdxKey, /* Unpacked index key */
  63006. i64 intKey, /* The table key */
  63007. int biasRight, /* If true, bias the search to the high end */
  63008. int *pRes /* Write search results here */
  63009. ){
  63010. int rc;
  63011. RecordCompare xRecordCompare;
  63012. assert( cursorOwnsBtShared(pCur) );
  63013. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63014. assert( pRes );
  63015. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  63016. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  63017. /* If the cursor is already positioned at the point we are trying
  63018. ** to move to, then just return without doing any work */
  63019. if( pIdxKey==0
  63020. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  63021. ){
  63022. if( pCur->info.nKey==intKey ){
  63023. *pRes = 0;
  63024. return SQLITE_OK;
  63025. }
  63026. if( pCur->info.nKey<intKey ){
  63027. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  63028. *pRes = -1;
  63029. return SQLITE_OK;
  63030. }
  63031. /* If the requested key is one more than the previous key, then
  63032. ** try to get there using sqlite3BtreeNext() rather than a full
  63033. ** binary search. This is an optimization only. The correct answer
  63034. ** is still obtained without this case, only a little more slowely */
  63035. if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
  63036. *pRes = 0;
  63037. rc = sqlite3BtreeNext(pCur, 0);
  63038. if( rc==SQLITE_OK ){
  63039. getCellInfo(pCur);
  63040. if( pCur->info.nKey==intKey ){
  63041. return SQLITE_OK;
  63042. }
  63043. }else if( rc==SQLITE_DONE ){
  63044. rc = SQLITE_OK;
  63045. }else{
  63046. return rc;
  63047. }
  63048. }
  63049. }
  63050. }
  63051. if( pIdxKey ){
  63052. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  63053. pIdxKey->errCode = 0;
  63054. assert( pIdxKey->default_rc==1
  63055. || pIdxKey->default_rc==0
  63056. || pIdxKey->default_rc==-1
  63057. );
  63058. }else{
  63059. xRecordCompare = 0; /* All keys are integers */
  63060. }
  63061. rc = moveToRoot(pCur);
  63062. if( rc ){
  63063. if( rc==SQLITE_EMPTY ){
  63064. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  63065. *pRes = -1;
  63066. return SQLITE_OK;
  63067. }
  63068. return rc;
  63069. }
  63070. assert( pCur->pPage );
  63071. assert( pCur->pPage->isInit );
  63072. assert( pCur->eState==CURSOR_VALID );
  63073. assert( pCur->pPage->nCell > 0 );
  63074. assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
  63075. assert( pCur->curIntKey || pIdxKey );
  63076. for(;;){
  63077. int lwr, upr, idx, c;
  63078. Pgno chldPg;
  63079. MemPage *pPage = pCur->pPage;
  63080. u8 *pCell; /* Pointer to current cell in pPage */
  63081. /* pPage->nCell must be greater than zero. If this is the root-page
  63082. ** the cursor would have been INVALID above and this for(;;) loop
  63083. ** not run. If this is not the root-page, then the moveToChild() routine
  63084. ** would have already detected db corruption. Similarly, pPage must
  63085. ** be the right kind (index or table) of b-tree page. Otherwise
  63086. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  63087. assert( pPage->nCell>0 );
  63088. assert( pPage->intKey==(pIdxKey==0) );
  63089. lwr = 0;
  63090. upr = pPage->nCell-1;
  63091. assert( biasRight==0 || biasRight==1 );
  63092. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  63093. pCur->ix = (u16)idx;
  63094. if( xRecordCompare==0 ){
  63095. for(;;){
  63096. i64 nCellKey;
  63097. pCell = findCellPastPtr(pPage, idx);
  63098. if( pPage->intKeyLeaf ){
  63099. while( 0x80 <= *(pCell++) ){
  63100. if( pCell>=pPage->aDataEnd ){
  63101. return SQLITE_CORRUPT_PAGE(pPage);
  63102. }
  63103. }
  63104. }
  63105. getVarint(pCell, (u64*)&nCellKey);
  63106. if( nCellKey<intKey ){
  63107. lwr = idx+1;
  63108. if( lwr>upr ){ c = -1; break; }
  63109. }else if( nCellKey>intKey ){
  63110. upr = idx-1;
  63111. if( lwr>upr ){ c = +1; break; }
  63112. }else{
  63113. assert( nCellKey==intKey );
  63114. pCur->ix = (u16)idx;
  63115. if( !pPage->leaf ){
  63116. lwr = idx;
  63117. goto moveto_next_layer;
  63118. }else{
  63119. pCur->curFlags |= BTCF_ValidNKey;
  63120. pCur->info.nKey = nCellKey;
  63121. pCur->info.nSize = 0;
  63122. *pRes = 0;
  63123. return SQLITE_OK;
  63124. }
  63125. }
  63126. assert( lwr+upr>=0 );
  63127. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  63128. }
  63129. }else{
  63130. for(;;){
  63131. int nCell; /* Size of the pCell cell in bytes */
  63132. pCell = findCellPastPtr(pPage, idx);
  63133. /* The maximum supported page-size is 65536 bytes. This means that
  63134. ** the maximum number of record bytes stored on an index B-Tree
  63135. ** page is less than 16384 bytes and may be stored as a 2-byte
  63136. ** varint. This information is used to attempt to avoid parsing
  63137. ** the entire cell by checking for the cases where the record is
  63138. ** stored entirely within the b-tree page by inspecting the first
  63139. ** 2 bytes of the cell.
  63140. */
  63141. nCell = pCell[0];
  63142. if( nCell<=pPage->max1bytePayload ){
  63143. /* This branch runs if the record-size field of the cell is a
  63144. ** single byte varint and the record fits entirely on the main
  63145. ** b-tree page. */
  63146. testcase( pCell+nCell+1==pPage->aDataEnd );
  63147. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  63148. }else if( !(pCell[1] & 0x80)
  63149. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  63150. ){
  63151. /* The record-size field is a 2 byte varint and the record
  63152. ** fits entirely on the main b-tree page. */
  63153. testcase( pCell+nCell+2==pPage->aDataEnd );
  63154. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  63155. }else{
  63156. /* The record flows over onto one or more overflow pages. In
  63157. ** this case the whole cell needs to be parsed, a buffer allocated
  63158. ** and accessPayload() used to retrieve the record into the
  63159. ** buffer before VdbeRecordCompare() can be called.
  63160. **
  63161. ** If the record is corrupt, the xRecordCompare routine may read
  63162. ** up to two varints past the end of the buffer. An extra 18
  63163. ** bytes of padding is allocated at the end of the buffer in
  63164. ** case this happens. */
  63165. void *pCellKey;
  63166. u8 * const pCellBody = pCell - pPage->childPtrSize;
  63167. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  63168. nCell = (int)pCur->info.nKey;
  63169. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  63170. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  63171. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  63172. testcase( nCell==2 ); /* Minimum legal index key size */
  63173. if( nCell<2 ){
  63174. rc = SQLITE_CORRUPT_PAGE(pPage);
  63175. goto moveto_finish;
  63176. }
  63177. pCellKey = sqlite3Malloc( nCell+18 );
  63178. if( pCellKey==0 ){
  63179. rc = SQLITE_NOMEM_BKPT;
  63180. goto moveto_finish;
  63181. }
  63182. pCur->ix = (u16)idx;
  63183. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  63184. pCur->curFlags &= ~BTCF_ValidOvfl;
  63185. if( rc ){
  63186. sqlite3_free(pCellKey);
  63187. goto moveto_finish;
  63188. }
  63189. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  63190. sqlite3_free(pCellKey);
  63191. }
  63192. assert(
  63193. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  63194. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  63195. );
  63196. if( c<0 ){
  63197. lwr = idx+1;
  63198. }else if( c>0 ){
  63199. upr = idx-1;
  63200. }else{
  63201. assert( c==0 );
  63202. *pRes = 0;
  63203. rc = SQLITE_OK;
  63204. pCur->ix = (u16)idx;
  63205. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
  63206. goto moveto_finish;
  63207. }
  63208. if( lwr>upr ) break;
  63209. assert( lwr+upr>=0 );
  63210. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  63211. }
  63212. }
  63213. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  63214. assert( pPage->isInit );
  63215. if( pPage->leaf ){
  63216. assert( pCur->ix<pCur->pPage->nCell );
  63217. pCur->ix = (u16)idx;
  63218. *pRes = c;
  63219. rc = SQLITE_OK;
  63220. goto moveto_finish;
  63221. }
  63222. moveto_next_layer:
  63223. if( lwr>=pPage->nCell ){
  63224. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  63225. }else{
  63226. chldPg = get4byte(findCell(pPage, lwr));
  63227. }
  63228. pCur->ix = (u16)lwr;
  63229. rc = moveToChild(pCur, chldPg);
  63230. if( rc ) break;
  63231. }
  63232. moveto_finish:
  63233. pCur->info.nSize = 0;
  63234. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  63235. return rc;
  63236. }
  63237. /*
  63238. ** Return TRUE if the cursor is not pointing at an entry of the table.
  63239. **
  63240. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  63241. ** past the last entry in the table or sqlite3BtreePrev() moves past
  63242. ** the first entry. TRUE is also returned if the table is empty.
  63243. */
  63244. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  63245. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  63246. ** have been deleted? This API will need to change to return an error code
  63247. ** as well as the boolean result value.
  63248. */
  63249. return (CURSOR_VALID!=pCur->eState);
  63250. }
  63251. /*
  63252. ** Return an estimate for the number of rows in the table that pCur is
  63253. ** pointing to. Return a negative number if no estimate is currently
  63254. ** available.
  63255. */
  63256. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  63257. i64 n;
  63258. u8 i;
  63259. assert( cursorOwnsBtShared(pCur) );
  63260. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63261. /* Currently this interface is only called by the OP_IfSmaller
  63262. ** opcode, and it that case the cursor will always be valid and
  63263. ** will always point to a leaf node. */
  63264. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  63265. if( NEVER(pCur->pPage->leaf==0) ) return -1;
  63266. n = pCur->pPage->nCell;
  63267. for(i=0; i<pCur->iPage; i++){
  63268. n *= pCur->apPage[i]->nCell;
  63269. }
  63270. return n;
  63271. }
  63272. /*
  63273. ** Advance the cursor to the next entry in the database.
  63274. ** Return value:
  63275. **
  63276. ** SQLITE_OK success
  63277. ** SQLITE_DONE cursor is already pointing at the last element
  63278. ** otherwise some kind of error occurred
  63279. **
  63280. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  63281. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  63282. ** to the next cell on the current page. The (slower) btreeNext() helper
  63283. ** routine is called when it is necessary to move to a different page or
  63284. ** to restore the cursor.
  63285. **
  63286. ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
  63287. ** cursor corresponds to an SQL index and this routine could have been
  63288. ** skipped if the SQL index had been a unique index. The F argument
  63289. ** is a hint to the implement. SQLite btree implementation does not use
  63290. ** this hint, but COMDB2 does.
  63291. */
  63292. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
  63293. int rc;
  63294. int idx;
  63295. MemPage *pPage;
  63296. assert( cursorOwnsBtShared(pCur) );
  63297. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  63298. if( pCur->eState!=CURSOR_VALID ){
  63299. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  63300. rc = restoreCursorPosition(pCur);
  63301. if( rc!=SQLITE_OK ){
  63302. return rc;
  63303. }
  63304. if( CURSOR_INVALID==pCur->eState ){
  63305. return SQLITE_DONE;
  63306. }
  63307. if( pCur->skipNext ){
  63308. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  63309. pCur->eState = CURSOR_VALID;
  63310. if( pCur->skipNext>0 ){
  63311. pCur->skipNext = 0;
  63312. return SQLITE_OK;
  63313. }
  63314. pCur->skipNext = 0;
  63315. }
  63316. }
  63317. pPage = pCur->pPage;
  63318. idx = ++pCur->ix;
  63319. assert( pPage->isInit );
  63320. /* If the database file is corrupt, it is possible for the value of idx
  63321. ** to be invalid here. This can only occur if a second cursor modifies
  63322. ** the page while cursor pCur is holding a reference to it. Which can
  63323. ** only happen if the database is corrupt in such a way as to link the
  63324. ** page into more than one b-tree structure. */
  63325. testcase( idx>pPage->nCell );
  63326. if( idx>=pPage->nCell ){
  63327. if( !pPage->leaf ){
  63328. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  63329. if( rc ) return rc;
  63330. return moveToLeftmost(pCur);
  63331. }
  63332. do{
  63333. if( pCur->iPage==0 ){
  63334. pCur->eState = CURSOR_INVALID;
  63335. return SQLITE_DONE;
  63336. }
  63337. moveToParent(pCur);
  63338. pPage = pCur->pPage;
  63339. }while( pCur->ix>=pPage->nCell );
  63340. if( pPage->intKey ){
  63341. return sqlite3BtreeNext(pCur, 0);
  63342. }else{
  63343. return SQLITE_OK;
  63344. }
  63345. }
  63346. if( pPage->leaf ){
  63347. return SQLITE_OK;
  63348. }else{
  63349. return moveToLeftmost(pCur);
  63350. }
  63351. }
  63352. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
  63353. MemPage *pPage;
  63354. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  63355. assert( cursorOwnsBtShared(pCur) );
  63356. assert( flags==0 || flags==1 );
  63357. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  63358. pCur->info.nSize = 0;
  63359. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  63360. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
  63361. pPage = pCur->pPage;
  63362. if( (++pCur->ix)>=pPage->nCell ){
  63363. pCur->ix--;
  63364. return btreeNext(pCur);
  63365. }
  63366. if( pPage->leaf ){
  63367. return SQLITE_OK;
  63368. }else{
  63369. return moveToLeftmost(pCur);
  63370. }
  63371. }
  63372. /*
  63373. ** Step the cursor to the back to the previous entry in the database.
  63374. ** Return values:
  63375. **
  63376. ** SQLITE_OK success
  63377. ** SQLITE_DONE the cursor is already on the first element of the table
  63378. ** otherwise some kind of error occurred
  63379. **
  63380. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  63381. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  63382. ** to the previous cell on the current page. The (slower) btreePrevious()
  63383. ** helper routine is called when it is necessary to move to a different page
  63384. ** or to restore the cursor.
  63385. **
  63386. ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
  63387. ** the cursor corresponds to an SQL index and this routine could have been
  63388. ** skipped if the SQL index had been a unique index. The F argument is a
  63389. ** hint to the implement. The native SQLite btree implementation does not
  63390. ** use this hint, but COMDB2 does.
  63391. */
  63392. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
  63393. int rc;
  63394. MemPage *pPage;
  63395. assert( cursorOwnsBtShared(pCur) );
  63396. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  63397. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  63398. assert( pCur->info.nSize==0 );
  63399. if( pCur->eState!=CURSOR_VALID ){
  63400. rc = restoreCursorPosition(pCur);
  63401. if( rc!=SQLITE_OK ){
  63402. return rc;
  63403. }
  63404. if( CURSOR_INVALID==pCur->eState ){
  63405. return SQLITE_DONE;
  63406. }
  63407. if( pCur->skipNext ){
  63408. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  63409. pCur->eState = CURSOR_VALID;
  63410. if( pCur->skipNext<0 ){
  63411. pCur->skipNext = 0;
  63412. return SQLITE_OK;
  63413. }
  63414. pCur->skipNext = 0;
  63415. }
  63416. }
  63417. pPage = pCur->pPage;
  63418. assert( pPage->isInit );
  63419. if( !pPage->leaf ){
  63420. int idx = pCur->ix;
  63421. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  63422. if( rc ) return rc;
  63423. rc = moveToRightmost(pCur);
  63424. }else{
  63425. while( pCur->ix==0 ){
  63426. if( pCur->iPage==0 ){
  63427. pCur->eState = CURSOR_INVALID;
  63428. return SQLITE_DONE;
  63429. }
  63430. moveToParent(pCur);
  63431. }
  63432. assert( pCur->info.nSize==0 );
  63433. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  63434. pCur->ix--;
  63435. pPage = pCur->pPage;
  63436. if( pPage->intKey && !pPage->leaf ){
  63437. rc = sqlite3BtreePrevious(pCur, 0);
  63438. }else{
  63439. rc = SQLITE_OK;
  63440. }
  63441. }
  63442. return rc;
  63443. }
  63444. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
  63445. assert( cursorOwnsBtShared(pCur) );
  63446. assert( flags==0 || flags==1 );
  63447. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  63448. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  63449. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  63450. pCur->info.nSize = 0;
  63451. if( pCur->eState!=CURSOR_VALID
  63452. || pCur->ix==0
  63453. || pCur->pPage->leaf==0
  63454. ){
  63455. return btreePrevious(pCur);
  63456. }
  63457. pCur->ix--;
  63458. return SQLITE_OK;
  63459. }
  63460. /*
  63461. ** Allocate a new page from the database file.
  63462. **
  63463. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  63464. ** has already been called on the new page.) The new page has also
  63465. ** been referenced and the calling routine is responsible for calling
  63466. ** sqlite3PagerUnref() on the new page when it is done.
  63467. **
  63468. ** SQLITE_OK is returned on success. Any other return value indicates
  63469. ** an error. *ppPage is set to NULL in the event of an error.
  63470. **
  63471. ** If the "nearby" parameter is not 0, then an effort is made to
  63472. ** locate a page close to the page number "nearby". This can be used in an
  63473. ** attempt to keep related pages close to each other in the database file,
  63474. ** which in turn can make database access faster.
  63475. **
  63476. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  63477. ** anywhere on the free-list, then it is guaranteed to be returned. If
  63478. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  63479. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  63480. ** are no restrictions on which page is returned.
  63481. */
  63482. static int allocateBtreePage(
  63483. BtShared *pBt, /* The btree */
  63484. MemPage **ppPage, /* Store pointer to the allocated page here */
  63485. Pgno *pPgno, /* Store the page number here */
  63486. Pgno nearby, /* Search for a page near this one */
  63487. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  63488. ){
  63489. MemPage *pPage1;
  63490. int rc;
  63491. u32 n; /* Number of pages on the freelist */
  63492. u32 k; /* Number of leaves on the trunk of the freelist */
  63493. MemPage *pTrunk = 0;
  63494. MemPage *pPrevTrunk = 0;
  63495. Pgno mxPage; /* Total size of the database file */
  63496. assert( sqlite3_mutex_held(pBt->mutex) );
  63497. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  63498. pPage1 = pBt->pPage1;
  63499. mxPage = btreePagecount(pBt);
  63500. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  63501. ** stores stores the total number of pages on the freelist. */
  63502. n = get4byte(&pPage1->aData[36]);
  63503. testcase( n==mxPage-1 );
  63504. if( n>=mxPage ){
  63505. return SQLITE_CORRUPT_BKPT;
  63506. }
  63507. if( n>0 ){
  63508. /* There are pages on the freelist. Reuse one of those pages. */
  63509. Pgno iTrunk;
  63510. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  63511. u32 nSearch = 0; /* Count of the number of search attempts */
  63512. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  63513. ** shows that the page 'nearby' is somewhere on the free-list, then
  63514. ** the entire-list will be searched for that page.
  63515. */
  63516. #ifndef SQLITE_OMIT_AUTOVACUUM
  63517. if( eMode==BTALLOC_EXACT ){
  63518. if( nearby<=mxPage ){
  63519. u8 eType;
  63520. assert( nearby>0 );
  63521. assert( pBt->autoVacuum );
  63522. rc = ptrmapGet(pBt, nearby, &eType, 0);
  63523. if( rc ) return rc;
  63524. if( eType==PTRMAP_FREEPAGE ){
  63525. searchList = 1;
  63526. }
  63527. }
  63528. }else if( eMode==BTALLOC_LE ){
  63529. searchList = 1;
  63530. }
  63531. #endif
  63532. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  63533. ** first free-list trunk page. iPrevTrunk is initially 1.
  63534. */
  63535. rc = sqlite3PagerWrite(pPage1->pDbPage);
  63536. if( rc ) return rc;
  63537. put4byte(&pPage1->aData[36], n-1);
  63538. /* The code within this loop is run only once if the 'searchList' variable
  63539. ** is not true. Otherwise, it runs once for each trunk-page on the
  63540. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  63541. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  63542. */
  63543. do {
  63544. pPrevTrunk = pTrunk;
  63545. if( pPrevTrunk ){
  63546. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  63547. ** is the page number of the next freelist trunk page in the list or
  63548. ** zero if this is the last freelist trunk page. */
  63549. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  63550. }else{
  63551. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  63552. ** stores the page number of the first page of the freelist, or zero if
  63553. ** the freelist is empty. */
  63554. iTrunk = get4byte(&pPage1->aData[32]);
  63555. }
  63556. testcase( iTrunk==mxPage );
  63557. if( iTrunk>mxPage || nSearch++ > n ){
  63558. rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
  63559. }else{
  63560. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  63561. }
  63562. if( rc ){
  63563. pTrunk = 0;
  63564. goto end_allocate_page;
  63565. }
  63566. assert( pTrunk!=0 );
  63567. assert( pTrunk->aData!=0 );
  63568. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  63569. ** is the number of leaf page pointers to follow. */
  63570. k = get4byte(&pTrunk->aData[4]);
  63571. if( k==0 && !searchList ){
  63572. /* The trunk has no leaves and the list is not being searched.
  63573. ** So extract the trunk page itself and use it as the newly
  63574. ** allocated page */
  63575. assert( pPrevTrunk==0 );
  63576. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63577. if( rc ){
  63578. goto end_allocate_page;
  63579. }
  63580. *pPgno = iTrunk;
  63581. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  63582. *ppPage = pTrunk;
  63583. pTrunk = 0;
  63584. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  63585. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  63586. /* Value of k is out of range. Database corruption */
  63587. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  63588. goto end_allocate_page;
  63589. #ifndef SQLITE_OMIT_AUTOVACUUM
  63590. }else if( searchList
  63591. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  63592. ){
  63593. /* The list is being searched and this trunk page is the page
  63594. ** to allocate, regardless of whether it has leaves.
  63595. */
  63596. *pPgno = iTrunk;
  63597. *ppPage = pTrunk;
  63598. searchList = 0;
  63599. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63600. if( rc ){
  63601. goto end_allocate_page;
  63602. }
  63603. if( k==0 ){
  63604. if( !pPrevTrunk ){
  63605. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  63606. }else{
  63607. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  63608. if( rc!=SQLITE_OK ){
  63609. goto end_allocate_page;
  63610. }
  63611. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  63612. }
  63613. }else{
  63614. /* The trunk page is required by the caller but it contains
  63615. ** pointers to free-list leaves. The first leaf becomes a trunk
  63616. ** page in this case.
  63617. */
  63618. MemPage *pNewTrunk;
  63619. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  63620. if( iNewTrunk>mxPage ){
  63621. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  63622. goto end_allocate_page;
  63623. }
  63624. testcase( iNewTrunk==mxPage );
  63625. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  63626. if( rc!=SQLITE_OK ){
  63627. goto end_allocate_page;
  63628. }
  63629. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  63630. if( rc!=SQLITE_OK ){
  63631. releasePage(pNewTrunk);
  63632. goto end_allocate_page;
  63633. }
  63634. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  63635. put4byte(&pNewTrunk->aData[4], k-1);
  63636. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  63637. releasePage(pNewTrunk);
  63638. if( !pPrevTrunk ){
  63639. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  63640. put4byte(&pPage1->aData[32], iNewTrunk);
  63641. }else{
  63642. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  63643. if( rc ){
  63644. goto end_allocate_page;
  63645. }
  63646. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  63647. }
  63648. }
  63649. pTrunk = 0;
  63650. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  63651. #endif
  63652. }else if( k>0 ){
  63653. /* Extract a leaf from the trunk */
  63654. u32 closest;
  63655. Pgno iPage;
  63656. unsigned char *aData = pTrunk->aData;
  63657. if( nearby>0 ){
  63658. u32 i;
  63659. closest = 0;
  63660. if( eMode==BTALLOC_LE ){
  63661. for(i=0; i<k; i++){
  63662. iPage = get4byte(&aData[8+i*4]);
  63663. if( iPage<=nearby ){
  63664. closest = i;
  63665. break;
  63666. }
  63667. }
  63668. }else{
  63669. int dist;
  63670. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  63671. for(i=1; i<k; i++){
  63672. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  63673. if( d2<dist ){
  63674. closest = i;
  63675. dist = d2;
  63676. }
  63677. }
  63678. }
  63679. }else{
  63680. closest = 0;
  63681. }
  63682. iPage = get4byte(&aData[8+closest*4]);
  63683. testcase( iPage==mxPage );
  63684. if( iPage>mxPage ){
  63685. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  63686. goto end_allocate_page;
  63687. }
  63688. testcase( iPage==mxPage );
  63689. if( !searchList
  63690. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  63691. ){
  63692. int noContent;
  63693. *pPgno = iPage;
  63694. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  63695. ": %d more free pages\n",
  63696. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  63697. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63698. if( rc ) goto end_allocate_page;
  63699. if( closest<k-1 ){
  63700. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  63701. }
  63702. put4byte(&aData[4], k-1);
  63703. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  63704. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  63705. if( rc==SQLITE_OK ){
  63706. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  63707. if( rc!=SQLITE_OK ){
  63708. releasePage(*ppPage);
  63709. *ppPage = 0;
  63710. }
  63711. }
  63712. searchList = 0;
  63713. }
  63714. }
  63715. releasePage(pPrevTrunk);
  63716. pPrevTrunk = 0;
  63717. }while( searchList );
  63718. }else{
  63719. /* There are no pages on the freelist, so append a new page to the
  63720. ** database image.
  63721. **
  63722. ** Normally, new pages allocated by this block can be requested from the
  63723. ** pager layer with the 'no-content' flag set. This prevents the pager
  63724. ** from trying to read the pages content from disk. However, if the
  63725. ** current transaction has already run one or more incremental-vacuum
  63726. ** steps, then the page we are about to allocate may contain content
  63727. ** that is required in the event of a rollback. In this case, do
  63728. ** not set the no-content flag. This causes the pager to load and journal
  63729. ** the current page content before overwriting it.
  63730. **
  63731. ** Note that the pager will not actually attempt to load or journal
  63732. ** content for any page that really does lie past the end of the database
  63733. ** file on disk. So the effects of disabling the no-content optimization
  63734. ** here are confined to those pages that lie between the end of the
  63735. ** database image and the end of the database file.
  63736. */
  63737. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  63738. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  63739. if( rc ) return rc;
  63740. pBt->nPage++;
  63741. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  63742. #ifndef SQLITE_OMIT_AUTOVACUUM
  63743. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  63744. /* If *pPgno refers to a pointer-map page, allocate two new pages
  63745. ** at the end of the file instead of one. The first allocated page
  63746. ** becomes a new pointer-map page, the second is used by the caller.
  63747. */
  63748. MemPage *pPg = 0;
  63749. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  63750. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  63751. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  63752. if( rc==SQLITE_OK ){
  63753. rc = sqlite3PagerWrite(pPg->pDbPage);
  63754. releasePage(pPg);
  63755. }
  63756. if( rc ) return rc;
  63757. pBt->nPage++;
  63758. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  63759. }
  63760. #endif
  63761. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  63762. *pPgno = pBt->nPage;
  63763. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  63764. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  63765. if( rc ) return rc;
  63766. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  63767. if( rc!=SQLITE_OK ){
  63768. releasePage(*ppPage);
  63769. *ppPage = 0;
  63770. }
  63771. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  63772. }
  63773. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  63774. end_allocate_page:
  63775. releasePage(pTrunk);
  63776. releasePage(pPrevTrunk);
  63777. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  63778. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  63779. return rc;
  63780. }
  63781. /*
  63782. ** This function is used to add page iPage to the database file free-list.
  63783. ** It is assumed that the page is not already a part of the free-list.
  63784. **
  63785. ** The value passed as the second argument to this function is optional.
  63786. ** If the caller happens to have a pointer to the MemPage object
  63787. ** corresponding to page iPage handy, it may pass it as the second value.
  63788. ** Otherwise, it may pass NULL.
  63789. **
  63790. ** If a pointer to a MemPage object is passed as the second argument,
  63791. ** its reference count is not altered by this function.
  63792. */
  63793. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  63794. MemPage *pTrunk = 0; /* Free-list trunk page */
  63795. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  63796. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  63797. MemPage *pPage; /* Page being freed. May be NULL. */
  63798. int rc; /* Return Code */
  63799. int nFree; /* Initial number of pages on free-list */
  63800. assert( sqlite3_mutex_held(pBt->mutex) );
  63801. assert( CORRUPT_DB || iPage>1 );
  63802. assert( !pMemPage || pMemPage->pgno==iPage );
  63803. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  63804. if( pMemPage ){
  63805. pPage = pMemPage;
  63806. sqlite3PagerRef(pPage->pDbPage);
  63807. }else{
  63808. pPage = btreePageLookup(pBt, iPage);
  63809. }
  63810. /* Increment the free page count on pPage1 */
  63811. rc = sqlite3PagerWrite(pPage1->pDbPage);
  63812. if( rc ) goto freepage_out;
  63813. nFree = get4byte(&pPage1->aData[36]);
  63814. put4byte(&pPage1->aData[36], nFree+1);
  63815. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  63816. /* If the secure_delete option is enabled, then
  63817. ** always fully overwrite deleted information with zeros.
  63818. */
  63819. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  63820. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  63821. ){
  63822. goto freepage_out;
  63823. }
  63824. memset(pPage->aData, 0, pPage->pBt->pageSize);
  63825. }
  63826. /* If the database supports auto-vacuum, write an entry in the pointer-map
  63827. ** to indicate that the page is free.
  63828. */
  63829. if( ISAUTOVACUUM ){
  63830. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  63831. if( rc ) goto freepage_out;
  63832. }
  63833. /* Now manipulate the actual database free-list structure. There are two
  63834. ** possibilities. If the free-list is currently empty, or if the first
  63835. ** trunk page in the free-list is full, then this page will become a
  63836. ** new free-list trunk page. Otherwise, it will become a leaf of the
  63837. ** first trunk page in the current free-list. This block tests if it
  63838. ** is possible to add the page as a new free-list leaf.
  63839. */
  63840. if( nFree!=0 ){
  63841. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  63842. iTrunk = get4byte(&pPage1->aData[32]);
  63843. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  63844. if( rc!=SQLITE_OK ){
  63845. goto freepage_out;
  63846. }
  63847. nLeaf = get4byte(&pTrunk->aData[4]);
  63848. assert( pBt->usableSize>32 );
  63849. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  63850. rc = SQLITE_CORRUPT_BKPT;
  63851. goto freepage_out;
  63852. }
  63853. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  63854. /* In this case there is room on the trunk page to insert the page
  63855. ** being freed as a new leaf.
  63856. **
  63857. ** Note that the trunk page is not really full until it contains
  63858. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  63859. ** coded. But due to a coding error in versions of SQLite prior to
  63860. ** 3.6.0, databases with freelist trunk pages holding more than
  63861. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  63862. ** to maintain backwards compatibility with older versions of SQLite,
  63863. ** we will continue to restrict the number of entries to usableSize/4 - 8
  63864. ** for now. At some point in the future (once everyone has upgraded
  63865. ** to 3.6.0 or later) we should consider fixing the conditional above
  63866. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  63867. **
  63868. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  63869. ** avoid using the last six entries in the freelist trunk page array in
  63870. ** order that database files created by newer versions of SQLite can be
  63871. ** read by older versions of SQLite.
  63872. */
  63873. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63874. if( rc==SQLITE_OK ){
  63875. put4byte(&pTrunk->aData[4], nLeaf+1);
  63876. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  63877. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  63878. sqlite3PagerDontWrite(pPage->pDbPage);
  63879. }
  63880. rc = btreeSetHasContent(pBt, iPage);
  63881. }
  63882. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  63883. goto freepage_out;
  63884. }
  63885. }
  63886. /* If control flows to this point, then it was not possible to add the
  63887. ** the page being freed as a leaf page of the first trunk in the free-list.
  63888. ** Possibly because the free-list is empty, or possibly because the
  63889. ** first trunk in the free-list is full. Either way, the page being freed
  63890. ** will become the new first trunk page in the free-list.
  63891. */
  63892. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  63893. goto freepage_out;
  63894. }
  63895. rc = sqlite3PagerWrite(pPage->pDbPage);
  63896. if( rc!=SQLITE_OK ){
  63897. goto freepage_out;
  63898. }
  63899. put4byte(pPage->aData, iTrunk);
  63900. put4byte(&pPage->aData[4], 0);
  63901. put4byte(&pPage1->aData[32], iPage);
  63902. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  63903. freepage_out:
  63904. if( pPage ){
  63905. pPage->isInit = 0;
  63906. }
  63907. releasePage(pPage);
  63908. releasePage(pTrunk);
  63909. return rc;
  63910. }
  63911. static void freePage(MemPage *pPage, int *pRC){
  63912. if( (*pRC)==SQLITE_OK ){
  63913. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  63914. }
  63915. }
  63916. /*
  63917. ** Free any overflow pages associated with the given Cell. Store
  63918. ** size information about the cell in pInfo.
  63919. */
  63920. static int clearCell(
  63921. MemPage *pPage, /* The page that contains the Cell */
  63922. unsigned char *pCell, /* First byte of the Cell */
  63923. CellInfo *pInfo /* Size information about the cell */
  63924. ){
  63925. BtShared *pBt;
  63926. Pgno ovflPgno;
  63927. int rc;
  63928. int nOvfl;
  63929. u32 ovflPageSize;
  63930. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  63931. pPage->xParseCell(pPage, pCell, pInfo);
  63932. if( pInfo->nLocal==pInfo->nPayload ){
  63933. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  63934. }
  63935. testcase( pCell + pInfo->nSize == pPage->aDataEnd );
  63936. testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
  63937. if( pCell + pInfo->nSize > pPage->aDataEnd ){
  63938. /* Cell extends past end of page */
  63939. return SQLITE_CORRUPT_PAGE(pPage);
  63940. }
  63941. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  63942. pBt = pPage->pBt;
  63943. assert( pBt->usableSize > 4 );
  63944. ovflPageSize = pBt->usableSize - 4;
  63945. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  63946. assert( nOvfl>0 ||
  63947. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  63948. );
  63949. while( nOvfl-- ){
  63950. Pgno iNext = 0;
  63951. MemPage *pOvfl = 0;
  63952. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  63953. /* 0 is not a legal page number and page 1 cannot be an
  63954. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  63955. ** file the database must be corrupt. */
  63956. return SQLITE_CORRUPT_BKPT;
  63957. }
  63958. if( nOvfl ){
  63959. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  63960. if( rc ) return rc;
  63961. }
  63962. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  63963. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  63964. ){
  63965. /* There is no reason any cursor should have an outstanding reference
  63966. ** to an overflow page belonging to a cell that is being deleted/updated.
  63967. ** So if there exists more than one reference to this page, then it
  63968. ** must not really be an overflow page and the database must be corrupt.
  63969. ** It is helpful to detect this before calling freePage2(), as
  63970. ** freePage2() may zero the page contents if secure-delete mode is
  63971. ** enabled. If this 'overflow' page happens to be a page that the
  63972. ** caller is iterating through or using in some other way, this
  63973. ** can be problematic.
  63974. */
  63975. rc = SQLITE_CORRUPT_BKPT;
  63976. }else{
  63977. rc = freePage2(pBt, pOvfl, ovflPgno);
  63978. }
  63979. if( pOvfl ){
  63980. sqlite3PagerUnref(pOvfl->pDbPage);
  63981. }
  63982. if( rc ) return rc;
  63983. ovflPgno = iNext;
  63984. }
  63985. return SQLITE_OK;
  63986. }
  63987. /*
  63988. ** Create the byte sequence used to represent a cell on page pPage
  63989. ** and write that byte sequence into pCell[]. Overflow pages are
  63990. ** allocated and filled in as necessary. The calling procedure
  63991. ** is responsible for making sure sufficient space has been allocated
  63992. ** for pCell[].
  63993. **
  63994. ** Note that pCell does not necessary need to point to the pPage->aData
  63995. ** area. pCell might point to some temporary storage. The cell will
  63996. ** be constructed in this temporary area then copied into pPage->aData
  63997. ** later.
  63998. */
  63999. static int fillInCell(
  64000. MemPage *pPage, /* The page that contains the cell */
  64001. unsigned char *pCell, /* Complete text of the cell */
  64002. const BtreePayload *pX, /* Payload with which to construct the cell */
  64003. int *pnSize /* Write cell size here */
  64004. ){
  64005. int nPayload;
  64006. const u8 *pSrc;
  64007. int nSrc, n, rc, mn;
  64008. int spaceLeft;
  64009. MemPage *pToRelease;
  64010. unsigned char *pPrior;
  64011. unsigned char *pPayload;
  64012. BtShared *pBt;
  64013. Pgno pgnoOvfl;
  64014. int nHeader;
  64015. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  64016. /* pPage is not necessarily writeable since pCell might be auxiliary
  64017. ** buffer space that is separate from the pPage buffer area */
  64018. assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
  64019. || sqlite3PagerIswriteable(pPage->pDbPage) );
  64020. /* Fill in the header. */
  64021. nHeader = pPage->childPtrSize;
  64022. if( pPage->intKey ){
  64023. nPayload = pX->nData + pX->nZero;
  64024. pSrc = pX->pData;
  64025. nSrc = pX->nData;
  64026. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  64027. nHeader += putVarint32(&pCell[nHeader], nPayload);
  64028. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  64029. }else{
  64030. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  64031. nSrc = nPayload = (int)pX->nKey;
  64032. pSrc = pX->pKey;
  64033. nHeader += putVarint32(&pCell[nHeader], nPayload);
  64034. }
  64035. /* Fill in the payload */
  64036. pPayload = &pCell[nHeader];
  64037. if( nPayload<=pPage->maxLocal ){
  64038. /* This is the common case where everything fits on the btree page
  64039. ** and no overflow pages are required. */
  64040. n = nHeader + nPayload;
  64041. testcase( n==3 );
  64042. testcase( n==4 );
  64043. if( n<4 ) n = 4;
  64044. *pnSize = n;
  64045. assert( nSrc<=nPayload );
  64046. testcase( nSrc<nPayload );
  64047. memcpy(pPayload, pSrc, nSrc);
  64048. memset(pPayload+nSrc, 0, nPayload-nSrc);
  64049. return SQLITE_OK;
  64050. }
  64051. /* If we reach this point, it means that some of the content will need
  64052. ** to spill onto overflow pages.
  64053. */
  64054. mn = pPage->minLocal;
  64055. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  64056. testcase( n==pPage->maxLocal );
  64057. testcase( n==pPage->maxLocal+1 );
  64058. if( n > pPage->maxLocal ) n = mn;
  64059. spaceLeft = n;
  64060. *pnSize = n + nHeader + 4;
  64061. pPrior = &pCell[nHeader+n];
  64062. pToRelease = 0;
  64063. pgnoOvfl = 0;
  64064. pBt = pPage->pBt;
  64065. /* At this point variables should be set as follows:
  64066. **
  64067. ** nPayload Total payload size in bytes
  64068. ** pPayload Begin writing payload here
  64069. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  64070. ** that means content must spill into overflow pages.
  64071. ** *pnSize Size of the local cell (not counting overflow pages)
  64072. ** pPrior Where to write the pgno of the first overflow page
  64073. **
  64074. ** Use a call to btreeParseCellPtr() to verify that the values above
  64075. ** were computed correctly.
  64076. */
  64077. #ifdef SQLITE_DEBUG
  64078. {
  64079. CellInfo info;
  64080. pPage->xParseCell(pPage, pCell, &info);
  64081. assert( nHeader==(int)(info.pPayload - pCell) );
  64082. assert( info.nKey==pX->nKey );
  64083. assert( *pnSize == info.nSize );
  64084. assert( spaceLeft == info.nLocal );
  64085. }
  64086. #endif
  64087. /* Write the payload into the local Cell and any extra into overflow pages */
  64088. while( 1 ){
  64089. n = nPayload;
  64090. if( n>spaceLeft ) n = spaceLeft;
  64091. /* If pToRelease is not zero than pPayload points into the data area
  64092. ** of pToRelease. Make sure pToRelease is still writeable. */
  64093. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  64094. /* If pPayload is part of the data area of pPage, then make sure pPage
  64095. ** is still writeable */
  64096. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  64097. || sqlite3PagerIswriteable(pPage->pDbPage) );
  64098. if( nSrc>=n ){
  64099. memcpy(pPayload, pSrc, n);
  64100. }else if( nSrc>0 ){
  64101. n = nSrc;
  64102. memcpy(pPayload, pSrc, n);
  64103. }else{
  64104. memset(pPayload, 0, n);
  64105. }
  64106. nPayload -= n;
  64107. if( nPayload<=0 ) break;
  64108. pPayload += n;
  64109. pSrc += n;
  64110. nSrc -= n;
  64111. spaceLeft -= n;
  64112. if( spaceLeft==0 ){
  64113. MemPage *pOvfl = 0;
  64114. #ifndef SQLITE_OMIT_AUTOVACUUM
  64115. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  64116. if( pBt->autoVacuum ){
  64117. do{
  64118. pgnoOvfl++;
  64119. } while(
  64120. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  64121. );
  64122. }
  64123. #endif
  64124. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  64125. #ifndef SQLITE_OMIT_AUTOVACUUM
  64126. /* If the database supports auto-vacuum, and the second or subsequent
  64127. ** overflow page is being allocated, add an entry to the pointer-map
  64128. ** for that page now.
  64129. **
  64130. ** If this is the first overflow page, then write a partial entry
  64131. ** to the pointer-map. If we write nothing to this pointer-map slot,
  64132. ** then the optimistic overflow chain processing in clearCell()
  64133. ** may misinterpret the uninitialized values and delete the
  64134. ** wrong pages from the database.
  64135. */
  64136. if( pBt->autoVacuum && rc==SQLITE_OK ){
  64137. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  64138. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  64139. if( rc ){
  64140. releasePage(pOvfl);
  64141. }
  64142. }
  64143. #endif
  64144. if( rc ){
  64145. releasePage(pToRelease);
  64146. return rc;
  64147. }
  64148. /* If pToRelease is not zero than pPrior points into the data area
  64149. ** of pToRelease. Make sure pToRelease is still writeable. */
  64150. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  64151. /* If pPrior is part of the data area of pPage, then make sure pPage
  64152. ** is still writeable */
  64153. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  64154. || sqlite3PagerIswriteable(pPage->pDbPage) );
  64155. put4byte(pPrior, pgnoOvfl);
  64156. releasePage(pToRelease);
  64157. pToRelease = pOvfl;
  64158. pPrior = pOvfl->aData;
  64159. put4byte(pPrior, 0);
  64160. pPayload = &pOvfl->aData[4];
  64161. spaceLeft = pBt->usableSize - 4;
  64162. }
  64163. }
  64164. releasePage(pToRelease);
  64165. return SQLITE_OK;
  64166. }
  64167. /*
  64168. ** Remove the i-th cell from pPage. This routine effects pPage only.
  64169. ** The cell content is not freed or deallocated. It is assumed that
  64170. ** the cell content has been copied someplace else. This routine just
  64171. ** removes the reference to the cell from pPage.
  64172. **
  64173. ** "sz" must be the number of bytes in the cell.
  64174. */
  64175. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  64176. u32 pc; /* Offset to cell content of cell being deleted */
  64177. u8 *data; /* pPage->aData */
  64178. u8 *ptr; /* Used to move bytes around within data[] */
  64179. int rc; /* The return code */
  64180. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  64181. if( *pRC ) return;
  64182. assert( idx>=0 && idx<pPage->nCell );
  64183. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  64184. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  64185. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  64186. data = pPage->aData;
  64187. ptr = &pPage->aCellIdx[2*idx];
  64188. pc = get2byte(ptr);
  64189. hdr = pPage->hdrOffset;
  64190. testcase( pc==get2byte(&data[hdr+5]) );
  64191. testcase( pc+sz==pPage->pBt->usableSize );
  64192. if( pc+sz > pPage->pBt->usableSize ){
  64193. *pRC = SQLITE_CORRUPT_BKPT;
  64194. return;
  64195. }
  64196. rc = freeSpace(pPage, pc, sz);
  64197. if( rc ){
  64198. *pRC = rc;
  64199. return;
  64200. }
  64201. pPage->nCell--;
  64202. if( pPage->nCell==0 ){
  64203. memset(&data[hdr+1], 0, 4);
  64204. data[hdr+7] = 0;
  64205. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  64206. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  64207. - pPage->childPtrSize - 8;
  64208. }else{
  64209. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  64210. put2byte(&data[hdr+3], pPage->nCell);
  64211. pPage->nFree += 2;
  64212. }
  64213. }
  64214. /*
  64215. ** Insert a new cell on pPage at cell index "i". pCell points to the
  64216. ** content of the cell.
  64217. **
  64218. ** If the cell content will fit on the page, then put it there. If it
  64219. ** will not fit, then make a copy of the cell content into pTemp if
  64220. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  64221. ** in pPage->apOvfl[] and make it point to the cell content (either
  64222. ** in pTemp or the original pCell) and also record its index.
  64223. ** Allocating a new entry in pPage->aCell[] implies that
  64224. ** pPage->nOverflow is incremented.
  64225. **
  64226. ** *pRC must be SQLITE_OK when this routine is called.
  64227. */
  64228. static void insertCell(
  64229. MemPage *pPage, /* Page into which we are copying */
  64230. int i, /* New cell becomes the i-th cell of the page */
  64231. u8 *pCell, /* Content of the new cell */
  64232. int sz, /* Bytes of content in pCell */
  64233. u8 *pTemp, /* Temp storage space for pCell, if needed */
  64234. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  64235. int *pRC /* Read and write return code from here */
  64236. ){
  64237. int idx = 0; /* Where to write new cell content in data[] */
  64238. int j; /* Loop counter */
  64239. u8 *data; /* The content of the whole page */
  64240. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  64241. assert( *pRC==SQLITE_OK );
  64242. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  64243. assert( MX_CELL(pPage->pBt)<=10921 );
  64244. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  64245. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  64246. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  64247. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  64248. /* The cell should normally be sized correctly. However, when moving a
  64249. ** malformed cell from a leaf page to an interior page, if the cell size
  64250. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  64251. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  64252. ** the term after the || in the following assert(). */
  64253. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  64254. if( pPage->nOverflow || sz+2>pPage->nFree ){
  64255. if( pTemp ){
  64256. memcpy(pTemp, pCell, sz);
  64257. pCell = pTemp;
  64258. }
  64259. if( iChild ){
  64260. put4byte(pCell, iChild);
  64261. }
  64262. j = pPage->nOverflow++;
  64263. /* Comparison against ArraySize-1 since we hold back one extra slot
  64264. ** as a contingency. In other words, never need more than 3 overflow
  64265. ** slots but 4 are allocated, just to be safe. */
  64266. assert( j < ArraySize(pPage->apOvfl)-1 );
  64267. pPage->apOvfl[j] = pCell;
  64268. pPage->aiOvfl[j] = (u16)i;
  64269. /* When multiple overflows occur, they are always sequential and in
  64270. ** sorted order. This invariants arise because multiple overflows can
  64271. ** only occur when inserting divider cells into the parent page during
  64272. ** balancing, and the dividers are adjacent and sorted.
  64273. */
  64274. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  64275. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  64276. }else{
  64277. int rc = sqlite3PagerWrite(pPage->pDbPage);
  64278. if( rc!=SQLITE_OK ){
  64279. *pRC = rc;
  64280. return;
  64281. }
  64282. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  64283. data = pPage->aData;
  64284. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  64285. rc = allocateSpace(pPage, sz, &idx);
  64286. if( rc ){ *pRC = rc; return; }
  64287. /* The allocateSpace() routine guarantees the following properties
  64288. ** if it returns successfully */
  64289. assert( idx >= 0 );
  64290. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  64291. assert( idx+sz <= (int)pPage->pBt->usableSize );
  64292. pPage->nFree -= (u16)(2 + sz);
  64293. memcpy(&data[idx], pCell, sz);
  64294. if( iChild ){
  64295. put4byte(&data[idx], iChild);
  64296. }
  64297. pIns = pPage->aCellIdx + i*2;
  64298. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  64299. put2byte(pIns, idx);
  64300. pPage->nCell++;
  64301. /* increment the cell count */
  64302. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  64303. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  64304. #ifndef SQLITE_OMIT_AUTOVACUUM
  64305. if( pPage->pBt->autoVacuum ){
  64306. /* The cell may contain a pointer to an overflow page. If so, write
  64307. ** the entry for the overflow page into the pointer map.
  64308. */
  64309. ptrmapPutOvflPtr(pPage, pCell, pRC);
  64310. }
  64311. #endif
  64312. }
  64313. }
  64314. /*
  64315. ** A CellArray object contains a cache of pointers and sizes for a
  64316. ** consecutive sequence of cells that might be held on multiple pages.
  64317. */
  64318. typedef struct CellArray CellArray;
  64319. struct CellArray {
  64320. int nCell; /* Number of cells in apCell[] */
  64321. MemPage *pRef; /* Reference page */
  64322. u8 **apCell; /* All cells begin balanced */
  64323. u16 *szCell; /* Local size of all cells in apCell[] */
  64324. };
  64325. /*
  64326. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  64327. ** computed.
  64328. */
  64329. static void populateCellCache(CellArray *p, int idx, int N){
  64330. assert( idx>=0 && idx+N<=p->nCell );
  64331. while( N>0 ){
  64332. assert( p->apCell[idx]!=0 );
  64333. if( p->szCell[idx]==0 ){
  64334. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  64335. }else{
  64336. assert( CORRUPT_DB ||
  64337. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  64338. }
  64339. idx++;
  64340. N--;
  64341. }
  64342. }
  64343. /*
  64344. ** Return the size of the Nth element of the cell array
  64345. */
  64346. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  64347. assert( N>=0 && N<p->nCell );
  64348. assert( p->szCell[N]==0 );
  64349. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  64350. return p->szCell[N];
  64351. }
  64352. static u16 cachedCellSize(CellArray *p, int N){
  64353. assert( N>=0 && N<p->nCell );
  64354. if( p->szCell[N] ) return p->szCell[N];
  64355. return computeCellSize(p, N);
  64356. }
  64357. /*
  64358. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  64359. ** szCell[] array contains the size in bytes of each cell. This function
  64360. ** replaces the current contents of page pPg with the contents of the cell
  64361. ** array.
  64362. **
  64363. ** Some of the cells in apCell[] may currently be stored in pPg. This
  64364. ** function works around problems caused by this by making a copy of any
  64365. ** such cells before overwriting the page data.
  64366. **
  64367. ** The MemPage.nFree field is invalidated by this function. It is the
  64368. ** responsibility of the caller to set it correctly.
  64369. */
  64370. static int rebuildPage(
  64371. MemPage *pPg, /* Edit this page */
  64372. int nCell, /* Final number of cells on page */
  64373. u8 **apCell, /* Array of cells */
  64374. u16 *szCell /* Array of cell sizes */
  64375. ){
  64376. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  64377. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  64378. const int usableSize = pPg->pBt->usableSize;
  64379. u8 * const pEnd = &aData[usableSize];
  64380. int i;
  64381. u8 *pCellptr = pPg->aCellIdx;
  64382. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  64383. u8 *pData;
  64384. i = get2byte(&aData[hdr+5]);
  64385. memcpy(&pTmp[i], &aData[i], usableSize - i);
  64386. pData = pEnd;
  64387. for(i=0; i<nCell; i++){
  64388. u8 *pCell = apCell[i];
  64389. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  64390. pCell = &pTmp[pCell - aData];
  64391. }
  64392. pData -= szCell[i];
  64393. put2byte(pCellptr, (pData - aData));
  64394. pCellptr += 2;
  64395. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  64396. memcpy(pData, pCell, szCell[i]);
  64397. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  64398. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  64399. }
  64400. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  64401. pPg->nCell = nCell;
  64402. pPg->nOverflow = 0;
  64403. put2byte(&aData[hdr+1], 0);
  64404. put2byte(&aData[hdr+3], pPg->nCell);
  64405. put2byte(&aData[hdr+5], pData - aData);
  64406. aData[hdr+7] = 0x00;
  64407. return SQLITE_OK;
  64408. }
  64409. /*
  64410. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  64411. ** contains the size in bytes of each such cell. This function attempts to
  64412. ** add the cells stored in the array to page pPg. If it cannot (because
  64413. ** the page needs to be defragmented before the cells will fit), non-zero
  64414. ** is returned. Otherwise, if the cells are added successfully, zero is
  64415. ** returned.
  64416. **
  64417. ** Argument pCellptr points to the first entry in the cell-pointer array
  64418. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  64419. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  64420. ** cell in the array. It is the responsibility of the caller to ensure
  64421. ** that it is safe to overwrite this part of the cell-pointer array.
  64422. **
  64423. ** When this function is called, *ppData points to the start of the
  64424. ** content area on page pPg. If the size of the content area is extended,
  64425. ** *ppData is updated to point to the new start of the content area
  64426. ** before returning.
  64427. **
  64428. ** Finally, argument pBegin points to the byte immediately following the
  64429. ** end of the space required by this page for the cell-pointer area (for
  64430. ** all cells - not just those inserted by the current call). If the content
  64431. ** area must be extended to before this point in order to accomodate all
  64432. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  64433. */
  64434. static int pageInsertArray(
  64435. MemPage *pPg, /* Page to add cells to */
  64436. u8 *pBegin, /* End of cell-pointer array */
  64437. u8 **ppData, /* IN/OUT: Page content -area pointer */
  64438. u8 *pCellptr, /* Pointer to cell-pointer area */
  64439. int iFirst, /* Index of first cell to add */
  64440. int nCell, /* Number of cells to add to pPg */
  64441. CellArray *pCArray /* Array of cells */
  64442. ){
  64443. int i;
  64444. u8 *aData = pPg->aData;
  64445. u8 *pData = *ppData;
  64446. int iEnd = iFirst + nCell;
  64447. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  64448. for(i=iFirst; i<iEnd; i++){
  64449. int sz, rc;
  64450. u8 *pSlot;
  64451. sz = cachedCellSize(pCArray, i);
  64452. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  64453. if( (pData - pBegin)<sz ) return 1;
  64454. pData -= sz;
  64455. pSlot = pData;
  64456. }
  64457. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  64458. ** database. But they might for a corrupt database. Hence use memmove()
  64459. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  64460. assert( (pSlot+sz)<=pCArray->apCell[i]
  64461. || pSlot>=(pCArray->apCell[i]+sz)
  64462. || CORRUPT_DB );
  64463. memmove(pSlot, pCArray->apCell[i], sz);
  64464. put2byte(pCellptr, (pSlot - aData));
  64465. pCellptr += 2;
  64466. }
  64467. *ppData = pData;
  64468. return 0;
  64469. }
  64470. /*
  64471. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  64472. ** contains the size in bytes of each such cell. This function adds the
  64473. ** space associated with each cell in the array that is currently stored
  64474. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  64475. ** fields of the page are not updated.
  64476. **
  64477. ** This function returns the total number of cells added to the free-list.
  64478. */
  64479. static int pageFreeArray(
  64480. MemPage *pPg, /* Page to edit */
  64481. int iFirst, /* First cell to delete */
  64482. int nCell, /* Cells to delete */
  64483. CellArray *pCArray /* Array of cells */
  64484. ){
  64485. u8 * const aData = pPg->aData;
  64486. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  64487. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  64488. int nRet = 0;
  64489. int i;
  64490. int iEnd = iFirst + nCell;
  64491. u8 *pFree = 0;
  64492. int szFree = 0;
  64493. for(i=iFirst; i<iEnd; i++){
  64494. u8 *pCell = pCArray->apCell[i];
  64495. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  64496. int sz;
  64497. /* No need to use cachedCellSize() here. The sizes of all cells that
  64498. ** are to be freed have already been computing while deciding which
  64499. ** cells need freeing */
  64500. sz = pCArray->szCell[i]; assert( sz>0 );
  64501. if( pFree!=(pCell + sz) ){
  64502. if( pFree ){
  64503. assert( pFree>aData && (pFree - aData)<65536 );
  64504. freeSpace(pPg, (u16)(pFree - aData), szFree);
  64505. }
  64506. pFree = pCell;
  64507. szFree = sz;
  64508. if( pFree+sz>pEnd ) return 0;
  64509. }else{
  64510. pFree = pCell;
  64511. szFree += sz;
  64512. }
  64513. nRet++;
  64514. }
  64515. }
  64516. if( pFree ){
  64517. assert( pFree>aData && (pFree - aData)<65536 );
  64518. freeSpace(pPg, (u16)(pFree - aData), szFree);
  64519. }
  64520. return nRet;
  64521. }
  64522. /*
  64523. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  64524. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  64525. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  64526. ** starting at apCell[iNew].
  64527. **
  64528. ** This routine makes the necessary adjustments to pPg so that it contains
  64529. ** the correct cells after being balanced.
  64530. **
  64531. ** The pPg->nFree field is invalid when this function returns. It is the
  64532. ** responsibility of the caller to set it correctly.
  64533. */
  64534. static int editPage(
  64535. MemPage *pPg, /* Edit this page */
  64536. int iOld, /* Index of first cell currently on page */
  64537. int iNew, /* Index of new first cell on page */
  64538. int nNew, /* Final number of cells on page */
  64539. CellArray *pCArray /* Array of cells and sizes */
  64540. ){
  64541. u8 * const aData = pPg->aData;
  64542. const int hdr = pPg->hdrOffset;
  64543. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  64544. int nCell = pPg->nCell; /* Cells stored on pPg */
  64545. u8 *pData;
  64546. u8 *pCellptr;
  64547. int i;
  64548. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  64549. int iNewEnd = iNew + nNew;
  64550. #ifdef SQLITE_DEBUG
  64551. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  64552. memcpy(pTmp, aData, pPg->pBt->usableSize);
  64553. #endif
  64554. /* Remove cells from the start and end of the page */
  64555. if( iOld<iNew ){
  64556. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  64557. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  64558. nCell -= nShift;
  64559. }
  64560. if( iNewEnd < iOldEnd ){
  64561. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  64562. }
  64563. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  64564. if( pData<pBegin ) goto editpage_fail;
  64565. /* Add cells to the start of the page */
  64566. if( iNew<iOld ){
  64567. int nAdd = MIN(nNew,iOld-iNew);
  64568. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  64569. pCellptr = pPg->aCellIdx;
  64570. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  64571. if( pageInsertArray(
  64572. pPg, pBegin, &pData, pCellptr,
  64573. iNew, nAdd, pCArray
  64574. ) ) goto editpage_fail;
  64575. nCell += nAdd;
  64576. }
  64577. /* Add any overflow cells */
  64578. for(i=0; i<pPg->nOverflow; i++){
  64579. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  64580. if( iCell>=0 && iCell<nNew ){
  64581. pCellptr = &pPg->aCellIdx[iCell * 2];
  64582. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  64583. nCell++;
  64584. if( pageInsertArray(
  64585. pPg, pBegin, &pData, pCellptr,
  64586. iCell+iNew, 1, pCArray
  64587. ) ) goto editpage_fail;
  64588. }
  64589. }
  64590. /* Append cells to the end of the page */
  64591. pCellptr = &pPg->aCellIdx[nCell*2];
  64592. if( pageInsertArray(
  64593. pPg, pBegin, &pData, pCellptr,
  64594. iNew+nCell, nNew-nCell, pCArray
  64595. ) ) goto editpage_fail;
  64596. pPg->nCell = nNew;
  64597. pPg->nOverflow = 0;
  64598. put2byte(&aData[hdr+3], pPg->nCell);
  64599. put2byte(&aData[hdr+5], pData - aData);
  64600. #ifdef SQLITE_DEBUG
  64601. for(i=0; i<nNew && !CORRUPT_DB; i++){
  64602. u8 *pCell = pCArray->apCell[i+iNew];
  64603. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  64604. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  64605. pCell = &pTmp[pCell - aData];
  64606. }
  64607. assert( 0==memcmp(pCell, &aData[iOff],
  64608. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  64609. }
  64610. #endif
  64611. return SQLITE_OK;
  64612. editpage_fail:
  64613. /* Unable to edit this page. Rebuild it from scratch instead. */
  64614. populateCellCache(pCArray, iNew, nNew);
  64615. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  64616. }
  64617. /*
  64618. ** The following parameters determine how many adjacent pages get involved
  64619. ** in a balancing operation. NN is the number of neighbors on either side
  64620. ** of the page that participate in the balancing operation. NB is the
  64621. ** total number of pages that participate, including the target page and
  64622. ** NN neighbors on either side.
  64623. **
  64624. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  64625. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  64626. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  64627. ** The value of NN appears to give the best results overall.
  64628. */
  64629. #define NN 1 /* Number of neighbors on either side of pPage */
  64630. #define NB (NN*2+1) /* Total pages involved in the balance */
  64631. #ifndef SQLITE_OMIT_QUICKBALANCE
  64632. /*
  64633. ** This version of balance() handles the common special case where
  64634. ** a new entry is being inserted on the extreme right-end of the
  64635. ** tree, in other words, when the new entry will become the largest
  64636. ** entry in the tree.
  64637. **
  64638. ** Instead of trying to balance the 3 right-most leaf pages, just add
  64639. ** a new page to the right-hand side and put the one new entry in
  64640. ** that page. This leaves the right side of the tree somewhat
  64641. ** unbalanced. But odds are that we will be inserting new entries
  64642. ** at the end soon afterwards so the nearly empty page will quickly
  64643. ** fill up. On average.
  64644. **
  64645. ** pPage is the leaf page which is the right-most page in the tree.
  64646. ** pParent is its parent. pPage must have a single overflow entry
  64647. ** which is also the right-most entry on the page.
  64648. **
  64649. ** The pSpace buffer is used to store a temporary copy of the divider
  64650. ** cell that will be inserted into pParent. Such a cell consists of a 4
  64651. ** byte page number followed by a variable length integer. In other
  64652. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  64653. ** least 13 bytes in size.
  64654. */
  64655. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  64656. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  64657. MemPage *pNew; /* Newly allocated page */
  64658. int rc; /* Return Code */
  64659. Pgno pgnoNew; /* Page number of pNew */
  64660. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  64661. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  64662. assert( pPage->nOverflow==1 );
  64663. /* This error condition is now caught prior to reaching this function */
  64664. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  64665. /* Allocate a new page. This page will become the right-sibling of
  64666. ** pPage. Make the parent page writable, so that the new divider cell
  64667. ** may be inserted. If both these operations are successful, proceed.
  64668. */
  64669. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  64670. if( rc==SQLITE_OK ){
  64671. u8 *pOut = &pSpace[4];
  64672. u8 *pCell = pPage->apOvfl[0];
  64673. u16 szCell = pPage->xCellSize(pPage, pCell);
  64674. u8 *pStop;
  64675. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  64676. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  64677. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  64678. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  64679. if( NEVER(rc) ) return rc;
  64680. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  64681. /* If this is an auto-vacuum database, update the pointer map
  64682. ** with entries for the new page, and any pointer from the
  64683. ** cell on the page to an overflow page. If either of these
  64684. ** operations fails, the return code is set, but the contents
  64685. ** of the parent page are still manipulated by thh code below.
  64686. ** That is Ok, at this point the parent page is guaranteed to
  64687. ** be marked as dirty. Returning an error code will cause a
  64688. ** rollback, undoing any changes made to the parent page.
  64689. */
  64690. if( ISAUTOVACUUM ){
  64691. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  64692. if( szCell>pNew->minLocal ){
  64693. ptrmapPutOvflPtr(pNew, pCell, &rc);
  64694. }
  64695. }
  64696. /* Create a divider cell to insert into pParent. The divider cell
  64697. ** consists of a 4-byte page number (the page number of pPage) and
  64698. ** a variable length key value (which must be the same value as the
  64699. ** largest key on pPage).
  64700. **
  64701. ** To find the largest key value on pPage, first find the right-most
  64702. ** cell on pPage. The first two fields of this cell are the
  64703. ** record-length (a variable length integer at most 32-bits in size)
  64704. ** and the key value (a variable length integer, may have any value).
  64705. ** The first of the while(...) loops below skips over the record-length
  64706. ** field. The second while(...) loop copies the key value from the
  64707. ** cell on pPage into the pSpace buffer.
  64708. */
  64709. pCell = findCell(pPage, pPage->nCell-1);
  64710. pStop = &pCell[9];
  64711. while( (*(pCell++)&0x80) && pCell<pStop );
  64712. pStop = &pCell[9];
  64713. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  64714. /* Insert the new divider cell into pParent. */
  64715. if( rc==SQLITE_OK ){
  64716. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  64717. 0, pPage->pgno, &rc);
  64718. }
  64719. /* Set the right-child pointer of pParent to point to the new page. */
  64720. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  64721. /* Release the reference to the new page. */
  64722. releasePage(pNew);
  64723. }
  64724. return rc;
  64725. }
  64726. #endif /* SQLITE_OMIT_QUICKBALANCE */
  64727. #if 0
  64728. /*
  64729. ** This function does not contribute anything to the operation of SQLite.
  64730. ** it is sometimes activated temporarily while debugging code responsible
  64731. ** for setting pointer-map entries.
  64732. */
  64733. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  64734. int i, j;
  64735. for(i=0; i<nPage; i++){
  64736. Pgno n;
  64737. u8 e;
  64738. MemPage *pPage = apPage[i];
  64739. BtShared *pBt = pPage->pBt;
  64740. assert( pPage->isInit );
  64741. for(j=0; j<pPage->nCell; j++){
  64742. CellInfo info;
  64743. u8 *z;
  64744. z = findCell(pPage, j);
  64745. pPage->xParseCell(pPage, z, &info);
  64746. if( info.nLocal<info.nPayload ){
  64747. Pgno ovfl = get4byte(&z[info.nSize-4]);
  64748. ptrmapGet(pBt, ovfl, &e, &n);
  64749. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  64750. }
  64751. if( !pPage->leaf ){
  64752. Pgno child = get4byte(z);
  64753. ptrmapGet(pBt, child, &e, &n);
  64754. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  64755. }
  64756. }
  64757. if( !pPage->leaf ){
  64758. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  64759. ptrmapGet(pBt, child, &e, &n);
  64760. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  64761. }
  64762. }
  64763. return 1;
  64764. }
  64765. #endif
  64766. /*
  64767. ** This function is used to copy the contents of the b-tree node stored
  64768. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  64769. ** the pointer-map entries for each child page are updated so that the
  64770. ** parent page stored in the pointer map is page pTo. If pFrom contained
  64771. ** any cells with overflow page pointers, then the corresponding pointer
  64772. ** map entries are also updated so that the parent page is page pTo.
  64773. **
  64774. ** If pFrom is currently carrying any overflow cells (entries in the
  64775. ** MemPage.apOvfl[] array), they are not copied to pTo.
  64776. **
  64777. ** Before returning, page pTo is reinitialized using btreeInitPage().
  64778. **
  64779. ** The performance of this function is not critical. It is only used by
  64780. ** the balance_shallower() and balance_deeper() procedures, neither of
  64781. ** which are called often under normal circumstances.
  64782. */
  64783. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  64784. if( (*pRC)==SQLITE_OK ){
  64785. BtShared * const pBt = pFrom->pBt;
  64786. u8 * const aFrom = pFrom->aData;
  64787. u8 * const aTo = pTo->aData;
  64788. int const iFromHdr = pFrom->hdrOffset;
  64789. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  64790. int rc;
  64791. int iData;
  64792. assert( pFrom->isInit );
  64793. assert( pFrom->nFree>=iToHdr );
  64794. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  64795. /* Copy the b-tree node content from page pFrom to page pTo. */
  64796. iData = get2byte(&aFrom[iFromHdr+5]);
  64797. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  64798. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  64799. /* Reinitialize page pTo so that the contents of the MemPage structure
  64800. ** match the new data. The initialization of pTo can actually fail under
  64801. ** fairly obscure circumstances, even though it is a copy of initialized
  64802. ** page pFrom.
  64803. */
  64804. pTo->isInit = 0;
  64805. rc = btreeInitPage(pTo);
  64806. if( rc!=SQLITE_OK ){
  64807. *pRC = rc;
  64808. return;
  64809. }
  64810. /* If this is an auto-vacuum database, update the pointer-map entries
  64811. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  64812. */
  64813. if( ISAUTOVACUUM ){
  64814. *pRC = setChildPtrmaps(pTo);
  64815. }
  64816. }
  64817. }
  64818. /*
  64819. ** This routine redistributes cells on the iParentIdx'th child of pParent
  64820. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  64821. ** same amount of free space. Usually a single sibling on either side of the
  64822. ** page are used in the balancing, though both siblings might come from one
  64823. ** side if the page is the first or last child of its parent. If the page
  64824. ** has fewer than 2 siblings (something which can only happen if the page
  64825. ** is a root page or a child of a root page) then all available siblings
  64826. ** participate in the balancing.
  64827. **
  64828. ** The number of siblings of the page might be increased or decreased by
  64829. ** one or two in an effort to keep pages nearly full but not over full.
  64830. **
  64831. ** Note that when this routine is called, some of the cells on the page
  64832. ** might not actually be stored in MemPage.aData[]. This can happen
  64833. ** if the page is overfull. This routine ensures that all cells allocated
  64834. ** to the page and its siblings fit into MemPage.aData[] before returning.
  64835. **
  64836. ** In the course of balancing the page and its siblings, cells may be
  64837. ** inserted into or removed from the parent page (pParent). Doing so
  64838. ** may cause the parent page to become overfull or underfull. If this
  64839. ** happens, it is the responsibility of the caller to invoke the correct
  64840. ** balancing routine to fix this problem (see the balance() routine).
  64841. **
  64842. ** If this routine fails for any reason, it might leave the database
  64843. ** in a corrupted state. So if this routine fails, the database should
  64844. ** be rolled back.
  64845. **
  64846. ** The third argument to this function, aOvflSpace, is a pointer to a
  64847. ** buffer big enough to hold one page. If while inserting cells into the parent
  64848. ** page (pParent) the parent page becomes overfull, this buffer is
  64849. ** used to store the parent's overflow cells. Because this function inserts
  64850. ** a maximum of four divider cells into the parent page, and the maximum
  64851. ** size of a cell stored within an internal node is always less than 1/4
  64852. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  64853. ** enough for all overflow cells.
  64854. **
  64855. ** If aOvflSpace is set to a null pointer, this function returns
  64856. ** SQLITE_NOMEM.
  64857. */
  64858. static int balance_nonroot(
  64859. MemPage *pParent, /* Parent page of siblings being balanced */
  64860. int iParentIdx, /* Index of "the page" in pParent */
  64861. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  64862. int isRoot, /* True if pParent is a root-page */
  64863. int bBulk /* True if this call is part of a bulk load */
  64864. ){
  64865. BtShared *pBt; /* The whole database */
  64866. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  64867. int nNew = 0; /* Number of pages in apNew[] */
  64868. int nOld; /* Number of pages in apOld[] */
  64869. int i, j, k; /* Loop counters */
  64870. int nxDiv; /* Next divider slot in pParent->aCell[] */
  64871. int rc = SQLITE_OK; /* The return code */
  64872. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  64873. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  64874. int usableSpace; /* Bytes in pPage beyond the header */
  64875. int pageFlags; /* Value of pPage->aData[0] */
  64876. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  64877. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  64878. int szScratch; /* Size of scratch memory requested */
  64879. MemPage *apOld[NB]; /* pPage and up to two siblings */
  64880. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  64881. u8 *pRight; /* Location in parent of right-sibling pointer */
  64882. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  64883. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  64884. int cntOld[NB+2]; /* Old index in b.apCell[] */
  64885. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  64886. u8 *aSpace1; /* Space for copies of dividers cells */
  64887. Pgno pgno; /* Temp var to store a page number in */
  64888. u8 abDone[NB+2]; /* True after i'th new page is populated */
  64889. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  64890. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  64891. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  64892. CellArray b; /* Parsed information on cells being balanced */
  64893. memset(abDone, 0, sizeof(abDone));
  64894. b.nCell = 0;
  64895. b.apCell = 0;
  64896. pBt = pParent->pBt;
  64897. assert( sqlite3_mutex_held(pBt->mutex) );
  64898. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  64899. #if 0
  64900. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  64901. #endif
  64902. /* At this point pParent may have at most one overflow cell. And if
  64903. ** this overflow cell is present, it must be the cell with
  64904. ** index iParentIdx. This scenario comes about when this function
  64905. ** is called (indirectly) from sqlite3BtreeDelete().
  64906. */
  64907. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  64908. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  64909. if( !aOvflSpace ){
  64910. return SQLITE_NOMEM_BKPT;
  64911. }
  64912. /* Find the sibling pages to balance. Also locate the cells in pParent
  64913. ** that divide the siblings. An attempt is made to find NN siblings on
  64914. ** either side of pPage. More siblings are taken from one side, however,
  64915. ** if there are fewer than NN siblings on the other side. If pParent
  64916. ** has NB or fewer children then all children of pParent are taken.
  64917. **
  64918. ** This loop also drops the divider cells from the parent page. This
  64919. ** way, the remainder of the function does not have to deal with any
  64920. ** overflow cells in the parent page, since if any existed they will
  64921. ** have already been removed.
  64922. */
  64923. i = pParent->nOverflow + pParent->nCell;
  64924. if( i<2 ){
  64925. nxDiv = 0;
  64926. }else{
  64927. assert( bBulk==0 || bBulk==1 );
  64928. if( iParentIdx==0 ){
  64929. nxDiv = 0;
  64930. }else if( iParentIdx==i ){
  64931. nxDiv = i-2+bBulk;
  64932. }else{
  64933. nxDiv = iParentIdx-1;
  64934. }
  64935. i = 2-bBulk;
  64936. }
  64937. nOld = i+1;
  64938. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  64939. pRight = &pParent->aData[pParent->hdrOffset+8];
  64940. }else{
  64941. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  64942. }
  64943. pgno = get4byte(pRight);
  64944. while( 1 ){
  64945. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  64946. if( rc ){
  64947. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  64948. goto balance_cleanup;
  64949. }
  64950. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  64951. if( (i--)==0 ) break;
  64952. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  64953. apDiv[i] = pParent->apOvfl[0];
  64954. pgno = get4byte(apDiv[i]);
  64955. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  64956. pParent->nOverflow = 0;
  64957. }else{
  64958. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  64959. pgno = get4byte(apDiv[i]);
  64960. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  64961. /* Drop the cell from the parent page. apDiv[i] still points to
  64962. ** the cell within the parent, even though it has been dropped.
  64963. ** This is safe because dropping a cell only overwrites the first
  64964. ** four bytes of it, and this function does not need the first
  64965. ** four bytes of the divider cell. So the pointer is safe to use
  64966. ** later on.
  64967. **
  64968. ** But not if we are in secure-delete mode. In secure-delete mode,
  64969. ** the dropCell() routine will overwrite the entire cell with zeroes.
  64970. ** In this case, temporarily copy the cell into the aOvflSpace[]
  64971. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  64972. ** is allocated. */
  64973. if( pBt->btsFlags & BTS_FAST_SECURE ){
  64974. int iOff;
  64975. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  64976. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  64977. rc = SQLITE_CORRUPT_BKPT;
  64978. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  64979. goto balance_cleanup;
  64980. }else{
  64981. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  64982. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  64983. }
  64984. }
  64985. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  64986. }
  64987. }
  64988. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  64989. ** alignment */
  64990. nMaxCells = (nMaxCells + 3)&~3;
  64991. /*
  64992. ** Allocate space for memory structures
  64993. */
  64994. szScratch =
  64995. nMaxCells*sizeof(u8*) /* b.apCell */
  64996. + nMaxCells*sizeof(u16) /* b.szCell */
  64997. + pBt->pageSize; /* aSpace1 */
  64998. assert( szScratch<=6*(int)pBt->pageSize );
  64999. b.apCell = sqlite3StackAllocRaw(0, szScratch );
  65000. if( b.apCell==0 ){
  65001. rc = SQLITE_NOMEM_BKPT;
  65002. goto balance_cleanup;
  65003. }
  65004. b.szCell = (u16*)&b.apCell[nMaxCells];
  65005. aSpace1 = (u8*)&b.szCell[nMaxCells];
  65006. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  65007. /*
  65008. ** Load pointers to all cells on sibling pages and the divider cells
  65009. ** into the local b.apCell[] array. Make copies of the divider cells
  65010. ** into space obtained from aSpace1[]. The divider cells have already
  65011. ** been removed from pParent.
  65012. **
  65013. ** If the siblings are on leaf pages, then the child pointers of the
  65014. ** divider cells are stripped from the cells before they are copied
  65015. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  65016. ** child pointers. If siblings are not leaves, then all cell in
  65017. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  65018. ** are alike.
  65019. **
  65020. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  65021. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  65022. */
  65023. b.pRef = apOld[0];
  65024. leafCorrection = b.pRef->leaf*4;
  65025. leafData = b.pRef->intKeyLeaf;
  65026. for(i=0; i<nOld; i++){
  65027. MemPage *pOld = apOld[i];
  65028. int limit = pOld->nCell;
  65029. u8 *aData = pOld->aData;
  65030. u16 maskPage = pOld->maskPage;
  65031. u8 *piCell = aData + pOld->cellOffset;
  65032. u8 *piEnd;
  65033. /* Verify that all sibling pages are of the same "type" (table-leaf,
  65034. ** table-interior, index-leaf, or index-interior).
  65035. */
  65036. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  65037. rc = SQLITE_CORRUPT_BKPT;
  65038. goto balance_cleanup;
  65039. }
  65040. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  65041. ** contains overflow cells, include them in the b.apCell[] array
  65042. ** in the correct spot.
  65043. **
  65044. ** Note that when there are multiple overflow cells, it is always the
  65045. ** case that they are sequential and adjacent. This invariant arises
  65046. ** because multiple overflows can only occurs when inserting divider
  65047. ** cells into a parent on a prior balance, and divider cells are always
  65048. ** adjacent and are inserted in order. There is an assert() tagged
  65049. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  65050. ** invariant.
  65051. **
  65052. ** This must be done in advance. Once the balance starts, the cell
  65053. ** offset section of the btree page will be overwritten and we will no
  65054. ** long be able to find the cells if a pointer to each cell is not saved
  65055. ** first.
  65056. */
  65057. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  65058. if( pOld->nOverflow>0 ){
  65059. limit = pOld->aiOvfl[0];
  65060. for(j=0; j<limit; j++){
  65061. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  65062. piCell += 2;
  65063. b.nCell++;
  65064. }
  65065. for(k=0; k<pOld->nOverflow; k++){
  65066. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  65067. b.apCell[b.nCell] = pOld->apOvfl[k];
  65068. b.nCell++;
  65069. }
  65070. }
  65071. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  65072. while( piCell<piEnd ){
  65073. assert( b.nCell<nMaxCells );
  65074. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  65075. piCell += 2;
  65076. b.nCell++;
  65077. }
  65078. cntOld[i] = b.nCell;
  65079. if( i<nOld-1 && !leafData){
  65080. u16 sz = (u16)szNew[i];
  65081. u8 *pTemp;
  65082. assert( b.nCell<nMaxCells );
  65083. b.szCell[b.nCell] = sz;
  65084. pTemp = &aSpace1[iSpace1];
  65085. iSpace1 += sz;
  65086. assert( sz<=pBt->maxLocal+23 );
  65087. assert( iSpace1 <= (int)pBt->pageSize );
  65088. memcpy(pTemp, apDiv[i], sz);
  65089. b.apCell[b.nCell] = pTemp+leafCorrection;
  65090. assert( leafCorrection==0 || leafCorrection==4 );
  65091. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  65092. if( !pOld->leaf ){
  65093. assert( leafCorrection==0 );
  65094. assert( pOld->hdrOffset==0 );
  65095. /* The right pointer of the child page pOld becomes the left
  65096. ** pointer of the divider cell */
  65097. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  65098. }else{
  65099. assert( leafCorrection==4 );
  65100. while( b.szCell[b.nCell]<4 ){
  65101. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  65102. ** does exist, pad it with 0x00 bytes. */
  65103. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  65104. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  65105. aSpace1[iSpace1++] = 0x00;
  65106. b.szCell[b.nCell]++;
  65107. }
  65108. }
  65109. b.nCell++;
  65110. }
  65111. }
  65112. /*
  65113. ** Figure out the number of pages needed to hold all b.nCell cells.
  65114. ** Store this number in "k". Also compute szNew[] which is the total
  65115. ** size of all cells on the i-th page and cntNew[] which is the index
  65116. ** in b.apCell[] of the cell that divides page i from page i+1.
  65117. ** cntNew[k] should equal b.nCell.
  65118. **
  65119. ** Values computed by this block:
  65120. **
  65121. ** k: The total number of sibling pages
  65122. ** szNew[i]: Spaced used on the i-th sibling page.
  65123. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  65124. ** the right of the i-th sibling page.
  65125. ** usableSpace: Number of bytes of space available on each sibling.
  65126. **
  65127. */
  65128. usableSpace = pBt->usableSize - 12 + leafCorrection;
  65129. for(i=0; i<nOld; i++){
  65130. MemPage *p = apOld[i];
  65131. szNew[i] = usableSpace - p->nFree;
  65132. for(j=0; j<p->nOverflow; j++){
  65133. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  65134. }
  65135. cntNew[i] = cntOld[i];
  65136. }
  65137. k = nOld;
  65138. for(i=0; i<k; i++){
  65139. int sz;
  65140. while( szNew[i]>usableSpace ){
  65141. if( i+1>=k ){
  65142. k = i+2;
  65143. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  65144. szNew[k-1] = 0;
  65145. cntNew[k-1] = b.nCell;
  65146. }
  65147. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  65148. szNew[i] -= sz;
  65149. if( !leafData ){
  65150. if( cntNew[i]<b.nCell ){
  65151. sz = 2 + cachedCellSize(&b, cntNew[i]);
  65152. }else{
  65153. sz = 0;
  65154. }
  65155. }
  65156. szNew[i+1] += sz;
  65157. cntNew[i]--;
  65158. }
  65159. while( cntNew[i]<b.nCell ){
  65160. sz = 2 + cachedCellSize(&b, cntNew[i]);
  65161. if( szNew[i]+sz>usableSpace ) break;
  65162. szNew[i] += sz;
  65163. cntNew[i]++;
  65164. if( !leafData ){
  65165. if( cntNew[i]<b.nCell ){
  65166. sz = 2 + cachedCellSize(&b, cntNew[i]);
  65167. }else{
  65168. sz = 0;
  65169. }
  65170. }
  65171. szNew[i+1] -= sz;
  65172. }
  65173. if( cntNew[i]>=b.nCell ){
  65174. k = i+1;
  65175. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  65176. rc = SQLITE_CORRUPT_BKPT;
  65177. goto balance_cleanup;
  65178. }
  65179. }
  65180. /*
  65181. ** The packing computed by the previous block is biased toward the siblings
  65182. ** on the left side (siblings with smaller keys). The left siblings are
  65183. ** always nearly full, while the right-most sibling might be nearly empty.
  65184. ** The next block of code attempts to adjust the packing of siblings to
  65185. ** get a better balance.
  65186. **
  65187. ** This adjustment is more than an optimization. The packing above might
  65188. ** be so out of balance as to be illegal. For example, the right-most
  65189. ** sibling might be completely empty. This adjustment is not optional.
  65190. */
  65191. for(i=k-1; i>0; i--){
  65192. int szRight = szNew[i]; /* Size of sibling on the right */
  65193. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  65194. int r; /* Index of right-most cell in left sibling */
  65195. int d; /* Index of first cell to the left of right sibling */
  65196. r = cntNew[i-1] - 1;
  65197. d = r + 1 - leafData;
  65198. (void)cachedCellSize(&b, d);
  65199. do{
  65200. assert( d<nMaxCells );
  65201. assert( r<nMaxCells );
  65202. (void)cachedCellSize(&b, r);
  65203. if( szRight!=0
  65204. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  65205. break;
  65206. }
  65207. szRight += b.szCell[d] + 2;
  65208. szLeft -= b.szCell[r] + 2;
  65209. cntNew[i-1] = r;
  65210. r--;
  65211. d--;
  65212. }while( r>=0 );
  65213. szNew[i] = szRight;
  65214. szNew[i-1] = szLeft;
  65215. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  65216. rc = SQLITE_CORRUPT_BKPT;
  65217. goto balance_cleanup;
  65218. }
  65219. }
  65220. /* Sanity check: For a non-corrupt database file one of the follwing
  65221. ** must be true:
  65222. ** (1) We found one or more cells (cntNew[0])>0), or
  65223. ** (2) pPage is a virtual root page. A virtual root page is when
  65224. ** the real root page is page 1 and we are the only child of
  65225. ** that page.
  65226. */
  65227. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  65228. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  65229. apOld[0]->pgno, apOld[0]->nCell,
  65230. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  65231. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  65232. ));
  65233. /*
  65234. ** Allocate k new pages. Reuse old pages where possible.
  65235. */
  65236. pageFlags = apOld[0]->aData[0];
  65237. for(i=0; i<k; i++){
  65238. MemPage *pNew;
  65239. if( i<nOld ){
  65240. pNew = apNew[i] = apOld[i];
  65241. apOld[i] = 0;
  65242. rc = sqlite3PagerWrite(pNew->pDbPage);
  65243. nNew++;
  65244. if( rc ) goto balance_cleanup;
  65245. }else{
  65246. assert( i>0 );
  65247. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  65248. if( rc ) goto balance_cleanup;
  65249. zeroPage(pNew, pageFlags);
  65250. apNew[i] = pNew;
  65251. nNew++;
  65252. cntOld[i] = b.nCell;
  65253. /* Set the pointer-map entry for the new sibling page. */
  65254. if( ISAUTOVACUUM ){
  65255. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  65256. if( rc!=SQLITE_OK ){
  65257. goto balance_cleanup;
  65258. }
  65259. }
  65260. }
  65261. }
  65262. /*
  65263. ** Reassign page numbers so that the new pages are in ascending order.
  65264. ** This helps to keep entries in the disk file in order so that a scan
  65265. ** of the table is closer to a linear scan through the file. That in turn
  65266. ** helps the operating system to deliver pages from the disk more rapidly.
  65267. **
  65268. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  65269. ** than (NB+2) (a small constant), that should not be a problem.
  65270. **
  65271. ** When NB==3, this one optimization makes the database about 25% faster
  65272. ** for large insertions and deletions.
  65273. */
  65274. for(i=0; i<nNew; i++){
  65275. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  65276. aPgFlags[i] = apNew[i]->pDbPage->flags;
  65277. for(j=0; j<i; j++){
  65278. if( aPgno[j]==aPgno[i] ){
  65279. /* This branch is taken if the set of sibling pages somehow contains
  65280. ** duplicate entries. This can happen if the database is corrupt.
  65281. ** It would be simpler to detect this as part of the loop below, but
  65282. ** we do the detection here in order to avoid populating the pager
  65283. ** cache with two separate objects associated with the same
  65284. ** page number. */
  65285. assert( CORRUPT_DB );
  65286. rc = SQLITE_CORRUPT_BKPT;
  65287. goto balance_cleanup;
  65288. }
  65289. }
  65290. }
  65291. for(i=0; i<nNew; i++){
  65292. int iBest = 0; /* aPgno[] index of page number to use */
  65293. for(j=1; j<nNew; j++){
  65294. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  65295. }
  65296. pgno = aPgOrder[iBest];
  65297. aPgOrder[iBest] = 0xffffffff;
  65298. if( iBest!=i ){
  65299. if( iBest>i ){
  65300. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  65301. }
  65302. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  65303. apNew[i]->pgno = pgno;
  65304. }
  65305. }
  65306. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  65307. "%d(%d nc=%d) %d(%d nc=%d)\n",
  65308. apNew[0]->pgno, szNew[0], cntNew[0],
  65309. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  65310. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  65311. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  65312. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  65313. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  65314. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  65315. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  65316. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  65317. ));
  65318. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  65319. put4byte(pRight, apNew[nNew-1]->pgno);
  65320. /* If the sibling pages are not leaves, ensure that the right-child pointer
  65321. ** of the right-most new sibling page is set to the value that was
  65322. ** originally in the same field of the right-most old sibling page. */
  65323. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  65324. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  65325. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  65326. }
  65327. /* Make any required updates to pointer map entries associated with
  65328. ** cells stored on sibling pages following the balance operation. Pointer
  65329. ** map entries associated with divider cells are set by the insertCell()
  65330. ** routine. The associated pointer map entries are:
  65331. **
  65332. ** a) if the cell contains a reference to an overflow chain, the
  65333. ** entry associated with the first page in the overflow chain, and
  65334. **
  65335. ** b) if the sibling pages are not leaves, the child page associated
  65336. ** with the cell.
  65337. **
  65338. ** If the sibling pages are not leaves, then the pointer map entry
  65339. ** associated with the right-child of each sibling may also need to be
  65340. ** updated. This happens below, after the sibling pages have been
  65341. ** populated, not here.
  65342. */
  65343. if( ISAUTOVACUUM ){
  65344. MemPage *pNew = apNew[0];
  65345. u8 *aOld = pNew->aData;
  65346. int cntOldNext = pNew->nCell + pNew->nOverflow;
  65347. int usableSize = pBt->usableSize;
  65348. int iNew = 0;
  65349. int iOld = 0;
  65350. for(i=0; i<b.nCell; i++){
  65351. u8 *pCell = b.apCell[i];
  65352. if( i==cntOldNext ){
  65353. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  65354. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  65355. aOld = pOld->aData;
  65356. }
  65357. if( i==cntNew[iNew] ){
  65358. pNew = apNew[++iNew];
  65359. if( !leafData ) continue;
  65360. }
  65361. /* Cell pCell is destined for new sibling page pNew. Originally, it
  65362. ** was either part of sibling page iOld (possibly an overflow cell),
  65363. ** or else the divider cell to the left of sibling page iOld. So,
  65364. ** if sibling page iOld had the same page number as pNew, and if
  65365. ** pCell really was a part of sibling page iOld (not a divider or
  65366. ** overflow cell), we can skip updating the pointer map entries. */
  65367. if( iOld>=nNew
  65368. || pNew->pgno!=aPgno[iOld]
  65369. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  65370. ){
  65371. if( !leafCorrection ){
  65372. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  65373. }
  65374. if( cachedCellSize(&b,i)>pNew->minLocal ){
  65375. ptrmapPutOvflPtr(pNew, pCell, &rc);
  65376. }
  65377. if( rc ) goto balance_cleanup;
  65378. }
  65379. }
  65380. }
  65381. /* Insert new divider cells into pParent. */
  65382. for(i=0; i<nNew-1; i++){
  65383. u8 *pCell;
  65384. u8 *pTemp;
  65385. int sz;
  65386. MemPage *pNew = apNew[i];
  65387. j = cntNew[i];
  65388. assert( j<nMaxCells );
  65389. assert( b.apCell[j]!=0 );
  65390. pCell = b.apCell[j];
  65391. sz = b.szCell[j] + leafCorrection;
  65392. pTemp = &aOvflSpace[iOvflSpace];
  65393. if( !pNew->leaf ){
  65394. memcpy(&pNew->aData[8], pCell, 4);
  65395. }else if( leafData ){
  65396. /* If the tree is a leaf-data tree, and the siblings are leaves,
  65397. ** then there is no divider cell in b.apCell[]. Instead, the divider
  65398. ** cell consists of the integer key for the right-most cell of
  65399. ** the sibling-page assembled above only.
  65400. */
  65401. CellInfo info;
  65402. j--;
  65403. pNew->xParseCell(pNew, b.apCell[j], &info);
  65404. pCell = pTemp;
  65405. sz = 4 + putVarint(&pCell[4], info.nKey);
  65406. pTemp = 0;
  65407. }else{
  65408. pCell -= 4;
  65409. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  65410. ** previously stored on a leaf node, and its reported size was 4
  65411. ** bytes, then it may actually be smaller than this
  65412. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  65413. ** any cell). But it is important to pass the correct size to
  65414. ** insertCell(), so reparse the cell now.
  65415. **
  65416. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  65417. ** and WITHOUT ROWID tables with exactly one column which is the
  65418. ** primary key.
  65419. */
  65420. if( b.szCell[j]==4 ){
  65421. assert(leafCorrection==4);
  65422. sz = pParent->xCellSize(pParent, pCell);
  65423. }
  65424. }
  65425. iOvflSpace += sz;
  65426. assert( sz<=pBt->maxLocal+23 );
  65427. assert( iOvflSpace <= (int)pBt->pageSize );
  65428. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  65429. if( rc!=SQLITE_OK ) goto balance_cleanup;
  65430. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  65431. }
  65432. /* Now update the actual sibling pages. The order in which they are updated
  65433. ** is important, as this code needs to avoid disrupting any page from which
  65434. ** cells may still to be read. In practice, this means:
  65435. **
  65436. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  65437. ** then it is not safe to update page apNew[iPg] until after
  65438. ** the left-hand sibling apNew[iPg-1] has been updated.
  65439. **
  65440. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  65441. ** then it is not safe to update page apNew[iPg] until after
  65442. ** the right-hand sibling apNew[iPg+1] has been updated.
  65443. **
  65444. ** If neither of the above apply, the page is safe to update.
  65445. **
  65446. ** The iPg value in the following loop starts at nNew-1 goes down
  65447. ** to 0, then back up to nNew-1 again, thus making two passes over
  65448. ** the pages. On the initial downward pass, only condition (1) above
  65449. ** needs to be tested because (2) will always be true from the previous
  65450. ** step. On the upward pass, both conditions are always true, so the
  65451. ** upwards pass simply processes pages that were missed on the downward
  65452. ** pass.
  65453. */
  65454. for(i=1-nNew; i<nNew; i++){
  65455. int iPg = i<0 ? -i : i;
  65456. assert( iPg>=0 && iPg<nNew );
  65457. if( abDone[iPg] ) continue; /* Skip pages already processed */
  65458. if( i>=0 /* On the upwards pass, or... */
  65459. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  65460. ){
  65461. int iNew;
  65462. int iOld;
  65463. int nNewCell;
  65464. /* Verify condition (1): If cells are moving left, update iPg
  65465. ** only after iPg-1 has already been updated. */
  65466. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  65467. /* Verify condition (2): If cells are moving right, update iPg
  65468. ** only after iPg+1 has already been updated. */
  65469. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  65470. if( iPg==0 ){
  65471. iNew = iOld = 0;
  65472. nNewCell = cntNew[0];
  65473. }else{
  65474. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  65475. iNew = cntNew[iPg-1] + !leafData;
  65476. nNewCell = cntNew[iPg] - iNew;
  65477. }
  65478. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  65479. if( rc ) goto balance_cleanup;
  65480. abDone[iPg]++;
  65481. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  65482. assert( apNew[iPg]->nOverflow==0 );
  65483. assert( apNew[iPg]->nCell==nNewCell );
  65484. }
  65485. }
  65486. /* All pages have been processed exactly once */
  65487. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  65488. assert( nOld>0 );
  65489. assert( nNew>0 );
  65490. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  65491. /* The root page of the b-tree now contains no cells. The only sibling
  65492. ** page is the right-child of the parent. Copy the contents of the
  65493. ** child page into the parent, decreasing the overall height of the
  65494. ** b-tree structure by one. This is described as the "balance-shallower"
  65495. ** sub-algorithm in some documentation.
  65496. **
  65497. ** If this is an auto-vacuum database, the call to copyNodeContent()
  65498. ** sets all pointer-map entries corresponding to database image pages
  65499. ** for which the pointer is stored within the content being copied.
  65500. **
  65501. ** It is critical that the child page be defragmented before being
  65502. ** copied into the parent, because if the parent is page 1 then it will
  65503. ** by smaller than the child due to the database header, and so all the
  65504. ** free space needs to be up front.
  65505. */
  65506. assert( nNew==1 || CORRUPT_DB );
  65507. rc = defragmentPage(apNew[0], -1);
  65508. testcase( rc!=SQLITE_OK );
  65509. assert( apNew[0]->nFree ==
  65510. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  65511. || rc!=SQLITE_OK
  65512. );
  65513. copyNodeContent(apNew[0], pParent, &rc);
  65514. freePage(apNew[0], &rc);
  65515. }else if( ISAUTOVACUUM && !leafCorrection ){
  65516. /* Fix the pointer map entries associated with the right-child of each
  65517. ** sibling page. All other pointer map entries have already been taken
  65518. ** care of. */
  65519. for(i=0; i<nNew; i++){
  65520. u32 key = get4byte(&apNew[i]->aData[8]);
  65521. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  65522. }
  65523. }
  65524. assert( pParent->isInit );
  65525. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  65526. nOld, nNew, b.nCell));
  65527. /* Free any old pages that were not reused as new pages.
  65528. */
  65529. for(i=nNew; i<nOld; i++){
  65530. freePage(apOld[i], &rc);
  65531. }
  65532. #if 0
  65533. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  65534. /* The ptrmapCheckPages() contains assert() statements that verify that
  65535. ** all pointer map pages are set correctly. This is helpful while
  65536. ** debugging. This is usually disabled because a corrupt database may
  65537. ** cause an assert() statement to fail. */
  65538. ptrmapCheckPages(apNew, nNew);
  65539. ptrmapCheckPages(&pParent, 1);
  65540. }
  65541. #endif
  65542. /*
  65543. ** Cleanup before returning.
  65544. */
  65545. balance_cleanup:
  65546. sqlite3StackFree(0, b.apCell);
  65547. for(i=0; i<nOld; i++){
  65548. releasePage(apOld[i]);
  65549. }
  65550. for(i=0; i<nNew; i++){
  65551. releasePage(apNew[i]);
  65552. }
  65553. return rc;
  65554. }
  65555. /*
  65556. ** This function is called when the root page of a b-tree structure is
  65557. ** overfull (has one or more overflow pages).
  65558. **
  65559. ** A new child page is allocated and the contents of the current root
  65560. ** page, including overflow cells, are copied into the child. The root
  65561. ** page is then overwritten to make it an empty page with the right-child
  65562. ** pointer pointing to the new page.
  65563. **
  65564. ** Before returning, all pointer-map entries corresponding to pages
  65565. ** that the new child-page now contains pointers to are updated. The
  65566. ** entry corresponding to the new right-child pointer of the root
  65567. ** page is also updated.
  65568. **
  65569. ** If successful, *ppChild is set to contain a reference to the child
  65570. ** page and SQLITE_OK is returned. In this case the caller is required
  65571. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  65572. ** an error code is returned and *ppChild is set to 0.
  65573. */
  65574. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  65575. int rc; /* Return value from subprocedures */
  65576. MemPage *pChild = 0; /* Pointer to a new child page */
  65577. Pgno pgnoChild = 0; /* Page number of the new child page */
  65578. BtShared *pBt = pRoot->pBt; /* The BTree */
  65579. assert( pRoot->nOverflow>0 );
  65580. assert( sqlite3_mutex_held(pBt->mutex) );
  65581. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  65582. ** page that will become the new right-child of pPage. Copy the contents
  65583. ** of the node stored on pRoot into the new child page.
  65584. */
  65585. rc = sqlite3PagerWrite(pRoot->pDbPage);
  65586. if( rc==SQLITE_OK ){
  65587. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  65588. copyNodeContent(pRoot, pChild, &rc);
  65589. if( ISAUTOVACUUM ){
  65590. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  65591. }
  65592. }
  65593. if( rc ){
  65594. *ppChild = 0;
  65595. releasePage(pChild);
  65596. return rc;
  65597. }
  65598. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  65599. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  65600. assert( pChild->nCell==pRoot->nCell );
  65601. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  65602. /* Copy the overflow cells from pRoot to pChild */
  65603. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  65604. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  65605. memcpy(pChild->apOvfl, pRoot->apOvfl,
  65606. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  65607. pChild->nOverflow = pRoot->nOverflow;
  65608. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  65609. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  65610. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  65611. *ppChild = pChild;
  65612. return SQLITE_OK;
  65613. }
  65614. /*
  65615. ** The page that pCur currently points to has just been modified in
  65616. ** some way. This function figures out if this modification means the
  65617. ** tree needs to be balanced, and if so calls the appropriate balancing
  65618. ** routine. Balancing routines are:
  65619. **
  65620. ** balance_quick()
  65621. ** balance_deeper()
  65622. ** balance_nonroot()
  65623. */
  65624. static int balance(BtCursor *pCur){
  65625. int rc = SQLITE_OK;
  65626. const int nMin = pCur->pBt->usableSize * 2 / 3;
  65627. u8 aBalanceQuickSpace[13];
  65628. u8 *pFree = 0;
  65629. VVA_ONLY( int balance_quick_called = 0 );
  65630. VVA_ONLY( int balance_deeper_called = 0 );
  65631. do {
  65632. int iPage = pCur->iPage;
  65633. MemPage *pPage = pCur->pPage;
  65634. if( iPage==0 ){
  65635. if( pPage->nOverflow ){
  65636. /* The root page of the b-tree is overfull. In this case call the
  65637. ** balance_deeper() function to create a new child for the root-page
  65638. ** and copy the current contents of the root-page to it. The
  65639. ** next iteration of the do-loop will balance the child page.
  65640. */
  65641. assert( balance_deeper_called==0 );
  65642. VVA_ONLY( balance_deeper_called++ );
  65643. rc = balance_deeper(pPage, &pCur->apPage[1]);
  65644. if( rc==SQLITE_OK ){
  65645. pCur->iPage = 1;
  65646. pCur->ix = 0;
  65647. pCur->aiIdx[0] = 0;
  65648. pCur->apPage[0] = pPage;
  65649. pCur->pPage = pCur->apPage[1];
  65650. assert( pCur->pPage->nOverflow );
  65651. }
  65652. }else{
  65653. break;
  65654. }
  65655. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  65656. break;
  65657. }else{
  65658. MemPage * const pParent = pCur->apPage[iPage-1];
  65659. int const iIdx = pCur->aiIdx[iPage-1];
  65660. rc = sqlite3PagerWrite(pParent->pDbPage);
  65661. if( rc==SQLITE_OK ){
  65662. #ifndef SQLITE_OMIT_QUICKBALANCE
  65663. if( pPage->intKeyLeaf
  65664. && pPage->nOverflow==1
  65665. && pPage->aiOvfl[0]==pPage->nCell
  65666. && pParent->pgno!=1
  65667. && pParent->nCell==iIdx
  65668. ){
  65669. /* Call balance_quick() to create a new sibling of pPage on which
  65670. ** to store the overflow cell. balance_quick() inserts a new cell
  65671. ** into pParent, which may cause pParent overflow. If this
  65672. ** happens, the next iteration of the do-loop will balance pParent
  65673. ** use either balance_nonroot() or balance_deeper(). Until this
  65674. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  65675. ** buffer.
  65676. **
  65677. ** The purpose of the following assert() is to check that only a
  65678. ** single call to balance_quick() is made for each call to this
  65679. ** function. If this were not verified, a subtle bug involving reuse
  65680. ** of the aBalanceQuickSpace[] might sneak in.
  65681. */
  65682. assert( balance_quick_called==0 );
  65683. VVA_ONLY( balance_quick_called++ );
  65684. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  65685. }else
  65686. #endif
  65687. {
  65688. /* In this case, call balance_nonroot() to redistribute cells
  65689. ** between pPage and up to 2 of its sibling pages. This involves
  65690. ** modifying the contents of pParent, which may cause pParent to
  65691. ** become overfull or underfull. The next iteration of the do-loop
  65692. ** will balance the parent page to correct this.
  65693. **
  65694. ** If the parent page becomes overfull, the overflow cell or cells
  65695. ** are stored in the pSpace buffer allocated immediately below.
  65696. ** A subsequent iteration of the do-loop will deal with this by
  65697. ** calling balance_nonroot() (balance_deeper() may be called first,
  65698. ** but it doesn't deal with overflow cells - just moves them to a
  65699. ** different page). Once this subsequent call to balance_nonroot()
  65700. ** has completed, it is safe to release the pSpace buffer used by
  65701. ** the previous call, as the overflow cell data will have been
  65702. ** copied either into the body of a database page or into the new
  65703. ** pSpace buffer passed to the latter call to balance_nonroot().
  65704. */
  65705. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  65706. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  65707. pCur->hints&BTREE_BULKLOAD);
  65708. if( pFree ){
  65709. /* If pFree is not NULL, it points to the pSpace buffer used
  65710. ** by a previous call to balance_nonroot(). Its contents are
  65711. ** now stored either on real database pages or within the
  65712. ** new pSpace buffer, so it may be safely freed here. */
  65713. sqlite3PageFree(pFree);
  65714. }
  65715. /* The pSpace buffer will be freed after the next call to
  65716. ** balance_nonroot(), or just before this function returns, whichever
  65717. ** comes first. */
  65718. pFree = pSpace;
  65719. }
  65720. }
  65721. pPage->nOverflow = 0;
  65722. /* The next iteration of the do-loop balances the parent page. */
  65723. releasePage(pPage);
  65724. pCur->iPage--;
  65725. assert( pCur->iPage>=0 );
  65726. pCur->pPage = pCur->apPage[pCur->iPage];
  65727. }
  65728. }while( rc==SQLITE_OK );
  65729. if( pFree ){
  65730. sqlite3PageFree(pFree);
  65731. }
  65732. return rc;
  65733. }
  65734. /* Overwrite content from pX into pDest. Only do the write if the
  65735. ** content is different from what is already there.
  65736. */
  65737. static int btreeOverwriteContent(
  65738. MemPage *pPage, /* MemPage on which writing will occur */
  65739. u8 *pDest, /* Pointer to the place to start writing */
  65740. const BtreePayload *pX, /* Source of data to write */
  65741. int iOffset, /* Offset of first byte to write */
  65742. int iAmt /* Number of bytes to be written */
  65743. ){
  65744. int nData = pX->nData - iOffset;
  65745. if( nData<=0 ){
  65746. /* Overwritting with zeros */
  65747. int i;
  65748. for(i=0; i<iAmt && pDest[i]==0; i++){}
  65749. if( i<iAmt ){
  65750. int rc = sqlite3PagerWrite(pPage->pDbPage);
  65751. if( rc ) return rc;
  65752. memset(pDest + i, 0, iAmt - i);
  65753. }
  65754. }else{
  65755. if( nData<iAmt ){
  65756. /* Mixed read data and zeros at the end. Make a recursive call
  65757. ** to write the zeros then fall through to write the real data */
  65758. int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
  65759. iAmt-nData);
  65760. if( rc ) return rc;
  65761. iAmt = nData;
  65762. }
  65763. if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
  65764. int rc = sqlite3PagerWrite(pPage->pDbPage);
  65765. if( rc ) return rc;
  65766. memcpy(pDest, ((u8*)pX->pData) + iOffset, iAmt);
  65767. }
  65768. }
  65769. return SQLITE_OK;
  65770. }
  65771. /*
  65772. ** Overwrite the cell that cursor pCur is pointing to with fresh content
  65773. ** contained in pX.
  65774. */
  65775. static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
  65776. int iOffset; /* Next byte of pX->pData to write */
  65777. int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
  65778. int rc; /* Return code */
  65779. MemPage *pPage = pCur->pPage; /* Page being written */
  65780. BtShared *pBt; /* Btree */
  65781. Pgno ovflPgno; /* Next overflow page to write */
  65782. u32 ovflPageSize; /* Size to write on overflow page */
  65783. if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
  65784. return SQLITE_CORRUPT_BKPT;
  65785. }
  65786. /* Overwrite the local portion first */
  65787. rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
  65788. 0, pCur->info.nLocal);
  65789. if( rc ) return rc;
  65790. if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
  65791. /* Now overwrite the overflow pages */
  65792. iOffset = pCur->info.nLocal;
  65793. assert( nTotal>=0 );
  65794. assert( iOffset>=0 );
  65795. ovflPgno = get4byte(pCur->info.pPayload + iOffset);
  65796. pBt = pPage->pBt;
  65797. ovflPageSize = pBt->usableSize - 4;
  65798. do{
  65799. rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
  65800. if( rc ) return rc;
  65801. if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
  65802. rc = SQLITE_CORRUPT_BKPT;
  65803. }else{
  65804. if( iOffset+ovflPageSize<(u32)nTotal ){
  65805. ovflPgno = get4byte(pPage->aData);
  65806. }else{
  65807. ovflPageSize = nTotal - iOffset;
  65808. }
  65809. rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
  65810. iOffset, ovflPageSize);
  65811. }
  65812. sqlite3PagerUnref(pPage->pDbPage);
  65813. if( rc ) return rc;
  65814. iOffset += ovflPageSize;
  65815. }while( iOffset<nTotal );
  65816. return SQLITE_OK;
  65817. }
  65818. /*
  65819. ** Insert a new record into the BTree. The content of the new record
  65820. ** is described by the pX object. The pCur cursor is used only to
  65821. ** define what table the record should be inserted into, and is left
  65822. ** pointing at a random location.
  65823. **
  65824. ** For a table btree (used for rowid tables), only the pX.nKey value of
  65825. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  65826. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  65827. ** hold the content of the row.
  65828. **
  65829. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  65830. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  65831. ** pX.pData,nData,nZero fields must be zero.
  65832. **
  65833. ** If the seekResult parameter is non-zero, then a successful call to
  65834. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  65835. ** been performed. In other words, if seekResult!=0 then the cursor
  65836. ** is currently pointing to a cell that will be adjacent to the cell
  65837. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  65838. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  65839. ** that is larger than (pKey,nKey).
  65840. **
  65841. ** If seekResult==0, that means pCur is pointing at some unknown location.
  65842. ** In that case, this routine must seek the cursor to the correct insertion
  65843. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  65844. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  65845. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  65846. ** to decode the key.
  65847. */
  65848. SQLITE_PRIVATE int sqlite3BtreeInsert(
  65849. BtCursor *pCur, /* Insert data into the table of this cursor */
  65850. const BtreePayload *pX, /* Content of the row to be inserted */
  65851. int flags, /* True if this is likely an append */
  65852. int seekResult /* Result of prior MovetoUnpacked() call */
  65853. ){
  65854. int rc;
  65855. int loc = seekResult; /* -1: before desired location +1: after */
  65856. int szNew = 0;
  65857. int idx;
  65858. MemPage *pPage;
  65859. Btree *p = pCur->pBtree;
  65860. BtShared *pBt = p->pBt;
  65861. unsigned char *oldCell;
  65862. unsigned char *newCell = 0;
  65863. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  65864. if( pCur->eState==CURSOR_FAULT ){
  65865. assert( pCur->skipNext!=SQLITE_OK );
  65866. return pCur->skipNext;
  65867. }
  65868. assert( cursorOwnsBtShared(pCur) );
  65869. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  65870. && pBt->inTransaction==TRANS_WRITE
  65871. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  65872. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  65873. /* Assert that the caller has been consistent. If this cursor was opened
  65874. ** expecting an index b-tree, then the caller should be inserting blob
  65875. ** keys with no associated data. If the cursor was opened expecting an
  65876. ** intkey table, the caller should be inserting integer keys with a
  65877. ** blob of associated data. */
  65878. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  65879. /* Save the positions of any other cursors open on this table.
  65880. **
  65881. ** In some cases, the call to btreeMoveto() below is a no-op. For
  65882. ** example, when inserting data into a table with auto-generated integer
  65883. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  65884. ** integer key to use. It then calls this function to actually insert the
  65885. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  65886. ** that the cursor is already where it needs to be and returns without
  65887. ** doing any work. To avoid thwarting these optimizations, it is important
  65888. ** not to clear the cursor here.
  65889. */
  65890. if( pCur->curFlags & BTCF_Multiple ){
  65891. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  65892. if( rc ) return rc;
  65893. }
  65894. if( pCur->pKeyInfo==0 ){
  65895. assert( pX->pKey==0 );
  65896. /* If this is an insert into a table b-tree, invalidate any incrblob
  65897. ** cursors open on the row being replaced */
  65898. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  65899. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  65900. ** to a row with the same key as the new entry being inserted.
  65901. */
  65902. #ifdef SQLITE_DEBUG
  65903. if( flags & BTREE_SAVEPOSITION ){
  65904. assert( pCur->curFlags & BTCF_ValidNKey );
  65905. assert( pX->nKey==pCur->info.nKey );
  65906. assert( pCur->info.nSize!=0 );
  65907. assert( loc==0 );
  65908. }
  65909. #endif
  65910. /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
  65911. ** that the cursor is not pointing to a row to be overwritten.
  65912. ** So do a complete check.
  65913. */
  65914. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  65915. /* The cursor is pointing to the entry that is to be
  65916. ** overwritten */
  65917. assert( pX->nData>=0 && pX->nZero>=0 );
  65918. if( pCur->info.nSize!=0
  65919. && pCur->info.nPayload==(u32)pX->nData+pX->nZero
  65920. ){
  65921. /* New entry is the same size as the old. Do an overwrite */
  65922. return btreeOverwriteCell(pCur, pX);
  65923. }
  65924. assert( loc==0 );
  65925. }else if( loc==0 ){
  65926. /* The cursor is *not* pointing to the cell to be overwritten, nor
  65927. ** to an adjacent cell. Move the cursor so that it is pointing either
  65928. ** to the cell to be overwritten or an adjacent cell.
  65929. */
  65930. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  65931. if( rc ) return rc;
  65932. }
  65933. }else{
  65934. /* This is an index or a WITHOUT ROWID table */
  65935. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  65936. ** to a row with the same key as the new entry being inserted.
  65937. */
  65938. assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
  65939. /* If the cursor is not already pointing either to the cell to be
  65940. ** overwritten, or if a new cell is being inserted, if the cursor is
  65941. ** not pointing to an immediately adjacent cell, then move the cursor
  65942. ** so that it does.
  65943. */
  65944. if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  65945. if( pX->nMem ){
  65946. UnpackedRecord r;
  65947. r.pKeyInfo = pCur->pKeyInfo;
  65948. r.aMem = pX->aMem;
  65949. r.nField = pX->nMem;
  65950. r.default_rc = 0;
  65951. r.errCode = 0;
  65952. r.r1 = 0;
  65953. r.r2 = 0;
  65954. r.eqSeen = 0;
  65955. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  65956. }else{
  65957. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  65958. }
  65959. if( rc ) return rc;
  65960. }
  65961. /* If the cursor is currently pointing to an entry to be overwritten
  65962. ** and the new content is the same as as the old, then use the
  65963. ** overwrite optimization.
  65964. */
  65965. if( loc==0 ){
  65966. getCellInfo(pCur);
  65967. if( pCur->info.nKey==pX->nKey ){
  65968. BtreePayload x2;
  65969. x2.pData = pX->pKey;
  65970. x2.nData = pX->nKey;
  65971. x2.nZero = 0;
  65972. return btreeOverwriteCell(pCur, &x2);
  65973. }
  65974. }
  65975. }
  65976. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  65977. pPage = pCur->pPage;
  65978. assert( pPage->intKey || pX->nKey>=0 );
  65979. assert( pPage->leaf || !pPage->intKey );
  65980. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  65981. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  65982. loc==0 ? "overwrite" : "new entry"));
  65983. assert( pPage->isInit );
  65984. newCell = pBt->pTmpSpace;
  65985. assert( newCell!=0 );
  65986. rc = fillInCell(pPage, newCell, pX, &szNew);
  65987. if( rc ) goto end_insert;
  65988. assert( szNew==pPage->xCellSize(pPage, newCell) );
  65989. assert( szNew <= MX_CELL_SIZE(pBt) );
  65990. idx = pCur->ix;
  65991. if( loc==0 ){
  65992. CellInfo info;
  65993. assert( idx<pPage->nCell );
  65994. rc = sqlite3PagerWrite(pPage->pDbPage);
  65995. if( rc ){
  65996. goto end_insert;
  65997. }
  65998. oldCell = findCell(pPage, idx);
  65999. if( !pPage->leaf ){
  66000. memcpy(newCell, oldCell, 4);
  66001. }
  66002. rc = clearCell(pPage, oldCell, &info);
  66003. if( info.nSize==szNew && info.nLocal==info.nPayload
  66004. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  66005. ){
  66006. /* Overwrite the old cell with the new if they are the same size.
  66007. ** We could also try to do this if the old cell is smaller, then add
  66008. ** the leftover space to the free list. But experiments show that
  66009. ** doing that is no faster then skipping this optimization and just
  66010. ** calling dropCell() and insertCell().
  66011. **
  66012. ** This optimization cannot be used on an autovacuum database if the
  66013. ** new entry uses overflow pages, as the insertCell() call below is
  66014. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  66015. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  66016. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  66017. memcpy(oldCell, newCell, szNew);
  66018. return SQLITE_OK;
  66019. }
  66020. dropCell(pPage, idx, info.nSize, &rc);
  66021. if( rc ) goto end_insert;
  66022. }else if( loc<0 && pPage->nCell>0 ){
  66023. assert( pPage->leaf );
  66024. idx = ++pCur->ix;
  66025. pCur->curFlags &= ~BTCF_ValidNKey;
  66026. }else{
  66027. assert( pPage->leaf );
  66028. }
  66029. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  66030. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  66031. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  66032. /* If no error has occurred and pPage has an overflow cell, call balance()
  66033. ** to redistribute the cells within the tree. Since balance() may move
  66034. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  66035. ** variables.
  66036. **
  66037. ** Previous versions of SQLite called moveToRoot() to move the cursor
  66038. ** back to the root page as balance() used to invalidate the contents
  66039. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  66040. ** set the cursor state to "invalid". This makes common insert operations
  66041. ** slightly faster.
  66042. **
  66043. ** There is a subtle but important optimization here too. When inserting
  66044. ** multiple records into an intkey b-tree using a single cursor (as can
  66045. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  66046. ** is advantageous to leave the cursor pointing to the last entry in
  66047. ** the b-tree if possible. If the cursor is left pointing to the last
  66048. ** entry in the table, and the next row inserted has an integer key
  66049. ** larger than the largest existing key, it is possible to insert the
  66050. ** row without seeking the cursor. This can be a big performance boost.
  66051. */
  66052. pCur->info.nSize = 0;
  66053. if( pPage->nOverflow ){
  66054. assert( rc==SQLITE_OK );
  66055. pCur->curFlags &= ~(BTCF_ValidNKey);
  66056. rc = balance(pCur);
  66057. /* Must make sure nOverflow is reset to zero even if the balance()
  66058. ** fails. Internal data structure corruption will result otherwise.
  66059. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  66060. ** from trying to save the current position of the cursor. */
  66061. pCur->pPage->nOverflow = 0;
  66062. pCur->eState = CURSOR_INVALID;
  66063. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  66064. btreeReleaseAllCursorPages(pCur);
  66065. if( pCur->pKeyInfo ){
  66066. assert( pCur->pKey==0 );
  66067. pCur->pKey = sqlite3Malloc( pX->nKey );
  66068. if( pCur->pKey==0 ){
  66069. rc = SQLITE_NOMEM;
  66070. }else{
  66071. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  66072. }
  66073. }
  66074. pCur->eState = CURSOR_REQUIRESEEK;
  66075. pCur->nKey = pX->nKey;
  66076. }
  66077. }
  66078. assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
  66079. end_insert:
  66080. return rc;
  66081. }
  66082. /*
  66083. ** Delete the entry that the cursor is pointing to.
  66084. **
  66085. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  66086. ** the cursor is left pointing at an arbitrary location after the delete.
  66087. ** But if that bit is set, then the cursor is left in a state such that
  66088. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  66089. ** as it would have been on if the call to BtreeDelete() had been omitted.
  66090. **
  66091. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  66092. ** associated with a single table entry and its indexes. Only one of those
  66093. ** deletes is considered the "primary" delete. The primary delete occurs
  66094. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  66095. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  66096. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  66097. ** but which might be used by alternative storage engines.
  66098. */
  66099. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  66100. Btree *p = pCur->pBtree;
  66101. BtShared *pBt = p->pBt;
  66102. int rc; /* Return code */
  66103. MemPage *pPage; /* Page to delete cell from */
  66104. unsigned char *pCell; /* Pointer to cell to delete */
  66105. int iCellIdx; /* Index of cell to delete */
  66106. int iCellDepth; /* Depth of node containing pCell */
  66107. CellInfo info; /* Size of the cell being deleted */
  66108. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  66109. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  66110. assert( cursorOwnsBtShared(pCur) );
  66111. assert( pBt->inTransaction==TRANS_WRITE );
  66112. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  66113. assert( pCur->curFlags & BTCF_WriteFlag );
  66114. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  66115. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  66116. assert( pCur->ix<pCur->pPage->nCell );
  66117. assert( pCur->eState==CURSOR_VALID );
  66118. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  66119. iCellDepth = pCur->iPage;
  66120. iCellIdx = pCur->ix;
  66121. pPage = pCur->pPage;
  66122. pCell = findCell(pPage, iCellIdx);
  66123. /* If the bPreserve flag is set to true, then the cursor position must
  66124. ** be preserved following this delete operation. If the current delete
  66125. ** will cause a b-tree rebalance, then this is done by saving the cursor
  66126. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  66127. ** returning.
  66128. **
  66129. ** Or, if the current delete will not cause a rebalance, then the cursor
  66130. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  66131. ** before or after the deleted entry. In this case set bSkipnext to true. */
  66132. if( bPreserve ){
  66133. if( !pPage->leaf
  66134. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  66135. ){
  66136. /* A b-tree rebalance will be required after deleting this entry.
  66137. ** Save the cursor key. */
  66138. rc = saveCursorKey(pCur);
  66139. if( rc ) return rc;
  66140. }else{
  66141. bSkipnext = 1;
  66142. }
  66143. }
  66144. /* If the page containing the entry to delete is not a leaf page, move
  66145. ** the cursor to the largest entry in the tree that is smaller than
  66146. ** the entry being deleted. This cell will replace the cell being deleted
  66147. ** from the internal node. The 'previous' entry is used for this instead
  66148. ** of the 'next' entry, as the previous entry is always a part of the
  66149. ** sub-tree headed by the child page of the cell being deleted. This makes
  66150. ** balancing the tree following the delete operation easier. */
  66151. if( !pPage->leaf ){
  66152. rc = sqlite3BtreePrevious(pCur, 0);
  66153. assert( rc!=SQLITE_DONE );
  66154. if( rc ) return rc;
  66155. }
  66156. /* Save the positions of any other cursors open on this table before
  66157. ** making any modifications. */
  66158. if( pCur->curFlags & BTCF_Multiple ){
  66159. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  66160. if( rc ) return rc;
  66161. }
  66162. /* If this is a delete operation to remove a row from a table b-tree,
  66163. ** invalidate any incrblob cursors open on the row being deleted. */
  66164. if( pCur->pKeyInfo==0 ){
  66165. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  66166. }
  66167. /* Make the page containing the entry to be deleted writable. Then free any
  66168. ** overflow pages associated with the entry and finally remove the cell
  66169. ** itself from within the page. */
  66170. rc = sqlite3PagerWrite(pPage->pDbPage);
  66171. if( rc ) return rc;
  66172. rc = clearCell(pPage, pCell, &info);
  66173. dropCell(pPage, iCellIdx, info.nSize, &rc);
  66174. if( rc ) return rc;
  66175. /* If the cell deleted was not located on a leaf page, then the cursor
  66176. ** is currently pointing to the largest entry in the sub-tree headed
  66177. ** by the child-page of the cell that was just deleted from an internal
  66178. ** node. The cell from the leaf node needs to be moved to the internal
  66179. ** node to replace the deleted cell. */
  66180. if( !pPage->leaf ){
  66181. MemPage *pLeaf = pCur->pPage;
  66182. int nCell;
  66183. Pgno n;
  66184. unsigned char *pTmp;
  66185. if( iCellDepth<pCur->iPage-1 ){
  66186. n = pCur->apPage[iCellDepth+1]->pgno;
  66187. }else{
  66188. n = pCur->pPage->pgno;
  66189. }
  66190. pCell = findCell(pLeaf, pLeaf->nCell-1);
  66191. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  66192. nCell = pLeaf->xCellSize(pLeaf, pCell);
  66193. assert( MX_CELL_SIZE(pBt) >= nCell );
  66194. pTmp = pBt->pTmpSpace;
  66195. assert( pTmp!=0 );
  66196. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  66197. if( rc==SQLITE_OK ){
  66198. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  66199. }
  66200. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  66201. if( rc ) return rc;
  66202. }
  66203. /* Balance the tree. If the entry deleted was located on a leaf page,
  66204. ** then the cursor still points to that page. In this case the first
  66205. ** call to balance() repairs the tree, and the if(...) condition is
  66206. ** never true.
  66207. **
  66208. ** Otherwise, if the entry deleted was on an internal node page, then
  66209. ** pCur is pointing to the leaf page from which a cell was removed to
  66210. ** replace the cell deleted from the internal node. This is slightly
  66211. ** tricky as the leaf node may be underfull, and the internal node may
  66212. ** be either under or overfull. In this case run the balancing algorithm
  66213. ** on the leaf node first. If the balance proceeds far enough up the
  66214. ** tree that we can be sure that any problem in the internal node has
  66215. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  66216. ** walk the cursor up the tree to the internal node and balance it as
  66217. ** well. */
  66218. rc = balance(pCur);
  66219. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  66220. releasePageNotNull(pCur->pPage);
  66221. pCur->iPage--;
  66222. while( pCur->iPage>iCellDepth ){
  66223. releasePage(pCur->apPage[pCur->iPage--]);
  66224. }
  66225. pCur->pPage = pCur->apPage[pCur->iPage];
  66226. rc = balance(pCur);
  66227. }
  66228. if( rc==SQLITE_OK ){
  66229. if( bSkipnext ){
  66230. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  66231. assert( pPage==pCur->pPage || CORRUPT_DB );
  66232. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  66233. pCur->eState = CURSOR_SKIPNEXT;
  66234. if( iCellIdx>=pPage->nCell ){
  66235. pCur->skipNext = -1;
  66236. pCur->ix = pPage->nCell-1;
  66237. }else{
  66238. pCur->skipNext = 1;
  66239. }
  66240. }else{
  66241. rc = moveToRoot(pCur);
  66242. if( bPreserve ){
  66243. btreeReleaseAllCursorPages(pCur);
  66244. pCur->eState = CURSOR_REQUIRESEEK;
  66245. }
  66246. if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
  66247. }
  66248. }
  66249. return rc;
  66250. }
  66251. /*
  66252. ** Create a new BTree table. Write into *piTable the page
  66253. ** number for the root page of the new table.
  66254. **
  66255. ** The type of type is determined by the flags parameter. Only the
  66256. ** following values of flags are currently in use. Other values for
  66257. ** flags might not work:
  66258. **
  66259. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  66260. ** BTREE_ZERODATA Used for SQL indices
  66261. */
  66262. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  66263. BtShared *pBt = p->pBt;
  66264. MemPage *pRoot;
  66265. Pgno pgnoRoot;
  66266. int rc;
  66267. int ptfFlags; /* Page-type flage for the root page of new table */
  66268. assert( sqlite3BtreeHoldsMutex(p) );
  66269. assert( pBt->inTransaction==TRANS_WRITE );
  66270. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  66271. #ifdef SQLITE_OMIT_AUTOVACUUM
  66272. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  66273. if( rc ){
  66274. return rc;
  66275. }
  66276. #else
  66277. if( pBt->autoVacuum ){
  66278. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  66279. MemPage *pPageMove; /* The page to move to. */
  66280. /* Creating a new table may probably require moving an existing database
  66281. ** to make room for the new tables root page. In case this page turns
  66282. ** out to be an overflow page, delete all overflow page-map caches
  66283. ** held by open cursors.
  66284. */
  66285. invalidateAllOverflowCache(pBt);
  66286. /* Read the value of meta[3] from the database to determine where the
  66287. ** root page of the new table should go. meta[3] is the largest root-page
  66288. ** created so far, so the new root-page is (meta[3]+1).
  66289. */
  66290. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  66291. pgnoRoot++;
  66292. /* The new root-page may not be allocated on a pointer-map page, or the
  66293. ** PENDING_BYTE page.
  66294. */
  66295. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  66296. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  66297. pgnoRoot++;
  66298. }
  66299. assert( pgnoRoot>=3 || CORRUPT_DB );
  66300. testcase( pgnoRoot<3 );
  66301. /* Allocate a page. The page that currently resides at pgnoRoot will
  66302. ** be moved to the allocated page (unless the allocated page happens
  66303. ** to reside at pgnoRoot).
  66304. */
  66305. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  66306. if( rc!=SQLITE_OK ){
  66307. return rc;
  66308. }
  66309. if( pgnoMove!=pgnoRoot ){
  66310. /* pgnoRoot is the page that will be used for the root-page of
  66311. ** the new table (assuming an error did not occur). But we were
  66312. ** allocated pgnoMove. If required (i.e. if it was not allocated
  66313. ** by extending the file), the current page at position pgnoMove
  66314. ** is already journaled.
  66315. */
  66316. u8 eType = 0;
  66317. Pgno iPtrPage = 0;
  66318. /* Save the positions of any open cursors. This is required in
  66319. ** case they are holding a reference to an xFetch reference
  66320. ** corresponding to page pgnoRoot. */
  66321. rc = saveAllCursors(pBt, 0, 0);
  66322. releasePage(pPageMove);
  66323. if( rc!=SQLITE_OK ){
  66324. return rc;
  66325. }
  66326. /* Move the page currently at pgnoRoot to pgnoMove. */
  66327. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  66328. if( rc!=SQLITE_OK ){
  66329. return rc;
  66330. }
  66331. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  66332. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  66333. rc = SQLITE_CORRUPT_BKPT;
  66334. }
  66335. if( rc!=SQLITE_OK ){
  66336. releasePage(pRoot);
  66337. return rc;
  66338. }
  66339. assert( eType!=PTRMAP_ROOTPAGE );
  66340. assert( eType!=PTRMAP_FREEPAGE );
  66341. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  66342. releasePage(pRoot);
  66343. /* Obtain the page at pgnoRoot */
  66344. if( rc!=SQLITE_OK ){
  66345. return rc;
  66346. }
  66347. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  66348. if( rc!=SQLITE_OK ){
  66349. return rc;
  66350. }
  66351. rc = sqlite3PagerWrite(pRoot->pDbPage);
  66352. if( rc!=SQLITE_OK ){
  66353. releasePage(pRoot);
  66354. return rc;
  66355. }
  66356. }else{
  66357. pRoot = pPageMove;
  66358. }
  66359. /* Update the pointer-map and meta-data with the new root-page number. */
  66360. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  66361. if( rc ){
  66362. releasePage(pRoot);
  66363. return rc;
  66364. }
  66365. /* When the new root page was allocated, page 1 was made writable in
  66366. ** order either to increase the database filesize, or to decrement the
  66367. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  66368. */
  66369. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  66370. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  66371. if( NEVER(rc) ){
  66372. releasePage(pRoot);
  66373. return rc;
  66374. }
  66375. }else{
  66376. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  66377. if( rc ) return rc;
  66378. }
  66379. #endif
  66380. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  66381. if( createTabFlags & BTREE_INTKEY ){
  66382. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  66383. }else{
  66384. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  66385. }
  66386. zeroPage(pRoot, ptfFlags);
  66387. sqlite3PagerUnref(pRoot->pDbPage);
  66388. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  66389. *piTable = (int)pgnoRoot;
  66390. return SQLITE_OK;
  66391. }
  66392. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  66393. int rc;
  66394. sqlite3BtreeEnter(p);
  66395. rc = btreeCreateTable(p, piTable, flags);
  66396. sqlite3BtreeLeave(p);
  66397. return rc;
  66398. }
  66399. /*
  66400. ** Erase the given database page and all its children. Return
  66401. ** the page to the freelist.
  66402. */
  66403. static int clearDatabasePage(
  66404. BtShared *pBt, /* The BTree that contains the table */
  66405. Pgno pgno, /* Page number to clear */
  66406. int freePageFlag, /* Deallocate page if true */
  66407. int *pnChange /* Add number of Cells freed to this counter */
  66408. ){
  66409. MemPage *pPage;
  66410. int rc;
  66411. unsigned char *pCell;
  66412. int i;
  66413. int hdr;
  66414. CellInfo info;
  66415. assert( sqlite3_mutex_held(pBt->mutex) );
  66416. if( pgno>btreePagecount(pBt) ){
  66417. return SQLITE_CORRUPT_BKPT;
  66418. }
  66419. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  66420. if( rc ) return rc;
  66421. if( pPage->bBusy ){
  66422. rc = SQLITE_CORRUPT_BKPT;
  66423. goto cleardatabasepage_out;
  66424. }
  66425. pPage->bBusy = 1;
  66426. hdr = pPage->hdrOffset;
  66427. for(i=0; i<pPage->nCell; i++){
  66428. pCell = findCell(pPage, i);
  66429. if( !pPage->leaf ){
  66430. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  66431. if( rc ) goto cleardatabasepage_out;
  66432. }
  66433. rc = clearCell(pPage, pCell, &info);
  66434. if( rc ) goto cleardatabasepage_out;
  66435. }
  66436. if( !pPage->leaf ){
  66437. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  66438. if( rc ) goto cleardatabasepage_out;
  66439. }else if( pnChange ){
  66440. assert( pPage->intKey || CORRUPT_DB );
  66441. testcase( !pPage->intKey );
  66442. *pnChange += pPage->nCell;
  66443. }
  66444. if( freePageFlag ){
  66445. freePage(pPage, &rc);
  66446. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  66447. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  66448. }
  66449. cleardatabasepage_out:
  66450. pPage->bBusy = 0;
  66451. releasePage(pPage);
  66452. return rc;
  66453. }
  66454. /*
  66455. ** Delete all information from a single table in the database. iTable is
  66456. ** the page number of the root of the table. After this routine returns,
  66457. ** the root page is empty, but still exists.
  66458. **
  66459. ** This routine will fail with SQLITE_LOCKED if there are any open
  66460. ** read cursors on the table. Open write cursors are moved to the
  66461. ** root of the table.
  66462. **
  66463. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  66464. ** integer value pointed to by pnChange is incremented by the number of
  66465. ** entries in the table.
  66466. */
  66467. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  66468. int rc;
  66469. BtShared *pBt = p->pBt;
  66470. sqlite3BtreeEnter(p);
  66471. assert( p->inTrans==TRANS_WRITE );
  66472. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  66473. if( SQLITE_OK==rc ){
  66474. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  66475. ** is the root of a table b-tree - if it is not, the following call is
  66476. ** a no-op). */
  66477. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  66478. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  66479. }
  66480. sqlite3BtreeLeave(p);
  66481. return rc;
  66482. }
  66483. /*
  66484. ** Delete all information from the single table that pCur is open on.
  66485. **
  66486. ** This routine only work for pCur on an ephemeral table.
  66487. */
  66488. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  66489. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  66490. }
  66491. /*
  66492. ** Erase all information in a table and add the root of the table to
  66493. ** the freelist. Except, the root of the principle table (the one on
  66494. ** page 1) is never added to the freelist.
  66495. **
  66496. ** This routine will fail with SQLITE_LOCKED if there are any open
  66497. ** cursors on the table.
  66498. **
  66499. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  66500. ** root page in the database file, then the last root page
  66501. ** in the database file is moved into the slot formerly occupied by
  66502. ** iTable and that last slot formerly occupied by the last root page
  66503. ** is added to the freelist instead of iTable. In this say, all
  66504. ** root pages are kept at the beginning of the database file, which
  66505. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  66506. ** page number that used to be the last root page in the file before
  66507. ** the move. If no page gets moved, *piMoved is set to 0.
  66508. ** The last root page is recorded in meta[3] and the value of
  66509. ** meta[3] is updated by this procedure.
  66510. */
  66511. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  66512. int rc;
  66513. MemPage *pPage = 0;
  66514. BtShared *pBt = p->pBt;
  66515. assert( sqlite3BtreeHoldsMutex(p) );
  66516. assert( p->inTrans==TRANS_WRITE );
  66517. assert( iTable>=2 );
  66518. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  66519. if( rc ) return rc;
  66520. rc = sqlite3BtreeClearTable(p, iTable, 0);
  66521. if( rc ){
  66522. releasePage(pPage);
  66523. return rc;
  66524. }
  66525. *piMoved = 0;
  66526. #ifdef SQLITE_OMIT_AUTOVACUUM
  66527. freePage(pPage, &rc);
  66528. releasePage(pPage);
  66529. #else
  66530. if( pBt->autoVacuum ){
  66531. Pgno maxRootPgno;
  66532. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  66533. if( iTable==maxRootPgno ){
  66534. /* If the table being dropped is the table with the largest root-page
  66535. ** number in the database, put the root page on the free list.
  66536. */
  66537. freePage(pPage, &rc);
  66538. releasePage(pPage);
  66539. if( rc!=SQLITE_OK ){
  66540. return rc;
  66541. }
  66542. }else{
  66543. /* The table being dropped does not have the largest root-page
  66544. ** number in the database. So move the page that does into the
  66545. ** gap left by the deleted root-page.
  66546. */
  66547. MemPage *pMove;
  66548. releasePage(pPage);
  66549. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  66550. if( rc!=SQLITE_OK ){
  66551. return rc;
  66552. }
  66553. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  66554. releasePage(pMove);
  66555. if( rc!=SQLITE_OK ){
  66556. return rc;
  66557. }
  66558. pMove = 0;
  66559. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  66560. freePage(pMove, &rc);
  66561. releasePage(pMove);
  66562. if( rc!=SQLITE_OK ){
  66563. return rc;
  66564. }
  66565. *piMoved = maxRootPgno;
  66566. }
  66567. /* Set the new 'max-root-page' value in the database header. This
  66568. ** is the old value less one, less one more if that happens to
  66569. ** be a root-page number, less one again if that is the
  66570. ** PENDING_BYTE_PAGE.
  66571. */
  66572. maxRootPgno--;
  66573. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  66574. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  66575. maxRootPgno--;
  66576. }
  66577. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  66578. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  66579. }else{
  66580. freePage(pPage, &rc);
  66581. releasePage(pPage);
  66582. }
  66583. #endif
  66584. return rc;
  66585. }
  66586. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  66587. int rc;
  66588. sqlite3BtreeEnter(p);
  66589. rc = btreeDropTable(p, iTable, piMoved);
  66590. sqlite3BtreeLeave(p);
  66591. return rc;
  66592. }
  66593. /*
  66594. ** This function may only be called if the b-tree connection already
  66595. ** has a read or write transaction open on the database.
  66596. **
  66597. ** Read the meta-information out of a database file. Meta[0]
  66598. ** is the number of free pages currently in the database. Meta[1]
  66599. ** through meta[15] are available for use by higher layers. Meta[0]
  66600. ** is read-only, the others are read/write.
  66601. **
  66602. ** The schema layer numbers meta values differently. At the schema
  66603. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  66604. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  66605. **
  66606. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  66607. ** of reading the value out of the header, it instead loads the "DataVersion"
  66608. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  66609. ** database file. It is a number computed by the pager. But its access
  66610. ** pattern is the same as header meta values, and so it is convenient to
  66611. ** read it from this routine.
  66612. */
  66613. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  66614. BtShared *pBt = p->pBt;
  66615. sqlite3BtreeEnter(p);
  66616. assert( p->inTrans>TRANS_NONE );
  66617. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  66618. assert( pBt->pPage1 );
  66619. assert( idx>=0 && idx<=15 );
  66620. if( idx==BTREE_DATA_VERSION ){
  66621. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  66622. }else{
  66623. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  66624. }
  66625. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  66626. ** database, mark the database as read-only. */
  66627. #ifdef SQLITE_OMIT_AUTOVACUUM
  66628. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  66629. pBt->btsFlags |= BTS_READ_ONLY;
  66630. }
  66631. #endif
  66632. sqlite3BtreeLeave(p);
  66633. }
  66634. /*
  66635. ** Write meta-information back into the database. Meta[0] is
  66636. ** read-only and may not be written.
  66637. */
  66638. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  66639. BtShared *pBt = p->pBt;
  66640. unsigned char *pP1;
  66641. int rc;
  66642. assert( idx>=1 && idx<=15 );
  66643. sqlite3BtreeEnter(p);
  66644. assert( p->inTrans==TRANS_WRITE );
  66645. assert( pBt->pPage1!=0 );
  66646. pP1 = pBt->pPage1->aData;
  66647. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  66648. if( rc==SQLITE_OK ){
  66649. put4byte(&pP1[36 + idx*4], iMeta);
  66650. #ifndef SQLITE_OMIT_AUTOVACUUM
  66651. if( idx==BTREE_INCR_VACUUM ){
  66652. assert( pBt->autoVacuum || iMeta==0 );
  66653. assert( iMeta==0 || iMeta==1 );
  66654. pBt->incrVacuum = (u8)iMeta;
  66655. }
  66656. #endif
  66657. }
  66658. sqlite3BtreeLeave(p);
  66659. return rc;
  66660. }
  66661. #ifndef SQLITE_OMIT_BTREECOUNT
  66662. /*
  66663. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  66664. ** number of entries in the b-tree and write the result to *pnEntry.
  66665. **
  66666. ** SQLITE_OK is returned if the operation is successfully executed.
  66667. ** Otherwise, if an error is encountered (i.e. an IO error or database
  66668. ** corruption) an SQLite error code is returned.
  66669. */
  66670. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  66671. i64 nEntry = 0; /* Value to return in *pnEntry */
  66672. int rc; /* Return code */
  66673. rc = moveToRoot(pCur);
  66674. if( rc==SQLITE_EMPTY ){
  66675. *pnEntry = 0;
  66676. return SQLITE_OK;
  66677. }
  66678. /* Unless an error occurs, the following loop runs one iteration for each
  66679. ** page in the B-Tree structure (not including overflow pages).
  66680. */
  66681. while( rc==SQLITE_OK ){
  66682. int iIdx; /* Index of child node in parent */
  66683. MemPage *pPage; /* Current page of the b-tree */
  66684. /* If this is a leaf page or the tree is not an int-key tree, then
  66685. ** this page contains countable entries. Increment the entry counter
  66686. ** accordingly.
  66687. */
  66688. pPage = pCur->pPage;
  66689. if( pPage->leaf || !pPage->intKey ){
  66690. nEntry += pPage->nCell;
  66691. }
  66692. /* pPage is a leaf node. This loop navigates the cursor so that it
  66693. ** points to the first interior cell that it points to the parent of
  66694. ** the next page in the tree that has not yet been visited. The
  66695. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  66696. ** of the page, or to the number of cells in the page if the next page
  66697. ** to visit is the right-child of its parent.
  66698. **
  66699. ** If all pages in the tree have been visited, return SQLITE_OK to the
  66700. ** caller.
  66701. */
  66702. if( pPage->leaf ){
  66703. do {
  66704. if( pCur->iPage==0 ){
  66705. /* All pages of the b-tree have been visited. Return successfully. */
  66706. *pnEntry = nEntry;
  66707. return moveToRoot(pCur);
  66708. }
  66709. moveToParent(pCur);
  66710. }while ( pCur->ix>=pCur->pPage->nCell );
  66711. pCur->ix++;
  66712. pPage = pCur->pPage;
  66713. }
  66714. /* Descend to the child node of the cell that the cursor currently
  66715. ** points at. This is the right-child if (iIdx==pPage->nCell).
  66716. */
  66717. iIdx = pCur->ix;
  66718. if( iIdx==pPage->nCell ){
  66719. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  66720. }else{
  66721. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  66722. }
  66723. }
  66724. /* An error has occurred. Return an error code. */
  66725. return rc;
  66726. }
  66727. #endif
  66728. /*
  66729. ** Return the pager associated with a BTree. This routine is used for
  66730. ** testing and debugging only.
  66731. */
  66732. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  66733. return p->pBt->pPager;
  66734. }
  66735. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66736. /*
  66737. ** Append a message to the error message string.
  66738. */
  66739. static void checkAppendMsg(
  66740. IntegrityCk *pCheck,
  66741. const char *zFormat,
  66742. ...
  66743. ){
  66744. va_list ap;
  66745. if( !pCheck->mxErr ) return;
  66746. pCheck->mxErr--;
  66747. pCheck->nErr++;
  66748. va_start(ap, zFormat);
  66749. if( pCheck->errMsg.nChar ){
  66750. sqlite3_str_append(&pCheck->errMsg, "\n", 1);
  66751. }
  66752. if( pCheck->zPfx ){
  66753. sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  66754. }
  66755. sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
  66756. va_end(ap);
  66757. if( pCheck->errMsg.accError==SQLITE_NOMEM ){
  66758. pCheck->mallocFailed = 1;
  66759. }
  66760. }
  66761. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66762. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66763. /*
  66764. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  66765. ** corresponds to page iPg is already set.
  66766. */
  66767. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  66768. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  66769. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  66770. }
  66771. /*
  66772. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  66773. */
  66774. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  66775. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  66776. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  66777. }
  66778. /*
  66779. ** Add 1 to the reference count for page iPage. If this is the second
  66780. ** reference to the page, add an error message to pCheck->zErrMsg.
  66781. ** Return 1 if there are 2 or more references to the page and 0 if
  66782. ** if this is the first reference to the page.
  66783. **
  66784. ** Also check that the page number is in bounds.
  66785. */
  66786. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  66787. if( iPage==0 ) return 1;
  66788. if( iPage>pCheck->nPage ){
  66789. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  66790. return 1;
  66791. }
  66792. if( getPageReferenced(pCheck, iPage) ){
  66793. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  66794. return 1;
  66795. }
  66796. setPageReferenced(pCheck, iPage);
  66797. return 0;
  66798. }
  66799. #ifndef SQLITE_OMIT_AUTOVACUUM
  66800. /*
  66801. ** Check that the entry in the pointer-map for page iChild maps to
  66802. ** page iParent, pointer type ptrType. If not, append an error message
  66803. ** to pCheck.
  66804. */
  66805. static void checkPtrmap(
  66806. IntegrityCk *pCheck, /* Integrity check context */
  66807. Pgno iChild, /* Child page number */
  66808. u8 eType, /* Expected pointer map type */
  66809. Pgno iParent /* Expected pointer map parent page number */
  66810. ){
  66811. int rc;
  66812. u8 ePtrmapType;
  66813. Pgno iPtrmapParent;
  66814. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  66815. if( rc!=SQLITE_OK ){
  66816. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  66817. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  66818. return;
  66819. }
  66820. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  66821. checkAppendMsg(pCheck,
  66822. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  66823. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  66824. }
  66825. }
  66826. #endif
  66827. /*
  66828. ** Check the integrity of the freelist or of an overflow page list.
  66829. ** Verify that the number of pages on the list is N.
  66830. */
  66831. static void checkList(
  66832. IntegrityCk *pCheck, /* Integrity checking context */
  66833. int isFreeList, /* True for a freelist. False for overflow page list */
  66834. int iPage, /* Page number for first page in the list */
  66835. int N /* Expected number of pages in the list */
  66836. ){
  66837. int i;
  66838. int expected = N;
  66839. int iFirst = iPage;
  66840. while( N-- > 0 && pCheck->mxErr ){
  66841. DbPage *pOvflPage;
  66842. unsigned char *pOvflData;
  66843. if( iPage<1 ){
  66844. checkAppendMsg(pCheck,
  66845. "%d of %d pages missing from overflow list starting at %d",
  66846. N+1, expected, iFirst);
  66847. break;
  66848. }
  66849. if( checkRef(pCheck, iPage) ) break;
  66850. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  66851. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  66852. break;
  66853. }
  66854. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  66855. if( isFreeList ){
  66856. int n = get4byte(&pOvflData[4]);
  66857. #ifndef SQLITE_OMIT_AUTOVACUUM
  66858. if( pCheck->pBt->autoVacuum ){
  66859. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  66860. }
  66861. #endif
  66862. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  66863. checkAppendMsg(pCheck,
  66864. "freelist leaf count too big on page %d", iPage);
  66865. N--;
  66866. }else{
  66867. for(i=0; i<n; i++){
  66868. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  66869. #ifndef SQLITE_OMIT_AUTOVACUUM
  66870. if( pCheck->pBt->autoVacuum ){
  66871. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  66872. }
  66873. #endif
  66874. checkRef(pCheck, iFreePage);
  66875. }
  66876. N -= n;
  66877. }
  66878. }
  66879. #ifndef SQLITE_OMIT_AUTOVACUUM
  66880. else{
  66881. /* If this database supports auto-vacuum and iPage is not the last
  66882. ** page in this overflow list, check that the pointer-map entry for
  66883. ** the following page matches iPage.
  66884. */
  66885. if( pCheck->pBt->autoVacuum && N>0 ){
  66886. i = get4byte(pOvflData);
  66887. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  66888. }
  66889. }
  66890. #endif
  66891. iPage = get4byte(pOvflData);
  66892. sqlite3PagerUnref(pOvflPage);
  66893. if( isFreeList && N<(iPage!=0) ){
  66894. checkAppendMsg(pCheck, "free-page count in header is too small");
  66895. }
  66896. }
  66897. }
  66898. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66899. /*
  66900. ** An implementation of a min-heap.
  66901. **
  66902. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  66903. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  66904. ** and aHeap[N*2+1].
  66905. **
  66906. ** The heap property is this: Every node is less than or equal to both
  66907. ** of its daughter nodes. A consequence of the heap property is that the
  66908. ** root node aHeap[1] is always the minimum value currently in the heap.
  66909. **
  66910. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  66911. ** the heap, preserving the heap property. The btreeHeapPull() routine
  66912. ** removes the root element from the heap (the minimum value in the heap)
  66913. ** and then moves other nodes around as necessary to preserve the heap
  66914. ** property.
  66915. **
  66916. ** This heap is used for cell overlap and coverage testing. Each u32
  66917. ** entry represents the span of a cell or freeblock on a btree page.
  66918. ** The upper 16 bits are the index of the first byte of a range and the
  66919. ** lower 16 bits are the index of the last byte of that range.
  66920. */
  66921. static void btreeHeapInsert(u32 *aHeap, u32 x){
  66922. u32 j, i = ++aHeap[0];
  66923. aHeap[i] = x;
  66924. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  66925. x = aHeap[j];
  66926. aHeap[j] = aHeap[i];
  66927. aHeap[i] = x;
  66928. i = j;
  66929. }
  66930. }
  66931. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  66932. u32 j, i, x;
  66933. if( (x = aHeap[0])==0 ) return 0;
  66934. *pOut = aHeap[1];
  66935. aHeap[1] = aHeap[x];
  66936. aHeap[x] = 0xffffffff;
  66937. aHeap[0]--;
  66938. i = 1;
  66939. while( (j = i*2)<=aHeap[0] ){
  66940. if( aHeap[j]>aHeap[j+1] ) j++;
  66941. if( aHeap[i]<aHeap[j] ) break;
  66942. x = aHeap[i];
  66943. aHeap[i] = aHeap[j];
  66944. aHeap[j] = x;
  66945. i = j;
  66946. }
  66947. return 1;
  66948. }
  66949. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66950. /*
  66951. ** Do various sanity checks on a single page of a tree. Return
  66952. ** the tree depth. Root pages return 0. Parents of root pages
  66953. ** return 1, and so forth.
  66954. **
  66955. ** These checks are done:
  66956. **
  66957. ** 1. Make sure that cells and freeblocks do not overlap
  66958. ** but combine to completely cover the page.
  66959. ** 2. Make sure integer cell keys are in order.
  66960. ** 3. Check the integrity of overflow pages.
  66961. ** 4. Recursively call checkTreePage on all children.
  66962. ** 5. Verify that the depth of all children is the same.
  66963. */
  66964. static int checkTreePage(
  66965. IntegrityCk *pCheck, /* Context for the sanity check */
  66966. int iPage, /* Page number of the page to check */
  66967. i64 *piMinKey, /* Write minimum integer primary key here */
  66968. i64 maxKey /* Error if integer primary key greater than this */
  66969. ){
  66970. MemPage *pPage = 0; /* The page being analyzed */
  66971. int i; /* Loop counter */
  66972. int rc; /* Result code from subroutine call */
  66973. int depth = -1, d2; /* Depth of a subtree */
  66974. int pgno; /* Page number */
  66975. int nFrag; /* Number of fragmented bytes on the page */
  66976. int hdr; /* Offset to the page header */
  66977. int cellStart; /* Offset to the start of the cell pointer array */
  66978. int nCell; /* Number of cells */
  66979. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  66980. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  66981. ** False if IPK must be strictly less than maxKey */
  66982. u8 *data; /* Page content */
  66983. u8 *pCell; /* Cell content */
  66984. u8 *pCellIdx; /* Next element of the cell pointer array */
  66985. BtShared *pBt; /* The BtShared object that owns pPage */
  66986. u32 pc; /* Address of a cell */
  66987. u32 usableSize; /* Usable size of the page */
  66988. u32 contentOffset; /* Offset to the start of the cell content area */
  66989. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  66990. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  66991. const char *saved_zPfx = pCheck->zPfx;
  66992. int saved_v1 = pCheck->v1;
  66993. int saved_v2 = pCheck->v2;
  66994. u8 savedIsInit = 0;
  66995. /* Check that the page exists
  66996. */
  66997. pBt = pCheck->pBt;
  66998. usableSize = pBt->usableSize;
  66999. if( iPage==0 ) return 0;
  67000. if( checkRef(pCheck, iPage) ) return 0;
  67001. pCheck->zPfx = "Page %d: ";
  67002. pCheck->v1 = iPage;
  67003. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  67004. checkAppendMsg(pCheck,
  67005. "unable to get the page. error code=%d", rc);
  67006. goto end_of_check;
  67007. }
  67008. /* Clear MemPage.isInit to make sure the corruption detection code in
  67009. ** btreeInitPage() is executed. */
  67010. savedIsInit = pPage->isInit;
  67011. pPage->isInit = 0;
  67012. if( (rc = btreeInitPage(pPage))!=0 ){
  67013. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  67014. checkAppendMsg(pCheck,
  67015. "btreeInitPage() returns error code %d", rc);
  67016. goto end_of_check;
  67017. }
  67018. data = pPage->aData;
  67019. hdr = pPage->hdrOffset;
  67020. /* Set up for cell analysis */
  67021. pCheck->zPfx = "On tree page %d cell %d: ";
  67022. contentOffset = get2byteNotZero(&data[hdr+5]);
  67023. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  67024. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  67025. ** number of cells on the page. */
  67026. nCell = get2byte(&data[hdr+3]);
  67027. assert( pPage->nCell==nCell );
  67028. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  67029. ** immediately follows the b-tree page header. */
  67030. cellStart = hdr + 12 - 4*pPage->leaf;
  67031. assert( pPage->aCellIdx==&data[cellStart] );
  67032. pCellIdx = &data[cellStart + 2*(nCell-1)];
  67033. if( !pPage->leaf ){
  67034. /* Analyze the right-child page of internal pages */
  67035. pgno = get4byte(&data[hdr+8]);
  67036. #ifndef SQLITE_OMIT_AUTOVACUUM
  67037. if( pBt->autoVacuum ){
  67038. pCheck->zPfx = "On page %d at right child: ";
  67039. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  67040. }
  67041. #endif
  67042. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  67043. keyCanBeEqual = 0;
  67044. }else{
  67045. /* For leaf pages, the coverage check will occur in the same loop
  67046. ** as the other cell checks, so initialize the heap. */
  67047. heap = pCheck->heap;
  67048. heap[0] = 0;
  67049. }
  67050. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  67051. ** integer offsets to the cell contents. */
  67052. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  67053. CellInfo info;
  67054. /* Check cell size */
  67055. pCheck->v2 = i;
  67056. assert( pCellIdx==&data[cellStart + i*2] );
  67057. pc = get2byteAligned(pCellIdx);
  67058. pCellIdx -= 2;
  67059. if( pc<contentOffset || pc>usableSize-4 ){
  67060. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  67061. pc, contentOffset, usableSize-4);
  67062. doCoverageCheck = 0;
  67063. continue;
  67064. }
  67065. pCell = &data[pc];
  67066. pPage->xParseCell(pPage, pCell, &info);
  67067. if( pc+info.nSize>usableSize ){
  67068. checkAppendMsg(pCheck, "Extends off end of page");
  67069. doCoverageCheck = 0;
  67070. continue;
  67071. }
  67072. /* Check for integer primary key out of range */
  67073. if( pPage->intKey ){
  67074. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  67075. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  67076. }
  67077. maxKey = info.nKey;
  67078. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  67079. }
  67080. /* Check the content overflow list */
  67081. if( info.nPayload>info.nLocal ){
  67082. int nPage; /* Number of pages on the overflow chain */
  67083. Pgno pgnoOvfl; /* First page of the overflow chain */
  67084. assert( pc + info.nSize - 4 <= usableSize );
  67085. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  67086. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  67087. #ifndef SQLITE_OMIT_AUTOVACUUM
  67088. if( pBt->autoVacuum ){
  67089. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  67090. }
  67091. #endif
  67092. checkList(pCheck, 0, pgnoOvfl, nPage);
  67093. }
  67094. if( !pPage->leaf ){
  67095. /* Check sanity of left child page for internal pages */
  67096. pgno = get4byte(pCell);
  67097. #ifndef SQLITE_OMIT_AUTOVACUUM
  67098. if( pBt->autoVacuum ){
  67099. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  67100. }
  67101. #endif
  67102. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  67103. keyCanBeEqual = 0;
  67104. if( d2!=depth ){
  67105. checkAppendMsg(pCheck, "Child page depth differs");
  67106. depth = d2;
  67107. }
  67108. }else{
  67109. /* Populate the coverage-checking heap for leaf pages */
  67110. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  67111. }
  67112. }
  67113. *piMinKey = maxKey;
  67114. /* Check for complete coverage of the page
  67115. */
  67116. pCheck->zPfx = 0;
  67117. if( doCoverageCheck && pCheck->mxErr>0 ){
  67118. /* For leaf pages, the min-heap has already been initialized and the
  67119. ** cells have already been inserted. But for internal pages, that has
  67120. ** not yet been done, so do it now */
  67121. if( !pPage->leaf ){
  67122. heap = pCheck->heap;
  67123. heap[0] = 0;
  67124. for(i=nCell-1; i>=0; i--){
  67125. u32 size;
  67126. pc = get2byteAligned(&data[cellStart+i*2]);
  67127. size = pPage->xCellSize(pPage, &data[pc]);
  67128. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  67129. }
  67130. }
  67131. /* Add the freeblocks to the min-heap
  67132. **
  67133. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  67134. ** is the offset of the first freeblock, or zero if there are no
  67135. ** freeblocks on the page.
  67136. */
  67137. i = get2byte(&data[hdr+1]);
  67138. while( i>0 ){
  67139. int size, j;
  67140. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  67141. size = get2byte(&data[i+2]);
  67142. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  67143. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  67144. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  67145. ** big-endian integer which is the offset in the b-tree page of the next
  67146. ** freeblock in the chain, or zero if the freeblock is the last on the
  67147. ** chain. */
  67148. j = get2byte(&data[i]);
  67149. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  67150. ** increasing offset. */
  67151. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  67152. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  67153. i = j;
  67154. }
  67155. /* Analyze the min-heap looking for overlap between cells and/or
  67156. ** freeblocks, and counting the number of untracked bytes in nFrag.
  67157. **
  67158. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  67159. ** There is an implied first entry the covers the page header, the cell
  67160. ** pointer index, and the gap between the cell pointer index and the start
  67161. ** of cell content.
  67162. **
  67163. ** The loop below pulls entries from the min-heap in order and compares
  67164. ** the start_address against the previous end_address. If there is an
  67165. ** overlap, that means bytes are used multiple times. If there is a gap,
  67166. ** that gap is added to the fragmentation count.
  67167. */
  67168. nFrag = 0;
  67169. prev = contentOffset - 1; /* Implied first min-heap entry */
  67170. while( btreeHeapPull(heap,&x) ){
  67171. if( (prev&0xffff)>=(x>>16) ){
  67172. checkAppendMsg(pCheck,
  67173. "Multiple uses for byte %u of page %d", x>>16, iPage);
  67174. break;
  67175. }else{
  67176. nFrag += (x>>16) - (prev&0xffff) - 1;
  67177. prev = x;
  67178. }
  67179. }
  67180. nFrag += usableSize - (prev&0xffff) - 1;
  67181. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  67182. ** is stored in the fifth field of the b-tree page header.
  67183. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  67184. ** number of fragmented free bytes within the cell content area.
  67185. */
  67186. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  67187. checkAppendMsg(pCheck,
  67188. "Fragmentation of %d bytes reported as %d on page %d",
  67189. nFrag, data[hdr+7], iPage);
  67190. }
  67191. }
  67192. end_of_check:
  67193. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  67194. releasePage(pPage);
  67195. pCheck->zPfx = saved_zPfx;
  67196. pCheck->v1 = saved_v1;
  67197. pCheck->v2 = saved_v2;
  67198. return depth+1;
  67199. }
  67200. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  67201. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  67202. /*
  67203. ** This routine does a complete check of the given BTree file. aRoot[] is
  67204. ** an array of pages numbers were each page number is the root page of
  67205. ** a table. nRoot is the number of entries in aRoot.
  67206. **
  67207. ** A read-only or read-write transaction must be opened before calling
  67208. ** this function.
  67209. **
  67210. ** Write the number of error seen in *pnErr. Except for some memory
  67211. ** allocation errors, an error message held in memory obtained from
  67212. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  67213. ** returned. If a memory allocation error occurs, NULL is returned.
  67214. */
  67215. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  67216. Btree *p, /* The btree to be checked */
  67217. int *aRoot, /* An array of root pages numbers for individual trees */
  67218. int nRoot, /* Number of entries in aRoot[] */
  67219. int mxErr, /* Stop reporting errors after this many */
  67220. int *pnErr /* Write number of errors seen to this variable */
  67221. ){
  67222. Pgno i;
  67223. IntegrityCk sCheck;
  67224. BtShared *pBt = p->pBt;
  67225. int savedDbFlags = pBt->db->flags;
  67226. char zErr[100];
  67227. VVA_ONLY( int nRef );
  67228. sqlite3BtreeEnter(p);
  67229. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  67230. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  67231. assert( nRef>=0 );
  67232. sCheck.pBt = pBt;
  67233. sCheck.pPager = pBt->pPager;
  67234. sCheck.nPage = btreePagecount(sCheck.pBt);
  67235. sCheck.mxErr = mxErr;
  67236. sCheck.nErr = 0;
  67237. sCheck.mallocFailed = 0;
  67238. sCheck.zPfx = 0;
  67239. sCheck.v1 = 0;
  67240. sCheck.v2 = 0;
  67241. sCheck.aPgRef = 0;
  67242. sCheck.heap = 0;
  67243. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  67244. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  67245. if( sCheck.nPage==0 ){
  67246. goto integrity_ck_cleanup;
  67247. }
  67248. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  67249. if( !sCheck.aPgRef ){
  67250. sCheck.mallocFailed = 1;
  67251. goto integrity_ck_cleanup;
  67252. }
  67253. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  67254. if( sCheck.heap==0 ){
  67255. sCheck.mallocFailed = 1;
  67256. goto integrity_ck_cleanup;
  67257. }
  67258. i = PENDING_BYTE_PAGE(pBt);
  67259. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  67260. /* Check the integrity of the freelist
  67261. */
  67262. sCheck.zPfx = "Main freelist: ";
  67263. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  67264. get4byte(&pBt->pPage1->aData[36]));
  67265. sCheck.zPfx = 0;
  67266. /* Check all the tables.
  67267. */
  67268. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  67269. pBt->db->flags &= ~SQLITE_CellSizeCk;
  67270. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  67271. i64 notUsed;
  67272. if( aRoot[i]==0 ) continue;
  67273. #ifndef SQLITE_OMIT_AUTOVACUUM
  67274. if( pBt->autoVacuum && aRoot[i]>1 ){
  67275. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  67276. }
  67277. #endif
  67278. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  67279. }
  67280. pBt->db->flags = savedDbFlags;
  67281. /* Make sure every page in the file is referenced
  67282. */
  67283. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  67284. #ifdef SQLITE_OMIT_AUTOVACUUM
  67285. if( getPageReferenced(&sCheck, i)==0 ){
  67286. checkAppendMsg(&sCheck, "Page %d is never used", i);
  67287. }
  67288. #else
  67289. /* If the database supports auto-vacuum, make sure no tables contain
  67290. ** references to pointer-map pages.
  67291. */
  67292. if( getPageReferenced(&sCheck, i)==0 &&
  67293. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  67294. checkAppendMsg(&sCheck, "Page %d is never used", i);
  67295. }
  67296. if( getPageReferenced(&sCheck, i)!=0 &&
  67297. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  67298. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  67299. }
  67300. #endif
  67301. }
  67302. /* Clean up and report errors.
  67303. */
  67304. integrity_ck_cleanup:
  67305. sqlite3PageFree(sCheck.heap);
  67306. sqlite3_free(sCheck.aPgRef);
  67307. if( sCheck.mallocFailed ){
  67308. sqlite3_str_reset(&sCheck.errMsg);
  67309. sCheck.nErr++;
  67310. }
  67311. *pnErr = sCheck.nErr;
  67312. if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
  67313. /* Make sure this analysis did not leave any unref() pages. */
  67314. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  67315. sqlite3BtreeLeave(p);
  67316. return sqlite3StrAccumFinish(&sCheck.errMsg);
  67317. }
  67318. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  67319. /*
  67320. ** Return the full pathname of the underlying database file. Return
  67321. ** an empty string if the database is in-memory or a TEMP database.
  67322. **
  67323. ** The pager filename is invariant as long as the pager is
  67324. ** open so it is safe to access without the BtShared mutex.
  67325. */
  67326. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  67327. assert( p->pBt->pPager!=0 );
  67328. return sqlite3PagerFilename(p->pBt->pPager, 1);
  67329. }
  67330. /*
  67331. ** Return the pathname of the journal file for this database. The return
  67332. ** value of this routine is the same regardless of whether the journal file
  67333. ** has been created or not.
  67334. **
  67335. ** The pager journal filename is invariant as long as the pager is
  67336. ** open so it is safe to access without the BtShared mutex.
  67337. */
  67338. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  67339. assert( p->pBt->pPager!=0 );
  67340. return sqlite3PagerJournalname(p->pBt->pPager);
  67341. }
  67342. /*
  67343. ** Return non-zero if a transaction is active.
  67344. */
  67345. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  67346. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  67347. return (p && (p->inTrans==TRANS_WRITE));
  67348. }
  67349. #ifndef SQLITE_OMIT_WAL
  67350. /*
  67351. ** Run a checkpoint on the Btree passed as the first argument.
  67352. **
  67353. ** Return SQLITE_LOCKED if this or any other connection has an open
  67354. ** transaction on the shared-cache the argument Btree is connected to.
  67355. **
  67356. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  67357. */
  67358. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  67359. int rc = SQLITE_OK;
  67360. if( p ){
  67361. BtShared *pBt = p->pBt;
  67362. sqlite3BtreeEnter(p);
  67363. if( pBt->inTransaction!=TRANS_NONE ){
  67364. rc = SQLITE_LOCKED;
  67365. }else{
  67366. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  67367. }
  67368. sqlite3BtreeLeave(p);
  67369. }
  67370. return rc;
  67371. }
  67372. #endif
  67373. /*
  67374. ** Return non-zero if a read (or write) transaction is active.
  67375. */
  67376. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  67377. assert( p );
  67378. assert( sqlite3_mutex_held(p->db->mutex) );
  67379. return p->inTrans!=TRANS_NONE;
  67380. }
  67381. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  67382. assert( p );
  67383. assert( sqlite3_mutex_held(p->db->mutex) );
  67384. return p->nBackup!=0;
  67385. }
  67386. /*
  67387. ** This function returns a pointer to a blob of memory associated with
  67388. ** a single shared-btree. The memory is used by client code for its own
  67389. ** purposes (for example, to store a high-level schema associated with
  67390. ** the shared-btree). The btree layer manages reference counting issues.
  67391. **
  67392. ** The first time this is called on a shared-btree, nBytes bytes of memory
  67393. ** are allocated, zeroed, and returned to the caller. For each subsequent
  67394. ** call the nBytes parameter is ignored and a pointer to the same blob
  67395. ** of memory returned.
  67396. **
  67397. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  67398. ** allocated, a null pointer is returned. If the blob has already been
  67399. ** allocated, it is returned as normal.
  67400. **
  67401. ** Just before the shared-btree is closed, the function passed as the
  67402. ** xFree argument when the memory allocation was made is invoked on the
  67403. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  67404. ** on the memory, the btree layer does that.
  67405. */
  67406. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  67407. BtShared *pBt = p->pBt;
  67408. sqlite3BtreeEnter(p);
  67409. if( !pBt->pSchema && nBytes ){
  67410. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  67411. pBt->xFreeSchema = xFree;
  67412. }
  67413. sqlite3BtreeLeave(p);
  67414. return pBt->pSchema;
  67415. }
  67416. /*
  67417. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  67418. ** btree as the argument handle holds an exclusive lock on the
  67419. ** sqlite_master table. Otherwise SQLITE_OK.
  67420. */
  67421. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  67422. int rc;
  67423. assert( sqlite3_mutex_held(p->db->mutex) );
  67424. sqlite3BtreeEnter(p);
  67425. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  67426. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  67427. sqlite3BtreeLeave(p);
  67428. return rc;
  67429. }
  67430. #ifndef SQLITE_OMIT_SHARED_CACHE
  67431. /*
  67432. ** Obtain a lock on the table whose root page is iTab. The
  67433. ** lock is a write lock if isWritelock is true or a read lock
  67434. ** if it is false.
  67435. */
  67436. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  67437. int rc = SQLITE_OK;
  67438. assert( p->inTrans!=TRANS_NONE );
  67439. if( p->sharable ){
  67440. u8 lockType = READ_LOCK + isWriteLock;
  67441. assert( READ_LOCK+1==WRITE_LOCK );
  67442. assert( isWriteLock==0 || isWriteLock==1 );
  67443. sqlite3BtreeEnter(p);
  67444. rc = querySharedCacheTableLock(p, iTab, lockType);
  67445. if( rc==SQLITE_OK ){
  67446. rc = setSharedCacheTableLock(p, iTab, lockType);
  67447. }
  67448. sqlite3BtreeLeave(p);
  67449. }
  67450. return rc;
  67451. }
  67452. #endif
  67453. #ifndef SQLITE_OMIT_INCRBLOB
  67454. /*
  67455. ** Argument pCsr must be a cursor opened for writing on an
  67456. ** INTKEY table currently pointing at a valid table entry.
  67457. ** This function modifies the data stored as part of that entry.
  67458. **
  67459. ** Only the data content may only be modified, it is not possible to
  67460. ** change the length of the data stored. If this function is called with
  67461. ** parameters that attempt to write past the end of the existing data,
  67462. ** no modifications are made and SQLITE_CORRUPT is returned.
  67463. */
  67464. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  67465. int rc;
  67466. assert( cursorOwnsBtShared(pCsr) );
  67467. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  67468. assert( pCsr->curFlags & BTCF_Incrblob );
  67469. rc = restoreCursorPosition(pCsr);
  67470. if( rc!=SQLITE_OK ){
  67471. return rc;
  67472. }
  67473. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  67474. if( pCsr->eState!=CURSOR_VALID ){
  67475. return SQLITE_ABORT;
  67476. }
  67477. /* Save the positions of all other cursors open on this table. This is
  67478. ** required in case any of them are holding references to an xFetch
  67479. ** version of the b-tree page modified by the accessPayload call below.
  67480. **
  67481. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  67482. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  67483. ** saveAllCursors can only return SQLITE_OK.
  67484. */
  67485. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  67486. assert( rc==SQLITE_OK );
  67487. /* Check some assumptions:
  67488. ** (a) the cursor is open for writing,
  67489. ** (b) there is a read/write transaction open,
  67490. ** (c) the connection holds a write-lock on the table (if required),
  67491. ** (d) there are no conflicting read-locks, and
  67492. ** (e) the cursor points at a valid row of an intKey table.
  67493. */
  67494. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  67495. return SQLITE_READONLY;
  67496. }
  67497. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  67498. && pCsr->pBt->inTransaction==TRANS_WRITE );
  67499. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  67500. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  67501. assert( pCsr->pPage->intKey );
  67502. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  67503. }
  67504. /*
  67505. ** Mark this cursor as an incremental blob cursor.
  67506. */
  67507. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  67508. pCur->curFlags |= BTCF_Incrblob;
  67509. pCur->pBtree->hasIncrblobCur = 1;
  67510. }
  67511. #endif
  67512. /*
  67513. ** Set both the "read version" (single byte at byte offset 18) and
  67514. ** "write version" (single byte at byte offset 19) fields in the database
  67515. ** header to iVersion.
  67516. */
  67517. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  67518. BtShared *pBt = pBtree->pBt;
  67519. int rc; /* Return code */
  67520. assert( iVersion==1 || iVersion==2 );
  67521. /* If setting the version fields to 1, do not automatically open the
  67522. ** WAL connection, even if the version fields are currently set to 2.
  67523. */
  67524. pBt->btsFlags &= ~BTS_NO_WAL;
  67525. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  67526. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  67527. if( rc==SQLITE_OK ){
  67528. u8 *aData = pBt->pPage1->aData;
  67529. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  67530. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  67531. if( rc==SQLITE_OK ){
  67532. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  67533. if( rc==SQLITE_OK ){
  67534. aData[18] = (u8)iVersion;
  67535. aData[19] = (u8)iVersion;
  67536. }
  67537. }
  67538. }
  67539. }
  67540. pBt->btsFlags &= ~BTS_NO_WAL;
  67541. return rc;
  67542. }
  67543. /*
  67544. ** Return true if the cursor has a hint specified. This routine is
  67545. ** only used from within assert() statements
  67546. */
  67547. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  67548. return (pCsr->hints & mask)!=0;
  67549. }
  67550. /*
  67551. ** Return true if the given Btree is read-only.
  67552. */
  67553. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  67554. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  67555. }
  67556. /*
  67557. ** Return the size of the header added to each page by this module.
  67558. */
  67559. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  67560. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  67561. /*
  67562. ** Return true if the Btree passed as the only argument is sharable.
  67563. */
  67564. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  67565. return p->sharable;
  67566. }
  67567. /*
  67568. ** Return the number of connections to the BtShared object accessed by
  67569. ** the Btree handle passed as the only argument. For private caches
  67570. ** this is always 1. For shared caches it may be 1 or greater.
  67571. */
  67572. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  67573. testcase( p->sharable );
  67574. return p->pBt->nRef;
  67575. }
  67576. #endif
  67577. /************** End of btree.c ***********************************************/
  67578. /************** Begin file backup.c ******************************************/
  67579. /*
  67580. ** 2009 January 28
  67581. **
  67582. ** The author disclaims copyright to this source code. In place of
  67583. ** a legal notice, here is a blessing:
  67584. **
  67585. ** May you do good and not evil.
  67586. ** May you find forgiveness for yourself and forgive others.
  67587. ** May you share freely, never taking more than you give.
  67588. **
  67589. *************************************************************************
  67590. ** This file contains the implementation of the sqlite3_backup_XXX()
  67591. ** API functions and the related features.
  67592. */
  67593. /* #include "sqliteInt.h" */
  67594. /* #include "btreeInt.h" */
  67595. /*
  67596. ** Structure allocated for each backup operation.
  67597. */
  67598. struct sqlite3_backup {
  67599. sqlite3* pDestDb; /* Destination database handle */
  67600. Btree *pDest; /* Destination b-tree file */
  67601. u32 iDestSchema; /* Original schema cookie in destination */
  67602. int bDestLocked; /* True once a write-transaction is open on pDest */
  67603. Pgno iNext; /* Page number of the next source page to copy */
  67604. sqlite3* pSrcDb; /* Source database handle */
  67605. Btree *pSrc; /* Source b-tree file */
  67606. int rc; /* Backup process error code */
  67607. /* These two variables are set by every call to backup_step(). They are
  67608. ** read by calls to backup_remaining() and backup_pagecount().
  67609. */
  67610. Pgno nRemaining; /* Number of pages left to copy */
  67611. Pgno nPagecount; /* Total number of pages to copy */
  67612. int isAttached; /* True once backup has been registered with pager */
  67613. sqlite3_backup *pNext; /* Next backup associated with source pager */
  67614. };
  67615. /*
  67616. ** THREAD SAFETY NOTES:
  67617. **
  67618. ** Once it has been created using backup_init(), a single sqlite3_backup
  67619. ** structure may be accessed via two groups of thread-safe entry points:
  67620. **
  67621. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  67622. ** backup_finish(). Both these functions obtain the source database
  67623. ** handle mutex and the mutex associated with the source BtShared
  67624. ** structure, in that order.
  67625. **
  67626. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  67627. ** invoked by the pager layer to report various state changes in
  67628. ** the page cache associated with the source database. The mutex
  67629. ** associated with the source database BtShared structure will always
  67630. ** be held when either of these functions are invoked.
  67631. **
  67632. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  67633. ** backup_pagecount() are not thread-safe functions. If they are called
  67634. ** while some other thread is calling backup_step() or backup_finish(),
  67635. ** the values returned may be invalid. There is no way for a call to
  67636. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  67637. ** or backup_pagecount().
  67638. **
  67639. ** Depending on the SQLite configuration, the database handles and/or
  67640. ** the Btree objects may have their own mutexes that require locking.
  67641. ** Non-sharable Btrees (in-memory databases for example), do not have
  67642. ** associated mutexes.
  67643. */
  67644. /*
  67645. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  67646. ** in connection handle pDb. If such a database cannot be found, return
  67647. ** a NULL pointer and write an error message to pErrorDb.
  67648. **
  67649. ** If the "temp" database is requested, it may need to be opened by this
  67650. ** function. If an error occurs while doing so, return 0 and write an
  67651. ** error message to pErrorDb.
  67652. */
  67653. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  67654. int i = sqlite3FindDbName(pDb, zDb);
  67655. if( i==1 ){
  67656. Parse sParse;
  67657. int rc = 0;
  67658. memset(&sParse, 0, sizeof(sParse));
  67659. sParse.db = pDb;
  67660. if( sqlite3OpenTempDatabase(&sParse) ){
  67661. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  67662. rc = SQLITE_ERROR;
  67663. }
  67664. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  67665. sqlite3ParserReset(&sParse);
  67666. if( rc ){
  67667. return 0;
  67668. }
  67669. }
  67670. if( i<0 ){
  67671. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  67672. return 0;
  67673. }
  67674. return pDb->aDb[i].pBt;
  67675. }
  67676. /*
  67677. ** Attempt to set the page size of the destination to match the page size
  67678. ** of the source.
  67679. */
  67680. static int setDestPgsz(sqlite3_backup *p){
  67681. int rc;
  67682. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  67683. return rc;
  67684. }
  67685. /*
  67686. ** Check that there is no open read-transaction on the b-tree passed as the
  67687. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  67688. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  67689. ** message in database handle db.
  67690. */
  67691. static int checkReadTransaction(sqlite3 *db, Btree *p){
  67692. if( sqlite3BtreeIsInReadTrans(p) ){
  67693. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  67694. return SQLITE_ERROR;
  67695. }
  67696. return SQLITE_OK;
  67697. }
  67698. /*
  67699. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  67700. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  67701. ** a pointer to the new sqlite3_backup object.
  67702. **
  67703. ** If an error occurs, NULL is returned and an error code and error message
  67704. ** stored in database handle pDestDb.
  67705. */
  67706. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  67707. sqlite3* pDestDb, /* Database to write to */
  67708. const char *zDestDb, /* Name of database within pDestDb */
  67709. sqlite3* pSrcDb, /* Database connection to read from */
  67710. const char *zSrcDb /* Name of database within pSrcDb */
  67711. ){
  67712. sqlite3_backup *p; /* Value to return */
  67713. #ifdef SQLITE_ENABLE_API_ARMOR
  67714. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  67715. (void)SQLITE_MISUSE_BKPT;
  67716. return 0;
  67717. }
  67718. #endif
  67719. /* Lock the source database handle. The destination database
  67720. ** handle is not locked in this routine, but it is locked in
  67721. ** sqlite3_backup_step(). The user is required to ensure that no
  67722. ** other thread accesses the destination handle for the duration
  67723. ** of the backup operation. Any attempt to use the destination
  67724. ** database connection while a backup is in progress may cause
  67725. ** a malfunction or a deadlock.
  67726. */
  67727. sqlite3_mutex_enter(pSrcDb->mutex);
  67728. sqlite3_mutex_enter(pDestDb->mutex);
  67729. if( pSrcDb==pDestDb ){
  67730. sqlite3ErrorWithMsg(
  67731. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  67732. );
  67733. p = 0;
  67734. }else {
  67735. /* Allocate space for a new sqlite3_backup object...
  67736. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  67737. ** call to sqlite3_backup_init() and is destroyed by a call to
  67738. ** sqlite3_backup_finish(). */
  67739. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  67740. if( !p ){
  67741. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  67742. }
  67743. }
  67744. /* If the allocation succeeded, populate the new object. */
  67745. if( p ){
  67746. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  67747. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  67748. p->pDestDb = pDestDb;
  67749. p->pSrcDb = pSrcDb;
  67750. p->iNext = 1;
  67751. p->isAttached = 0;
  67752. if( 0==p->pSrc || 0==p->pDest
  67753. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  67754. ){
  67755. /* One (or both) of the named databases did not exist or an OOM
  67756. ** error was hit. Or there is a transaction open on the destination
  67757. ** database. The error has already been written into the pDestDb
  67758. ** handle. All that is left to do here is free the sqlite3_backup
  67759. ** structure. */
  67760. sqlite3_free(p);
  67761. p = 0;
  67762. }
  67763. }
  67764. if( p ){
  67765. p->pSrc->nBackup++;
  67766. }
  67767. sqlite3_mutex_leave(pDestDb->mutex);
  67768. sqlite3_mutex_leave(pSrcDb->mutex);
  67769. return p;
  67770. }
  67771. /*
  67772. ** Argument rc is an SQLite error code. Return true if this error is
  67773. ** considered fatal if encountered during a backup operation. All errors
  67774. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  67775. */
  67776. static int isFatalError(int rc){
  67777. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  67778. }
  67779. /*
  67780. ** Parameter zSrcData points to a buffer containing the data for
  67781. ** page iSrcPg from the source database. Copy this data into the
  67782. ** destination database.
  67783. */
  67784. static int backupOnePage(
  67785. sqlite3_backup *p, /* Backup handle */
  67786. Pgno iSrcPg, /* Source database page to backup */
  67787. const u8 *zSrcData, /* Source database page data */
  67788. int bUpdate /* True for an update, false otherwise */
  67789. ){
  67790. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  67791. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  67792. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  67793. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  67794. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  67795. #ifdef SQLITE_HAS_CODEC
  67796. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  67797. ** guaranteed that the shared-mutex is held by this thread, handle
  67798. ** p->pSrc may not actually be the owner. */
  67799. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  67800. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  67801. #endif
  67802. int rc = SQLITE_OK;
  67803. i64 iOff;
  67804. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  67805. assert( p->bDestLocked );
  67806. assert( !isFatalError(p->rc) );
  67807. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  67808. assert( zSrcData );
  67809. /* Catch the case where the destination is an in-memory database and the
  67810. ** page sizes of the source and destination differ.
  67811. */
  67812. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  67813. rc = SQLITE_READONLY;
  67814. }
  67815. #ifdef SQLITE_HAS_CODEC
  67816. /* Backup is not possible if the page size of the destination is changing
  67817. ** and a codec is in use.
  67818. */
  67819. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  67820. rc = SQLITE_READONLY;
  67821. }
  67822. /* Backup is not possible if the number of bytes of reserve space differ
  67823. ** between source and destination. If there is a difference, try to
  67824. ** fix the destination to agree with the source. If that is not possible,
  67825. ** then the backup cannot proceed.
  67826. */
  67827. if( nSrcReserve!=nDestReserve ){
  67828. u32 newPgsz = nSrcPgsz;
  67829. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  67830. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  67831. }
  67832. #endif
  67833. /* This loop runs once for each destination page spanned by the source
  67834. ** page. For each iteration, variable iOff is set to the byte offset
  67835. ** of the destination page.
  67836. */
  67837. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  67838. DbPage *pDestPg = 0;
  67839. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  67840. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  67841. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  67842. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  67843. ){
  67844. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  67845. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  67846. u8 *zOut = &zDestData[iOff%nDestPgsz];
  67847. /* Copy the data from the source page into the destination page.
  67848. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  67849. ** and the pager code use this trick (clearing the first byte
  67850. ** of the page 'extra' space to invalidate the Btree layers
  67851. ** cached parse of the page). MemPage.isInit is marked
  67852. ** "MUST BE FIRST" for this purpose.
  67853. */
  67854. memcpy(zOut, zIn, nCopy);
  67855. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  67856. if( iOff==0 && bUpdate==0 ){
  67857. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  67858. }
  67859. }
  67860. sqlite3PagerUnref(pDestPg);
  67861. }
  67862. return rc;
  67863. }
  67864. /*
  67865. ** If pFile is currently larger than iSize bytes, then truncate it to
  67866. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  67867. ** this function is a no-op.
  67868. **
  67869. ** Return SQLITE_OK if everything is successful, or an SQLite error
  67870. ** code if an error occurs.
  67871. */
  67872. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  67873. i64 iCurrent;
  67874. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  67875. if( rc==SQLITE_OK && iCurrent>iSize ){
  67876. rc = sqlite3OsTruncate(pFile, iSize);
  67877. }
  67878. return rc;
  67879. }
  67880. /*
  67881. ** Register this backup object with the associated source pager for
  67882. ** callbacks when pages are changed or the cache invalidated.
  67883. */
  67884. static void attachBackupObject(sqlite3_backup *p){
  67885. sqlite3_backup **pp;
  67886. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  67887. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  67888. p->pNext = *pp;
  67889. *pp = p;
  67890. p->isAttached = 1;
  67891. }
  67892. /*
  67893. ** Copy nPage pages from the source b-tree to the destination.
  67894. */
  67895. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  67896. int rc;
  67897. int destMode; /* Destination journal mode */
  67898. int pgszSrc = 0; /* Source page size */
  67899. int pgszDest = 0; /* Destination page size */
  67900. #ifdef SQLITE_ENABLE_API_ARMOR
  67901. if( p==0 ) return SQLITE_MISUSE_BKPT;
  67902. #endif
  67903. sqlite3_mutex_enter(p->pSrcDb->mutex);
  67904. sqlite3BtreeEnter(p->pSrc);
  67905. if( p->pDestDb ){
  67906. sqlite3_mutex_enter(p->pDestDb->mutex);
  67907. }
  67908. rc = p->rc;
  67909. if( !isFatalError(rc) ){
  67910. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  67911. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  67912. int ii; /* Iterator variable */
  67913. int nSrcPage = -1; /* Size of source db in pages */
  67914. int bCloseTrans = 0; /* True if src db requires unlocking */
  67915. /* If the source pager is currently in a write-transaction, return
  67916. ** SQLITE_BUSY immediately.
  67917. */
  67918. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  67919. rc = SQLITE_BUSY;
  67920. }else{
  67921. rc = SQLITE_OK;
  67922. }
  67923. /* If there is no open read-transaction on the source database, open
  67924. ** one now. If a transaction is opened here, then it will be closed
  67925. ** before this function exits.
  67926. */
  67927. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  67928. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  67929. bCloseTrans = 1;
  67930. }
  67931. /* If the destination database has not yet been locked (i.e. if this
  67932. ** is the first call to backup_step() for the current backup operation),
  67933. ** try to set its page size to the same as the source database. This
  67934. ** is especially important on ZipVFS systems, as in that case it is
  67935. ** not possible to create a database file that uses one page size by
  67936. ** writing to it with another. */
  67937. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  67938. rc = SQLITE_NOMEM;
  67939. }
  67940. /* Lock the destination database, if it is not locked already. */
  67941. if( SQLITE_OK==rc && p->bDestLocked==0
  67942. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  67943. ){
  67944. p->bDestLocked = 1;
  67945. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  67946. }
  67947. /* Do not allow backup if the destination database is in WAL mode
  67948. ** and the page sizes are different between source and destination */
  67949. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  67950. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  67951. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  67952. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  67953. rc = SQLITE_READONLY;
  67954. }
  67955. /* Now that there is a read-lock on the source database, query the
  67956. ** source pager for the number of pages in the database.
  67957. */
  67958. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  67959. assert( nSrcPage>=0 );
  67960. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  67961. const Pgno iSrcPg = p->iNext; /* Source page number */
  67962. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  67963. DbPage *pSrcPg; /* Source page object */
  67964. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  67965. if( rc==SQLITE_OK ){
  67966. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  67967. sqlite3PagerUnref(pSrcPg);
  67968. }
  67969. }
  67970. p->iNext++;
  67971. }
  67972. if( rc==SQLITE_OK ){
  67973. p->nPagecount = nSrcPage;
  67974. p->nRemaining = nSrcPage+1-p->iNext;
  67975. if( p->iNext>(Pgno)nSrcPage ){
  67976. rc = SQLITE_DONE;
  67977. }else if( !p->isAttached ){
  67978. attachBackupObject(p);
  67979. }
  67980. }
  67981. /* Update the schema version field in the destination database. This
  67982. ** is to make sure that the schema-version really does change in
  67983. ** the case where the source and destination databases have the
  67984. ** same schema version.
  67985. */
  67986. if( rc==SQLITE_DONE ){
  67987. if( nSrcPage==0 ){
  67988. rc = sqlite3BtreeNewDb(p->pDest);
  67989. nSrcPage = 1;
  67990. }
  67991. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  67992. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  67993. }
  67994. if( rc==SQLITE_OK ){
  67995. if( p->pDestDb ){
  67996. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  67997. }
  67998. if( destMode==PAGER_JOURNALMODE_WAL ){
  67999. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  68000. }
  68001. }
  68002. if( rc==SQLITE_OK ){
  68003. int nDestTruncate;
  68004. /* Set nDestTruncate to the final number of pages in the destination
  68005. ** database. The complication here is that the destination page
  68006. ** size may be different to the source page size.
  68007. **
  68008. ** If the source page size is smaller than the destination page size,
  68009. ** round up. In this case the call to sqlite3OsTruncate() below will
  68010. ** fix the size of the file. However it is important to call
  68011. ** sqlite3PagerTruncateImage() here so that any pages in the
  68012. ** destination file that lie beyond the nDestTruncate page mark are
  68013. ** journalled by PagerCommitPhaseOne() before they are destroyed
  68014. ** by the file truncation.
  68015. */
  68016. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  68017. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  68018. if( pgszSrc<pgszDest ){
  68019. int ratio = pgszDest/pgszSrc;
  68020. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  68021. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  68022. nDestTruncate--;
  68023. }
  68024. }else{
  68025. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  68026. }
  68027. assert( nDestTruncate>0 );
  68028. if( pgszSrc<pgszDest ){
  68029. /* If the source page-size is smaller than the destination page-size,
  68030. ** two extra things may need to happen:
  68031. **
  68032. ** * The destination may need to be truncated, and
  68033. **
  68034. ** * Data stored on the pages immediately following the
  68035. ** pending-byte page in the source database may need to be
  68036. ** copied into the destination database.
  68037. */
  68038. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  68039. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  68040. Pgno iPg;
  68041. int nDstPage;
  68042. i64 iOff;
  68043. i64 iEnd;
  68044. assert( pFile );
  68045. assert( nDestTruncate==0
  68046. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  68047. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  68048. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  68049. ));
  68050. /* This block ensures that all data required to recreate the original
  68051. ** database has been stored in the journal for pDestPager and the
  68052. ** journal synced to disk. So at this point we may safely modify
  68053. ** the database file in any way, knowing that if a power failure
  68054. ** occurs, the original database will be reconstructed from the
  68055. ** journal file. */
  68056. sqlite3PagerPagecount(pDestPager, &nDstPage);
  68057. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  68058. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  68059. DbPage *pPg;
  68060. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  68061. if( rc==SQLITE_OK ){
  68062. rc = sqlite3PagerWrite(pPg);
  68063. sqlite3PagerUnref(pPg);
  68064. }
  68065. }
  68066. }
  68067. if( rc==SQLITE_OK ){
  68068. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  68069. }
  68070. /* Write the extra pages and truncate the database file as required */
  68071. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  68072. for(
  68073. iOff=PENDING_BYTE+pgszSrc;
  68074. rc==SQLITE_OK && iOff<iEnd;
  68075. iOff+=pgszSrc
  68076. ){
  68077. PgHdr *pSrcPg = 0;
  68078. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  68079. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  68080. if( rc==SQLITE_OK ){
  68081. u8 *zData = sqlite3PagerGetData(pSrcPg);
  68082. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  68083. }
  68084. sqlite3PagerUnref(pSrcPg);
  68085. }
  68086. if( rc==SQLITE_OK ){
  68087. rc = backupTruncateFile(pFile, iSize);
  68088. }
  68089. /* Sync the database file to disk. */
  68090. if( rc==SQLITE_OK ){
  68091. rc = sqlite3PagerSync(pDestPager, 0);
  68092. }
  68093. }else{
  68094. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  68095. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  68096. }
  68097. /* Finish committing the transaction to the destination database. */
  68098. if( SQLITE_OK==rc
  68099. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  68100. ){
  68101. rc = SQLITE_DONE;
  68102. }
  68103. }
  68104. }
  68105. /* If bCloseTrans is true, then this function opened a read transaction
  68106. ** on the source database. Close the read transaction here. There is
  68107. ** no need to check the return values of the btree methods here, as
  68108. ** "committing" a read-only transaction cannot fail.
  68109. */
  68110. if( bCloseTrans ){
  68111. TESTONLY( int rc2 );
  68112. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  68113. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  68114. assert( rc2==SQLITE_OK );
  68115. }
  68116. if( rc==SQLITE_IOERR_NOMEM ){
  68117. rc = SQLITE_NOMEM_BKPT;
  68118. }
  68119. p->rc = rc;
  68120. }
  68121. if( p->pDestDb ){
  68122. sqlite3_mutex_leave(p->pDestDb->mutex);
  68123. }
  68124. sqlite3BtreeLeave(p->pSrc);
  68125. sqlite3_mutex_leave(p->pSrcDb->mutex);
  68126. return rc;
  68127. }
  68128. /*
  68129. ** Release all resources associated with an sqlite3_backup* handle.
  68130. */
  68131. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  68132. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  68133. sqlite3 *pSrcDb; /* Source database connection */
  68134. int rc; /* Value to return */
  68135. /* Enter the mutexes */
  68136. if( p==0 ) return SQLITE_OK;
  68137. pSrcDb = p->pSrcDb;
  68138. sqlite3_mutex_enter(pSrcDb->mutex);
  68139. sqlite3BtreeEnter(p->pSrc);
  68140. if( p->pDestDb ){
  68141. sqlite3_mutex_enter(p->pDestDb->mutex);
  68142. }
  68143. /* Detach this backup from the source pager. */
  68144. if( p->pDestDb ){
  68145. p->pSrc->nBackup--;
  68146. }
  68147. if( p->isAttached ){
  68148. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  68149. while( *pp!=p ){
  68150. pp = &(*pp)->pNext;
  68151. }
  68152. *pp = p->pNext;
  68153. }
  68154. /* If a transaction is still open on the Btree, roll it back. */
  68155. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  68156. /* Set the error code of the destination database handle. */
  68157. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  68158. if( p->pDestDb ){
  68159. sqlite3Error(p->pDestDb, rc);
  68160. /* Exit the mutexes and free the backup context structure. */
  68161. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  68162. }
  68163. sqlite3BtreeLeave(p->pSrc);
  68164. if( p->pDestDb ){
  68165. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  68166. ** call to sqlite3_backup_init() and is destroyed by a call to
  68167. ** sqlite3_backup_finish(). */
  68168. sqlite3_free(p);
  68169. }
  68170. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  68171. return rc;
  68172. }
  68173. /*
  68174. ** Return the number of pages still to be backed up as of the most recent
  68175. ** call to sqlite3_backup_step().
  68176. */
  68177. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  68178. #ifdef SQLITE_ENABLE_API_ARMOR
  68179. if( p==0 ){
  68180. (void)SQLITE_MISUSE_BKPT;
  68181. return 0;
  68182. }
  68183. #endif
  68184. return p->nRemaining;
  68185. }
  68186. /*
  68187. ** Return the total number of pages in the source database as of the most
  68188. ** recent call to sqlite3_backup_step().
  68189. */
  68190. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  68191. #ifdef SQLITE_ENABLE_API_ARMOR
  68192. if( p==0 ){
  68193. (void)SQLITE_MISUSE_BKPT;
  68194. return 0;
  68195. }
  68196. #endif
  68197. return p->nPagecount;
  68198. }
  68199. /*
  68200. ** This function is called after the contents of page iPage of the
  68201. ** source database have been modified. If page iPage has already been
  68202. ** copied into the destination database, then the data written to the
  68203. ** destination is now invalidated. The destination copy of iPage needs
  68204. ** to be updated with the new data before the backup operation is
  68205. ** complete.
  68206. **
  68207. ** It is assumed that the mutex associated with the BtShared object
  68208. ** corresponding to the source database is held when this function is
  68209. ** called.
  68210. */
  68211. static SQLITE_NOINLINE void backupUpdate(
  68212. sqlite3_backup *p,
  68213. Pgno iPage,
  68214. const u8 *aData
  68215. ){
  68216. assert( p!=0 );
  68217. do{
  68218. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  68219. if( !isFatalError(p->rc) && iPage<p->iNext ){
  68220. /* The backup process p has already copied page iPage. But now it
  68221. ** has been modified by a transaction on the source pager. Copy
  68222. ** the new data into the backup.
  68223. */
  68224. int rc;
  68225. assert( p->pDestDb );
  68226. sqlite3_mutex_enter(p->pDestDb->mutex);
  68227. rc = backupOnePage(p, iPage, aData, 1);
  68228. sqlite3_mutex_leave(p->pDestDb->mutex);
  68229. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  68230. if( rc!=SQLITE_OK ){
  68231. p->rc = rc;
  68232. }
  68233. }
  68234. }while( (p = p->pNext)!=0 );
  68235. }
  68236. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  68237. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  68238. }
  68239. /*
  68240. ** Restart the backup process. This is called when the pager layer
  68241. ** detects that the database has been modified by an external database
  68242. ** connection. In this case there is no way of knowing which of the
  68243. ** pages that have been copied into the destination database are still
  68244. ** valid and which are not, so the entire process needs to be restarted.
  68245. **
  68246. ** It is assumed that the mutex associated with the BtShared object
  68247. ** corresponding to the source database is held when this function is
  68248. ** called.
  68249. */
  68250. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  68251. sqlite3_backup *p; /* Iterator variable */
  68252. for(p=pBackup; p; p=p->pNext){
  68253. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  68254. p->iNext = 1;
  68255. }
  68256. }
  68257. #ifndef SQLITE_OMIT_VACUUM
  68258. /*
  68259. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  68260. ** must be active for both files.
  68261. **
  68262. ** The size of file pTo may be reduced by this operation. If anything
  68263. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  68264. ** transaction is committed before returning.
  68265. */
  68266. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  68267. int rc;
  68268. sqlite3_file *pFd; /* File descriptor for database pTo */
  68269. sqlite3_backup b;
  68270. sqlite3BtreeEnter(pTo);
  68271. sqlite3BtreeEnter(pFrom);
  68272. assert( sqlite3BtreeIsInTrans(pTo) );
  68273. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  68274. if( pFd->pMethods ){
  68275. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  68276. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  68277. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  68278. if( rc ) goto copy_finished;
  68279. }
  68280. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  68281. ** to 0. This is used by the implementations of sqlite3_backup_step()
  68282. ** and sqlite3_backup_finish() to detect that they are being called
  68283. ** from this function, not directly by the user.
  68284. */
  68285. memset(&b, 0, sizeof(b));
  68286. b.pSrcDb = pFrom->db;
  68287. b.pSrc = pFrom;
  68288. b.pDest = pTo;
  68289. b.iNext = 1;
  68290. #ifdef SQLITE_HAS_CODEC
  68291. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  68292. #endif
  68293. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  68294. ** file. By passing this as the number of pages to copy to
  68295. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  68296. ** within a single call (unless an error occurs). The assert() statement
  68297. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  68298. ** or an error code. */
  68299. sqlite3_backup_step(&b, 0x7FFFFFFF);
  68300. assert( b.rc!=SQLITE_OK );
  68301. rc = sqlite3_backup_finish(&b);
  68302. if( rc==SQLITE_OK ){
  68303. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  68304. }else{
  68305. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  68306. }
  68307. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  68308. copy_finished:
  68309. sqlite3BtreeLeave(pFrom);
  68310. sqlite3BtreeLeave(pTo);
  68311. return rc;
  68312. }
  68313. #endif /* SQLITE_OMIT_VACUUM */
  68314. /************** End of backup.c **********************************************/
  68315. /************** Begin file vdbemem.c *****************************************/
  68316. /*
  68317. ** 2004 May 26
  68318. **
  68319. ** The author disclaims copyright to this source code. In place of
  68320. ** a legal notice, here is a blessing:
  68321. **
  68322. ** May you do good and not evil.
  68323. ** May you find forgiveness for yourself and forgive others.
  68324. ** May you share freely, never taking more than you give.
  68325. **
  68326. *************************************************************************
  68327. **
  68328. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  68329. ** stores a single value in the VDBE. Mem is an opaque structure visible
  68330. ** only within the VDBE. Interface routines refer to a Mem using the
  68331. ** name sqlite_value
  68332. */
  68333. /* #include "sqliteInt.h" */
  68334. /* #include "vdbeInt.h" */
  68335. #ifdef SQLITE_DEBUG
  68336. /*
  68337. ** Check invariants on a Mem object.
  68338. **
  68339. ** This routine is intended for use inside of assert() statements, like
  68340. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  68341. */
  68342. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  68343. /* If MEM_Dyn is set then Mem.xDel!=0.
  68344. ** Mem.xDel might not be initialized if MEM_Dyn is clear.
  68345. */
  68346. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  68347. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  68348. ** ensure that if Mem.szMalloc>0 then it is safe to do
  68349. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  68350. ** That saves a few cycles in inner loops. */
  68351. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  68352. /* Cannot be both MEM_Int and MEM_Real at the same time */
  68353. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  68354. if( p->flags & MEM_Null ){
  68355. /* Cannot be both MEM_Null and some other type */
  68356. assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob
  68357. |MEM_RowSet|MEM_Frame|MEM_Agg))==0 );
  68358. /* If MEM_Null is set, then either the value is a pure NULL (the usual
  68359. ** case) or it is a pointer set using sqlite3_bind_pointer() or
  68360. ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
  68361. ** set.
  68362. */
  68363. if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
  68364. /* This is a pointer type. There may be a flag to indicate what to
  68365. ** do with the pointer. */
  68366. assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  68367. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  68368. ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
  68369. /* No other bits set */
  68370. assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
  68371. |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
  68372. }else{
  68373. /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
  68374. ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
  68375. }
  68376. }else{
  68377. /* The MEM_Cleared bit is only allowed on NULLs */
  68378. assert( (p->flags & MEM_Cleared)==0 );
  68379. }
  68380. /* The szMalloc field holds the correct memory allocation size */
  68381. assert( p->szMalloc==0
  68382. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  68383. /* If p holds a string or blob, the Mem.z must point to exactly
  68384. ** one of the following:
  68385. **
  68386. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  68387. ** (2) Memory to be freed using Mem.xDel
  68388. ** (3) An ephemeral string or blob
  68389. ** (4) A static string or blob
  68390. */
  68391. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  68392. assert(
  68393. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  68394. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  68395. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  68396. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  68397. );
  68398. }
  68399. return 1;
  68400. }
  68401. #endif
  68402. #ifdef SQLITE_DEBUG
  68403. /*
  68404. ** Check that string value of pMem agrees with its integer or real value.
  68405. **
  68406. ** A single int or real value always converts to the same strings. But
  68407. ** many different strings can be converted into the same int or real.
  68408. ** If a table contains a numeric value and an index is based on the
  68409. ** corresponding string value, then it is important that the string be
  68410. ** derived from the numeric value, not the other way around, to ensure
  68411. ** that the index and table are consistent. See ticket
  68412. ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
  68413. ** an example.
  68414. **
  68415. ** This routine looks at pMem to verify that if it has both a numeric
  68416. ** representation and a string representation then the string rep has
  68417. ** been derived from the numeric and not the other way around. It returns
  68418. ** true if everything is ok and false if there is a problem.
  68419. **
  68420. ** This routine is for use inside of assert() statements only.
  68421. */
  68422. SQLITE_PRIVATE int sqlite3VdbeMemConsistentDualRep(Mem *p){
  68423. char zBuf[100];
  68424. char *z;
  68425. int i, j, incr;
  68426. if( (p->flags & MEM_Str)==0 ) return 1;
  68427. if( (p->flags & (MEM_Int|MEM_Real))==0 ) return 1;
  68428. if( p->flags & MEM_Int ){
  68429. sqlite3_snprintf(sizeof(zBuf),zBuf,"%lld",p->u.i);
  68430. }else{
  68431. sqlite3_snprintf(sizeof(zBuf),zBuf,"%!.15g",p->u.r);
  68432. }
  68433. z = p->z;
  68434. i = j = 0;
  68435. incr = 1;
  68436. if( p->enc!=SQLITE_UTF8 ){
  68437. incr = 2;
  68438. if( p->enc==SQLITE_UTF16BE ) z++;
  68439. }
  68440. while( zBuf[j] ){
  68441. if( zBuf[j++]!=z[i] ) return 0;
  68442. i += incr;
  68443. }
  68444. return 1;
  68445. }
  68446. #endif /* SQLITE_DEBUG */
  68447. /*
  68448. ** If pMem is an object with a valid string representation, this routine
  68449. ** ensures the internal encoding for the string representation is
  68450. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  68451. **
  68452. ** If pMem is not a string object, or the encoding of the string
  68453. ** representation is already stored using the requested encoding, then this
  68454. ** routine is a no-op.
  68455. **
  68456. ** SQLITE_OK is returned if the conversion is successful (or not required).
  68457. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  68458. ** between formats.
  68459. */
  68460. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  68461. #ifndef SQLITE_OMIT_UTF16
  68462. int rc;
  68463. #endif
  68464. assert( (pMem->flags&MEM_RowSet)==0 );
  68465. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  68466. || desiredEnc==SQLITE_UTF16BE );
  68467. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  68468. return SQLITE_OK;
  68469. }
  68470. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68471. #ifdef SQLITE_OMIT_UTF16
  68472. return SQLITE_ERROR;
  68473. #else
  68474. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  68475. ** then the encoding of the value may not have changed.
  68476. */
  68477. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  68478. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  68479. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  68480. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  68481. return rc;
  68482. #endif
  68483. }
  68484. /*
  68485. ** Make sure pMem->z points to a writable allocation of at least
  68486. ** min(n,32) bytes.
  68487. **
  68488. ** If the bPreserve argument is true, then copy of the content of
  68489. ** pMem->z into the new allocation. pMem must be either a string or
  68490. ** blob if bPreserve is true. If bPreserve is false, any prior content
  68491. ** in pMem->z is discarded.
  68492. */
  68493. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  68494. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  68495. assert( (pMem->flags&MEM_RowSet)==0 );
  68496. testcase( pMem->db==0 );
  68497. /* If the bPreserve flag is set to true, then the memory cell must already
  68498. ** contain a valid string or blob value. */
  68499. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  68500. testcase( bPreserve && pMem->z==0 );
  68501. assert( pMem->szMalloc==0
  68502. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  68503. if( n<32 ) n = 32;
  68504. if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
  68505. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  68506. bPreserve = 0;
  68507. }else{
  68508. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  68509. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  68510. }
  68511. if( pMem->zMalloc==0 ){
  68512. sqlite3VdbeMemSetNull(pMem);
  68513. pMem->z = 0;
  68514. pMem->szMalloc = 0;
  68515. return SQLITE_NOMEM_BKPT;
  68516. }else{
  68517. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  68518. }
  68519. if( bPreserve && pMem->z ){
  68520. assert( pMem->z!=pMem->zMalloc );
  68521. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  68522. }
  68523. if( (pMem->flags&MEM_Dyn)!=0 ){
  68524. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  68525. pMem->xDel((void *)(pMem->z));
  68526. }
  68527. pMem->z = pMem->zMalloc;
  68528. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  68529. return SQLITE_OK;
  68530. }
  68531. /*
  68532. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  68533. ** If pMem->zMalloc already meets or exceeds the requested size, this
  68534. ** routine is a no-op.
  68535. **
  68536. ** Any prior string or blob content in the pMem object may be discarded.
  68537. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  68538. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  68539. ** values are preserved.
  68540. **
  68541. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  68542. ** if unable to complete the resizing.
  68543. */
  68544. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  68545. assert( szNew>0 );
  68546. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  68547. if( pMem->szMalloc<szNew ){
  68548. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  68549. }
  68550. assert( (pMem->flags & MEM_Dyn)==0 );
  68551. pMem->z = pMem->zMalloc;
  68552. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  68553. return SQLITE_OK;
  68554. }
  68555. /*
  68556. ** It is already known that pMem contains an unterminated string.
  68557. ** Add the zero terminator.
  68558. */
  68559. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  68560. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  68561. return SQLITE_NOMEM_BKPT;
  68562. }
  68563. pMem->z[pMem->n] = 0;
  68564. pMem->z[pMem->n+1] = 0;
  68565. pMem->flags |= MEM_Term;
  68566. return SQLITE_OK;
  68567. }
  68568. /*
  68569. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  68570. ** MEM.zMalloc, where it can be safely written.
  68571. **
  68572. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  68573. */
  68574. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  68575. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68576. assert( (pMem->flags&MEM_RowSet)==0 );
  68577. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  68578. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  68579. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  68580. int rc = vdbeMemAddTerminator(pMem);
  68581. if( rc ) return rc;
  68582. }
  68583. }
  68584. pMem->flags &= ~MEM_Ephem;
  68585. #ifdef SQLITE_DEBUG
  68586. pMem->pScopyFrom = 0;
  68587. #endif
  68588. return SQLITE_OK;
  68589. }
  68590. /*
  68591. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  68592. ** blob stored in dynamically allocated space.
  68593. */
  68594. #ifndef SQLITE_OMIT_INCRBLOB
  68595. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  68596. int nByte;
  68597. assert( pMem->flags & MEM_Zero );
  68598. assert( pMem->flags&MEM_Blob );
  68599. assert( (pMem->flags&MEM_RowSet)==0 );
  68600. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68601. /* Set nByte to the number of bytes required to store the expanded blob. */
  68602. nByte = pMem->n + pMem->u.nZero;
  68603. if( nByte<=0 ){
  68604. nByte = 1;
  68605. }
  68606. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  68607. return SQLITE_NOMEM_BKPT;
  68608. }
  68609. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  68610. pMem->n += pMem->u.nZero;
  68611. pMem->flags &= ~(MEM_Zero|MEM_Term);
  68612. return SQLITE_OK;
  68613. }
  68614. #endif
  68615. /*
  68616. ** Make sure the given Mem is \u0000 terminated.
  68617. */
  68618. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  68619. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68620. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  68621. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  68622. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  68623. return SQLITE_OK; /* Nothing to do */
  68624. }else{
  68625. return vdbeMemAddTerminator(pMem);
  68626. }
  68627. }
  68628. /*
  68629. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  68630. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  68631. ** is a no-op.
  68632. **
  68633. ** Existing representations MEM_Int and MEM_Real are invalidated if
  68634. ** bForce is true but are retained if bForce is false.
  68635. **
  68636. ** A MEM_Null value will never be passed to this function. This function is
  68637. ** used for converting values to text for returning to the user (i.e. via
  68638. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  68639. ** keys are strings. In the former case a NULL pointer is returned the
  68640. ** user and the latter is an internal programming error.
  68641. */
  68642. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  68643. int fg = pMem->flags;
  68644. const int nByte = 32;
  68645. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68646. assert( !(fg&MEM_Zero) );
  68647. assert( !(fg&(MEM_Str|MEM_Blob)) );
  68648. assert( fg&(MEM_Int|MEM_Real) );
  68649. assert( (pMem->flags&MEM_RowSet)==0 );
  68650. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68651. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  68652. pMem->enc = 0;
  68653. return SQLITE_NOMEM_BKPT;
  68654. }
  68655. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  68656. ** string representation of the value. Then, if the required encoding
  68657. ** is UTF-16le or UTF-16be do a translation.
  68658. **
  68659. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  68660. */
  68661. if( fg & MEM_Int ){
  68662. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  68663. }else{
  68664. assert( fg & MEM_Real );
  68665. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  68666. }
  68667. pMem->n = sqlite3Strlen30(pMem->z);
  68668. pMem->enc = SQLITE_UTF8;
  68669. pMem->flags |= MEM_Str|MEM_Term;
  68670. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  68671. sqlite3VdbeChangeEncoding(pMem, enc);
  68672. return SQLITE_OK;
  68673. }
  68674. /*
  68675. ** Memory cell pMem contains the context of an aggregate function.
  68676. ** This routine calls the finalize method for that function. The
  68677. ** result of the aggregate is stored back into pMem.
  68678. **
  68679. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  68680. ** otherwise.
  68681. */
  68682. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  68683. sqlite3_context ctx;
  68684. Mem t;
  68685. assert( pFunc!=0 );
  68686. assert( pFunc->xFinalize!=0 );
  68687. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  68688. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68689. memset(&ctx, 0, sizeof(ctx));
  68690. memset(&t, 0, sizeof(t));
  68691. t.flags = MEM_Null;
  68692. t.db = pMem->db;
  68693. ctx.pOut = &t;
  68694. ctx.pMem = pMem;
  68695. ctx.pFunc = pFunc;
  68696. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  68697. assert( (pMem->flags & MEM_Dyn)==0 );
  68698. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  68699. memcpy(pMem, &t, sizeof(t));
  68700. return ctx.isError;
  68701. }
  68702. /*
  68703. ** If the memory cell contains a value that must be freed by
  68704. ** invoking the external callback in Mem.xDel, then this routine
  68705. ** will free that value. It also sets Mem.flags to MEM_Null.
  68706. **
  68707. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  68708. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  68709. ** entry point for releasing Mem resources.
  68710. */
  68711. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  68712. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  68713. assert( VdbeMemDynamic(p) );
  68714. if( p->flags&MEM_Agg ){
  68715. sqlite3VdbeMemFinalize(p, p->u.pDef);
  68716. assert( (p->flags & MEM_Agg)==0 );
  68717. testcase( p->flags & MEM_Dyn );
  68718. }
  68719. if( p->flags&MEM_Dyn ){
  68720. assert( (p->flags&MEM_RowSet)==0 );
  68721. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  68722. p->xDel((void *)p->z);
  68723. }else if( p->flags&MEM_RowSet ){
  68724. sqlite3RowSetClear(p->u.pRowSet);
  68725. }else if( p->flags&MEM_Frame ){
  68726. VdbeFrame *pFrame = p->u.pFrame;
  68727. pFrame->pParent = pFrame->v->pDelFrame;
  68728. pFrame->v->pDelFrame = pFrame;
  68729. }
  68730. p->flags = MEM_Null;
  68731. }
  68732. /*
  68733. ** Release memory held by the Mem p, both external memory cleared
  68734. ** by p->xDel and memory in p->zMalloc.
  68735. **
  68736. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  68737. ** the unusual case where there really is memory in p that needs
  68738. ** to be freed.
  68739. */
  68740. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  68741. if( VdbeMemDynamic(p) ){
  68742. vdbeMemClearExternAndSetNull(p);
  68743. }
  68744. if( p->szMalloc ){
  68745. sqlite3DbFreeNN(p->db, p->zMalloc);
  68746. p->szMalloc = 0;
  68747. }
  68748. p->z = 0;
  68749. }
  68750. /*
  68751. ** Release any memory resources held by the Mem. Both the memory that is
  68752. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  68753. **
  68754. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  68755. ** reset a Mem back to its minimum memory utilization.
  68756. **
  68757. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  68758. ** prior to inserting new content into the Mem.
  68759. */
  68760. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  68761. assert( sqlite3VdbeCheckMemInvariants(p) );
  68762. if( VdbeMemDynamic(p) || p->szMalloc ){
  68763. vdbeMemClear(p);
  68764. }
  68765. }
  68766. /*
  68767. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  68768. ** If the double is out of range of a 64-bit signed integer then
  68769. ** return the closest available 64-bit signed integer.
  68770. */
  68771. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  68772. #ifdef SQLITE_OMIT_FLOATING_POINT
  68773. /* When floating-point is omitted, double and int64 are the same thing */
  68774. return r;
  68775. #else
  68776. /*
  68777. ** Many compilers we encounter do not define constants for the
  68778. ** minimum and maximum 64-bit integers, or they define them
  68779. ** inconsistently. And many do not understand the "LL" notation.
  68780. ** So we define our own static constants here using nothing
  68781. ** larger than a 32-bit integer constant.
  68782. */
  68783. static const i64 maxInt = LARGEST_INT64;
  68784. static const i64 minInt = SMALLEST_INT64;
  68785. if( r<=(double)minInt ){
  68786. return minInt;
  68787. }else if( r>=(double)maxInt ){
  68788. return maxInt;
  68789. }else{
  68790. return (i64)r;
  68791. }
  68792. #endif
  68793. }
  68794. /*
  68795. ** Return some kind of integer value which is the best we can do
  68796. ** at representing the value that *pMem describes as an integer.
  68797. ** If pMem is an integer, then the value is exact. If pMem is
  68798. ** a floating-point then the value returned is the integer part.
  68799. ** If pMem is a string or blob, then we make an attempt to convert
  68800. ** it into an integer and return that. If pMem represents an
  68801. ** an SQL-NULL value, return 0.
  68802. **
  68803. ** If pMem represents a string value, its encoding might be changed.
  68804. */
  68805. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  68806. i64 value = 0;
  68807. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  68808. return value;
  68809. }
  68810. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  68811. int flags;
  68812. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68813. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68814. flags = pMem->flags;
  68815. if( flags & MEM_Int ){
  68816. return pMem->u.i;
  68817. }else if( flags & MEM_Real ){
  68818. return doubleToInt64(pMem->u.r);
  68819. }else if( flags & (MEM_Str|MEM_Blob) ){
  68820. assert( pMem->z || pMem->n==0 );
  68821. return memIntValue(pMem);
  68822. }else{
  68823. return 0;
  68824. }
  68825. }
  68826. /*
  68827. ** Return the best representation of pMem that we can get into a
  68828. ** double. If pMem is already a double or an integer, return its
  68829. ** value. If it is a string or blob, try to convert it to a double.
  68830. ** If it is a NULL, return 0.0.
  68831. */
  68832. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  68833. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  68834. double val = (double)0;
  68835. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  68836. return val;
  68837. }
  68838. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  68839. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68840. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68841. if( pMem->flags & MEM_Real ){
  68842. return pMem->u.r;
  68843. }else if( pMem->flags & MEM_Int ){
  68844. return (double)pMem->u.i;
  68845. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  68846. return memRealValue(pMem);
  68847. }else{
  68848. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  68849. return (double)0;
  68850. }
  68851. }
  68852. /*
  68853. ** Return 1 if pMem represents true, and return 0 if pMem represents false.
  68854. ** Return the value ifNull if pMem is NULL.
  68855. */
  68856. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
  68857. if( pMem->flags & MEM_Int ) return pMem->u.i!=0;
  68858. if( pMem->flags & MEM_Null ) return ifNull;
  68859. return sqlite3VdbeRealValue(pMem)!=0.0;
  68860. }
  68861. /*
  68862. ** The MEM structure is already a MEM_Real. Try to also make it a
  68863. ** MEM_Int if we can.
  68864. */
  68865. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  68866. i64 ix;
  68867. assert( pMem->flags & MEM_Real );
  68868. assert( (pMem->flags & MEM_RowSet)==0 );
  68869. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68870. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68871. ix = doubleToInt64(pMem->u.r);
  68872. /* Only mark the value as an integer if
  68873. **
  68874. ** (1) the round-trip conversion real->int->real is a no-op, and
  68875. ** (2) The integer is neither the largest nor the smallest
  68876. ** possible integer (ticket #3922)
  68877. **
  68878. ** The second and third terms in the following conditional enforces
  68879. ** the second condition under the assumption that addition overflow causes
  68880. ** values to wrap around.
  68881. */
  68882. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  68883. pMem->u.i = ix;
  68884. MemSetTypeFlag(pMem, MEM_Int);
  68885. }
  68886. }
  68887. /*
  68888. ** Convert pMem to type integer. Invalidate any prior representations.
  68889. */
  68890. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  68891. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68892. assert( (pMem->flags & MEM_RowSet)==0 );
  68893. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68894. pMem->u.i = sqlite3VdbeIntValue(pMem);
  68895. MemSetTypeFlag(pMem, MEM_Int);
  68896. return SQLITE_OK;
  68897. }
  68898. /*
  68899. ** Convert pMem so that it is of type MEM_Real.
  68900. ** Invalidate any prior representations.
  68901. */
  68902. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  68903. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68904. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68905. pMem->u.r = sqlite3VdbeRealValue(pMem);
  68906. MemSetTypeFlag(pMem, MEM_Real);
  68907. return SQLITE_OK;
  68908. }
  68909. /* Compare a floating point value to an integer. Return true if the two
  68910. ** values are the same within the precision of the floating point value.
  68911. **
  68912. ** For some versions of GCC on 32-bit machines, if you do the more obvious
  68913. ** comparison of "r1==(double)i" you sometimes get an answer of false even
  68914. ** though the r1 and (double)i values are bit-for-bit the same.
  68915. */
  68916. static int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
  68917. double r2 = (double)i;
  68918. return memcmp(&r1, &r2, sizeof(r1))==0;
  68919. }
  68920. /*
  68921. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  68922. ** Invalidate any prior representations.
  68923. **
  68924. ** Every effort is made to force the conversion, even if the input
  68925. ** is a string that does not look completely like a number. Convert
  68926. ** as much of the string as we can and ignore the rest.
  68927. */
  68928. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  68929. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  68930. int rc;
  68931. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  68932. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68933. rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
  68934. if( rc==0 ){
  68935. MemSetTypeFlag(pMem, MEM_Int);
  68936. }else{
  68937. i64 i = pMem->u.i;
  68938. sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  68939. if( rc==1 && sqlite3RealSameAsInt(pMem->u.r, i) ){
  68940. pMem->u.i = i;
  68941. MemSetTypeFlag(pMem, MEM_Int);
  68942. }else{
  68943. MemSetTypeFlag(pMem, MEM_Real);
  68944. }
  68945. }
  68946. }
  68947. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  68948. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  68949. return SQLITE_OK;
  68950. }
  68951. /*
  68952. ** Cast the datatype of the value in pMem according to the affinity
  68953. ** "aff". Casting is different from applying affinity in that a cast
  68954. ** is forced. In other words, the value is converted into the desired
  68955. ** affinity even if that results in loss of data. This routine is
  68956. ** used (for example) to implement the SQL "cast()" operator.
  68957. */
  68958. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  68959. if( pMem->flags & MEM_Null ) return;
  68960. switch( aff ){
  68961. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  68962. if( (pMem->flags & MEM_Blob)==0 ){
  68963. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  68964. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  68965. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  68966. }else{
  68967. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  68968. }
  68969. break;
  68970. }
  68971. case SQLITE_AFF_NUMERIC: {
  68972. sqlite3VdbeMemNumerify(pMem);
  68973. break;
  68974. }
  68975. case SQLITE_AFF_INTEGER: {
  68976. sqlite3VdbeMemIntegerify(pMem);
  68977. break;
  68978. }
  68979. case SQLITE_AFF_REAL: {
  68980. sqlite3VdbeMemRealify(pMem);
  68981. break;
  68982. }
  68983. default: {
  68984. assert( aff==SQLITE_AFF_TEXT );
  68985. assert( MEM_Str==(MEM_Blob>>3) );
  68986. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  68987. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  68988. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  68989. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  68990. break;
  68991. }
  68992. }
  68993. }
  68994. /*
  68995. ** Initialize bulk memory to be a consistent Mem object.
  68996. **
  68997. ** The minimum amount of initialization feasible is performed.
  68998. */
  68999. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  69000. assert( (flags & ~MEM_TypeMask)==0 );
  69001. pMem->flags = flags;
  69002. pMem->db = db;
  69003. pMem->szMalloc = 0;
  69004. }
  69005. /*
  69006. ** Delete any previous value and set the value stored in *pMem to NULL.
  69007. **
  69008. ** This routine calls the Mem.xDel destructor to dispose of values that
  69009. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  69010. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  69011. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  69012. **
  69013. ** Use this routine to reset the Mem prior to insert a new value.
  69014. **
  69015. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  69016. */
  69017. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  69018. if( VdbeMemDynamic(pMem) ){
  69019. vdbeMemClearExternAndSetNull(pMem);
  69020. }else{
  69021. pMem->flags = MEM_Null;
  69022. }
  69023. }
  69024. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  69025. sqlite3VdbeMemSetNull((Mem*)p);
  69026. }
  69027. /*
  69028. ** Delete any previous value and set the value to be a BLOB of length
  69029. ** n containing all zeros.
  69030. */
  69031. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  69032. sqlite3VdbeMemRelease(pMem);
  69033. pMem->flags = MEM_Blob|MEM_Zero;
  69034. pMem->n = 0;
  69035. if( n<0 ) n = 0;
  69036. pMem->u.nZero = n;
  69037. pMem->enc = SQLITE_UTF8;
  69038. pMem->z = 0;
  69039. }
  69040. /*
  69041. ** The pMem is known to contain content that needs to be destroyed prior
  69042. ** to a value change. So invoke the destructor, then set the value to
  69043. ** a 64-bit integer.
  69044. */
  69045. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  69046. sqlite3VdbeMemSetNull(pMem);
  69047. pMem->u.i = val;
  69048. pMem->flags = MEM_Int;
  69049. }
  69050. /*
  69051. ** Delete any previous value and set the value stored in *pMem to val,
  69052. ** manifest type INTEGER.
  69053. */
  69054. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  69055. if( VdbeMemDynamic(pMem) ){
  69056. vdbeReleaseAndSetInt64(pMem, val);
  69057. }else{
  69058. pMem->u.i = val;
  69059. pMem->flags = MEM_Int;
  69060. }
  69061. }
  69062. /* A no-op destructor */
  69063. SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
  69064. /*
  69065. ** Set the value stored in *pMem should already be a NULL.
  69066. ** Also store a pointer to go with it.
  69067. */
  69068. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
  69069. Mem *pMem,
  69070. void *pPtr,
  69071. const char *zPType,
  69072. void (*xDestructor)(void*)
  69073. ){
  69074. assert( pMem->flags==MEM_Null );
  69075. pMem->u.zPType = zPType ? zPType : "";
  69076. pMem->z = pPtr;
  69077. pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
  69078. pMem->eSubtype = 'p';
  69079. pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
  69080. }
  69081. #ifndef SQLITE_OMIT_FLOATING_POINT
  69082. /*
  69083. ** Delete any previous value and set the value stored in *pMem to val,
  69084. ** manifest type REAL.
  69085. */
  69086. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  69087. sqlite3VdbeMemSetNull(pMem);
  69088. if( !sqlite3IsNaN(val) ){
  69089. pMem->u.r = val;
  69090. pMem->flags = MEM_Real;
  69091. }
  69092. }
  69093. #endif
  69094. /*
  69095. ** Delete any previous value and set the value of pMem to be an
  69096. ** empty boolean index.
  69097. */
  69098. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  69099. sqlite3 *db = pMem->db;
  69100. assert( db!=0 );
  69101. assert( (pMem->flags & MEM_RowSet)==0 );
  69102. sqlite3VdbeMemRelease(pMem);
  69103. pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
  69104. if( db->mallocFailed ){
  69105. pMem->flags = MEM_Null;
  69106. pMem->szMalloc = 0;
  69107. }else{
  69108. assert( pMem->zMalloc );
  69109. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  69110. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  69111. assert( pMem->u.pRowSet!=0 );
  69112. pMem->flags = MEM_RowSet;
  69113. }
  69114. }
  69115. /*
  69116. ** Return true if the Mem object contains a TEXT or BLOB that is
  69117. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  69118. */
  69119. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  69120. assert( p->db!=0 );
  69121. if( p->flags & (MEM_Str|MEM_Blob) ){
  69122. int n = p->n;
  69123. if( p->flags & MEM_Zero ){
  69124. n += p->u.nZero;
  69125. }
  69126. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  69127. }
  69128. return 0;
  69129. }
  69130. #ifdef SQLITE_DEBUG
  69131. /*
  69132. ** This routine prepares a memory cell for modification by breaking
  69133. ** its link to a shallow copy and by marking any current shallow
  69134. ** copies of this cell as invalid.
  69135. **
  69136. ** This is used for testing and debugging only - to make sure shallow
  69137. ** copies are not misused.
  69138. */
  69139. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  69140. int i;
  69141. Mem *pX;
  69142. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  69143. if( pX->pScopyFrom==pMem ){
  69144. pX->flags |= MEM_Undefined;
  69145. pX->pScopyFrom = 0;
  69146. }
  69147. }
  69148. pMem->pScopyFrom = 0;
  69149. }
  69150. #endif /* SQLITE_DEBUG */
  69151. /*
  69152. ** Make an shallow copy of pFrom into pTo. Prior contents of
  69153. ** pTo are freed. The pFrom->z field is not duplicated. If
  69154. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  69155. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  69156. */
  69157. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  69158. vdbeMemClearExternAndSetNull(pTo);
  69159. assert( !VdbeMemDynamic(pTo) );
  69160. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  69161. }
  69162. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  69163. assert( (pFrom->flags & MEM_RowSet)==0 );
  69164. assert( pTo->db==pFrom->db );
  69165. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  69166. memcpy(pTo, pFrom, MEMCELLSIZE);
  69167. if( (pFrom->flags&MEM_Static)==0 ){
  69168. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  69169. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  69170. pTo->flags |= srcType;
  69171. }
  69172. }
  69173. /*
  69174. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  69175. ** freed before the copy is made.
  69176. */
  69177. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  69178. int rc = SQLITE_OK;
  69179. assert( (pFrom->flags & MEM_RowSet)==0 );
  69180. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  69181. memcpy(pTo, pFrom, MEMCELLSIZE);
  69182. pTo->flags &= ~MEM_Dyn;
  69183. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  69184. if( 0==(pFrom->flags&MEM_Static) ){
  69185. pTo->flags |= MEM_Ephem;
  69186. rc = sqlite3VdbeMemMakeWriteable(pTo);
  69187. }
  69188. }
  69189. return rc;
  69190. }
  69191. /*
  69192. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  69193. ** freed. If pFrom contains ephemeral data, a copy is made.
  69194. **
  69195. ** pFrom contains an SQL NULL when this routine returns.
  69196. */
  69197. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  69198. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  69199. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  69200. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  69201. sqlite3VdbeMemRelease(pTo);
  69202. memcpy(pTo, pFrom, sizeof(Mem));
  69203. pFrom->flags = MEM_Null;
  69204. pFrom->szMalloc = 0;
  69205. }
  69206. /*
  69207. ** Change the value of a Mem to be a string or a BLOB.
  69208. **
  69209. ** The memory management strategy depends on the value of the xDel
  69210. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  69211. ** string is copied into a (possibly existing) buffer managed by the
  69212. ** Mem structure. Otherwise, any existing buffer is freed and the
  69213. ** pointer copied.
  69214. **
  69215. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  69216. ** size limit) then no memory allocation occurs. If the string can be
  69217. ** stored without allocating memory, then it is. If a memory allocation
  69218. ** is required to store the string, then value of pMem is unchanged. In
  69219. ** either case, SQLITE_TOOBIG is returned.
  69220. */
  69221. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  69222. Mem *pMem, /* Memory cell to set to string value */
  69223. const char *z, /* String pointer */
  69224. int n, /* Bytes in string, or negative */
  69225. u8 enc, /* Encoding of z. 0 for BLOBs */
  69226. void (*xDel)(void*) /* Destructor function */
  69227. ){
  69228. int nByte = n; /* New value for pMem->n */
  69229. int iLimit; /* Maximum allowed string or blob size */
  69230. u16 flags = 0; /* New value for pMem->flags */
  69231. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69232. assert( (pMem->flags & MEM_RowSet)==0 );
  69233. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  69234. if( !z ){
  69235. sqlite3VdbeMemSetNull(pMem);
  69236. return SQLITE_OK;
  69237. }
  69238. if( pMem->db ){
  69239. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  69240. }else{
  69241. iLimit = SQLITE_MAX_LENGTH;
  69242. }
  69243. flags = (enc==0?MEM_Blob:MEM_Str);
  69244. if( nByte<0 ){
  69245. assert( enc!=0 );
  69246. if( enc==SQLITE_UTF8 ){
  69247. nByte = 0x7fffffff & (int)strlen(z);
  69248. if( nByte>iLimit ) nByte = iLimit+1;
  69249. }else{
  69250. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  69251. }
  69252. flags |= MEM_Term;
  69253. }
  69254. /* The following block sets the new values of Mem.z and Mem.xDel. It
  69255. ** also sets a flag in local variable "flags" to indicate the memory
  69256. ** management (one of MEM_Dyn or MEM_Static).
  69257. */
  69258. if( xDel==SQLITE_TRANSIENT ){
  69259. int nAlloc = nByte;
  69260. if( flags&MEM_Term ){
  69261. nAlloc += (enc==SQLITE_UTF8?1:2);
  69262. }
  69263. if( nByte>iLimit ){
  69264. return SQLITE_TOOBIG;
  69265. }
  69266. testcase( nAlloc==0 );
  69267. testcase( nAlloc==31 );
  69268. testcase( nAlloc==32 );
  69269. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  69270. return SQLITE_NOMEM_BKPT;
  69271. }
  69272. memcpy(pMem->z, z, nAlloc);
  69273. }else if( xDel==SQLITE_DYNAMIC ){
  69274. sqlite3VdbeMemRelease(pMem);
  69275. pMem->zMalloc = pMem->z = (char *)z;
  69276. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  69277. }else{
  69278. sqlite3VdbeMemRelease(pMem);
  69279. pMem->z = (char *)z;
  69280. pMem->xDel = xDel;
  69281. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  69282. }
  69283. pMem->n = nByte;
  69284. pMem->flags = flags;
  69285. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  69286. #ifndef SQLITE_OMIT_UTF16
  69287. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  69288. return SQLITE_NOMEM_BKPT;
  69289. }
  69290. #endif
  69291. if( nByte>iLimit ){
  69292. return SQLITE_TOOBIG;
  69293. }
  69294. return SQLITE_OK;
  69295. }
  69296. /*
  69297. ** Move data out of a btree key or data field and into a Mem structure.
  69298. ** The data is payload from the entry that pCur is currently pointing
  69299. ** to. offset and amt determine what portion of the data or key to retrieve.
  69300. ** The result is written into the pMem element.
  69301. **
  69302. ** The pMem object must have been initialized. This routine will use
  69303. ** pMem->zMalloc to hold the content from the btree, if possible. New
  69304. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  69305. ** is responsible for making sure that the pMem object is eventually
  69306. ** destroyed.
  69307. **
  69308. ** If this routine fails for any reason (malloc returns NULL or unable
  69309. ** to read from the disk) then the pMem is left in an inconsistent state.
  69310. */
  69311. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  69312. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  69313. u32 offset, /* Offset from the start of data to return bytes from. */
  69314. u32 amt, /* Number of bytes to return. */
  69315. Mem *pMem /* OUT: Return data in this Mem structure. */
  69316. ){
  69317. int rc;
  69318. pMem->flags = MEM_Null;
  69319. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
  69320. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  69321. if( rc==SQLITE_OK ){
  69322. pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
  69323. pMem->flags = MEM_Blob;
  69324. pMem->n = (int)amt;
  69325. }else{
  69326. sqlite3VdbeMemRelease(pMem);
  69327. }
  69328. }
  69329. return rc;
  69330. }
  69331. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  69332. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  69333. u32 offset, /* Offset from the start of data to return bytes from. */
  69334. u32 amt, /* Number of bytes to return. */
  69335. Mem *pMem /* OUT: Return data in this Mem structure. */
  69336. ){
  69337. char *zData; /* Data from the btree layer */
  69338. u32 available = 0; /* Number of bytes available on the local btree page */
  69339. int rc = SQLITE_OK; /* Return code */
  69340. assert( sqlite3BtreeCursorIsValid(pCur) );
  69341. assert( !VdbeMemDynamic(pMem) );
  69342. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  69343. ** that both the BtShared and database handle mutexes are held. */
  69344. assert( (pMem->flags & MEM_RowSet)==0 );
  69345. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  69346. assert( zData!=0 );
  69347. if( offset+amt<=available ){
  69348. pMem->z = &zData[offset];
  69349. pMem->flags = MEM_Blob|MEM_Ephem;
  69350. pMem->n = (int)amt;
  69351. }else{
  69352. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  69353. }
  69354. return rc;
  69355. }
  69356. /*
  69357. ** The pVal argument is known to be a value other than NULL.
  69358. ** Convert it into a string with encoding enc and return a pointer
  69359. ** to a zero-terminated version of that string.
  69360. */
  69361. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  69362. assert( pVal!=0 );
  69363. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  69364. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  69365. assert( (pVal->flags & MEM_RowSet)==0 );
  69366. assert( (pVal->flags & (MEM_Null))==0 );
  69367. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  69368. if( ExpandBlob(pVal) ) return 0;
  69369. pVal->flags |= MEM_Str;
  69370. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  69371. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  69372. }
  69373. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  69374. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  69375. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  69376. return 0;
  69377. }
  69378. }
  69379. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  69380. }else{
  69381. sqlite3VdbeMemStringify(pVal, enc, 0);
  69382. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  69383. }
  69384. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  69385. || pVal->db->mallocFailed );
  69386. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  69387. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  69388. return pVal->z;
  69389. }else{
  69390. return 0;
  69391. }
  69392. }
  69393. /* This function is only available internally, it is not part of the
  69394. ** external API. It works in a similar way to sqlite3_value_text(),
  69395. ** except the data returned is in the encoding specified by the second
  69396. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  69397. ** SQLITE_UTF8.
  69398. **
  69399. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  69400. ** If that is the case, then the result must be aligned on an even byte
  69401. ** boundary.
  69402. */
  69403. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  69404. if( !pVal ) return 0;
  69405. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  69406. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  69407. assert( (pVal->flags & MEM_RowSet)==0 );
  69408. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  69409. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  69410. return pVal->z;
  69411. }
  69412. if( pVal->flags&MEM_Null ){
  69413. return 0;
  69414. }
  69415. return valueToText(pVal, enc);
  69416. }
  69417. /*
  69418. ** Create a new sqlite3_value object.
  69419. */
  69420. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  69421. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  69422. if( p ){
  69423. p->flags = MEM_Null;
  69424. p->db = db;
  69425. }
  69426. return p;
  69427. }
  69428. /*
  69429. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  69430. ** valueNew(). See comments above valueNew() for details.
  69431. */
  69432. struct ValueNewStat4Ctx {
  69433. Parse *pParse;
  69434. Index *pIdx;
  69435. UnpackedRecord **ppRec;
  69436. int iVal;
  69437. };
  69438. /*
  69439. ** Allocate and return a pointer to a new sqlite3_value object. If
  69440. ** the second argument to this function is NULL, the object is allocated
  69441. ** by calling sqlite3ValueNew().
  69442. **
  69443. ** Otherwise, if the second argument is non-zero, then this function is
  69444. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  69445. ** already been allocated, allocate the UnpackedRecord structure that
  69446. ** that function will return to its caller here. Then return a pointer to
  69447. ** an sqlite3_value within the UnpackedRecord.a[] array.
  69448. */
  69449. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  69450. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69451. if( p ){
  69452. UnpackedRecord *pRec = p->ppRec[0];
  69453. if( pRec==0 ){
  69454. Index *pIdx = p->pIdx; /* Index being probed */
  69455. int nByte; /* Bytes of space to allocate */
  69456. int i; /* Counter variable */
  69457. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  69458. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  69459. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  69460. if( pRec ){
  69461. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  69462. if( pRec->pKeyInfo ){
  69463. assert( pRec->pKeyInfo->nAllField==nCol );
  69464. assert( pRec->pKeyInfo->enc==ENC(db) );
  69465. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  69466. for(i=0; i<nCol; i++){
  69467. pRec->aMem[i].flags = MEM_Null;
  69468. pRec->aMem[i].db = db;
  69469. }
  69470. }else{
  69471. sqlite3DbFreeNN(db, pRec);
  69472. pRec = 0;
  69473. }
  69474. }
  69475. if( pRec==0 ) return 0;
  69476. p->ppRec[0] = pRec;
  69477. }
  69478. pRec->nField = p->iVal+1;
  69479. return &pRec->aMem[p->iVal];
  69480. }
  69481. #else
  69482. UNUSED_PARAMETER(p);
  69483. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  69484. return sqlite3ValueNew(db);
  69485. }
  69486. /*
  69487. ** The expression object indicated by the second argument is guaranteed
  69488. ** to be a scalar SQL function. If
  69489. **
  69490. ** * all function arguments are SQL literals,
  69491. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  69492. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  69493. **
  69494. ** then this routine attempts to invoke the SQL function. Assuming no
  69495. ** error occurs, output parameter (*ppVal) is set to point to a value
  69496. ** object containing the result before returning SQLITE_OK.
  69497. **
  69498. ** Affinity aff is applied to the result of the function before returning.
  69499. ** If the result is a text value, the sqlite3_value object uses encoding
  69500. ** enc.
  69501. **
  69502. ** If the conditions above are not met, this function returns SQLITE_OK
  69503. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  69504. ** NULL and an SQLite error code returned.
  69505. */
  69506. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69507. static int valueFromFunction(
  69508. sqlite3 *db, /* The database connection */
  69509. Expr *p, /* The expression to evaluate */
  69510. u8 enc, /* Encoding to use */
  69511. u8 aff, /* Affinity to use */
  69512. sqlite3_value **ppVal, /* Write the new value here */
  69513. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  69514. ){
  69515. sqlite3_context ctx; /* Context object for function invocation */
  69516. sqlite3_value **apVal = 0; /* Function arguments */
  69517. int nVal = 0; /* Size of apVal[] array */
  69518. FuncDef *pFunc = 0; /* Function definition */
  69519. sqlite3_value *pVal = 0; /* New value */
  69520. int rc = SQLITE_OK; /* Return code */
  69521. ExprList *pList = 0; /* Function arguments */
  69522. int i; /* Iterator variable */
  69523. assert( pCtx!=0 );
  69524. assert( (p->flags & EP_TokenOnly)==0 );
  69525. pList = p->x.pList;
  69526. if( pList ) nVal = pList->nExpr;
  69527. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  69528. assert( pFunc );
  69529. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  69530. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  69531. ){
  69532. return SQLITE_OK;
  69533. }
  69534. if( pList ){
  69535. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  69536. if( apVal==0 ){
  69537. rc = SQLITE_NOMEM_BKPT;
  69538. goto value_from_function_out;
  69539. }
  69540. for(i=0; i<nVal; i++){
  69541. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  69542. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  69543. }
  69544. }
  69545. pVal = valueNew(db, pCtx);
  69546. if( pVal==0 ){
  69547. rc = SQLITE_NOMEM_BKPT;
  69548. goto value_from_function_out;
  69549. }
  69550. assert( pCtx->pParse->rc==SQLITE_OK );
  69551. memset(&ctx, 0, sizeof(ctx));
  69552. ctx.pOut = pVal;
  69553. ctx.pFunc = pFunc;
  69554. pFunc->xSFunc(&ctx, nVal, apVal);
  69555. if( ctx.isError ){
  69556. rc = ctx.isError;
  69557. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  69558. }else{
  69559. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  69560. assert( rc==SQLITE_OK );
  69561. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  69562. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  69563. rc = SQLITE_TOOBIG;
  69564. pCtx->pParse->nErr++;
  69565. }
  69566. }
  69567. pCtx->pParse->rc = rc;
  69568. value_from_function_out:
  69569. if( rc!=SQLITE_OK ){
  69570. pVal = 0;
  69571. }
  69572. if( apVal ){
  69573. for(i=0; i<nVal; i++){
  69574. sqlite3ValueFree(apVal[i]);
  69575. }
  69576. sqlite3DbFreeNN(db, apVal);
  69577. }
  69578. *ppVal = pVal;
  69579. return rc;
  69580. }
  69581. #else
  69582. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  69583. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  69584. /*
  69585. ** Extract a value from the supplied expression in the manner described
  69586. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  69587. ** using valueNew().
  69588. **
  69589. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  69590. ** has been allocated, it is freed before returning. Or, if pCtx is not
  69591. ** NULL, it is assumed that the caller will free any allocated object
  69592. ** in all cases.
  69593. */
  69594. static int valueFromExpr(
  69595. sqlite3 *db, /* The database connection */
  69596. Expr *pExpr, /* The expression to evaluate */
  69597. u8 enc, /* Encoding to use */
  69598. u8 affinity, /* Affinity to use */
  69599. sqlite3_value **ppVal, /* Write the new value here */
  69600. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  69601. ){
  69602. int op;
  69603. char *zVal = 0;
  69604. sqlite3_value *pVal = 0;
  69605. int negInt = 1;
  69606. const char *zNeg = "";
  69607. int rc = SQLITE_OK;
  69608. assert( pExpr!=0 );
  69609. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  69610. #if defined(SQLITE_ENABLE_STAT3_OR_STAT4)
  69611. if( op==TK_REGISTER ) op = pExpr->op2;
  69612. #else
  69613. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  69614. #endif
  69615. /* Compressed expressions only appear when parsing the DEFAULT clause
  69616. ** on a table column definition, and hence only when pCtx==0. This
  69617. ** check ensures that an EP_TokenOnly expression is never passed down
  69618. ** into valueFromFunction(). */
  69619. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  69620. if( op==TK_CAST ){
  69621. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  69622. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  69623. testcase( rc!=SQLITE_OK );
  69624. if( *ppVal ){
  69625. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  69626. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  69627. }
  69628. return rc;
  69629. }
  69630. /* Handle negative integers in a single step. This is needed in the
  69631. ** case when the value is -9223372036854775808.
  69632. */
  69633. if( op==TK_UMINUS
  69634. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  69635. pExpr = pExpr->pLeft;
  69636. op = pExpr->op;
  69637. negInt = -1;
  69638. zNeg = "-";
  69639. }
  69640. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  69641. pVal = valueNew(db, pCtx);
  69642. if( pVal==0 ) goto no_mem;
  69643. if( ExprHasProperty(pExpr, EP_IntValue) ){
  69644. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  69645. }else{
  69646. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  69647. if( zVal==0 ) goto no_mem;
  69648. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  69649. }
  69650. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  69651. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  69652. }else{
  69653. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  69654. }
  69655. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  69656. if( enc!=SQLITE_UTF8 ){
  69657. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  69658. }
  69659. }else if( op==TK_UMINUS ) {
  69660. /* This branch happens for multiple negative signs. Ex: -(-5) */
  69661. if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
  69662. && pVal!=0
  69663. ){
  69664. sqlite3VdbeMemNumerify(pVal);
  69665. if( pVal->flags & MEM_Real ){
  69666. pVal->u.r = -pVal->u.r;
  69667. }else if( pVal->u.i==SMALLEST_INT64 ){
  69668. pVal->u.r = -(double)SMALLEST_INT64;
  69669. MemSetTypeFlag(pVal, MEM_Real);
  69670. }else{
  69671. pVal->u.i = -pVal->u.i;
  69672. }
  69673. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  69674. }
  69675. }else if( op==TK_NULL ){
  69676. pVal = valueNew(db, pCtx);
  69677. if( pVal==0 ) goto no_mem;
  69678. sqlite3VdbeMemNumerify(pVal);
  69679. }
  69680. #ifndef SQLITE_OMIT_BLOB_LITERAL
  69681. else if( op==TK_BLOB ){
  69682. int nVal;
  69683. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  69684. assert( pExpr->u.zToken[1]=='\'' );
  69685. pVal = valueNew(db, pCtx);
  69686. if( !pVal ) goto no_mem;
  69687. zVal = &pExpr->u.zToken[2];
  69688. nVal = sqlite3Strlen30(zVal)-1;
  69689. assert( zVal[nVal]=='\'' );
  69690. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  69691. 0, SQLITE_DYNAMIC);
  69692. }
  69693. #endif
  69694. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69695. else if( op==TK_FUNCTION && pCtx!=0 ){
  69696. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  69697. }
  69698. #endif
  69699. else if( op==TK_TRUEFALSE ){
  69700. pVal = valueNew(db, pCtx);
  69701. pVal->flags = MEM_Int;
  69702. pVal->u.i = pExpr->u.zToken[4]==0;
  69703. }
  69704. *ppVal = pVal;
  69705. return rc;
  69706. no_mem:
  69707. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69708. if( pCtx==0 || pCtx->pParse->nErr==0 )
  69709. #endif
  69710. sqlite3OomFault(db);
  69711. sqlite3DbFree(db, zVal);
  69712. assert( *ppVal==0 );
  69713. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69714. if( pCtx==0 ) sqlite3ValueFree(pVal);
  69715. #else
  69716. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  69717. #endif
  69718. return SQLITE_NOMEM_BKPT;
  69719. }
  69720. /*
  69721. ** Create a new sqlite3_value object, containing the value of pExpr.
  69722. **
  69723. ** This only works for very simple expressions that consist of one constant
  69724. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  69725. ** be converted directly into a value, then the value is allocated and
  69726. ** a pointer written to *ppVal. The caller is responsible for deallocating
  69727. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  69728. ** cannot be converted to a value, then *ppVal is set to NULL.
  69729. */
  69730. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  69731. sqlite3 *db, /* The database connection */
  69732. Expr *pExpr, /* The expression to evaluate */
  69733. u8 enc, /* Encoding to use */
  69734. u8 affinity, /* Affinity to use */
  69735. sqlite3_value **ppVal /* Write the new value here */
  69736. ){
  69737. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  69738. }
  69739. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69740. /*
  69741. ** The implementation of the sqlite_record() function. This function accepts
  69742. ** a single argument of any type. The return value is a formatted database
  69743. ** record (a blob) containing the argument value.
  69744. **
  69745. ** This is used to convert the value stored in the 'sample' column of the
  69746. ** sqlite_stat3 table to the record format SQLite uses internally.
  69747. */
  69748. static void recordFunc(
  69749. sqlite3_context *context,
  69750. int argc,
  69751. sqlite3_value **argv
  69752. ){
  69753. const int file_format = 1;
  69754. u32 iSerial; /* Serial type */
  69755. int nSerial; /* Bytes of space for iSerial as varint */
  69756. u32 nVal; /* Bytes of space required for argv[0] */
  69757. int nRet;
  69758. sqlite3 *db;
  69759. u8 *aRet;
  69760. UNUSED_PARAMETER( argc );
  69761. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  69762. nSerial = sqlite3VarintLen(iSerial);
  69763. db = sqlite3_context_db_handle(context);
  69764. nRet = 1 + nSerial + nVal;
  69765. aRet = sqlite3DbMallocRawNN(db, nRet);
  69766. if( aRet==0 ){
  69767. sqlite3_result_error_nomem(context);
  69768. }else{
  69769. aRet[0] = nSerial+1;
  69770. putVarint32(&aRet[1], iSerial);
  69771. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  69772. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  69773. sqlite3DbFreeNN(db, aRet);
  69774. }
  69775. }
  69776. /*
  69777. ** Register built-in functions used to help read ANALYZE data.
  69778. */
  69779. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  69780. static FuncDef aAnalyzeTableFuncs[] = {
  69781. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  69782. };
  69783. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  69784. }
  69785. /*
  69786. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  69787. **
  69788. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  69789. ** pAlloc if one does not exist and the new value is added to the
  69790. ** UnpackedRecord object.
  69791. **
  69792. ** A value is extracted in the following cases:
  69793. **
  69794. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  69795. **
  69796. ** * The expression is a bound variable, and this is a reprepare, or
  69797. **
  69798. ** * The expression is a literal value.
  69799. **
  69800. ** On success, *ppVal is made to point to the extracted value. The caller
  69801. ** is responsible for ensuring that the value is eventually freed.
  69802. */
  69803. static int stat4ValueFromExpr(
  69804. Parse *pParse, /* Parse context */
  69805. Expr *pExpr, /* The expression to extract a value from */
  69806. u8 affinity, /* Affinity to use */
  69807. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  69808. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  69809. ){
  69810. int rc = SQLITE_OK;
  69811. sqlite3_value *pVal = 0;
  69812. sqlite3 *db = pParse->db;
  69813. /* Skip over any TK_COLLATE nodes */
  69814. pExpr = sqlite3ExprSkipCollate(pExpr);
  69815. assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
  69816. if( !pExpr ){
  69817. pVal = valueNew(db, pAlloc);
  69818. if( pVal ){
  69819. sqlite3VdbeMemSetNull((Mem*)pVal);
  69820. }
  69821. }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  69822. Vdbe *v;
  69823. int iBindVar = pExpr->iColumn;
  69824. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  69825. if( (v = pParse->pReprepare)!=0 ){
  69826. pVal = valueNew(db, pAlloc);
  69827. if( pVal ){
  69828. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  69829. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  69830. pVal->db = pParse->db;
  69831. }
  69832. }
  69833. }else{
  69834. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  69835. }
  69836. assert( pVal==0 || pVal->db==db );
  69837. *ppVal = pVal;
  69838. return rc;
  69839. }
  69840. /*
  69841. ** This function is used to allocate and populate UnpackedRecord
  69842. ** structures intended to be compared against sample index keys stored
  69843. ** in the sqlite_stat4 table.
  69844. **
  69845. ** A single call to this function populates zero or more fields of the
  69846. ** record starting with field iVal (fields are numbered from left to
  69847. ** right starting with 0). A single field is populated if:
  69848. **
  69849. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  69850. **
  69851. ** * The expression is a bound variable, and this is a reprepare, or
  69852. **
  69853. ** * The sqlite3ValueFromExpr() function is able to extract a value
  69854. ** from the expression (i.e. the expression is a literal value).
  69855. **
  69856. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  69857. ** vector components that match either of the two latter criteria listed
  69858. ** above.
  69859. **
  69860. ** Before any value is appended to the record, the affinity of the
  69861. ** corresponding column within index pIdx is applied to it. Before
  69862. ** this function returns, output parameter *pnExtract is set to the
  69863. ** number of values appended to the record.
  69864. **
  69865. ** When this function is called, *ppRec must either point to an object
  69866. ** allocated by an earlier call to this function, or must be NULL. If it
  69867. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  69868. ** is allocated (and *ppRec set to point to it) before returning.
  69869. **
  69870. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  69871. ** error if a value cannot be extracted from pExpr. If an error does
  69872. ** occur, an SQLite error code is returned.
  69873. */
  69874. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  69875. Parse *pParse, /* Parse context */
  69876. Index *pIdx, /* Index being probed */
  69877. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  69878. Expr *pExpr, /* The expression to extract a value from */
  69879. int nElem, /* Maximum number of values to append */
  69880. int iVal, /* Array element to populate */
  69881. int *pnExtract /* OUT: Values appended to the record */
  69882. ){
  69883. int rc = SQLITE_OK;
  69884. int nExtract = 0;
  69885. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  69886. int i;
  69887. struct ValueNewStat4Ctx alloc;
  69888. alloc.pParse = pParse;
  69889. alloc.pIdx = pIdx;
  69890. alloc.ppRec = ppRec;
  69891. for(i=0; i<nElem; i++){
  69892. sqlite3_value *pVal = 0;
  69893. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  69894. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  69895. alloc.iVal = iVal+i;
  69896. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  69897. if( !pVal ) break;
  69898. nExtract++;
  69899. }
  69900. }
  69901. *pnExtract = nExtract;
  69902. return rc;
  69903. }
  69904. /*
  69905. ** Attempt to extract a value from expression pExpr using the methods
  69906. ** as described for sqlite3Stat4ProbeSetValue() above.
  69907. **
  69908. ** If successful, set *ppVal to point to a new value object and return
  69909. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  69910. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  69911. ** does occur, return an SQLite error code. The final value of *ppVal
  69912. ** is undefined in this case.
  69913. */
  69914. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  69915. Parse *pParse, /* Parse context */
  69916. Expr *pExpr, /* The expression to extract a value from */
  69917. u8 affinity, /* Affinity to use */
  69918. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  69919. ){
  69920. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  69921. }
  69922. /*
  69923. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  69924. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  69925. ** sqlite3_value object is allocated.
  69926. **
  69927. ** If *ppVal is initially NULL then the caller is responsible for
  69928. ** ensuring that the value written into *ppVal is eventually freed.
  69929. */
  69930. SQLITE_PRIVATE int sqlite3Stat4Column(
  69931. sqlite3 *db, /* Database handle */
  69932. const void *pRec, /* Pointer to buffer containing record */
  69933. int nRec, /* Size of buffer pRec in bytes */
  69934. int iCol, /* Column to extract */
  69935. sqlite3_value **ppVal /* OUT: Extracted value */
  69936. ){
  69937. u32 t; /* a column type code */
  69938. int nHdr; /* Size of the header in the record */
  69939. int iHdr; /* Next unread header byte */
  69940. int iField; /* Next unread data byte */
  69941. int szField; /* Size of the current data field */
  69942. int i; /* Column index */
  69943. u8 *a = (u8*)pRec; /* Typecast byte array */
  69944. Mem *pMem = *ppVal; /* Write result into this Mem object */
  69945. assert( iCol>0 );
  69946. iHdr = getVarint32(a, nHdr);
  69947. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  69948. iField = nHdr;
  69949. for(i=0; i<=iCol; i++){
  69950. iHdr += getVarint32(&a[iHdr], t);
  69951. testcase( iHdr==nHdr );
  69952. testcase( iHdr==nHdr+1 );
  69953. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  69954. szField = sqlite3VdbeSerialTypeLen(t);
  69955. iField += szField;
  69956. }
  69957. testcase( iField==nRec );
  69958. testcase( iField==nRec+1 );
  69959. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  69960. if( pMem==0 ){
  69961. pMem = *ppVal = sqlite3ValueNew(db);
  69962. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  69963. }
  69964. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  69965. pMem->enc = ENC(db);
  69966. return SQLITE_OK;
  69967. }
  69968. /*
  69969. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  69970. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  69971. ** the object.
  69972. */
  69973. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  69974. if( pRec ){
  69975. int i;
  69976. int nCol = pRec->pKeyInfo->nAllField;
  69977. Mem *aMem = pRec->aMem;
  69978. sqlite3 *db = aMem[0].db;
  69979. for(i=0; i<nCol; i++){
  69980. sqlite3VdbeMemRelease(&aMem[i]);
  69981. }
  69982. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  69983. sqlite3DbFreeNN(db, pRec);
  69984. }
  69985. }
  69986. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  69987. /*
  69988. ** Change the string value of an sqlite3_value object
  69989. */
  69990. SQLITE_PRIVATE void sqlite3ValueSetStr(
  69991. sqlite3_value *v, /* Value to be set */
  69992. int n, /* Length of string z */
  69993. const void *z, /* Text of the new string */
  69994. u8 enc, /* Encoding to use */
  69995. void (*xDel)(void*) /* Destructor for the string */
  69996. ){
  69997. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  69998. }
  69999. /*
  70000. ** Free an sqlite3_value object
  70001. */
  70002. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  70003. if( !v ) return;
  70004. sqlite3VdbeMemRelease((Mem *)v);
  70005. sqlite3DbFreeNN(((Mem*)v)->db, v);
  70006. }
  70007. /*
  70008. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  70009. ** sqlite3_value object assuming that it uses the encoding "enc".
  70010. ** The valueBytes() routine is a helper function.
  70011. */
  70012. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  70013. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  70014. }
  70015. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  70016. Mem *p = (Mem*)pVal;
  70017. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  70018. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  70019. return p->n;
  70020. }
  70021. if( (p->flags & MEM_Blob)!=0 ){
  70022. if( p->flags & MEM_Zero ){
  70023. return p->n + p->u.nZero;
  70024. }else{
  70025. return p->n;
  70026. }
  70027. }
  70028. if( p->flags & MEM_Null ) return 0;
  70029. return valueBytes(pVal, enc);
  70030. }
  70031. /************** End of vdbemem.c *********************************************/
  70032. /************** Begin file vdbeaux.c *****************************************/
  70033. /*
  70034. ** 2003 September 6
  70035. **
  70036. ** The author disclaims copyright to this source code. In place of
  70037. ** a legal notice, here is a blessing:
  70038. **
  70039. ** May you do good and not evil.
  70040. ** May you find forgiveness for yourself and forgive others.
  70041. ** May you share freely, never taking more than you give.
  70042. **
  70043. *************************************************************************
  70044. ** This file contains code used for creating, destroying, and populating
  70045. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  70046. */
  70047. /* #include "sqliteInt.h" */
  70048. /* #include "vdbeInt.h" */
  70049. /*
  70050. ** Create a new virtual database engine.
  70051. */
  70052. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  70053. sqlite3 *db = pParse->db;
  70054. Vdbe *p;
  70055. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  70056. if( p==0 ) return 0;
  70057. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  70058. p->db = db;
  70059. if( db->pVdbe ){
  70060. db->pVdbe->pPrev = p;
  70061. }
  70062. p->pNext = db->pVdbe;
  70063. p->pPrev = 0;
  70064. db->pVdbe = p;
  70065. p->magic = VDBE_MAGIC_INIT;
  70066. p->pParse = pParse;
  70067. pParse->pVdbe = p;
  70068. assert( pParse->aLabel==0 );
  70069. assert( pParse->nLabel==0 );
  70070. assert( pParse->nOpAlloc==0 );
  70071. assert( pParse->szOpAlloc==0 );
  70072. sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
  70073. return p;
  70074. }
  70075. /*
  70076. ** Change the error string stored in Vdbe.zErrMsg
  70077. */
  70078. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  70079. va_list ap;
  70080. sqlite3DbFree(p->db, p->zErrMsg);
  70081. va_start(ap, zFormat);
  70082. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  70083. va_end(ap);
  70084. }
  70085. /*
  70086. ** Remember the SQL string for a prepared statement.
  70087. */
  70088. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
  70089. if( p==0 ) return;
  70090. p->prepFlags = prepFlags;
  70091. if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
  70092. p->expmask = 0;
  70093. }
  70094. assert( p->zSql==0 );
  70095. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  70096. }
  70097. /*
  70098. ** Swap all content between two VDBE structures.
  70099. */
  70100. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  70101. Vdbe tmp, *pTmp;
  70102. char *zTmp;
  70103. assert( pA->db==pB->db );
  70104. tmp = *pA;
  70105. *pA = *pB;
  70106. *pB = tmp;
  70107. pTmp = pA->pNext;
  70108. pA->pNext = pB->pNext;
  70109. pB->pNext = pTmp;
  70110. pTmp = pA->pPrev;
  70111. pA->pPrev = pB->pPrev;
  70112. pB->pPrev = pTmp;
  70113. zTmp = pA->zSql;
  70114. pA->zSql = pB->zSql;
  70115. pB->zSql = zTmp;
  70116. pB->expmask = pA->expmask;
  70117. pB->prepFlags = pA->prepFlags;
  70118. memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  70119. pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
  70120. }
  70121. /*
  70122. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  70123. ** than its current size. nOp is guaranteed to be less than or equal
  70124. ** to 1024/sizeof(Op).
  70125. **
  70126. ** If an out-of-memory error occurs while resizing the array, return
  70127. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  70128. ** unchanged (this is so that any opcodes already allocated can be
  70129. ** correctly deallocated along with the rest of the Vdbe).
  70130. */
  70131. static int growOpArray(Vdbe *v, int nOp){
  70132. VdbeOp *pNew;
  70133. Parse *p = v->pParse;
  70134. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  70135. ** more frequent reallocs and hence provide more opportunities for
  70136. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  70137. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  70138. ** by the minimum* amount required until the size reaches 512. Normal
  70139. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  70140. ** size of the op array or add 1KB of space, whichever is smaller. */
  70141. #ifdef SQLITE_TEST_REALLOC_STRESS
  70142. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  70143. #else
  70144. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  70145. UNUSED_PARAMETER(nOp);
  70146. #endif
  70147. /* Ensure that the size of a VDBE does not grow too large */
  70148. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  70149. sqlite3OomFault(p->db);
  70150. return SQLITE_NOMEM;
  70151. }
  70152. assert( nOp<=(1024/sizeof(Op)) );
  70153. assert( nNew>=(p->nOpAlloc+nOp) );
  70154. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  70155. if( pNew ){
  70156. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  70157. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  70158. v->aOp = pNew;
  70159. }
  70160. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  70161. }
  70162. #ifdef SQLITE_DEBUG
  70163. /* This routine is just a convenient place to set a breakpoint that will
  70164. ** fire after each opcode is inserted and displayed using
  70165. ** "PRAGMA vdbe_addoptrace=on".
  70166. */
  70167. static void test_addop_breakpoint(void){
  70168. static int n = 0;
  70169. n++;
  70170. }
  70171. #endif
  70172. /*
  70173. ** Add a new instruction to the list of instructions current in the
  70174. ** VDBE. Return the address of the new instruction.
  70175. **
  70176. ** Parameters:
  70177. **
  70178. ** p Pointer to the VDBE
  70179. **
  70180. ** op The opcode for this instruction
  70181. **
  70182. ** p1, p2, p3 Operands
  70183. **
  70184. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  70185. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  70186. ** operand.
  70187. */
  70188. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  70189. assert( p->pParse->nOpAlloc<=p->nOp );
  70190. if( growOpArray(p, 1) ) return 1;
  70191. assert( p->pParse->nOpAlloc>p->nOp );
  70192. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  70193. }
  70194. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  70195. int i;
  70196. VdbeOp *pOp;
  70197. i = p->nOp;
  70198. assert( p->magic==VDBE_MAGIC_INIT );
  70199. assert( op>=0 && op<0xff );
  70200. if( p->pParse->nOpAlloc<=i ){
  70201. return growOp3(p, op, p1, p2, p3);
  70202. }
  70203. p->nOp++;
  70204. pOp = &p->aOp[i];
  70205. pOp->opcode = (u8)op;
  70206. pOp->p5 = 0;
  70207. pOp->p1 = p1;
  70208. pOp->p2 = p2;
  70209. pOp->p3 = p3;
  70210. pOp->p4.p = 0;
  70211. pOp->p4type = P4_NOTUSED;
  70212. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  70213. pOp->zComment = 0;
  70214. #endif
  70215. #ifdef SQLITE_DEBUG
  70216. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  70217. int jj, kk;
  70218. Parse *pParse = p->pParse;
  70219. for(jj=kk=0; jj<pParse->nColCache; jj++){
  70220. struct yColCache *x = pParse->aColCache + jj;
  70221. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  70222. kk++;
  70223. }
  70224. if( kk ) printf("\n");
  70225. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  70226. test_addop_breakpoint();
  70227. }
  70228. #endif
  70229. #ifdef VDBE_PROFILE
  70230. pOp->cycles = 0;
  70231. pOp->cnt = 0;
  70232. #endif
  70233. #ifdef SQLITE_VDBE_COVERAGE
  70234. pOp->iSrcLine = 0;
  70235. #endif
  70236. return i;
  70237. }
  70238. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  70239. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  70240. }
  70241. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  70242. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  70243. }
  70244. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  70245. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  70246. }
  70247. /* Generate code for an unconditional jump to instruction iDest
  70248. */
  70249. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  70250. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  70251. }
  70252. /* Generate code to cause the string zStr to be loaded into
  70253. ** register iDest
  70254. */
  70255. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  70256. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  70257. }
  70258. /*
  70259. ** Generate code that initializes multiple registers to string or integer
  70260. ** constants. The registers begin with iDest and increase consecutively.
  70261. ** One register is initialized for each characgter in zTypes[]. For each
  70262. ** "s" character in zTypes[], the register is a string if the argument is
  70263. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  70264. ** in zTypes[], the register is initialized to an integer.
  70265. **
  70266. ** If the input string does not end with "X" then an OP_ResultRow instruction
  70267. ** is generated for the values inserted.
  70268. */
  70269. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  70270. va_list ap;
  70271. int i;
  70272. char c;
  70273. va_start(ap, zTypes);
  70274. for(i=0; (c = zTypes[i])!=0; i++){
  70275. if( c=='s' ){
  70276. const char *z = va_arg(ap, const char*);
  70277. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
  70278. }else if( c=='i' ){
  70279. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
  70280. }else{
  70281. goto skip_op_resultrow;
  70282. }
  70283. }
  70284. sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
  70285. skip_op_resultrow:
  70286. va_end(ap);
  70287. }
  70288. /*
  70289. ** Add an opcode that includes the p4 value as a pointer.
  70290. */
  70291. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  70292. Vdbe *p, /* Add the opcode to this VM */
  70293. int op, /* The new opcode */
  70294. int p1, /* The P1 operand */
  70295. int p2, /* The P2 operand */
  70296. int p3, /* The P3 operand */
  70297. const char *zP4, /* The P4 operand */
  70298. int p4type /* P4 operand type */
  70299. ){
  70300. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  70301. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  70302. return addr;
  70303. }
  70304. /*
  70305. ** Add an opcode that includes the p4 value with a P4_INT64 or
  70306. ** P4_REAL type.
  70307. */
  70308. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  70309. Vdbe *p, /* Add the opcode to this VM */
  70310. int op, /* The new opcode */
  70311. int p1, /* The P1 operand */
  70312. int p2, /* The P2 operand */
  70313. int p3, /* The P3 operand */
  70314. const u8 *zP4, /* The P4 operand */
  70315. int p4type /* P4 operand type */
  70316. ){
  70317. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  70318. if( p4copy ) memcpy(p4copy, zP4, 8);
  70319. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  70320. }
  70321. #ifndef SQLITE_OMIT_EXPLAIN
  70322. /*
  70323. ** Return the address of the current EXPLAIN QUERY PLAN baseline.
  70324. ** 0 means "none".
  70325. */
  70326. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
  70327. VdbeOp *pOp;
  70328. if( pParse->addrExplain==0 ) return 0;
  70329. pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
  70330. return pOp->p2;
  70331. }
  70332. /*
  70333. ** Add a new OP_Explain opcode.
  70334. **
  70335. ** If the bPush flag is true, then make this opcode the parent for
  70336. ** subsequent Explains until sqlite3VdbeExplainPop() is called.
  70337. */
  70338. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
  70339. if( pParse->explain==2 ){
  70340. char *zMsg;
  70341. Vdbe *v = pParse->pVdbe;
  70342. va_list ap;
  70343. int iThis;
  70344. va_start(ap, zFmt);
  70345. zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
  70346. va_end(ap);
  70347. v = pParse->pVdbe;
  70348. iThis = v->nOp;
  70349. sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
  70350. zMsg, P4_DYNAMIC);
  70351. if( bPush) pParse->addrExplain = iThis;
  70352. }
  70353. }
  70354. /*
  70355. ** Pop the EXPLAIN QUERY PLAN stack one level.
  70356. */
  70357. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
  70358. pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
  70359. }
  70360. #endif /* SQLITE_OMIT_EXPLAIN */
  70361. /*
  70362. ** Add an OP_ParseSchema opcode. This routine is broken out from
  70363. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  70364. ** as having been used.
  70365. **
  70366. ** The zWhere string must have been obtained from sqlite3_malloc().
  70367. ** This routine will take ownership of the allocated memory.
  70368. */
  70369. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  70370. int j;
  70371. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  70372. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  70373. }
  70374. /*
  70375. ** Add an opcode that includes the p4 value as an integer.
  70376. */
  70377. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  70378. Vdbe *p, /* Add the opcode to this VM */
  70379. int op, /* The new opcode */
  70380. int p1, /* The P1 operand */
  70381. int p2, /* The P2 operand */
  70382. int p3, /* The P3 operand */
  70383. int p4 /* The P4 operand as an integer */
  70384. ){
  70385. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  70386. if( p->db->mallocFailed==0 ){
  70387. VdbeOp *pOp = &p->aOp[addr];
  70388. pOp->p4type = P4_INT32;
  70389. pOp->p4.i = p4;
  70390. }
  70391. return addr;
  70392. }
  70393. /* Insert the end of a co-routine
  70394. */
  70395. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  70396. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  70397. /* Clear the temporary register cache, thereby ensuring that each
  70398. ** co-routine has its own independent set of registers, because co-routines
  70399. ** might expect their registers to be preserved across an OP_Yield, and
  70400. ** that could cause problems if two or more co-routines are using the same
  70401. ** temporary register.
  70402. */
  70403. v->pParse->nTempReg = 0;
  70404. v->pParse->nRangeReg = 0;
  70405. }
  70406. /*
  70407. ** Create a new symbolic label for an instruction that has yet to be
  70408. ** coded. The symbolic label is really just a negative number. The
  70409. ** label can be used as the P2 value of an operation. Later, when
  70410. ** the label is resolved to a specific address, the VDBE will scan
  70411. ** through its operation list and change all values of P2 which match
  70412. ** the label into the resolved address.
  70413. **
  70414. ** The VDBE knows that a P2 value is a label because labels are
  70415. ** always negative and P2 values are suppose to be non-negative.
  70416. ** Hence, a negative P2 value is a label that has yet to be resolved.
  70417. **
  70418. ** Zero is returned if a malloc() fails.
  70419. */
  70420. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  70421. Parse *p = v->pParse;
  70422. int i = p->nLabel++;
  70423. assert( v->magic==VDBE_MAGIC_INIT );
  70424. if( (i & (i-1))==0 ){
  70425. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  70426. (i*2+1)*sizeof(p->aLabel[0]));
  70427. }
  70428. if( p->aLabel ){
  70429. p->aLabel[i] = -1;
  70430. }
  70431. return ADDR(i);
  70432. }
  70433. /*
  70434. ** Resolve label "x" to be the address of the next instruction to
  70435. ** be inserted. The parameter "x" must have been obtained from
  70436. ** a prior call to sqlite3VdbeMakeLabel().
  70437. */
  70438. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  70439. Parse *p = v->pParse;
  70440. int j = ADDR(x);
  70441. assert( v->magic==VDBE_MAGIC_INIT );
  70442. assert( j<p->nLabel );
  70443. assert( j>=0 );
  70444. if( p->aLabel ){
  70445. #ifdef SQLITE_DEBUG
  70446. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  70447. printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
  70448. }
  70449. #endif
  70450. assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
  70451. p->aLabel[j] = v->nOp;
  70452. }
  70453. }
  70454. #ifdef SQLITE_COVERAGE_TEST
  70455. /*
  70456. ** Return TRUE if and only if the label x has already been resolved.
  70457. ** Return FALSE (zero) if label x is still unresolved.
  70458. **
  70459. ** This routine is only used inside of testcase() macros, and so it
  70460. ** only exists when measuring test coverage.
  70461. */
  70462. SQLITE_PRIVATE int sqlite3VdbeLabelHasBeenResolved(Vdbe *v, int x){
  70463. return v->pParse->aLabel && v->pParse->aLabel[ADDR(x)]>=0;
  70464. }
  70465. #endif /* SQLITE_COVERAGE_TEST */
  70466. /*
  70467. ** Mark the VDBE as one that can only be run one time.
  70468. */
  70469. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  70470. p->runOnlyOnce = 1;
  70471. }
  70472. /*
  70473. ** Mark the VDBE as one that can only be run multiple times.
  70474. */
  70475. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  70476. p->runOnlyOnce = 0;
  70477. }
  70478. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  70479. /*
  70480. ** The following type and function are used to iterate through all opcodes
  70481. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  70482. ** invoke directly or indirectly. It should be used as follows:
  70483. **
  70484. ** Op *pOp;
  70485. ** VdbeOpIter sIter;
  70486. **
  70487. ** memset(&sIter, 0, sizeof(sIter));
  70488. ** sIter.v = v; // v is of type Vdbe*
  70489. ** while( (pOp = opIterNext(&sIter)) ){
  70490. ** // Do something with pOp
  70491. ** }
  70492. ** sqlite3DbFree(v->db, sIter.apSub);
  70493. **
  70494. */
  70495. typedef struct VdbeOpIter VdbeOpIter;
  70496. struct VdbeOpIter {
  70497. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  70498. SubProgram **apSub; /* Array of subprograms */
  70499. int nSub; /* Number of entries in apSub */
  70500. int iAddr; /* Address of next instruction to return */
  70501. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  70502. };
  70503. static Op *opIterNext(VdbeOpIter *p){
  70504. Vdbe *v = p->v;
  70505. Op *pRet = 0;
  70506. Op *aOp;
  70507. int nOp;
  70508. if( p->iSub<=p->nSub ){
  70509. if( p->iSub==0 ){
  70510. aOp = v->aOp;
  70511. nOp = v->nOp;
  70512. }else{
  70513. aOp = p->apSub[p->iSub-1]->aOp;
  70514. nOp = p->apSub[p->iSub-1]->nOp;
  70515. }
  70516. assert( p->iAddr<nOp );
  70517. pRet = &aOp[p->iAddr];
  70518. p->iAddr++;
  70519. if( p->iAddr==nOp ){
  70520. p->iSub++;
  70521. p->iAddr = 0;
  70522. }
  70523. if( pRet->p4type==P4_SUBPROGRAM ){
  70524. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  70525. int j;
  70526. for(j=0; j<p->nSub; j++){
  70527. if( p->apSub[j]==pRet->p4.pProgram ) break;
  70528. }
  70529. if( j==p->nSub ){
  70530. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  70531. if( !p->apSub ){
  70532. pRet = 0;
  70533. }else{
  70534. p->apSub[p->nSub++] = pRet->p4.pProgram;
  70535. }
  70536. }
  70537. }
  70538. }
  70539. return pRet;
  70540. }
  70541. /*
  70542. ** Check if the program stored in the VM associated with pParse may
  70543. ** throw an ABORT exception (causing the statement, but not entire transaction
  70544. ** to be rolled back). This condition is true if the main program or any
  70545. ** sub-programs contains any of the following:
  70546. **
  70547. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  70548. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  70549. ** * OP_Destroy
  70550. ** * OP_VUpdate
  70551. ** * OP_VRename
  70552. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  70553. ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
  70554. ** (for CREATE TABLE AS SELECT ...)
  70555. **
  70556. ** Then check that the value of Parse.mayAbort is true if an
  70557. ** ABORT may be thrown, or false otherwise. Return true if it does
  70558. ** match, or false otherwise. This function is intended to be used as
  70559. ** part of an assert statement in the compiler. Similar to:
  70560. **
  70561. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  70562. */
  70563. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  70564. int hasAbort = 0;
  70565. int hasFkCounter = 0;
  70566. int hasCreateTable = 0;
  70567. int hasInitCoroutine = 0;
  70568. Op *pOp;
  70569. VdbeOpIter sIter;
  70570. memset(&sIter, 0, sizeof(sIter));
  70571. sIter.v = v;
  70572. while( (pOp = opIterNext(&sIter))!=0 ){
  70573. int opcode = pOp->opcode;
  70574. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  70575. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  70576. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  70577. ){
  70578. hasAbort = 1;
  70579. break;
  70580. }
  70581. if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
  70582. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  70583. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70584. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  70585. hasFkCounter = 1;
  70586. }
  70587. #endif
  70588. }
  70589. sqlite3DbFree(v->db, sIter.apSub);
  70590. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  70591. ** If malloc failed, then the while() loop above may not have iterated
  70592. ** through all opcodes and hasAbort may be set incorrectly. Return
  70593. ** true for this case to prevent the assert() in the callers frame
  70594. ** from failing. */
  70595. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  70596. || (hasCreateTable && hasInitCoroutine) );
  70597. }
  70598. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  70599. #ifdef SQLITE_DEBUG
  70600. /*
  70601. ** Increment the nWrite counter in the VDBE if the cursor is not an
  70602. ** ephemeral cursor, or if the cursor argument is NULL.
  70603. */
  70604. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
  70605. if( pC==0
  70606. || (pC->eCurType!=CURTYPE_SORTER
  70607. && pC->eCurType!=CURTYPE_PSEUDO
  70608. && !pC->isEphemeral)
  70609. ){
  70610. p->nWrite++;
  70611. }
  70612. }
  70613. #endif
  70614. #ifdef SQLITE_DEBUG
  70615. /*
  70616. ** Assert if an Abort at this point in time might result in a corrupt
  70617. ** database.
  70618. */
  70619. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
  70620. assert( p->nWrite==0 || p->usesStmtJournal );
  70621. }
  70622. #endif
  70623. /*
  70624. ** This routine is called after all opcodes have been inserted. It loops
  70625. ** through all the opcodes and fixes up some details.
  70626. **
  70627. ** (1) For each jump instruction with a negative P2 value (a label)
  70628. ** resolve the P2 value to an actual address.
  70629. **
  70630. ** (2) Compute the maximum number of arguments used by any SQL function
  70631. ** and store that value in *pMaxFuncArgs.
  70632. **
  70633. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  70634. ** indicate what the prepared statement actually does.
  70635. **
  70636. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  70637. **
  70638. ** (5) Reclaim the memory allocated for storing labels.
  70639. **
  70640. ** This routine will only function correctly if the mkopcodeh.tcl generator
  70641. ** script numbers the opcodes correctly. Changes to this routine must be
  70642. ** coordinated with changes to mkopcodeh.tcl.
  70643. */
  70644. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  70645. int nMaxArgs = *pMaxFuncArgs;
  70646. Op *pOp;
  70647. Parse *pParse = p->pParse;
  70648. int *aLabel = pParse->aLabel;
  70649. p->readOnly = 1;
  70650. p->bIsReader = 0;
  70651. pOp = &p->aOp[p->nOp-1];
  70652. while(1){
  70653. /* Only JUMP opcodes and the short list of special opcodes in the switch
  70654. ** below need to be considered. The mkopcodeh.tcl generator script groups
  70655. ** all these opcodes together near the front of the opcode list. Skip
  70656. ** any opcode that does not need processing by virtual of the fact that
  70657. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  70658. */
  70659. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  70660. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  70661. ** cases from this switch! */
  70662. switch( pOp->opcode ){
  70663. case OP_Transaction: {
  70664. if( pOp->p2!=0 ) p->readOnly = 0;
  70665. /* fall thru */
  70666. }
  70667. case OP_AutoCommit:
  70668. case OP_Savepoint: {
  70669. p->bIsReader = 1;
  70670. break;
  70671. }
  70672. #ifndef SQLITE_OMIT_WAL
  70673. case OP_Checkpoint:
  70674. #endif
  70675. case OP_Vacuum:
  70676. case OP_JournalMode: {
  70677. p->readOnly = 0;
  70678. p->bIsReader = 1;
  70679. break;
  70680. }
  70681. case OP_Next:
  70682. case OP_NextIfOpen:
  70683. case OP_SorterNext: {
  70684. pOp->p4.xAdvance = sqlite3BtreeNext;
  70685. pOp->p4type = P4_ADVANCE;
  70686. /* The code generator never codes any of these opcodes as a jump
  70687. ** to a label. They are always coded as a jump backwards to a
  70688. ** known address */
  70689. assert( pOp->p2>=0 );
  70690. break;
  70691. }
  70692. case OP_Prev:
  70693. case OP_PrevIfOpen: {
  70694. pOp->p4.xAdvance = sqlite3BtreePrevious;
  70695. pOp->p4type = P4_ADVANCE;
  70696. /* The code generator never codes any of these opcodes as a jump
  70697. ** to a label. They are always coded as a jump backwards to a
  70698. ** known address */
  70699. assert( pOp->p2>=0 );
  70700. break;
  70701. }
  70702. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70703. case OP_VUpdate: {
  70704. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  70705. break;
  70706. }
  70707. case OP_VFilter: {
  70708. int n;
  70709. assert( (pOp - p->aOp) >= 3 );
  70710. assert( pOp[-1].opcode==OP_Integer );
  70711. n = pOp[-1].p1;
  70712. if( n>nMaxArgs ) nMaxArgs = n;
  70713. /* Fall through into the default case */
  70714. }
  70715. #endif
  70716. default: {
  70717. if( pOp->p2<0 ){
  70718. /* The mkopcodeh.tcl script has so arranged things that the only
  70719. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  70720. ** have non-negative values for P2. */
  70721. assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
  70722. assert( ADDR(pOp->p2)<pParse->nLabel );
  70723. pOp->p2 = aLabel[ADDR(pOp->p2)];
  70724. }
  70725. break;
  70726. }
  70727. }
  70728. /* The mkopcodeh.tcl script has so arranged things that the only
  70729. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  70730. ** have non-negative values for P2. */
  70731. assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
  70732. }
  70733. if( pOp==p->aOp ) break;
  70734. pOp--;
  70735. }
  70736. sqlite3DbFree(p->db, pParse->aLabel);
  70737. pParse->aLabel = 0;
  70738. pParse->nLabel = 0;
  70739. *pMaxFuncArgs = nMaxArgs;
  70740. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  70741. }
  70742. /*
  70743. ** Return the address of the next instruction to be inserted.
  70744. */
  70745. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  70746. assert( p->magic==VDBE_MAGIC_INIT );
  70747. return p->nOp;
  70748. }
  70749. /*
  70750. ** Verify that at least N opcode slots are available in p without
  70751. ** having to malloc for more space (except when compiled using
  70752. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  70753. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  70754. ** fail due to a OOM fault and hence that the return value from
  70755. ** sqlite3VdbeAddOpList() will always be non-NULL.
  70756. */
  70757. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  70758. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  70759. assert( p->nOp + N <= p->pParse->nOpAlloc );
  70760. }
  70761. #endif
  70762. /*
  70763. ** Verify that the VM passed as the only argument does not contain
  70764. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  70765. ** by code in pragma.c to ensure that the implementation of certain
  70766. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  70767. ** script.
  70768. */
  70769. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  70770. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  70771. int i;
  70772. for(i=0; i<p->nOp; i++){
  70773. assert( p->aOp[i].opcode!=OP_ResultRow );
  70774. }
  70775. }
  70776. #endif
  70777. /*
  70778. ** Generate code (a single OP_Abortable opcode) that will
  70779. ** verify that the VDBE program can safely call Abort in the current
  70780. ** context.
  70781. */
  70782. #if defined(SQLITE_DEBUG)
  70783. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
  70784. if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
  70785. }
  70786. #endif
  70787. /*
  70788. ** This function returns a pointer to the array of opcodes associated with
  70789. ** the Vdbe passed as the first argument. It is the callers responsibility
  70790. ** to arrange for the returned array to be eventually freed using the
  70791. ** vdbeFreeOpArray() function.
  70792. **
  70793. ** Before returning, *pnOp is set to the number of entries in the returned
  70794. ** array. Also, *pnMaxArg is set to the larger of its current value and
  70795. ** the number of entries in the Vdbe.apArg[] array required to execute the
  70796. ** returned program.
  70797. */
  70798. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  70799. VdbeOp *aOp = p->aOp;
  70800. assert( aOp && !p->db->mallocFailed );
  70801. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  70802. assert( DbMaskAllZero(p->btreeMask) );
  70803. resolveP2Values(p, pnMaxArg);
  70804. *pnOp = p->nOp;
  70805. p->aOp = 0;
  70806. return aOp;
  70807. }
  70808. /*
  70809. ** Add a whole list of operations to the operation stack. Return a
  70810. ** pointer to the first operation inserted.
  70811. **
  70812. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  70813. ** so that the jump target is relative to the first operation inserted.
  70814. */
  70815. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  70816. Vdbe *p, /* Add opcodes to the prepared statement */
  70817. int nOp, /* Number of opcodes to add */
  70818. VdbeOpList const *aOp, /* The opcodes to be added */
  70819. int iLineno /* Source-file line number of first opcode */
  70820. ){
  70821. int i;
  70822. VdbeOp *pOut, *pFirst;
  70823. assert( nOp>0 );
  70824. assert( p->magic==VDBE_MAGIC_INIT );
  70825. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  70826. return 0;
  70827. }
  70828. pFirst = pOut = &p->aOp[p->nOp];
  70829. for(i=0; i<nOp; i++, aOp++, pOut++){
  70830. pOut->opcode = aOp->opcode;
  70831. pOut->p1 = aOp->p1;
  70832. pOut->p2 = aOp->p2;
  70833. assert( aOp->p2>=0 );
  70834. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  70835. pOut->p2 += p->nOp;
  70836. }
  70837. pOut->p3 = aOp->p3;
  70838. pOut->p4type = P4_NOTUSED;
  70839. pOut->p4.p = 0;
  70840. pOut->p5 = 0;
  70841. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  70842. pOut->zComment = 0;
  70843. #endif
  70844. #ifdef SQLITE_VDBE_COVERAGE
  70845. pOut->iSrcLine = iLineno+i;
  70846. #else
  70847. (void)iLineno;
  70848. #endif
  70849. #ifdef SQLITE_DEBUG
  70850. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  70851. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  70852. }
  70853. #endif
  70854. }
  70855. p->nOp += nOp;
  70856. return pFirst;
  70857. }
  70858. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  70859. /*
  70860. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  70861. */
  70862. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  70863. Vdbe *p, /* VM to add scanstatus() to */
  70864. int addrExplain, /* Address of OP_Explain (or 0) */
  70865. int addrLoop, /* Address of loop counter */
  70866. int addrVisit, /* Address of rows visited counter */
  70867. LogEst nEst, /* Estimated number of output rows */
  70868. const char *zName /* Name of table or index being scanned */
  70869. ){
  70870. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  70871. ScanStatus *aNew;
  70872. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  70873. if( aNew ){
  70874. ScanStatus *pNew = &aNew[p->nScan++];
  70875. pNew->addrExplain = addrExplain;
  70876. pNew->addrLoop = addrLoop;
  70877. pNew->addrVisit = addrVisit;
  70878. pNew->nEst = nEst;
  70879. pNew->zName = sqlite3DbStrDup(p->db, zName);
  70880. p->aScan = aNew;
  70881. }
  70882. }
  70883. #endif
  70884. /*
  70885. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  70886. ** for a specific instruction.
  70887. */
  70888. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  70889. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  70890. }
  70891. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  70892. sqlite3VdbeGetOp(p,addr)->p1 = val;
  70893. }
  70894. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  70895. sqlite3VdbeGetOp(p,addr)->p2 = val;
  70896. }
  70897. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  70898. sqlite3VdbeGetOp(p,addr)->p3 = val;
  70899. }
  70900. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  70901. assert( p->nOp>0 || p->db->mallocFailed );
  70902. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  70903. }
  70904. /*
  70905. ** Change the P2 operand of instruction addr so that it points to
  70906. ** the address of the next instruction to be coded.
  70907. */
  70908. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  70909. sqlite3VdbeChangeP2(p, addr, p->nOp);
  70910. }
  70911. /*
  70912. ** If the input FuncDef structure is ephemeral, then free it. If
  70913. ** the FuncDef is not ephermal, then do nothing.
  70914. */
  70915. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  70916. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  70917. sqlite3DbFreeNN(db, pDef);
  70918. }
  70919. }
  70920. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  70921. /*
  70922. ** Delete a P4 value if necessary.
  70923. */
  70924. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  70925. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  70926. sqlite3DbFreeNN(db, p);
  70927. }
  70928. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  70929. freeEphemeralFunction(db, p->pFunc);
  70930. sqlite3DbFreeNN(db, p);
  70931. }
  70932. static void freeP4(sqlite3 *db, int p4type, void *p4){
  70933. assert( db );
  70934. switch( p4type ){
  70935. case P4_FUNCCTX: {
  70936. freeP4FuncCtx(db, (sqlite3_context*)p4);
  70937. break;
  70938. }
  70939. case P4_REAL:
  70940. case P4_INT64:
  70941. case P4_DYNAMIC:
  70942. case P4_DYNBLOB:
  70943. case P4_INTARRAY: {
  70944. sqlite3DbFree(db, p4);
  70945. break;
  70946. }
  70947. case P4_KEYINFO: {
  70948. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  70949. break;
  70950. }
  70951. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  70952. case P4_EXPR: {
  70953. sqlite3ExprDelete(db, (Expr*)p4);
  70954. break;
  70955. }
  70956. #endif
  70957. case P4_FUNCDEF: {
  70958. freeEphemeralFunction(db, (FuncDef*)p4);
  70959. break;
  70960. }
  70961. case P4_MEM: {
  70962. if( db->pnBytesFreed==0 ){
  70963. sqlite3ValueFree((sqlite3_value*)p4);
  70964. }else{
  70965. freeP4Mem(db, (Mem*)p4);
  70966. }
  70967. break;
  70968. }
  70969. case P4_VTAB : {
  70970. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  70971. break;
  70972. }
  70973. }
  70974. }
  70975. /*
  70976. ** Free the space allocated for aOp and any p4 values allocated for the
  70977. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  70978. ** nOp entries.
  70979. */
  70980. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  70981. if( aOp ){
  70982. Op *pOp;
  70983. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  70984. if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
  70985. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  70986. sqlite3DbFree(db, pOp->zComment);
  70987. #endif
  70988. }
  70989. sqlite3DbFreeNN(db, aOp);
  70990. }
  70991. }
  70992. /*
  70993. ** Link the SubProgram object passed as the second argument into the linked
  70994. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  70995. ** objects when the VM is no longer required.
  70996. */
  70997. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  70998. p->pNext = pVdbe->pProgram;
  70999. pVdbe->pProgram = p;
  71000. }
  71001. /*
  71002. ** Change the opcode at addr into OP_Noop
  71003. */
  71004. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  71005. VdbeOp *pOp;
  71006. if( p->db->mallocFailed ) return 0;
  71007. assert( addr>=0 && addr<p->nOp );
  71008. pOp = &p->aOp[addr];
  71009. freeP4(p->db, pOp->p4type, pOp->p4.p);
  71010. pOp->p4type = P4_NOTUSED;
  71011. pOp->p4.z = 0;
  71012. pOp->opcode = OP_Noop;
  71013. return 1;
  71014. }
  71015. /*
  71016. ** If the last opcode is "op" and it is not a jump destination,
  71017. ** then remove it. Return true if and only if an opcode was removed.
  71018. */
  71019. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  71020. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  71021. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  71022. }else{
  71023. return 0;
  71024. }
  71025. }
  71026. /*
  71027. ** Change the value of the P4 operand for a specific instruction.
  71028. ** This routine is useful when a large program is loaded from a
  71029. ** static array using sqlite3VdbeAddOpList but we want to make a
  71030. ** few minor changes to the program.
  71031. **
  71032. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  71033. ** the string is made into memory obtained from sqlite3_malloc().
  71034. ** A value of n==0 means copy bytes of zP4 up to and including the
  71035. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  71036. **
  71037. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  71038. ** to a string or structure that is guaranteed to exist for the lifetime of
  71039. ** the Vdbe. In these cases we can just copy the pointer.
  71040. **
  71041. ** If addr<0 then change P4 on the most recently inserted instruction.
  71042. */
  71043. static void SQLITE_NOINLINE vdbeChangeP4Full(
  71044. Vdbe *p,
  71045. Op *pOp,
  71046. const char *zP4,
  71047. int n
  71048. ){
  71049. if( pOp->p4type ){
  71050. freeP4(p->db, pOp->p4type, pOp->p4.p);
  71051. pOp->p4type = 0;
  71052. pOp->p4.p = 0;
  71053. }
  71054. if( n<0 ){
  71055. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  71056. }else{
  71057. if( n==0 ) n = sqlite3Strlen30(zP4);
  71058. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  71059. pOp->p4type = P4_DYNAMIC;
  71060. }
  71061. }
  71062. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  71063. Op *pOp;
  71064. sqlite3 *db;
  71065. assert( p!=0 );
  71066. db = p->db;
  71067. assert( p->magic==VDBE_MAGIC_INIT );
  71068. assert( p->aOp!=0 || db->mallocFailed );
  71069. if( db->mallocFailed ){
  71070. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  71071. return;
  71072. }
  71073. assert( p->nOp>0 );
  71074. assert( addr<p->nOp );
  71075. if( addr<0 ){
  71076. addr = p->nOp - 1;
  71077. }
  71078. pOp = &p->aOp[addr];
  71079. if( n>=0 || pOp->p4type ){
  71080. vdbeChangeP4Full(p, pOp, zP4, n);
  71081. return;
  71082. }
  71083. if( n==P4_INT32 ){
  71084. /* Note: this cast is safe, because the origin data point was an int
  71085. ** that was cast to a (const char *). */
  71086. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  71087. pOp->p4type = P4_INT32;
  71088. }else if( zP4!=0 ){
  71089. assert( n<0 );
  71090. pOp->p4.p = (void*)zP4;
  71091. pOp->p4type = (signed char)n;
  71092. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  71093. }
  71094. }
  71095. /*
  71096. ** Change the P4 operand of the most recently coded instruction
  71097. ** to the value defined by the arguments. This is a high-speed
  71098. ** version of sqlite3VdbeChangeP4().
  71099. **
  71100. ** The P4 operand must not have been previously defined. And the new
  71101. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  71102. ** those cases.
  71103. */
  71104. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  71105. VdbeOp *pOp;
  71106. assert( n!=P4_INT32 && n!=P4_VTAB );
  71107. assert( n<=0 );
  71108. if( p->db->mallocFailed ){
  71109. freeP4(p->db, n, pP4);
  71110. }else{
  71111. assert( pP4!=0 );
  71112. assert( p->nOp>0 );
  71113. pOp = &p->aOp[p->nOp-1];
  71114. assert( pOp->p4type==P4_NOTUSED );
  71115. pOp->p4type = n;
  71116. pOp->p4.p = pP4;
  71117. }
  71118. }
  71119. /*
  71120. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  71121. ** index given.
  71122. */
  71123. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  71124. Vdbe *v = pParse->pVdbe;
  71125. KeyInfo *pKeyInfo;
  71126. assert( v!=0 );
  71127. assert( pIdx!=0 );
  71128. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  71129. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  71130. }
  71131. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71132. /*
  71133. ** Change the comment on the most recently coded instruction. Or
  71134. ** insert a No-op and add the comment to that new instruction. This
  71135. ** makes the code easier to read during debugging. None of this happens
  71136. ** in a production build.
  71137. */
  71138. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  71139. assert( p->nOp>0 || p->aOp==0 );
  71140. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  71141. if( p->nOp ){
  71142. assert( p->aOp );
  71143. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  71144. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  71145. }
  71146. }
  71147. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  71148. va_list ap;
  71149. if( p ){
  71150. va_start(ap, zFormat);
  71151. vdbeVComment(p, zFormat, ap);
  71152. va_end(ap);
  71153. }
  71154. }
  71155. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  71156. va_list ap;
  71157. if( p ){
  71158. sqlite3VdbeAddOp0(p, OP_Noop);
  71159. va_start(ap, zFormat);
  71160. vdbeVComment(p, zFormat, ap);
  71161. va_end(ap);
  71162. }
  71163. }
  71164. #endif /* NDEBUG */
  71165. #ifdef SQLITE_VDBE_COVERAGE
  71166. /*
  71167. ** Set the value if the iSrcLine field for the previously coded instruction.
  71168. */
  71169. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  71170. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  71171. }
  71172. #endif /* SQLITE_VDBE_COVERAGE */
  71173. /*
  71174. ** Return the opcode for a given address. If the address is -1, then
  71175. ** return the most recently inserted opcode.
  71176. **
  71177. ** If a memory allocation error has occurred prior to the calling of this
  71178. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  71179. ** is readable but not writable, though it is cast to a writable value.
  71180. ** The return of a dummy opcode allows the call to continue functioning
  71181. ** after an OOM fault without having to check to see if the return from
  71182. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  71183. ** dummy will never be written to. This is verified by code inspection and
  71184. ** by running with Valgrind.
  71185. */
  71186. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  71187. /* C89 specifies that the constant "dummy" will be initialized to all
  71188. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  71189. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  71190. assert( p->magic==VDBE_MAGIC_INIT );
  71191. if( addr<0 ){
  71192. addr = p->nOp - 1;
  71193. }
  71194. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  71195. if( p->db->mallocFailed ){
  71196. return (VdbeOp*)&dummy;
  71197. }else{
  71198. return &p->aOp[addr];
  71199. }
  71200. }
  71201. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  71202. /*
  71203. ** Return an integer value for one of the parameters to the opcode pOp
  71204. ** determined by character c.
  71205. */
  71206. static int translateP(char c, const Op *pOp){
  71207. if( c=='1' ) return pOp->p1;
  71208. if( c=='2' ) return pOp->p2;
  71209. if( c=='3' ) return pOp->p3;
  71210. if( c=='4' ) return pOp->p4.i;
  71211. return pOp->p5;
  71212. }
  71213. /*
  71214. ** Compute a string for the "comment" field of a VDBE opcode listing.
  71215. **
  71216. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  71217. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  71218. ** absence of other comments, this synopsis becomes the comment on the opcode.
  71219. ** Some translation occurs:
  71220. **
  71221. ** "PX" -> "r[X]"
  71222. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  71223. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  71224. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  71225. */
  71226. static int displayComment(
  71227. const Op *pOp, /* The opcode to be commented */
  71228. const char *zP4, /* Previously obtained value for P4 */
  71229. char *zTemp, /* Write result here */
  71230. int nTemp /* Space available in zTemp[] */
  71231. ){
  71232. const char *zOpName;
  71233. const char *zSynopsis;
  71234. int nOpName;
  71235. int ii, jj;
  71236. char zAlt[50];
  71237. zOpName = sqlite3OpcodeName(pOp->opcode);
  71238. nOpName = sqlite3Strlen30(zOpName);
  71239. if( zOpName[nOpName+1] ){
  71240. int seenCom = 0;
  71241. char c;
  71242. zSynopsis = zOpName += nOpName + 1;
  71243. if( strncmp(zSynopsis,"IF ",3)==0 ){
  71244. if( pOp->p5 & SQLITE_STOREP2 ){
  71245. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  71246. }else{
  71247. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  71248. }
  71249. zSynopsis = zAlt;
  71250. }
  71251. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  71252. if( c=='P' ){
  71253. c = zSynopsis[++ii];
  71254. if( c=='4' ){
  71255. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  71256. }else if( c=='X' ){
  71257. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  71258. seenCom = 1;
  71259. }else{
  71260. int v1 = translateP(c, pOp);
  71261. int v2;
  71262. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  71263. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  71264. ii += 3;
  71265. jj += sqlite3Strlen30(zTemp+jj);
  71266. v2 = translateP(zSynopsis[ii], pOp);
  71267. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  71268. ii += 2;
  71269. v2++;
  71270. }
  71271. if( v2>1 ){
  71272. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  71273. }
  71274. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  71275. ii += 4;
  71276. }
  71277. }
  71278. jj += sqlite3Strlen30(zTemp+jj);
  71279. }else{
  71280. zTemp[jj++] = c;
  71281. }
  71282. }
  71283. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  71284. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  71285. jj += sqlite3Strlen30(zTemp+jj);
  71286. }
  71287. if( jj<nTemp ) zTemp[jj] = 0;
  71288. }else if( pOp->zComment ){
  71289. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  71290. jj = sqlite3Strlen30(zTemp);
  71291. }else{
  71292. zTemp[0] = 0;
  71293. jj = 0;
  71294. }
  71295. return jj;
  71296. }
  71297. #endif /* SQLITE_DEBUG */
  71298. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  71299. /*
  71300. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  71301. ** that can be displayed in the P4 column of EXPLAIN output.
  71302. */
  71303. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  71304. const char *zOp = 0;
  71305. switch( pExpr->op ){
  71306. case TK_STRING:
  71307. sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
  71308. break;
  71309. case TK_INTEGER:
  71310. sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
  71311. break;
  71312. case TK_NULL:
  71313. sqlite3_str_appendf(p, "NULL");
  71314. break;
  71315. case TK_REGISTER: {
  71316. sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
  71317. break;
  71318. }
  71319. case TK_COLUMN: {
  71320. if( pExpr->iColumn<0 ){
  71321. sqlite3_str_appendf(p, "rowid");
  71322. }else{
  71323. sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
  71324. }
  71325. break;
  71326. }
  71327. case TK_LT: zOp = "LT"; break;
  71328. case TK_LE: zOp = "LE"; break;
  71329. case TK_GT: zOp = "GT"; break;
  71330. case TK_GE: zOp = "GE"; break;
  71331. case TK_NE: zOp = "NE"; break;
  71332. case TK_EQ: zOp = "EQ"; break;
  71333. case TK_IS: zOp = "IS"; break;
  71334. case TK_ISNOT: zOp = "ISNOT"; break;
  71335. case TK_AND: zOp = "AND"; break;
  71336. case TK_OR: zOp = "OR"; break;
  71337. case TK_PLUS: zOp = "ADD"; break;
  71338. case TK_STAR: zOp = "MUL"; break;
  71339. case TK_MINUS: zOp = "SUB"; break;
  71340. case TK_REM: zOp = "REM"; break;
  71341. case TK_BITAND: zOp = "BITAND"; break;
  71342. case TK_BITOR: zOp = "BITOR"; break;
  71343. case TK_SLASH: zOp = "DIV"; break;
  71344. case TK_LSHIFT: zOp = "LSHIFT"; break;
  71345. case TK_RSHIFT: zOp = "RSHIFT"; break;
  71346. case TK_CONCAT: zOp = "CONCAT"; break;
  71347. case TK_UMINUS: zOp = "MINUS"; break;
  71348. case TK_UPLUS: zOp = "PLUS"; break;
  71349. case TK_BITNOT: zOp = "BITNOT"; break;
  71350. case TK_NOT: zOp = "NOT"; break;
  71351. case TK_ISNULL: zOp = "ISNULL"; break;
  71352. case TK_NOTNULL: zOp = "NOTNULL"; break;
  71353. default:
  71354. sqlite3_str_appendf(p, "%s", "expr");
  71355. break;
  71356. }
  71357. if( zOp ){
  71358. sqlite3_str_appendf(p, "%s(", zOp);
  71359. displayP4Expr(p, pExpr->pLeft);
  71360. if( pExpr->pRight ){
  71361. sqlite3_str_append(p, ",", 1);
  71362. displayP4Expr(p, pExpr->pRight);
  71363. }
  71364. sqlite3_str_append(p, ")", 1);
  71365. }
  71366. }
  71367. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  71368. #if VDBE_DISPLAY_P4
  71369. /*
  71370. ** Compute a string that describes the P4 parameter for an opcode.
  71371. ** Use zTemp for any required temporary buffer space.
  71372. */
  71373. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  71374. char *zP4 = zTemp;
  71375. StrAccum x;
  71376. assert( nTemp>=20 );
  71377. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  71378. switch( pOp->p4type ){
  71379. case P4_KEYINFO: {
  71380. int j;
  71381. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  71382. assert( pKeyInfo->aSortOrder!=0 );
  71383. sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
  71384. for(j=0; j<pKeyInfo->nKeyField; j++){
  71385. CollSeq *pColl = pKeyInfo->aColl[j];
  71386. const char *zColl = pColl ? pColl->zName : "";
  71387. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  71388. sqlite3_str_appendf(&x, ",%s%s",
  71389. pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  71390. }
  71391. sqlite3_str_append(&x, ")", 1);
  71392. break;
  71393. }
  71394. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  71395. case P4_EXPR: {
  71396. displayP4Expr(&x, pOp->p4.pExpr);
  71397. break;
  71398. }
  71399. #endif
  71400. case P4_COLLSEQ: {
  71401. CollSeq *pColl = pOp->p4.pColl;
  71402. sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
  71403. break;
  71404. }
  71405. case P4_FUNCDEF: {
  71406. FuncDef *pDef = pOp->p4.pFunc;
  71407. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  71408. break;
  71409. }
  71410. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  71411. case P4_FUNCCTX: {
  71412. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  71413. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  71414. break;
  71415. }
  71416. #endif
  71417. case P4_INT64: {
  71418. sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
  71419. break;
  71420. }
  71421. case P4_INT32: {
  71422. sqlite3_str_appendf(&x, "%d", pOp->p4.i);
  71423. break;
  71424. }
  71425. case P4_REAL: {
  71426. sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
  71427. break;
  71428. }
  71429. case P4_MEM: {
  71430. Mem *pMem = pOp->p4.pMem;
  71431. if( pMem->flags & MEM_Str ){
  71432. zP4 = pMem->z;
  71433. }else if( pMem->flags & MEM_Int ){
  71434. sqlite3_str_appendf(&x, "%lld", pMem->u.i);
  71435. }else if( pMem->flags & MEM_Real ){
  71436. sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
  71437. }else if( pMem->flags & MEM_Null ){
  71438. zP4 = "NULL";
  71439. }else{
  71440. assert( pMem->flags & MEM_Blob );
  71441. zP4 = "(blob)";
  71442. }
  71443. break;
  71444. }
  71445. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71446. case P4_VTAB: {
  71447. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  71448. sqlite3_str_appendf(&x, "vtab:%p", pVtab);
  71449. break;
  71450. }
  71451. #endif
  71452. case P4_INTARRAY: {
  71453. int i;
  71454. int *ai = pOp->p4.ai;
  71455. int n = ai[0]; /* The first element of an INTARRAY is always the
  71456. ** count of the number of elements to follow */
  71457. for(i=1; i<=n; i++){
  71458. sqlite3_str_appendf(&x, ",%d", ai[i]);
  71459. }
  71460. zTemp[0] = '[';
  71461. sqlite3_str_append(&x, "]", 1);
  71462. break;
  71463. }
  71464. case P4_SUBPROGRAM: {
  71465. sqlite3_str_appendf(&x, "program");
  71466. break;
  71467. }
  71468. case P4_DYNBLOB:
  71469. case P4_ADVANCE: {
  71470. zTemp[0] = 0;
  71471. break;
  71472. }
  71473. case P4_TABLE: {
  71474. sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
  71475. break;
  71476. }
  71477. default: {
  71478. zP4 = pOp->p4.z;
  71479. if( zP4==0 ){
  71480. zP4 = zTemp;
  71481. zTemp[0] = 0;
  71482. }
  71483. }
  71484. }
  71485. sqlite3StrAccumFinish(&x);
  71486. assert( zP4!=0 );
  71487. return zP4;
  71488. }
  71489. #endif /* VDBE_DISPLAY_P4 */
  71490. /*
  71491. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  71492. **
  71493. ** The prepared statements need to know in advance the complete set of
  71494. ** attached databases that will be use. A mask of these databases
  71495. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  71496. ** p->btreeMask of databases that will require a lock.
  71497. */
  71498. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  71499. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  71500. assert( i<(int)sizeof(p->btreeMask)*8 );
  71501. DbMaskSet(p->btreeMask, i);
  71502. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  71503. DbMaskSet(p->lockMask, i);
  71504. }
  71505. }
  71506. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  71507. /*
  71508. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  71509. ** this routine obtains the mutex associated with each BtShared structure
  71510. ** that may be accessed by the VM passed as an argument. In doing so it also
  71511. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  71512. ** that the correct busy-handler callback is invoked if required.
  71513. **
  71514. ** If SQLite is not threadsafe but does support shared-cache mode, then
  71515. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  71516. ** of all of BtShared structures accessible via the database handle
  71517. ** associated with the VM.
  71518. **
  71519. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  71520. ** function is a no-op.
  71521. **
  71522. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  71523. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  71524. ** corresponding to btrees that use shared cache. Then the runtime of
  71525. ** this routine is N*N. But as N is rarely more than 1, this should not
  71526. ** be a problem.
  71527. */
  71528. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  71529. int i;
  71530. sqlite3 *db;
  71531. Db *aDb;
  71532. int nDb;
  71533. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  71534. db = p->db;
  71535. aDb = db->aDb;
  71536. nDb = db->nDb;
  71537. for(i=0; i<nDb; i++){
  71538. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  71539. sqlite3BtreeEnter(aDb[i].pBt);
  71540. }
  71541. }
  71542. }
  71543. #endif
  71544. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  71545. /*
  71546. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  71547. */
  71548. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  71549. int i;
  71550. sqlite3 *db;
  71551. Db *aDb;
  71552. int nDb;
  71553. db = p->db;
  71554. aDb = db->aDb;
  71555. nDb = db->nDb;
  71556. for(i=0; i<nDb; i++){
  71557. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  71558. sqlite3BtreeLeave(aDb[i].pBt);
  71559. }
  71560. }
  71561. }
  71562. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  71563. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  71564. vdbeLeave(p);
  71565. }
  71566. #endif
  71567. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  71568. /*
  71569. ** Print a single opcode. This routine is used for debugging only.
  71570. */
  71571. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  71572. char *zP4;
  71573. char zPtr[50];
  71574. char zCom[100];
  71575. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  71576. if( pOut==0 ) pOut = stdout;
  71577. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  71578. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71579. displayComment(pOp, zP4, zCom, sizeof(zCom));
  71580. #else
  71581. zCom[0] = 0;
  71582. #endif
  71583. /* NB: The sqlite3OpcodeName() function is implemented by code created
  71584. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  71585. ** information from the vdbe.c source text */
  71586. fprintf(pOut, zFormat1, pc,
  71587. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  71588. zCom
  71589. );
  71590. fflush(pOut);
  71591. }
  71592. #endif
  71593. /*
  71594. ** Initialize an array of N Mem element.
  71595. */
  71596. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  71597. while( (N--)>0 ){
  71598. p->db = db;
  71599. p->flags = flags;
  71600. p->szMalloc = 0;
  71601. #ifdef SQLITE_DEBUG
  71602. p->pScopyFrom = 0;
  71603. #endif
  71604. p++;
  71605. }
  71606. }
  71607. /*
  71608. ** Release an array of N Mem elements
  71609. */
  71610. static void releaseMemArray(Mem *p, int N){
  71611. if( p && N ){
  71612. Mem *pEnd = &p[N];
  71613. sqlite3 *db = p->db;
  71614. if( db->pnBytesFreed ){
  71615. do{
  71616. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  71617. }while( (++p)<pEnd );
  71618. return;
  71619. }
  71620. do{
  71621. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  71622. assert( sqlite3VdbeCheckMemInvariants(p) );
  71623. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  71624. ** that takes advantage of the fact that the memory cell value is
  71625. ** being set to NULL after releasing any dynamic resources.
  71626. **
  71627. ** The justification for duplicating code is that according to
  71628. ** callgrind, this causes a certain test case to hit the CPU 4.7
  71629. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  71630. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  71631. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  71632. ** with no indexes using a single prepared INSERT statement, bind()
  71633. ** and reset(). Inserts are grouped into a transaction.
  71634. */
  71635. testcase( p->flags & MEM_Agg );
  71636. testcase( p->flags & MEM_Dyn );
  71637. testcase( p->flags & MEM_Frame );
  71638. testcase( p->flags & MEM_RowSet );
  71639. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  71640. sqlite3VdbeMemRelease(p);
  71641. }else if( p->szMalloc ){
  71642. sqlite3DbFreeNN(db, p->zMalloc);
  71643. p->szMalloc = 0;
  71644. }
  71645. p->flags = MEM_Undefined;
  71646. }while( (++p)<pEnd );
  71647. }
  71648. }
  71649. /*
  71650. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  71651. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  71652. */
  71653. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  71654. int i;
  71655. Mem *aMem = VdbeFrameMem(p);
  71656. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  71657. for(i=0; i<p->nChildCsr; i++){
  71658. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  71659. }
  71660. releaseMemArray(aMem, p->nChildMem);
  71661. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  71662. sqlite3DbFree(p->v->db, p);
  71663. }
  71664. #ifndef SQLITE_OMIT_EXPLAIN
  71665. /*
  71666. ** Give a listing of the program in the virtual machine.
  71667. **
  71668. ** The interface is the same as sqlite3VdbeExec(). But instead of
  71669. ** running the code, it invokes the callback once for each instruction.
  71670. ** This feature is used to implement "EXPLAIN".
  71671. **
  71672. ** When p->explain==1, each instruction is listed. When
  71673. ** p->explain==2, only OP_Explain instructions are listed and these
  71674. ** are shown in a different format. p->explain==2 is used to implement
  71675. ** EXPLAIN QUERY PLAN.
  71676. ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
  71677. ** are also shown, so that the boundaries between the main program and
  71678. ** each trigger are clear.
  71679. **
  71680. ** When p->explain==1, first the main program is listed, then each of
  71681. ** the trigger subprograms are listed one by one.
  71682. */
  71683. SQLITE_PRIVATE int sqlite3VdbeList(
  71684. Vdbe *p /* The VDBE */
  71685. ){
  71686. int nRow; /* Stop when row count reaches this */
  71687. int nSub = 0; /* Number of sub-vdbes seen so far */
  71688. SubProgram **apSub = 0; /* Array of sub-vdbes */
  71689. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  71690. sqlite3 *db = p->db; /* The database connection */
  71691. int i; /* Loop counter */
  71692. int rc = SQLITE_OK; /* Return code */
  71693. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  71694. int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
  71695. Op *pOp = 0;
  71696. assert( p->explain );
  71697. assert( p->magic==VDBE_MAGIC_RUN );
  71698. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  71699. /* Even though this opcode does not use dynamic strings for
  71700. ** the result, result columns may become dynamic if the user calls
  71701. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  71702. */
  71703. releaseMemArray(pMem, 8);
  71704. p->pResultSet = 0;
  71705. if( p->rc==SQLITE_NOMEM ){
  71706. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  71707. ** sqlite3_column_text16() failed. */
  71708. sqlite3OomFault(db);
  71709. return SQLITE_ERROR;
  71710. }
  71711. /* When the number of output rows reaches nRow, that means the
  71712. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  71713. ** nRow is the sum of the number of rows in the main program, plus
  71714. ** the sum of the number of rows in all trigger subprograms encountered
  71715. ** so far. The nRow value will increase as new trigger subprograms are
  71716. ** encountered, but p->pc will eventually catch up to nRow.
  71717. */
  71718. nRow = p->nOp;
  71719. if( bListSubprogs ){
  71720. /* The first 8 memory cells are used for the result set. So we will
  71721. ** commandeer the 9th cell to use as storage for an array of pointers
  71722. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  71723. ** cells. */
  71724. assert( p->nMem>9 );
  71725. pSub = &p->aMem[9];
  71726. if( pSub->flags&MEM_Blob ){
  71727. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  71728. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  71729. nSub = pSub->n/sizeof(Vdbe*);
  71730. apSub = (SubProgram **)pSub->z;
  71731. }
  71732. for(i=0; i<nSub; i++){
  71733. nRow += apSub[i]->nOp;
  71734. }
  71735. }
  71736. while(1){ /* Loop exits via break */
  71737. i = p->pc++;
  71738. if( i>=nRow ){
  71739. p->rc = SQLITE_OK;
  71740. rc = SQLITE_DONE;
  71741. break;
  71742. }
  71743. if( i<p->nOp ){
  71744. /* The output line number is small enough that we are still in the
  71745. ** main program. */
  71746. pOp = &p->aOp[i];
  71747. }else{
  71748. /* We are currently listing subprograms. Figure out which one and
  71749. ** pick up the appropriate opcode. */
  71750. int j;
  71751. i -= p->nOp;
  71752. for(j=0; i>=apSub[j]->nOp; j++){
  71753. i -= apSub[j]->nOp;
  71754. }
  71755. pOp = &apSub[j]->aOp[i];
  71756. }
  71757. /* When an OP_Program opcode is encounter (the only opcode that has
  71758. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  71759. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  71760. ** has not already been seen.
  71761. */
  71762. if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
  71763. int nByte = (nSub+1)*sizeof(SubProgram*);
  71764. int j;
  71765. for(j=0; j<nSub; j++){
  71766. if( apSub[j]==pOp->p4.pProgram ) break;
  71767. }
  71768. if( j==nSub ){
  71769. p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
  71770. if( p->rc!=SQLITE_OK ){
  71771. rc = SQLITE_ERROR;
  71772. break;
  71773. }
  71774. apSub = (SubProgram **)pSub->z;
  71775. apSub[nSub++] = pOp->p4.pProgram;
  71776. pSub->flags |= MEM_Blob;
  71777. pSub->n = nSub*sizeof(SubProgram*);
  71778. nRow += pOp->p4.pProgram->nOp;
  71779. }
  71780. }
  71781. if( p->explain<2 ) break;
  71782. if( pOp->opcode==OP_Explain ) break;
  71783. if( pOp->opcode==OP_Init && p->pc>1 ) break;
  71784. }
  71785. if( rc==SQLITE_OK ){
  71786. if( db->u1.isInterrupted ){
  71787. p->rc = SQLITE_INTERRUPT;
  71788. rc = SQLITE_ERROR;
  71789. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  71790. }else{
  71791. char *zP4;
  71792. if( p->explain==1 ){
  71793. pMem->flags = MEM_Int;
  71794. pMem->u.i = i; /* Program counter */
  71795. pMem++;
  71796. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  71797. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  71798. assert( pMem->z!=0 );
  71799. pMem->n = sqlite3Strlen30(pMem->z);
  71800. pMem->enc = SQLITE_UTF8;
  71801. pMem++;
  71802. }
  71803. pMem->flags = MEM_Int;
  71804. pMem->u.i = pOp->p1; /* P1 */
  71805. pMem++;
  71806. pMem->flags = MEM_Int;
  71807. pMem->u.i = pOp->p2; /* P2 */
  71808. pMem++;
  71809. pMem->flags = MEM_Int;
  71810. pMem->u.i = pOp->p3; /* P3 */
  71811. pMem++;
  71812. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  71813. assert( p->db->mallocFailed );
  71814. return SQLITE_ERROR;
  71815. }
  71816. pMem->flags = MEM_Str|MEM_Term;
  71817. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  71818. if( zP4!=pMem->z ){
  71819. pMem->n = 0;
  71820. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  71821. }else{
  71822. assert( pMem->z!=0 );
  71823. pMem->n = sqlite3Strlen30(pMem->z);
  71824. pMem->enc = SQLITE_UTF8;
  71825. }
  71826. pMem++;
  71827. if( p->explain==1 ){
  71828. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  71829. assert( p->db->mallocFailed );
  71830. return SQLITE_ERROR;
  71831. }
  71832. pMem->flags = MEM_Str|MEM_Term;
  71833. pMem->n = 2;
  71834. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  71835. pMem->enc = SQLITE_UTF8;
  71836. pMem++;
  71837. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71838. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  71839. assert( p->db->mallocFailed );
  71840. return SQLITE_ERROR;
  71841. }
  71842. pMem->flags = MEM_Str|MEM_Term;
  71843. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  71844. pMem->enc = SQLITE_UTF8;
  71845. #else
  71846. pMem->flags = MEM_Null; /* Comment */
  71847. #endif
  71848. }
  71849. p->nResColumn = 8 - 4*(p->explain-1);
  71850. p->pResultSet = &p->aMem[1];
  71851. p->rc = SQLITE_OK;
  71852. rc = SQLITE_ROW;
  71853. }
  71854. }
  71855. return rc;
  71856. }
  71857. #endif /* SQLITE_OMIT_EXPLAIN */
  71858. #ifdef SQLITE_DEBUG
  71859. /*
  71860. ** Print the SQL that was used to generate a VDBE program.
  71861. */
  71862. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  71863. const char *z = 0;
  71864. if( p->zSql ){
  71865. z = p->zSql;
  71866. }else if( p->nOp>=1 ){
  71867. const VdbeOp *pOp = &p->aOp[0];
  71868. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  71869. z = pOp->p4.z;
  71870. while( sqlite3Isspace(*z) ) z++;
  71871. }
  71872. }
  71873. if( z ) printf("SQL: [%s]\n", z);
  71874. }
  71875. #endif
  71876. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  71877. /*
  71878. ** Print an IOTRACE message showing SQL content.
  71879. */
  71880. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  71881. int nOp = p->nOp;
  71882. VdbeOp *pOp;
  71883. if( sqlite3IoTrace==0 ) return;
  71884. if( nOp<1 ) return;
  71885. pOp = &p->aOp[0];
  71886. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  71887. int i, j;
  71888. char z[1000];
  71889. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  71890. for(i=0; sqlite3Isspace(z[i]); i++){}
  71891. for(j=0; z[i]; i++){
  71892. if( sqlite3Isspace(z[i]) ){
  71893. if( z[i-1]!=' ' ){
  71894. z[j++] = ' ';
  71895. }
  71896. }else{
  71897. z[j++] = z[i];
  71898. }
  71899. }
  71900. z[j] = 0;
  71901. sqlite3IoTrace("SQL %s\n", z);
  71902. }
  71903. }
  71904. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  71905. /* An instance of this object describes bulk memory available for use
  71906. ** by subcomponents of a prepared statement. Space is allocated out
  71907. ** of a ReusableSpace object by the allocSpace() routine below.
  71908. */
  71909. struct ReusableSpace {
  71910. u8 *pSpace; /* Available memory */
  71911. int nFree; /* Bytes of available memory */
  71912. int nNeeded; /* Total bytes that could not be allocated */
  71913. };
  71914. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  71915. ** from the ReusableSpace object. Return a pointer to the allocated
  71916. ** memory on success. If insufficient memory is available in the
  71917. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  71918. ** value by the amount needed and return NULL.
  71919. **
  71920. ** If pBuf is not initially NULL, that means that the memory has already
  71921. ** been allocated by a prior call to this routine, so just return a copy
  71922. ** of pBuf and leave ReusableSpace unchanged.
  71923. **
  71924. ** This allocator is employed to repurpose unused slots at the end of the
  71925. ** opcode array of prepared state for other memory needs of the prepared
  71926. ** statement.
  71927. */
  71928. static void *allocSpace(
  71929. struct ReusableSpace *p, /* Bulk memory available for allocation */
  71930. void *pBuf, /* Pointer to a prior allocation */
  71931. int nByte /* Bytes of memory needed */
  71932. ){
  71933. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  71934. if( pBuf==0 ){
  71935. nByte = ROUND8(nByte);
  71936. if( nByte <= p->nFree ){
  71937. p->nFree -= nByte;
  71938. pBuf = &p->pSpace[p->nFree];
  71939. }else{
  71940. p->nNeeded += nByte;
  71941. }
  71942. }
  71943. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  71944. return pBuf;
  71945. }
  71946. /*
  71947. ** Rewind the VDBE back to the beginning in preparation for
  71948. ** running it.
  71949. */
  71950. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  71951. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  71952. int i;
  71953. #endif
  71954. assert( p!=0 );
  71955. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  71956. /* There should be at least one opcode.
  71957. */
  71958. assert( p->nOp>0 );
  71959. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  71960. p->magic = VDBE_MAGIC_RUN;
  71961. #ifdef SQLITE_DEBUG
  71962. for(i=0; i<p->nMem; i++){
  71963. assert( p->aMem[i].db==p->db );
  71964. }
  71965. #endif
  71966. p->pc = -1;
  71967. p->rc = SQLITE_OK;
  71968. p->errorAction = OE_Abort;
  71969. p->nChange = 0;
  71970. p->cacheCtr = 1;
  71971. p->minWriteFileFormat = 255;
  71972. p->iStatement = 0;
  71973. p->nFkConstraint = 0;
  71974. #ifdef VDBE_PROFILE
  71975. for(i=0; i<p->nOp; i++){
  71976. p->aOp[i].cnt = 0;
  71977. p->aOp[i].cycles = 0;
  71978. }
  71979. #endif
  71980. }
  71981. /*
  71982. ** Prepare a virtual machine for execution for the first time after
  71983. ** creating the virtual machine. This involves things such
  71984. ** as allocating registers and initializing the program counter.
  71985. ** After the VDBE has be prepped, it can be executed by one or more
  71986. ** calls to sqlite3VdbeExec().
  71987. **
  71988. ** This function may be called exactly once on each virtual machine.
  71989. ** After this routine is called the VM has been "packaged" and is ready
  71990. ** to run. After this routine is called, further calls to
  71991. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  71992. ** the Vdbe from the Parse object that helped generate it so that the
  71993. ** the Vdbe becomes an independent entity and the Parse object can be
  71994. ** destroyed.
  71995. **
  71996. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  71997. ** to its initial state after it has been run.
  71998. */
  71999. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  72000. Vdbe *p, /* The VDBE */
  72001. Parse *pParse /* Parsing context */
  72002. ){
  72003. sqlite3 *db; /* The database connection */
  72004. int nVar; /* Number of parameters */
  72005. int nMem; /* Number of VM memory registers */
  72006. int nCursor; /* Number of cursors required */
  72007. int nArg; /* Number of arguments in subprograms */
  72008. int n; /* Loop counter */
  72009. struct ReusableSpace x; /* Reusable bulk memory */
  72010. assert( p!=0 );
  72011. assert( p->nOp>0 );
  72012. assert( pParse!=0 );
  72013. assert( p->magic==VDBE_MAGIC_INIT );
  72014. assert( pParse==p->pParse );
  72015. db = p->db;
  72016. assert( db->mallocFailed==0 );
  72017. nVar = pParse->nVar;
  72018. nMem = pParse->nMem;
  72019. nCursor = pParse->nTab;
  72020. nArg = pParse->nMaxArg;
  72021. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  72022. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  72023. ** space at the end of aMem[] for cursors 1 and greater.
  72024. ** See also: allocateCursor().
  72025. */
  72026. nMem += nCursor;
  72027. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  72028. /* Figure out how much reusable memory is available at the end of the
  72029. ** opcode array. This extra memory will be reallocated for other elements
  72030. ** of the prepared statement.
  72031. */
  72032. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  72033. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  72034. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  72035. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  72036. assert( x.nFree>=0 );
  72037. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  72038. resolveP2Values(p, &nArg);
  72039. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  72040. if( pParse->explain && nMem<10 ){
  72041. nMem = 10;
  72042. }
  72043. p->expired = 0;
  72044. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  72045. ** passes. On the first pass, we try to reuse unused memory at the
  72046. ** end of the opcode array. If we are unable to satisfy all memory
  72047. ** requirements by reusing the opcode array tail, then the second
  72048. ** pass will fill in the remainder using a fresh memory allocation.
  72049. **
  72050. ** This two-pass approach that reuses as much memory as possible from
  72051. ** the leftover memory at the end of the opcode array. This can significantly
  72052. ** reduce the amount of memory held by a prepared statement.
  72053. */
  72054. do {
  72055. x.nNeeded = 0;
  72056. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  72057. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  72058. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  72059. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  72060. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72061. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  72062. #endif
  72063. if( x.nNeeded==0 ) break;
  72064. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  72065. x.nFree = x.nNeeded;
  72066. }while( !db->mallocFailed );
  72067. p->pVList = pParse->pVList;
  72068. pParse->pVList = 0;
  72069. p->explain = pParse->explain;
  72070. if( db->mallocFailed ){
  72071. p->nVar = 0;
  72072. p->nCursor = 0;
  72073. p->nMem = 0;
  72074. }else{
  72075. p->nCursor = nCursor;
  72076. p->nVar = (ynVar)nVar;
  72077. initMemArray(p->aVar, nVar, db, MEM_Null);
  72078. p->nMem = nMem;
  72079. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  72080. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  72081. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72082. memset(p->anExec, 0, p->nOp*sizeof(i64));
  72083. #endif
  72084. }
  72085. sqlite3VdbeRewind(p);
  72086. }
  72087. /*
  72088. ** Close a VDBE cursor and release all the resources that cursor
  72089. ** happens to hold.
  72090. */
  72091. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  72092. if( pCx==0 ){
  72093. return;
  72094. }
  72095. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  72096. switch( pCx->eCurType ){
  72097. case CURTYPE_SORTER: {
  72098. sqlite3VdbeSorterClose(p->db, pCx);
  72099. break;
  72100. }
  72101. case CURTYPE_BTREE: {
  72102. if( pCx->isEphemeral ){
  72103. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  72104. /* The pCx->pCursor will be close automatically, if it exists, by
  72105. ** the call above. */
  72106. }else{
  72107. assert( pCx->uc.pCursor!=0 );
  72108. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  72109. }
  72110. break;
  72111. }
  72112. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72113. case CURTYPE_VTAB: {
  72114. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  72115. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  72116. assert( pVCur->pVtab->nRef>0 );
  72117. pVCur->pVtab->nRef--;
  72118. pModule->xClose(pVCur);
  72119. break;
  72120. }
  72121. #endif
  72122. }
  72123. }
  72124. /*
  72125. ** Close all cursors in the current frame.
  72126. */
  72127. static void closeCursorsInFrame(Vdbe *p){
  72128. if( p->apCsr ){
  72129. int i;
  72130. for(i=0; i<p->nCursor; i++){
  72131. VdbeCursor *pC = p->apCsr[i];
  72132. if( pC ){
  72133. sqlite3VdbeFreeCursor(p, pC);
  72134. p->apCsr[i] = 0;
  72135. }
  72136. }
  72137. }
  72138. }
  72139. /*
  72140. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  72141. ** is used, for example, when a trigger sub-program is halted to restore
  72142. ** control to the main program.
  72143. */
  72144. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  72145. Vdbe *v = pFrame->v;
  72146. closeCursorsInFrame(v);
  72147. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72148. v->anExec = pFrame->anExec;
  72149. #endif
  72150. v->aOp = pFrame->aOp;
  72151. v->nOp = pFrame->nOp;
  72152. v->aMem = pFrame->aMem;
  72153. v->nMem = pFrame->nMem;
  72154. v->apCsr = pFrame->apCsr;
  72155. v->nCursor = pFrame->nCursor;
  72156. v->db->lastRowid = pFrame->lastRowid;
  72157. v->nChange = pFrame->nChange;
  72158. v->db->nChange = pFrame->nDbChange;
  72159. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  72160. v->pAuxData = pFrame->pAuxData;
  72161. pFrame->pAuxData = 0;
  72162. return pFrame->pc;
  72163. }
  72164. /*
  72165. ** Close all cursors.
  72166. **
  72167. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  72168. ** cell array. This is necessary as the memory cell array may contain
  72169. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  72170. ** open cursors.
  72171. */
  72172. static void closeAllCursors(Vdbe *p){
  72173. if( p->pFrame ){
  72174. VdbeFrame *pFrame;
  72175. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  72176. sqlite3VdbeFrameRestore(pFrame);
  72177. p->pFrame = 0;
  72178. p->nFrame = 0;
  72179. }
  72180. assert( p->nFrame==0 );
  72181. closeCursorsInFrame(p);
  72182. if( p->aMem ){
  72183. releaseMemArray(p->aMem, p->nMem);
  72184. }
  72185. while( p->pDelFrame ){
  72186. VdbeFrame *pDel = p->pDelFrame;
  72187. p->pDelFrame = pDel->pParent;
  72188. sqlite3VdbeFrameDelete(pDel);
  72189. }
  72190. /* Delete any auxdata allocations made by the VM */
  72191. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  72192. assert( p->pAuxData==0 );
  72193. }
  72194. /*
  72195. ** Set the number of result columns that will be returned by this SQL
  72196. ** statement. This is now set at compile time, rather than during
  72197. ** execution of the vdbe program so that sqlite3_column_count() can
  72198. ** be called on an SQL statement before sqlite3_step().
  72199. */
  72200. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  72201. int n;
  72202. sqlite3 *db = p->db;
  72203. if( p->nResColumn ){
  72204. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  72205. sqlite3DbFree(db, p->aColName);
  72206. }
  72207. n = nResColumn*COLNAME_N;
  72208. p->nResColumn = (u16)nResColumn;
  72209. p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  72210. if( p->aColName==0 ) return;
  72211. initMemArray(p->aColName, n, db, MEM_Null);
  72212. }
  72213. /*
  72214. ** Set the name of the idx'th column to be returned by the SQL statement.
  72215. ** zName must be a pointer to a nul terminated string.
  72216. **
  72217. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  72218. **
  72219. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  72220. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  72221. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  72222. */
  72223. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  72224. Vdbe *p, /* Vdbe being configured */
  72225. int idx, /* Index of column zName applies to */
  72226. int var, /* One of the COLNAME_* constants */
  72227. const char *zName, /* Pointer to buffer containing name */
  72228. void (*xDel)(void*) /* Memory management strategy for zName */
  72229. ){
  72230. int rc;
  72231. Mem *pColName;
  72232. assert( idx<p->nResColumn );
  72233. assert( var<COLNAME_N );
  72234. if( p->db->mallocFailed ){
  72235. assert( !zName || xDel!=SQLITE_DYNAMIC );
  72236. return SQLITE_NOMEM_BKPT;
  72237. }
  72238. assert( p->aColName!=0 );
  72239. pColName = &(p->aColName[idx+var*p->nResColumn]);
  72240. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  72241. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  72242. return rc;
  72243. }
  72244. /*
  72245. ** A read or write transaction may or may not be active on database handle
  72246. ** db. If a transaction is active, commit it. If there is a
  72247. ** write-transaction spanning more than one database file, this routine
  72248. ** takes care of the master journal trickery.
  72249. */
  72250. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  72251. int i;
  72252. int nTrans = 0; /* Number of databases with an active write-transaction
  72253. ** that are candidates for a two-phase commit using a
  72254. ** master-journal */
  72255. int rc = SQLITE_OK;
  72256. int needXcommit = 0;
  72257. #ifdef SQLITE_OMIT_VIRTUALTABLE
  72258. /* With this option, sqlite3VtabSync() is defined to be simply
  72259. ** SQLITE_OK so p is not used.
  72260. */
  72261. UNUSED_PARAMETER(p);
  72262. #endif
  72263. /* Before doing anything else, call the xSync() callback for any
  72264. ** virtual module tables written in this transaction. This has to
  72265. ** be done before determining whether a master journal file is
  72266. ** required, as an xSync() callback may add an attached database
  72267. ** to the transaction.
  72268. */
  72269. rc = sqlite3VtabSync(db, p);
  72270. /* This loop determines (a) if the commit hook should be invoked and
  72271. ** (b) how many database files have open write transactions, not
  72272. ** including the temp database. (b) is important because if more than
  72273. ** one database file has an open write transaction, a master journal
  72274. ** file is required for an atomic commit.
  72275. */
  72276. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  72277. Btree *pBt = db->aDb[i].pBt;
  72278. if( sqlite3BtreeIsInTrans(pBt) ){
  72279. /* Whether or not a database might need a master journal depends upon
  72280. ** its journal mode (among other things). This matrix determines which
  72281. ** journal modes use a master journal and which do not */
  72282. static const u8 aMJNeeded[] = {
  72283. /* DELETE */ 1,
  72284. /* PERSIST */ 1,
  72285. /* OFF */ 0,
  72286. /* TRUNCATE */ 1,
  72287. /* MEMORY */ 0,
  72288. /* WAL */ 0
  72289. };
  72290. Pager *pPager; /* Pager associated with pBt */
  72291. needXcommit = 1;
  72292. sqlite3BtreeEnter(pBt);
  72293. pPager = sqlite3BtreePager(pBt);
  72294. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  72295. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  72296. && sqlite3PagerIsMemdb(pPager)==0
  72297. ){
  72298. assert( i!=1 );
  72299. nTrans++;
  72300. }
  72301. rc = sqlite3PagerExclusiveLock(pPager);
  72302. sqlite3BtreeLeave(pBt);
  72303. }
  72304. }
  72305. if( rc!=SQLITE_OK ){
  72306. return rc;
  72307. }
  72308. /* If there are any write-transactions at all, invoke the commit hook */
  72309. if( needXcommit && db->xCommitCallback ){
  72310. rc = db->xCommitCallback(db->pCommitArg);
  72311. if( rc ){
  72312. return SQLITE_CONSTRAINT_COMMITHOOK;
  72313. }
  72314. }
  72315. /* The simple case - no more than one database file (not counting the
  72316. ** TEMP database) has a transaction active. There is no need for the
  72317. ** master-journal.
  72318. **
  72319. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  72320. ** string, it means the main database is :memory: or a temp file. In
  72321. ** that case we do not support atomic multi-file commits, so use the
  72322. ** simple case then too.
  72323. */
  72324. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  72325. || nTrans<=1
  72326. ){
  72327. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  72328. Btree *pBt = db->aDb[i].pBt;
  72329. if( pBt ){
  72330. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  72331. }
  72332. }
  72333. /* Do the commit only if all databases successfully complete phase 1.
  72334. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  72335. ** IO error while deleting or truncating a journal file. It is unlikely,
  72336. ** but could happen. In this case abandon processing and return the error.
  72337. */
  72338. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  72339. Btree *pBt = db->aDb[i].pBt;
  72340. if( pBt ){
  72341. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  72342. }
  72343. }
  72344. if( rc==SQLITE_OK ){
  72345. sqlite3VtabCommit(db);
  72346. }
  72347. }
  72348. /* The complex case - There is a multi-file write-transaction active.
  72349. ** This requires a master journal file to ensure the transaction is
  72350. ** committed atomically.
  72351. */
  72352. #ifndef SQLITE_OMIT_DISKIO
  72353. else{
  72354. sqlite3_vfs *pVfs = db->pVfs;
  72355. char *zMaster = 0; /* File-name for the master journal */
  72356. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  72357. sqlite3_file *pMaster = 0;
  72358. i64 offset = 0;
  72359. int res;
  72360. int retryCount = 0;
  72361. int nMainFile;
  72362. /* Select a master journal file name */
  72363. nMainFile = sqlite3Strlen30(zMainFile);
  72364. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  72365. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  72366. do {
  72367. u32 iRandom;
  72368. if( retryCount ){
  72369. if( retryCount>100 ){
  72370. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  72371. sqlite3OsDelete(pVfs, zMaster, 0);
  72372. break;
  72373. }else if( retryCount==1 ){
  72374. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  72375. }
  72376. }
  72377. retryCount++;
  72378. sqlite3_randomness(sizeof(iRandom), &iRandom);
  72379. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  72380. (iRandom>>8)&0xffffff, iRandom&0xff);
  72381. /* The antipenultimate character of the master journal name must
  72382. ** be "9" to avoid name collisions when using 8+3 filenames. */
  72383. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  72384. sqlite3FileSuffix3(zMainFile, zMaster);
  72385. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  72386. }while( rc==SQLITE_OK && res );
  72387. if( rc==SQLITE_OK ){
  72388. /* Open the master journal. */
  72389. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  72390. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  72391. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  72392. );
  72393. }
  72394. if( rc!=SQLITE_OK ){
  72395. sqlite3DbFree(db, zMaster);
  72396. return rc;
  72397. }
  72398. /* Write the name of each database file in the transaction into the new
  72399. ** master journal file. If an error occurs at this point close
  72400. ** and delete the master journal file. All the individual journal files
  72401. ** still have 'null' as the master journal pointer, so they will roll
  72402. ** back independently if a failure occurs.
  72403. */
  72404. for(i=0; i<db->nDb; i++){
  72405. Btree *pBt = db->aDb[i].pBt;
  72406. if( sqlite3BtreeIsInTrans(pBt) ){
  72407. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  72408. if( zFile==0 ){
  72409. continue; /* Ignore TEMP and :memory: databases */
  72410. }
  72411. assert( zFile[0]!=0 );
  72412. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  72413. offset += sqlite3Strlen30(zFile)+1;
  72414. if( rc!=SQLITE_OK ){
  72415. sqlite3OsCloseFree(pMaster);
  72416. sqlite3OsDelete(pVfs, zMaster, 0);
  72417. sqlite3DbFree(db, zMaster);
  72418. return rc;
  72419. }
  72420. }
  72421. }
  72422. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  72423. ** flag is set this is not required.
  72424. */
  72425. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  72426. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  72427. ){
  72428. sqlite3OsCloseFree(pMaster);
  72429. sqlite3OsDelete(pVfs, zMaster, 0);
  72430. sqlite3DbFree(db, zMaster);
  72431. return rc;
  72432. }
  72433. /* Sync all the db files involved in the transaction. The same call
  72434. ** sets the master journal pointer in each individual journal. If
  72435. ** an error occurs here, do not delete the master journal file.
  72436. **
  72437. ** If the error occurs during the first call to
  72438. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  72439. ** master journal file will be orphaned. But we cannot delete it,
  72440. ** in case the master journal file name was written into the journal
  72441. ** file before the failure occurred.
  72442. */
  72443. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  72444. Btree *pBt = db->aDb[i].pBt;
  72445. if( pBt ){
  72446. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  72447. }
  72448. }
  72449. sqlite3OsCloseFree(pMaster);
  72450. assert( rc!=SQLITE_BUSY );
  72451. if( rc!=SQLITE_OK ){
  72452. sqlite3DbFree(db, zMaster);
  72453. return rc;
  72454. }
  72455. /* Delete the master journal file. This commits the transaction. After
  72456. ** doing this the directory is synced again before any individual
  72457. ** transaction files are deleted.
  72458. */
  72459. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  72460. sqlite3DbFree(db, zMaster);
  72461. zMaster = 0;
  72462. if( rc ){
  72463. return rc;
  72464. }
  72465. /* All files and directories have already been synced, so the following
  72466. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  72467. ** deleting or truncating journals. If something goes wrong while
  72468. ** this is happening we don't really care. The integrity of the
  72469. ** transaction is already guaranteed, but some stray 'cold' journals
  72470. ** may be lying around. Returning an error code won't help matters.
  72471. */
  72472. disable_simulated_io_errors();
  72473. sqlite3BeginBenignMalloc();
  72474. for(i=0; i<db->nDb; i++){
  72475. Btree *pBt = db->aDb[i].pBt;
  72476. if( pBt ){
  72477. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  72478. }
  72479. }
  72480. sqlite3EndBenignMalloc();
  72481. enable_simulated_io_errors();
  72482. sqlite3VtabCommit(db);
  72483. }
  72484. #endif
  72485. return rc;
  72486. }
  72487. /*
  72488. ** This routine checks that the sqlite3.nVdbeActive count variable
  72489. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  72490. ** currently active. An assertion fails if the two counts do not match.
  72491. ** This is an internal self-check only - it is not an essential processing
  72492. ** step.
  72493. **
  72494. ** This is a no-op if NDEBUG is defined.
  72495. */
  72496. #ifndef NDEBUG
  72497. static void checkActiveVdbeCnt(sqlite3 *db){
  72498. Vdbe *p;
  72499. int cnt = 0;
  72500. int nWrite = 0;
  72501. int nRead = 0;
  72502. p = db->pVdbe;
  72503. while( p ){
  72504. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  72505. cnt++;
  72506. if( p->readOnly==0 ) nWrite++;
  72507. if( p->bIsReader ) nRead++;
  72508. }
  72509. p = p->pNext;
  72510. }
  72511. assert( cnt==db->nVdbeActive );
  72512. assert( nWrite==db->nVdbeWrite );
  72513. assert( nRead==db->nVdbeRead );
  72514. }
  72515. #else
  72516. #define checkActiveVdbeCnt(x)
  72517. #endif
  72518. /*
  72519. ** If the Vdbe passed as the first argument opened a statement-transaction,
  72520. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  72521. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  72522. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  72523. ** statement transaction is committed.
  72524. **
  72525. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  72526. ** Otherwise SQLITE_OK.
  72527. */
  72528. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  72529. sqlite3 *const db = p->db;
  72530. int rc = SQLITE_OK;
  72531. int i;
  72532. const int iSavepoint = p->iStatement-1;
  72533. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  72534. assert( db->nStatement>0 );
  72535. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  72536. for(i=0; i<db->nDb; i++){
  72537. int rc2 = SQLITE_OK;
  72538. Btree *pBt = db->aDb[i].pBt;
  72539. if( pBt ){
  72540. if( eOp==SAVEPOINT_ROLLBACK ){
  72541. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  72542. }
  72543. if( rc2==SQLITE_OK ){
  72544. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  72545. }
  72546. if( rc==SQLITE_OK ){
  72547. rc = rc2;
  72548. }
  72549. }
  72550. }
  72551. db->nStatement--;
  72552. p->iStatement = 0;
  72553. if( rc==SQLITE_OK ){
  72554. if( eOp==SAVEPOINT_ROLLBACK ){
  72555. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  72556. }
  72557. if( rc==SQLITE_OK ){
  72558. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  72559. }
  72560. }
  72561. /* If the statement transaction is being rolled back, also restore the
  72562. ** database handles deferred constraint counter to the value it had when
  72563. ** the statement transaction was opened. */
  72564. if( eOp==SAVEPOINT_ROLLBACK ){
  72565. db->nDeferredCons = p->nStmtDefCons;
  72566. db->nDeferredImmCons = p->nStmtDefImmCons;
  72567. }
  72568. return rc;
  72569. }
  72570. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  72571. if( p->db->nStatement && p->iStatement ){
  72572. return vdbeCloseStatement(p, eOp);
  72573. }
  72574. return SQLITE_OK;
  72575. }
  72576. /*
  72577. ** This function is called when a transaction opened by the database
  72578. ** handle associated with the VM passed as an argument is about to be
  72579. ** committed. If there are outstanding deferred foreign key constraint
  72580. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  72581. **
  72582. ** If there are outstanding FK violations and this function returns
  72583. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  72584. ** and write an error message to it. Then return SQLITE_ERROR.
  72585. */
  72586. #ifndef SQLITE_OMIT_FOREIGN_KEY
  72587. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  72588. sqlite3 *db = p->db;
  72589. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  72590. || (!deferred && p->nFkConstraint>0)
  72591. ){
  72592. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  72593. p->errorAction = OE_Abort;
  72594. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  72595. return SQLITE_ERROR;
  72596. }
  72597. return SQLITE_OK;
  72598. }
  72599. #endif
  72600. /*
  72601. ** This routine is called the when a VDBE tries to halt. If the VDBE
  72602. ** has made changes and is in autocommit mode, then commit those
  72603. ** changes. If a rollback is needed, then do the rollback.
  72604. **
  72605. ** This routine is the only way to move the state of a VM from
  72606. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  72607. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  72608. **
  72609. ** Return an error code. If the commit could not complete because of
  72610. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  72611. ** means the close did not happen and needs to be repeated.
  72612. */
  72613. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  72614. int rc; /* Used to store transient return codes */
  72615. sqlite3 *db = p->db;
  72616. /* This function contains the logic that determines if a statement or
  72617. ** transaction will be committed or rolled back as a result of the
  72618. ** execution of this virtual machine.
  72619. **
  72620. ** If any of the following errors occur:
  72621. **
  72622. ** SQLITE_NOMEM
  72623. ** SQLITE_IOERR
  72624. ** SQLITE_FULL
  72625. ** SQLITE_INTERRUPT
  72626. **
  72627. ** Then the internal cache might have been left in an inconsistent
  72628. ** state. We need to rollback the statement transaction, if there is
  72629. ** one, or the complete transaction if there is no statement transaction.
  72630. */
  72631. if( p->magic!=VDBE_MAGIC_RUN ){
  72632. return SQLITE_OK;
  72633. }
  72634. if( db->mallocFailed ){
  72635. p->rc = SQLITE_NOMEM_BKPT;
  72636. }
  72637. closeAllCursors(p);
  72638. checkActiveVdbeCnt(db);
  72639. /* No commit or rollback needed if the program never started or if the
  72640. ** SQL statement does not read or write a database file. */
  72641. if( p->pc>=0 && p->bIsReader ){
  72642. int mrc; /* Primary error code from p->rc */
  72643. int eStatementOp = 0;
  72644. int isSpecialError; /* Set to true if a 'special' error */
  72645. /* Lock all btrees used by the statement */
  72646. sqlite3VdbeEnter(p);
  72647. /* Check for one of the special errors */
  72648. mrc = p->rc & 0xff;
  72649. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  72650. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  72651. if( isSpecialError ){
  72652. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  72653. ** no rollback is necessary. Otherwise, at least a savepoint
  72654. ** transaction must be rolled back to restore the database to a
  72655. ** consistent state.
  72656. **
  72657. ** Even if the statement is read-only, it is important to perform
  72658. ** a statement or transaction rollback operation. If the error
  72659. ** occurred while writing to the journal, sub-journal or database
  72660. ** file as part of an effort to free up cache space (see function
  72661. ** pagerStress() in pager.c), the rollback is required to restore
  72662. ** the pager to a consistent state.
  72663. */
  72664. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  72665. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  72666. eStatementOp = SAVEPOINT_ROLLBACK;
  72667. }else{
  72668. /* We are forced to roll back the active transaction. Before doing
  72669. ** so, abort any other statements this handle currently has active.
  72670. */
  72671. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  72672. sqlite3CloseSavepoints(db);
  72673. db->autoCommit = 1;
  72674. p->nChange = 0;
  72675. }
  72676. }
  72677. }
  72678. /* Check for immediate foreign key violations. */
  72679. if( p->rc==SQLITE_OK ){
  72680. sqlite3VdbeCheckFk(p, 0);
  72681. }
  72682. /* If the auto-commit flag is set and this is the only active writer
  72683. ** VM, then we do either a commit or rollback of the current transaction.
  72684. **
  72685. ** Note: This block also runs if one of the special errors handled
  72686. ** above has occurred.
  72687. */
  72688. if( !sqlite3VtabInSync(db)
  72689. && db->autoCommit
  72690. && db->nVdbeWrite==(p->readOnly==0)
  72691. ){
  72692. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  72693. rc = sqlite3VdbeCheckFk(p, 1);
  72694. if( rc!=SQLITE_OK ){
  72695. if( NEVER(p->readOnly) ){
  72696. sqlite3VdbeLeave(p);
  72697. return SQLITE_ERROR;
  72698. }
  72699. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  72700. }else{
  72701. /* The auto-commit flag is true, the vdbe program was successful
  72702. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  72703. ** key constraints to hold up the transaction. This means a commit
  72704. ** is required. */
  72705. rc = vdbeCommit(db, p);
  72706. }
  72707. if( rc==SQLITE_BUSY && p->readOnly ){
  72708. sqlite3VdbeLeave(p);
  72709. return SQLITE_BUSY;
  72710. }else if( rc!=SQLITE_OK ){
  72711. p->rc = rc;
  72712. sqlite3RollbackAll(db, SQLITE_OK);
  72713. p->nChange = 0;
  72714. }else{
  72715. db->nDeferredCons = 0;
  72716. db->nDeferredImmCons = 0;
  72717. db->flags &= ~SQLITE_DeferFKs;
  72718. sqlite3CommitInternalChanges(db);
  72719. }
  72720. }else{
  72721. sqlite3RollbackAll(db, SQLITE_OK);
  72722. p->nChange = 0;
  72723. }
  72724. db->nStatement = 0;
  72725. }else if( eStatementOp==0 ){
  72726. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  72727. eStatementOp = SAVEPOINT_RELEASE;
  72728. }else if( p->errorAction==OE_Abort ){
  72729. eStatementOp = SAVEPOINT_ROLLBACK;
  72730. }else{
  72731. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  72732. sqlite3CloseSavepoints(db);
  72733. db->autoCommit = 1;
  72734. p->nChange = 0;
  72735. }
  72736. }
  72737. /* If eStatementOp is non-zero, then a statement transaction needs to
  72738. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  72739. ** do so. If this operation returns an error, and the current statement
  72740. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  72741. ** current statement error code.
  72742. */
  72743. if( eStatementOp ){
  72744. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  72745. if( rc ){
  72746. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  72747. p->rc = rc;
  72748. sqlite3DbFree(db, p->zErrMsg);
  72749. p->zErrMsg = 0;
  72750. }
  72751. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  72752. sqlite3CloseSavepoints(db);
  72753. db->autoCommit = 1;
  72754. p->nChange = 0;
  72755. }
  72756. }
  72757. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  72758. ** has been rolled back, update the database connection change-counter.
  72759. */
  72760. if( p->changeCntOn ){
  72761. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  72762. sqlite3VdbeSetChanges(db, p->nChange);
  72763. }else{
  72764. sqlite3VdbeSetChanges(db, 0);
  72765. }
  72766. p->nChange = 0;
  72767. }
  72768. /* Release the locks */
  72769. sqlite3VdbeLeave(p);
  72770. }
  72771. /* We have successfully halted and closed the VM. Record this fact. */
  72772. if( p->pc>=0 ){
  72773. db->nVdbeActive--;
  72774. if( !p->readOnly ) db->nVdbeWrite--;
  72775. if( p->bIsReader ) db->nVdbeRead--;
  72776. assert( db->nVdbeActive>=db->nVdbeRead );
  72777. assert( db->nVdbeRead>=db->nVdbeWrite );
  72778. assert( db->nVdbeWrite>=0 );
  72779. }
  72780. p->magic = VDBE_MAGIC_HALT;
  72781. checkActiveVdbeCnt(db);
  72782. if( db->mallocFailed ){
  72783. p->rc = SQLITE_NOMEM_BKPT;
  72784. }
  72785. /* If the auto-commit flag is set to true, then any locks that were held
  72786. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  72787. ** to invoke any required unlock-notify callbacks.
  72788. */
  72789. if( db->autoCommit ){
  72790. sqlite3ConnectionUnlocked(db);
  72791. }
  72792. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  72793. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  72794. }
  72795. /*
  72796. ** Each VDBE holds the result of the most recent sqlite3_step() call
  72797. ** in p->rc. This routine sets that result back to SQLITE_OK.
  72798. */
  72799. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  72800. p->rc = SQLITE_OK;
  72801. }
  72802. /*
  72803. ** Copy the error code and error message belonging to the VDBE passed
  72804. ** as the first argument to its database handle (so that they will be
  72805. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  72806. **
  72807. ** This function does not clear the VDBE error code or message, just
  72808. ** copies them to the database handle.
  72809. */
  72810. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  72811. sqlite3 *db = p->db;
  72812. int rc = p->rc;
  72813. if( p->zErrMsg ){
  72814. db->bBenignMalloc++;
  72815. sqlite3BeginBenignMalloc();
  72816. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  72817. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  72818. sqlite3EndBenignMalloc();
  72819. db->bBenignMalloc--;
  72820. }else if( db->pErr ){
  72821. sqlite3ValueSetNull(db->pErr);
  72822. }
  72823. db->errCode = rc;
  72824. return rc;
  72825. }
  72826. #ifdef SQLITE_ENABLE_SQLLOG
  72827. /*
  72828. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  72829. ** invoke it.
  72830. */
  72831. static void vdbeInvokeSqllog(Vdbe *v){
  72832. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  72833. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  72834. assert( v->db->init.busy==0 );
  72835. if( zExpanded ){
  72836. sqlite3GlobalConfig.xSqllog(
  72837. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  72838. );
  72839. sqlite3DbFree(v->db, zExpanded);
  72840. }
  72841. }
  72842. }
  72843. #else
  72844. # define vdbeInvokeSqllog(x)
  72845. #endif
  72846. /*
  72847. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  72848. ** Write any error messages into *pzErrMsg. Return the result code.
  72849. **
  72850. ** After this routine is run, the VDBE should be ready to be executed
  72851. ** again.
  72852. **
  72853. ** To look at it another way, this routine resets the state of the
  72854. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  72855. ** VDBE_MAGIC_INIT.
  72856. */
  72857. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  72858. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  72859. int i;
  72860. #endif
  72861. sqlite3 *db;
  72862. db = p->db;
  72863. /* If the VM did not run to completion or if it encountered an
  72864. ** error, then it might not have been halted properly. So halt
  72865. ** it now.
  72866. */
  72867. sqlite3VdbeHalt(p);
  72868. /* If the VDBE has be run even partially, then transfer the error code
  72869. ** and error message from the VDBE into the main database structure. But
  72870. ** if the VDBE has just been set to run but has not actually executed any
  72871. ** instructions yet, leave the main database error information unchanged.
  72872. */
  72873. if( p->pc>=0 ){
  72874. vdbeInvokeSqllog(p);
  72875. sqlite3VdbeTransferError(p);
  72876. if( p->runOnlyOnce ) p->expired = 1;
  72877. }else if( p->rc && p->expired ){
  72878. /* The expired flag was set on the VDBE before the first call
  72879. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  72880. ** called), set the database error in this case as well.
  72881. */
  72882. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  72883. }
  72884. /* Reset register contents and reclaim error message memory.
  72885. */
  72886. #ifdef SQLITE_DEBUG
  72887. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  72888. ** Vdbe.aMem[] arrays have already been cleaned up. */
  72889. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  72890. if( p->aMem ){
  72891. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  72892. }
  72893. #endif
  72894. sqlite3DbFree(db, p->zErrMsg);
  72895. p->zErrMsg = 0;
  72896. p->pResultSet = 0;
  72897. #ifdef SQLITE_DEBUG
  72898. p->nWrite = 0;
  72899. #endif
  72900. /* Save profiling information from this VDBE run.
  72901. */
  72902. #ifdef VDBE_PROFILE
  72903. {
  72904. FILE *out = fopen("vdbe_profile.out", "a");
  72905. if( out ){
  72906. fprintf(out, "---- ");
  72907. for(i=0; i<p->nOp; i++){
  72908. fprintf(out, "%02x", p->aOp[i].opcode);
  72909. }
  72910. fprintf(out, "\n");
  72911. if( p->zSql ){
  72912. char c, pc = 0;
  72913. fprintf(out, "-- ");
  72914. for(i=0; (c = p->zSql[i])!=0; i++){
  72915. if( pc=='\n' ) fprintf(out, "-- ");
  72916. putc(c, out);
  72917. pc = c;
  72918. }
  72919. if( pc!='\n' ) fprintf(out, "\n");
  72920. }
  72921. for(i=0; i<p->nOp; i++){
  72922. char zHdr[100];
  72923. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  72924. p->aOp[i].cnt,
  72925. p->aOp[i].cycles,
  72926. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  72927. );
  72928. fprintf(out, "%s", zHdr);
  72929. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  72930. }
  72931. fclose(out);
  72932. }
  72933. }
  72934. #endif
  72935. p->magic = VDBE_MAGIC_RESET;
  72936. return p->rc & db->errMask;
  72937. }
  72938. /*
  72939. ** Clean up and delete a VDBE after execution. Return an integer which is
  72940. ** the result code. Write any error message text into *pzErrMsg.
  72941. */
  72942. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  72943. int rc = SQLITE_OK;
  72944. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  72945. rc = sqlite3VdbeReset(p);
  72946. assert( (rc & p->db->errMask)==rc );
  72947. }
  72948. sqlite3VdbeDelete(p);
  72949. return rc;
  72950. }
  72951. /*
  72952. ** If parameter iOp is less than zero, then invoke the destructor for
  72953. ** all auxiliary data pointers currently cached by the VM passed as
  72954. ** the first argument.
  72955. **
  72956. ** Or, if iOp is greater than or equal to zero, then the destructor is
  72957. ** only invoked for those auxiliary data pointers created by the user
  72958. ** function invoked by the OP_Function opcode at instruction iOp of
  72959. ** VM pVdbe, and only then if:
  72960. **
  72961. ** * the associated function parameter is the 32nd or later (counting
  72962. ** from left to right), or
  72963. **
  72964. ** * the corresponding bit in argument mask is clear (where the first
  72965. ** function parameter corresponds to bit 0 etc.).
  72966. */
  72967. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  72968. while( *pp ){
  72969. AuxData *pAux = *pp;
  72970. if( (iOp<0)
  72971. || (pAux->iAuxOp==iOp
  72972. && pAux->iAuxArg>=0
  72973. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  72974. ){
  72975. testcase( pAux->iAuxArg==31 );
  72976. if( pAux->xDeleteAux ){
  72977. pAux->xDeleteAux(pAux->pAux);
  72978. }
  72979. *pp = pAux->pNextAux;
  72980. sqlite3DbFree(db, pAux);
  72981. }else{
  72982. pp= &pAux->pNextAux;
  72983. }
  72984. }
  72985. }
  72986. /*
  72987. ** Free all memory associated with the Vdbe passed as the second argument,
  72988. ** except for object itself, which is preserved.
  72989. **
  72990. ** The difference between this function and sqlite3VdbeDelete() is that
  72991. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  72992. ** the database connection and frees the object itself.
  72993. */
  72994. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  72995. SubProgram *pSub, *pNext;
  72996. assert( p->db==0 || p->db==db );
  72997. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  72998. for(pSub=p->pProgram; pSub; pSub=pNext){
  72999. pNext = pSub->pNext;
  73000. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  73001. sqlite3DbFree(db, pSub);
  73002. }
  73003. if( p->magic!=VDBE_MAGIC_INIT ){
  73004. releaseMemArray(p->aVar, p->nVar);
  73005. sqlite3DbFree(db, p->pVList);
  73006. sqlite3DbFree(db, p->pFree);
  73007. }
  73008. vdbeFreeOpArray(db, p->aOp, p->nOp);
  73009. sqlite3DbFree(db, p->aColName);
  73010. sqlite3DbFree(db, p->zSql);
  73011. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73012. {
  73013. int i;
  73014. for(i=0; i<p->nScan; i++){
  73015. sqlite3DbFree(db, p->aScan[i].zName);
  73016. }
  73017. sqlite3DbFree(db, p->aScan);
  73018. }
  73019. #endif
  73020. }
  73021. /*
  73022. ** Delete an entire VDBE.
  73023. */
  73024. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  73025. sqlite3 *db;
  73026. assert( p!=0 );
  73027. db = p->db;
  73028. assert( sqlite3_mutex_held(db->mutex) );
  73029. sqlite3VdbeClearObject(db, p);
  73030. if( p->pPrev ){
  73031. p->pPrev->pNext = p->pNext;
  73032. }else{
  73033. assert( db->pVdbe==p );
  73034. db->pVdbe = p->pNext;
  73035. }
  73036. if( p->pNext ){
  73037. p->pNext->pPrev = p->pPrev;
  73038. }
  73039. p->magic = VDBE_MAGIC_DEAD;
  73040. p->db = 0;
  73041. sqlite3DbFreeNN(db, p);
  73042. }
  73043. /*
  73044. ** The cursor "p" has a pending seek operation that has not yet been
  73045. ** carried out. Seek the cursor now. If an error occurs, return
  73046. ** the appropriate error code.
  73047. */
  73048. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  73049. int res, rc;
  73050. #ifdef SQLITE_TEST
  73051. extern int sqlite3_search_count;
  73052. #endif
  73053. assert( p->deferredMoveto );
  73054. assert( p->isTable );
  73055. assert( p->eCurType==CURTYPE_BTREE );
  73056. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  73057. if( rc ) return rc;
  73058. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  73059. #ifdef SQLITE_TEST
  73060. sqlite3_search_count++;
  73061. #endif
  73062. p->deferredMoveto = 0;
  73063. p->cacheStatus = CACHE_STALE;
  73064. return SQLITE_OK;
  73065. }
  73066. /*
  73067. ** Something has moved cursor "p" out of place. Maybe the row it was
  73068. ** pointed to was deleted out from under it. Or maybe the btree was
  73069. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  73070. ** is supposed to be pointing. If the row was deleted out from under the
  73071. ** cursor, set the cursor to point to a NULL row.
  73072. */
  73073. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  73074. int isDifferentRow, rc;
  73075. assert( p->eCurType==CURTYPE_BTREE );
  73076. assert( p->uc.pCursor!=0 );
  73077. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  73078. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  73079. p->cacheStatus = CACHE_STALE;
  73080. if( isDifferentRow ) p->nullRow = 1;
  73081. return rc;
  73082. }
  73083. /*
  73084. ** Check to ensure that the cursor is valid. Restore the cursor
  73085. ** if need be. Return any I/O error from the restore operation.
  73086. */
  73087. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  73088. assert( p->eCurType==CURTYPE_BTREE );
  73089. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  73090. return handleMovedCursor(p);
  73091. }
  73092. return SQLITE_OK;
  73093. }
  73094. /*
  73095. ** Make sure the cursor p is ready to read or write the row to which it
  73096. ** was last positioned. Return an error code if an OOM fault or I/O error
  73097. ** prevents us from positioning the cursor to its correct position.
  73098. **
  73099. ** If a MoveTo operation is pending on the given cursor, then do that
  73100. ** MoveTo now. If no move is pending, check to see if the row has been
  73101. ** deleted out from under the cursor and if it has, mark the row as
  73102. ** a NULL row.
  73103. **
  73104. ** If the cursor is already pointing to the correct row and that row has
  73105. ** not been deleted out from under the cursor, then this routine is a no-op.
  73106. */
  73107. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  73108. VdbeCursor *p = *pp;
  73109. assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
  73110. if( p->deferredMoveto ){
  73111. int iMap;
  73112. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  73113. *pp = p->pAltCursor;
  73114. *piCol = iMap - 1;
  73115. return SQLITE_OK;
  73116. }
  73117. return handleDeferredMoveto(p);
  73118. }
  73119. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  73120. return handleMovedCursor(p);
  73121. }
  73122. return SQLITE_OK;
  73123. }
  73124. /*
  73125. ** The following functions:
  73126. **
  73127. ** sqlite3VdbeSerialType()
  73128. ** sqlite3VdbeSerialTypeLen()
  73129. ** sqlite3VdbeSerialLen()
  73130. ** sqlite3VdbeSerialPut()
  73131. ** sqlite3VdbeSerialGet()
  73132. **
  73133. ** encapsulate the code that serializes values for storage in SQLite
  73134. ** data and index records. Each serialized value consists of a
  73135. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  73136. ** integer, stored as a varint.
  73137. **
  73138. ** In an SQLite index record, the serial type is stored directly before
  73139. ** the blob of data that it corresponds to. In a table record, all serial
  73140. ** types are stored at the start of the record, and the blobs of data at
  73141. ** the end. Hence these functions allow the caller to handle the
  73142. ** serial-type and data blob separately.
  73143. **
  73144. ** The following table describes the various storage classes for data:
  73145. **
  73146. ** serial type bytes of data type
  73147. ** -------------- --------------- ---------------
  73148. ** 0 0 NULL
  73149. ** 1 1 signed integer
  73150. ** 2 2 signed integer
  73151. ** 3 3 signed integer
  73152. ** 4 4 signed integer
  73153. ** 5 6 signed integer
  73154. ** 6 8 signed integer
  73155. ** 7 8 IEEE float
  73156. ** 8 0 Integer constant 0
  73157. ** 9 0 Integer constant 1
  73158. ** 10,11 reserved for expansion
  73159. ** N>=12 and even (N-12)/2 BLOB
  73160. ** N>=13 and odd (N-13)/2 text
  73161. **
  73162. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  73163. ** of SQLite will not understand those serial types.
  73164. */
  73165. /*
  73166. ** Return the serial-type for the value stored in pMem.
  73167. */
  73168. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  73169. int flags = pMem->flags;
  73170. u32 n;
  73171. assert( pLen!=0 );
  73172. if( flags&MEM_Null ){
  73173. *pLen = 0;
  73174. return 0;
  73175. }
  73176. if( flags&MEM_Int ){
  73177. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  73178. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  73179. i64 i = pMem->u.i;
  73180. u64 u;
  73181. if( i<0 ){
  73182. u = ~i;
  73183. }else{
  73184. u = i;
  73185. }
  73186. if( u<=127 ){
  73187. if( (i&1)==i && file_format>=4 ){
  73188. *pLen = 0;
  73189. return 8+(u32)u;
  73190. }else{
  73191. *pLen = 1;
  73192. return 1;
  73193. }
  73194. }
  73195. if( u<=32767 ){ *pLen = 2; return 2; }
  73196. if( u<=8388607 ){ *pLen = 3; return 3; }
  73197. if( u<=2147483647 ){ *pLen = 4; return 4; }
  73198. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  73199. *pLen = 8;
  73200. return 6;
  73201. }
  73202. if( flags&MEM_Real ){
  73203. *pLen = 8;
  73204. return 7;
  73205. }
  73206. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  73207. assert( pMem->n>=0 );
  73208. n = (u32)pMem->n;
  73209. if( flags & MEM_Zero ){
  73210. n += pMem->u.nZero;
  73211. }
  73212. *pLen = n;
  73213. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  73214. }
  73215. /*
  73216. ** The sizes for serial types less than 128
  73217. */
  73218. static const u8 sqlite3SmallTypeSizes[] = {
  73219. /* 0 1 2 3 4 5 6 7 8 9 */
  73220. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  73221. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  73222. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  73223. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  73224. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  73225. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  73226. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  73227. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  73228. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  73229. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  73230. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  73231. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  73232. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  73233. };
  73234. /*
  73235. ** Return the length of the data corresponding to the supplied serial-type.
  73236. */
  73237. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  73238. if( serial_type>=128 ){
  73239. return (serial_type-12)/2;
  73240. }else{
  73241. assert( serial_type<12
  73242. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  73243. return sqlite3SmallTypeSizes[serial_type];
  73244. }
  73245. }
  73246. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  73247. assert( serial_type<128 );
  73248. return sqlite3SmallTypeSizes[serial_type];
  73249. }
  73250. /*
  73251. ** If we are on an architecture with mixed-endian floating
  73252. ** points (ex: ARM7) then swap the lower 4 bytes with the
  73253. ** upper 4 bytes. Return the result.
  73254. **
  73255. ** For most architectures, this is a no-op.
  73256. **
  73257. ** (later): It is reported to me that the mixed-endian problem
  73258. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  73259. ** that early versions of GCC stored the two words of a 64-bit
  73260. ** float in the wrong order. And that error has been propagated
  73261. ** ever since. The blame is not necessarily with GCC, though.
  73262. ** GCC might have just copying the problem from a prior compiler.
  73263. ** I am also told that newer versions of GCC that follow a different
  73264. ** ABI get the byte order right.
  73265. **
  73266. ** Developers using SQLite on an ARM7 should compile and run their
  73267. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  73268. ** enabled, some asserts below will ensure that the byte order of
  73269. ** floating point values is correct.
  73270. **
  73271. ** (2007-08-30) Frank van Vugt has studied this problem closely
  73272. ** and has send his findings to the SQLite developers. Frank
  73273. ** writes that some Linux kernels offer floating point hardware
  73274. ** emulation that uses only 32-bit mantissas instead of a full
  73275. ** 48-bits as required by the IEEE standard. (This is the
  73276. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  73277. ** byte swapping becomes very complicated. To avoid problems,
  73278. ** the necessary byte swapping is carried out using a 64-bit integer
  73279. ** rather than a 64-bit float. Frank assures us that the code here
  73280. ** works for him. We, the developers, have no way to independently
  73281. ** verify this, but Frank seems to know what he is talking about
  73282. ** so we trust him.
  73283. */
  73284. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  73285. static u64 floatSwap(u64 in){
  73286. union {
  73287. u64 r;
  73288. u32 i[2];
  73289. } u;
  73290. u32 t;
  73291. u.r = in;
  73292. t = u.i[0];
  73293. u.i[0] = u.i[1];
  73294. u.i[1] = t;
  73295. return u.r;
  73296. }
  73297. # define swapMixedEndianFloat(X) X = floatSwap(X)
  73298. #else
  73299. # define swapMixedEndianFloat(X)
  73300. #endif
  73301. /*
  73302. ** Write the serialized data blob for the value stored in pMem into
  73303. ** buf. It is assumed that the caller has allocated sufficient space.
  73304. ** Return the number of bytes written.
  73305. **
  73306. ** nBuf is the amount of space left in buf[]. The caller is responsible
  73307. ** for allocating enough space to buf[] to hold the entire field, exclusive
  73308. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  73309. **
  73310. ** Return the number of bytes actually written into buf[]. The number
  73311. ** of bytes in the zero-filled tail is included in the return value only
  73312. ** if those bytes were zeroed in buf[].
  73313. */
  73314. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  73315. u32 len;
  73316. /* Integer and Real */
  73317. if( serial_type<=7 && serial_type>0 ){
  73318. u64 v;
  73319. u32 i;
  73320. if( serial_type==7 ){
  73321. assert( sizeof(v)==sizeof(pMem->u.r) );
  73322. memcpy(&v, &pMem->u.r, sizeof(v));
  73323. swapMixedEndianFloat(v);
  73324. }else{
  73325. v = pMem->u.i;
  73326. }
  73327. len = i = sqlite3SmallTypeSizes[serial_type];
  73328. assert( i>0 );
  73329. do{
  73330. buf[--i] = (u8)(v&0xFF);
  73331. v >>= 8;
  73332. }while( i );
  73333. return len;
  73334. }
  73335. /* String or blob */
  73336. if( serial_type>=12 ){
  73337. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  73338. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  73339. len = pMem->n;
  73340. if( len>0 ) memcpy(buf, pMem->z, len);
  73341. return len;
  73342. }
  73343. /* NULL or constants 0 or 1 */
  73344. return 0;
  73345. }
  73346. /* Input "x" is a sequence of unsigned characters that represent a
  73347. ** big-endian integer. Return the equivalent native integer
  73348. */
  73349. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  73350. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  73351. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  73352. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  73353. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  73354. /*
  73355. ** Deserialize the data blob pointed to by buf as serial type serial_type
  73356. ** and store the result in pMem. Return the number of bytes read.
  73357. **
  73358. ** This function is implemented as two separate routines for performance.
  73359. ** The few cases that require local variables are broken out into a separate
  73360. ** routine so that in most cases the overhead of moving the stack pointer
  73361. ** is avoided.
  73362. */
  73363. static u32 SQLITE_NOINLINE serialGet(
  73364. const unsigned char *buf, /* Buffer to deserialize from */
  73365. u32 serial_type, /* Serial type to deserialize */
  73366. Mem *pMem /* Memory cell to write value into */
  73367. ){
  73368. u64 x = FOUR_BYTE_UINT(buf);
  73369. u32 y = FOUR_BYTE_UINT(buf+4);
  73370. x = (x<<32) + y;
  73371. if( serial_type==6 ){
  73372. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  73373. ** twos-complement integer. */
  73374. pMem->u.i = *(i64*)&x;
  73375. pMem->flags = MEM_Int;
  73376. testcase( pMem->u.i<0 );
  73377. }else{
  73378. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  73379. ** floating point number. */
  73380. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  73381. /* Verify that integers and floating point values use the same
  73382. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  73383. ** defined that 64-bit floating point values really are mixed
  73384. ** endian.
  73385. */
  73386. static const u64 t1 = ((u64)0x3ff00000)<<32;
  73387. static const double r1 = 1.0;
  73388. u64 t2 = t1;
  73389. swapMixedEndianFloat(t2);
  73390. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  73391. #endif
  73392. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  73393. swapMixedEndianFloat(x);
  73394. memcpy(&pMem->u.r, &x, sizeof(x));
  73395. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  73396. }
  73397. return 8;
  73398. }
  73399. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  73400. const unsigned char *buf, /* Buffer to deserialize from */
  73401. u32 serial_type, /* Serial type to deserialize */
  73402. Mem *pMem /* Memory cell to write value into */
  73403. ){
  73404. switch( serial_type ){
  73405. case 10: { /* Internal use only: NULL with virtual table
  73406. ** UPDATE no-change flag set */
  73407. pMem->flags = MEM_Null|MEM_Zero;
  73408. pMem->n = 0;
  73409. pMem->u.nZero = 0;
  73410. break;
  73411. }
  73412. case 11: /* Reserved for future use */
  73413. case 0: { /* Null */
  73414. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  73415. pMem->flags = MEM_Null;
  73416. break;
  73417. }
  73418. case 1: {
  73419. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  73420. ** integer. */
  73421. pMem->u.i = ONE_BYTE_INT(buf);
  73422. pMem->flags = MEM_Int;
  73423. testcase( pMem->u.i<0 );
  73424. return 1;
  73425. }
  73426. case 2: { /* 2-byte signed integer */
  73427. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  73428. ** twos-complement integer. */
  73429. pMem->u.i = TWO_BYTE_INT(buf);
  73430. pMem->flags = MEM_Int;
  73431. testcase( pMem->u.i<0 );
  73432. return 2;
  73433. }
  73434. case 3: { /* 3-byte signed integer */
  73435. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  73436. ** twos-complement integer. */
  73437. pMem->u.i = THREE_BYTE_INT(buf);
  73438. pMem->flags = MEM_Int;
  73439. testcase( pMem->u.i<0 );
  73440. return 3;
  73441. }
  73442. case 4: { /* 4-byte signed integer */
  73443. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  73444. ** twos-complement integer. */
  73445. pMem->u.i = FOUR_BYTE_INT(buf);
  73446. #ifdef __HP_cc
  73447. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  73448. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  73449. #endif
  73450. pMem->flags = MEM_Int;
  73451. testcase( pMem->u.i<0 );
  73452. return 4;
  73453. }
  73454. case 5: { /* 6-byte signed integer */
  73455. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  73456. ** twos-complement integer. */
  73457. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  73458. pMem->flags = MEM_Int;
  73459. testcase( pMem->u.i<0 );
  73460. return 6;
  73461. }
  73462. case 6: /* 8-byte signed integer */
  73463. case 7: { /* IEEE floating point */
  73464. /* These use local variables, so do them in a separate routine
  73465. ** to avoid having to move the frame pointer in the common case */
  73466. return serialGet(buf,serial_type,pMem);
  73467. }
  73468. case 8: /* Integer 0 */
  73469. case 9: { /* Integer 1 */
  73470. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  73471. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  73472. pMem->u.i = serial_type-8;
  73473. pMem->flags = MEM_Int;
  73474. return 0;
  73475. }
  73476. default: {
  73477. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  73478. ** length.
  73479. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  73480. ** (N-13)/2 bytes in length. */
  73481. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  73482. pMem->z = (char *)buf;
  73483. pMem->n = (serial_type-12)/2;
  73484. pMem->flags = aFlag[serial_type&1];
  73485. return pMem->n;
  73486. }
  73487. }
  73488. return 0;
  73489. }
  73490. /*
  73491. ** This routine is used to allocate sufficient space for an UnpackedRecord
  73492. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  73493. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  73494. **
  73495. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  73496. ** the unaligned buffer passed via the second and third arguments (presumably
  73497. ** stack space). If the former, then *ppFree is set to a pointer that should
  73498. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  73499. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  73500. ** before returning.
  73501. **
  73502. ** If an OOM error occurs, NULL is returned.
  73503. */
  73504. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  73505. KeyInfo *pKeyInfo /* Description of the record */
  73506. ){
  73507. UnpackedRecord *p; /* Unpacked record to return */
  73508. int nByte; /* Number of bytes required for *p */
  73509. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
  73510. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  73511. if( !p ) return 0;
  73512. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  73513. assert( pKeyInfo->aSortOrder!=0 );
  73514. p->pKeyInfo = pKeyInfo;
  73515. p->nField = pKeyInfo->nKeyField + 1;
  73516. return p;
  73517. }
  73518. /*
  73519. ** Given the nKey-byte encoding of a record in pKey[], populate the
  73520. ** UnpackedRecord structure indicated by the fourth argument with the
  73521. ** contents of the decoded record.
  73522. */
  73523. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  73524. KeyInfo *pKeyInfo, /* Information about the record format */
  73525. int nKey, /* Size of the binary record */
  73526. const void *pKey, /* The binary record */
  73527. UnpackedRecord *p /* Populate this structure before returning. */
  73528. ){
  73529. const unsigned char *aKey = (const unsigned char *)pKey;
  73530. int d;
  73531. u32 idx; /* Offset in aKey[] to read from */
  73532. u16 u; /* Unsigned loop counter */
  73533. u32 szHdr;
  73534. Mem *pMem = p->aMem;
  73535. p->default_rc = 0;
  73536. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  73537. idx = getVarint32(aKey, szHdr);
  73538. d = szHdr;
  73539. u = 0;
  73540. while( idx<szHdr && d<=nKey ){
  73541. u32 serial_type;
  73542. idx += getVarint32(&aKey[idx], serial_type);
  73543. pMem->enc = pKeyInfo->enc;
  73544. pMem->db = pKeyInfo->db;
  73545. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  73546. pMem->szMalloc = 0;
  73547. pMem->z = 0;
  73548. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  73549. pMem++;
  73550. if( (++u)>=p->nField ) break;
  73551. }
  73552. assert( u<=pKeyInfo->nKeyField + 1 );
  73553. p->nField = u;
  73554. }
  73555. #ifdef SQLITE_DEBUG
  73556. /*
  73557. ** This function compares two index or table record keys in the same way
  73558. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  73559. ** this function deserializes and compares values using the
  73560. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  73561. ** in assert() statements to ensure that the optimized code in
  73562. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  73563. **
  73564. ** Return true if the result of comparison is equivalent to desiredResult.
  73565. ** Return false if there is a disagreement.
  73566. */
  73567. static int vdbeRecordCompareDebug(
  73568. int nKey1, const void *pKey1, /* Left key */
  73569. const UnpackedRecord *pPKey2, /* Right key */
  73570. int desiredResult /* Correct answer */
  73571. ){
  73572. u32 d1; /* Offset into aKey[] of next data element */
  73573. u32 idx1; /* Offset into aKey[] of next header element */
  73574. u32 szHdr1; /* Number of bytes in header */
  73575. int i = 0;
  73576. int rc = 0;
  73577. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  73578. KeyInfo *pKeyInfo;
  73579. Mem mem1;
  73580. pKeyInfo = pPKey2->pKeyInfo;
  73581. if( pKeyInfo->db==0 ) return 1;
  73582. mem1.enc = pKeyInfo->enc;
  73583. mem1.db = pKeyInfo->db;
  73584. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  73585. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  73586. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  73587. ** We could initialize it, as shown here, to silence those complaints.
  73588. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  73589. ** the unnecessary initialization has a measurable negative performance
  73590. ** impact, since this routine is a very high runner. And so, we choose
  73591. ** to ignore the compiler warnings and leave this variable uninitialized.
  73592. */
  73593. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  73594. idx1 = getVarint32(aKey1, szHdr1);
  73595. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  73596. d1 = szHdr1;
  73597. assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
  73598. assert( pKeyInfo->aSortOrder!=0 );
  73599. assert( pKeyInfo->nKeyField>0 );
  73600. assert( idx1<=szHdr1 || CORRUPT_DB );
  73601. do{
  73602. u32 serial_type1;
  73603. /* Read the serial types for the next element in each key. */
  73604. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  73605. /* Verify that there is enough key space remaining to avoid
  73606. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  73607. ** always be greater than or equal to the amount of required key space.
  73608. ** Use that approximation to avoid the more expensive call to
  73609. ** sqlite3VdbeSerialTypeLen() in the common case.
  73610. */
  73611. if( d1+serial_type1+2>(u32)nKey1
  73612. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  73613. ){
  73614. break;
  73615. }
  73616. /* Extract the values to be compared.
  73617. */
  73618. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  73619. /* Do the comparison
  73620. */
  73621. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  73622. if( rc!=0 ){
  73623. assert( mem1.szMalloc==0 ); /* See comment below */
  73624. if( pKeyInfo->aSortOrder[i] ){
  73625. rc = -rc; /* Invert the result for DESC sort order. */
  73626. }
  73627. goto debugCompareEnd;
  73628. }
  73629. i++;
  73630. }while( idx1<szHdr1 && i<pPKey2->nField );
  73631. /* No memory allocation is ever used on mem1. Prove this using
  73632. ** the following assert(). If the assert() fails, it indicates a
  73633. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  73634. */
  73635. assert( mem1.szMalloc==0 );
  73636. /* rc==0 here means that one of the keys ran out of fields and
  73637. ** all the fields up to that point were equal. Return the default_rc
  73638. ** value. */
  73639. rc = pPKey2->default_rc;
  73640. debugCompareEnd:
  73641. if( desiredResult==0 && rc==0 ) return 1;
  73642. if( desiredResult<0 && rc<0 ) return 1;
  73643. if( desiredResult>0 && rc>0 ) return 1;
  73644. if( CORRUPT_DB ) return 1;
  73645. if( pKeyInfo->db->mallocFailed ) return 1;
  73646. return 0;
  73647. }
  73648. #endif
  73649. #ifdef SQLITE_DEBUG
  73650. /*
  73651. ** Count the number of fields (a.k.a. columns) in the record given by
  73652. ** pKey,nKey. The verify that this count is less than or equal to the
  73653. ** limit given by pKeyInfo->nAllField.
  73654. **
  73655. ** If this constraint is not satisfied, it means that the high-speed
  73656. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  73657. ** not work correctly. If this assert() ever fires, it probably means
  73658. ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
  73659. ** incorrectly.
  73660. */
  73661. static void vdbeAssertFieldCountWithinLimits(
  73662. int nKey, const void *pKey, /* The record to verify */
  73663. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  73664. ){
  73665. int nField = 0;
  73666. u32 szHdr;
  73667. u32 idx;
  73668. u32 notUsed;
  73669. const unsigned char *aKey = (const unsigned char*)pKey;
  73670. if( CORRUPT_DB ) return;
  73671. idx = getVarint32(aKey, szHdr);
  73672. assert( nKey>=0 );
  73673. assert( szHdr<=(u32)nKey );
  73674. while( idx<szHdr ){
  73675. idx += getVarint32(aKey+idx, notUsed);
  73676. nField++;
  73677. }
  73678. assert( nField <= pKeyInfo->nAllField );
  73679. }
  73680. #else
  73681. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  73682. #endif
  73683. /*
  73684. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  73685. ** using the collation sequence pColl. As usual, return a negative , zero
  73686. ** or positive value if *pMem1 is less than, equal to or greater than
  73687. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  73688. */
  73689. static int vdbeCompareMemString(
  73690. const Mem *pMem1,
  73691. const Mem *pMem2,
  73692. const CollSeq *pColl,
  73693. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  73694. ){
  73695. if( pMem1->enc==pColl->enc ){
  73696. /* The strings are already in the correct encoding. Call the
  73697. ** comparison function directly */
  73698. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  73699. }else{
  73700. int rc;
  73701. const void *v1, *v2;
  73702. Mem c1;
  73703. Mem c2;
  73704. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  73705. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  73706. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  73707. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  73708. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  73709. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  73710. if( (v1==0 || v2==0) ){
  73711. if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  73712. rc = 0;
  73713. }else{
  73714. rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
  73715. }
  73716. sqlite3VdbeMemRelease(&c1);
  73717. sqlite3VdbeMemRelease(&c2);
  73718. return rc;
  73719. }
  73720. }
  73721. /*
  73722. ** The input pBlob is guaranteed to be a Blob that is not marked
  73723. ** with MEM_Zero. Return true if it could be a zero-blob.
  73724. */
  73725. static int isAllZero(const char *z, int n){
  73726. int i;
  73727. for(i=0; i<n; i++){
  73728. if( z[i] ) return 0;
  73729. }
  73730. return 1;
  73731. }
  73732. /*
  73733. ** Compare two blobs. Return negative, zero, or positive if the first
  73734. ** is less than, equal to, or greater than the second, respectively.
  73735. ** If one blob is a prefix of the other, then the shorter is the lessor.
  73736. */
  73737. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  73738. int c;
  73739. int n1 = pB1->n;
  73740. int n2 = pB2->n;
  73741. /* It is possible to have a Blob value that has some non-zero content
  73742. ** followed by zero content. But that only comes up for Blobs formed
  73743. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  73744. ** sqlite3MemCompare(). */
  73745. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  73746. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  73747. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  73748. if( pB1->flags & pB2->flags & MEM_Zero ){
  73749. return pB1->u.nZero - pB2->u.nZero;
  73750. }else if( pB1->flags & MEM_Zero ){
  73751. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  73752. return pB1->u.nZero - n2;
  73753. }else{
  73754. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  73755. return n1 - pB2->u.nZero;
  73756. }
  73757. }
  73758. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  73759. if( c ) return c;
  73760. return n1 - n2;
  73761. }
  73762. /*
  73763. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  73764. ** number. Return negative, zero, or positive if the first (i64) is less than,
  73765. ** equal to, or greater than the second (double).
  73766. */
  73767. static int sqlite3IntFloatCompare(i64 i, double r){
  73768. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  73769. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  73770. if( x<r ) return -1;
  73771. if( x>r ) return +1;
  73772. return 0;
  73773. }else{
  73774. i64 y;
  73775. double s;
  73776. if( r<-9223372036854775808.0 ) return +1;
  73777. if( r>=9223372036854775808.0 ) return -1;
  73778. y = (i64)r;
  73779. if( i<y ) return -1;
  73780. if( i>y ) return +1;
  73781. s = (double)i;
  73782. if( s<r ) return -1;
  73783. if( s>r ) return +1;
  73784. return 0;
  73785. }
  73786. }
  73787. /*
  73788. ** Compare the values contained by the two memory cells, returning
  73789. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  73790. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  73791. ** and reals) sorted numerically, followed by text ordered by the collating
  73792. ** sequence pColl and finally blob's ordered by memcmp().
  73793. **
  73794. ** Two NULL values are considered equal by this function.
  73795. */
  73796. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  73797. int f1, f2;
  73798. int combined_flags;
  73799. f1 = pMem1->flags;
  73800. f2 = pMem2->flags;
  73801. combined_flags = f1|f2;
  73802. assert( (combined_flags & MEM_RowSet)==0 );
  73803. /* If one value is NULL, it is less than the other. If both values
  73804. ** are NULL, return 0.
  73805. */
  73806. if( combined_flags&MEM_Null ){
  73807. return (f2&MEM_Null) - (f1&MEM_Null);
  73808. }
  73809. /* At least one of the two values is a number
  73810. */
  73811. if( combined_flags&(MEM_Int|MEM_Real) ){
  73812. if( (f1 & f2 & MEM_Int)!=0 ){
  73813. if( pMem1->u.i < pMem2->u.i ) return -1;
  73814. if( pMem1->u.i > pMem2->u.i ) return +1;
  73815. return 0;
  73816. }
  73817. if( (f1 & f2 & MEM_Real)!=0 ){
  73818. if( pMem1->u.r < pMem2->u.r ) return -1;
  73819. if( pMem1->u.r > pMem2->u.r ) return +1;
  73820. return 0;
  73821. }
  73822. if( (f1&MEM_Int)!=0 ){
  73823. if( (f2&MEM_Real)!=0 ){
  73824. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  73825. }else{
  73826. return -1;
  73827. }
  73828. }
  73829. if( (f1&MEM_Real)!=0 ){
  73830. if( (f2&MEM_Int)!=0 ){
  73831. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  73832. }else{
  73833. return -1;
  73834. }
  73835. }
  73836. return +1;
  73837. }
  73838. /* If one value is a string and the other is a blob, the string is less.
  73839. ** If both are strings, compare using the collating functions.
  73840. */
  73841. if( combined_flags&MEM_Str ){
  73842. if( (f1 & MEM_Str)==0 ){
  73843. return 1;
  73844. }
  73845. if( (f2 & MEM_Str)==0 ){
  73846. return -1;
  73847. }
  73848. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  73849. assert( pMem1->enc==SQLITE_UTF8 ||
  73850. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  73851. /* The collation sequence must be defined at this point, even if
  73852. ** the user deletes the collation sequence after the vdbe program is
  73853. ** compiled (this was not always the case).
  73854. */
  73855. assert( !pColl || pColl->xCmp );
  73856. if( pColl ){
  73857. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  73858. }
  73859. /* If a NULL pointer was passed as the collate function, fall through
  73860. ** to the blob case and use memcmp(). */
  73861. }
  73862. /* Both values must be blobs. Compare using memcmp(). */
  73863. return sqlite3BlobCompare(pMem1, pMem2);
  73864. }
  73865. /*
  73866. ** The first argument passed to this function is a serial-type that
  73867. ** corresponds to an integer - all values between 1 and 9 inclusive
  73868. ** except 7. The second points to a buffer containing an integer value
  73869. ** serialized according to serial_type. This function deserializes
  73870. ** and returns the value.
  73871. */
  73872. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  73873. u32 y;
  73874. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  73875. switch( serial_type ){
  73876. case 0:
  73877. case 1:
  73878. testcase( aKey[0]&0x80 );
  73879. return ONE_BYTE_INT(aKey);
  73880. case 2:
  73881. testcase( aKey[0]&0x80 );
  73882. return TWO_BYTE_INT(aKey);
  73883. case 3:
  73884. testcase( aKey[0]&0x80 );
  73885. return THREE_BYTE_INT(aKey);
  73886. case 4: {
  73887. testcase( aKey[0]&0x80 );
  73888. y = FOUR_BYTE_UINT(aKey);
  73889. return (i64)*(int*)&y;
  73890. }
  73891. case 5: {
  73892. testcase( aKey[0]&0x80 );
  73893. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  73894. }
  73895. case 6: {
  73896. u64 x = FOUR_BYTE_UINT(aKey);
  73897. testcase( aKey[0]&0x80 );
  73898. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  73899. return (i64)*(i64*)&x;
  73900. }
  73901. }
  73902. return (serial_type - 8);
  73903. }
  73904. /*
  73905. ** This function compares the two table rows or index records
  73906. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  73907. ** or positive integer if key1 is less than, equal to or
  73908. ** greater than key2. The {nKey1, pKey1} key must be a blob
  73909. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  73910. ** key must be a parsed key such as obtained from
  73911. ** sqlite3VdbeParseRecord.
  73912. **
  73913. ** If argument bSkip is non-zero, it is assumed that the caller has already
  73914. ** determined that the first fields of the keys are equal.
  73915. **
  73916. ** Key1 and Key2 do not have to contain the same number of fields. If all
  73917. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  73918. ** returned.
  73919. **
  73920. ** If database corruption is discovered, set pPKey2->errCode to
  73921. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  73922. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  73923. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  73924. */
  73925. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  73926. int nKey1, const void *pKey1, /* Left key */
  73927. UnpackedRecord *pPKey2, /* Right key */
  73928. int bSkip /* If true, skip the first field */
  73929. ){
  73930. u32 d1; /* Offset into aKey[] of next data element */
  73931. int i; /* Index of next field to compare */
  73932. u32 szHdr1; /* Size of record header in bytes */
  73933. u32 idx1; /* Offset of first type in header */
  73934. int rc = 0; /* Return value */
  73935. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  73936. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  73937. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  73938. Mem mem1;
  73939. /* If bSkip is true, then the caller has already determined that the first
  73940. ** two elements in the keys are equal. Fix the various stack variables so
  73941. ** that this routine begins comparing at the second field. */
  73942. if( bSkip ){
  73943. u32 s1;
  73944. idx1 = 1 + getVarint32(&aKey1[1], s1);
  73945. szHdr1 = aKey1[0];
  73946. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  73947. i = 1;
  73948. pRhs++;
  73949. }else{
  73950. idx1 = getVarint32(aKey1, szHdr1);
  73951. d1 = szHdr1;
  73952. if( d1>(unsigned)nKey1 ){
  73953. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  73954. return 0; /* Corruption */
  73955. }
  73956. i = 0;
  73957. }
  73958. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  73959. assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
  73960. || CORRUPT_DB );
  73961. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  73962. assert( pPKey2->pKeyInfo->nKeyField>0 );
  73963. assert( idx1<=szHdr1 || CORRUPT_DB );
  73964. do{
  73965. u32 serial_type;
  73966. /* RHS is an integer */
  73967. if( pRhs->flags & MEM_Int ){
  73968. serial_type = aKey1[idx1];
  73969. testcase( serial_type==12 );
  73970. if( serial_type>=10 ){
  73971. rc = +1;
  73972. }else if( serial_type==0 ){
  73973. rc = -1;
  73974. }else if( serial_type==7 ){
  73975. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  73976. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  73977. }else{
  73978. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  73979. i64 rhs = pRhs->u.i;
  73980. if( lhs<rhs ){
  73981. rc = -1;
  73982. }else if( lhs>rhs ){
  73983. rc = +1;
  73984. }
  73985. }
  73986. }
  73987. /* RHS is real */
  73988. else if( pRhs->flags & MEM_Real ){
  73989. serial_type = aKey1[idx1];
  73990. if( serial_type>=10 ){
  73991. /* Serial types 12 or greater are strings and blobs (greater than
  73992. ** numbers). Types 10 and 11 are currently "reserved for future
  73993. ** use", so it doesn't really matter what the results of comparing
  73994. ** them to numberic values are. */
  73995. rc = +1;
  73996. }else if( serial_type==0 ){
  73997. rc = -1;
  73998. }else{
  73999. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  74000. if( serial_type==7 ){
  74001. if( mem1.u.r<pRhs->u.r ){
  74002. rc = -1;
  74003. }else if( mem1.u.r>pRhs->u.r ){
  74004. rc = +1;
  74005. }
  74006. }else{
  74007. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  74008. }
  74009. }
  74010. }
  74011. /* RHS is a string */
  74012. else if( pRhs->flags & MEM_Str ){
  74013. getVarint32(&aKey1[idx1], serial_type);
  74014. testcase( serial_type==12 );
  74015. if( serial_type<12 ){
  74016. rc = -1;
  74017. }else if( !(serial_type & 0x01) ){
  74018. rc = +1;
  74019. }else{
  74020. mem1.n = (serial_type - 12) / 2;
  74021. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  74022. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  74023. if( (d1+mem1.n) > (unsigned)nKey1 ){
  74024. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  74025. return 0; /* Corruption */
  74026. }else if( pKeyInfo->aColl[i] ){
  74027. mem1.enc = pKeyInfo->enc;
  74028. mem1.db = pKeyInfo->db;
  74029. mem1.flags = MEM_Str;
  74030. mem1.z = (char*)&aKey1[d1];
  74031. rc = vdbeCompareMemString(
  74032. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  74033. );
  74034. }else{
  74035. int nCmp = MIN(mem1.n, pRhs->n);
  74036. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  74037. if( rc==0 ) rc = mem1.n - pRhs->n;
  74038. }
  74039. }
  74040. }
  74041. /* RHS is a blob */
  74042. else if( pRhs->flags & MEM_Blob ){
  74043. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  74044. getVarint32(&aKey1[idx1], serial_type);
  74045. testcase( serial_type==12 );
  74046. if( serial_type<12 || (serial_type & 0x01) ){
  74047. rc = -1;
  74048. }else{
  74049. int nStr = (serial_type - 12) / 2;
  74050. testcase( (d1+nStr)==(unsigned)nKey1 );
  74051. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  74052. if( (d1+nStr) > (unsigned)nKey1 ){
  74053. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  74054. return 0; /* Corruption */
  74055. }else if( pRhs->flags & MEM_Zero ){
  74056. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  74057. rc = 1;
  74058. }else{
  74059. rc = nStr - pRhs->u.nZero;
  74060. }
  74061. }else{
  74062. int nCmp = MIN(nStr, pRhs->n);
  74063. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  74064. if( rc==0 ) rc = nStr - pRhs->n;
  74065. }
  74066. }
  74067. }
  74068. /* RHS is null */
  74069. else{
  74070. serial_type = aKey1[idx1];
  74071. rc = (serial_type!=0);
  74072. }
  74073. if( rc!=0 ){
  74074. if( pKeyInfo->aSortOrder[i] ){
  74075. rc = -rc;
  74076. }
  74077. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  74078. assert( mem1.szMalloc==0 ); /* See comment below */
  74079. return rc;
  74080. }
  74081. i++;
  74082. pRhs++;
  74083. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  74084. idx1 += sqlite3VarintLen(serial_type);
  74085. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  74086. /* No memory allocation is ever used on mem1. Prove this using
  74087. ** the following assert(). If the assert() fails, it indicates a
  74088. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  74089. assert( mem1.szMalloc==0 );
  74090. /* rc==0 here means that one or both of the keys ran out of fields and
  74091. ** all the fields up to that point were equal. Return the default_rc
  74092. ** value. */
  74093. assert( CORRUPT_DB
  74094. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  74095. || pKeyInfo->db->mallocFailed
  74096. );
  74097. pPKey2->eqSeen = 1;
  74098. return pPKey2->default_rc;
  74099. }
  74100. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  74101. int nKey1, const void *pKey1, /* Left key */
  74102. UnpackedRecord *pPKey2 /* Right key */
  74103. ){
  74104. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  74105. }
  74106. /*
  74107. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  74108. ** that (a) the first field of pPKey2 is an integer, and (b) the
  74109. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  74110. ** byte (i.e. is less than 128).
  74111. **
  74112. ** To avoid concerns about buffer overreads, this routine is only used
  74113. ** on schemas where the maximum valid header size is 63 bytes or less.
  74114. */
  74115. static int vdbeRecordCompareInt(
  74116. int nKey1, const void *pKey1, /* Left key */
  74117. UnpackedRecord *pPKey2 /* Right key */
  74118. ){
  74119. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  74120. int serial_type = ((const u8*)pKey1)[1];
  74121. int res;
  74122. u32 y;
  74123. u64 x;
  74124. i64 v;
  74125. i64 lhs;
  74126. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  74127. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  74128. switch( serial_type ){
  74129. case 1: { /* 1-byte signed integer */
  74130. lhs = ONE_BYTE_INT(aKey);
  74131. testcase( lhs<0 );
  74132. break;
  74133. }
  74134. case 2: { /* 2-byte signed integer */
  74135. lhs = TWO_BYTE_INT(aKey);
  74136. testcase( lhs<0 );
  74137. break;
  74138. }
  74139. case 3: { /* 3-byte signed integer */
  74140. lhs = THREE_BYTE_INT(aKey);
  74141. testcase( lhs<0 );
  74142. break;
  74143. }
  74144. case 4: { /* 4-byte signed integer */
  74145. y = FOUR_BYTE_UINT(aKey);
  74146. lhs = (i64)*(int*)&y;
  74147. testcase( lhs<0 );
  74148. break;
  74149. }
  74150. case 5: { /* 6-byte signed integer */
  74151. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  74152. testcase( lhs<0 );
  74153. break;
  74154. }
  74155. case 6: { /* 8-byte signed integer */
  74156. x = FOUR_BYTE_UINT(aKey);
  74157. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  74158. lhs = *(i64*)&x;
  74159. testcase( lhs<0 );
  74160. break;
  74161. }
  74162. case 8:
  74163. lhs = 0;
  74164. break;
  74165. case 9:
  74166. lhs = 1;
  74167. break;
  74168. /* This case could be removed without changing the results of running
  74169. ** this code. Including it causes gcc to generate a faster switch
  74170. ** statement (since the range of switch targets now starts at zero and
  74171. ** is contiguous) but does not cause any duplicate code to be generated
  74172. ** (as gcc is clever enough to combine the two like cases). Other
  74173. ** compilers might be similar. */
  74174. case 0: case 7:
  74175. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  74176. default:
  74177. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  74178. }
  74179. v = pPKey2->aMem[0].u.i;
  74180. if( v>lhs ){
  74181. res = pPKey2->r1;
  74182. }else if( v<lhs ){
  74183. res = pPKey2->r2;
  74184. }else if( pPKey2->nField>1 ){
  74185. /* The first fields of the two keys are equal. Compare the trailing
  74186. ** fields. */
  74187. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  74188. }else{
  74189. /* The first fields of the two keys are equal and there are no trailing
  74190. ** fields. Return pPKey2->default_rc in this case. */
  74191. res = pPKey2->default_rc;
  74192. pPKey2->eqSeen = 1;
  74193. }
  74194. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  74195. return res;
  74196. }
  74197. /*
  74198. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  74199. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  74200. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  74201. ** at the start of (pKey1/nKey1) fits in a single byte.
  74202. */
  74203. static int vdbeRecordCompareString(
  74204. int nKey1, const void *pKey1, /* Left key */
  74205. UnpackedRecord *pPKey2 /* Right key */
  74206. ){
  74207. const u8 *aKey1 = (const u8*)pKey1;
  74208. int serial_type;
  74209. int res;
  74210. assert( pPKey2->aMem[0].flags & MEM_Str );
  74211. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  74212. getVarint32(&aKey1[1], serial_type);
  74213. if( serial_type<12 ){
  74214. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  74215. }else if( !(serial_type & 0x01) ){
  74216. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  74217. }else{
  74218. int nCmp;
  74219. int nStr;
  74220. int szHdr = aKey1[0];
  74221. nStr = (serial_type-12) / 2;
  74222. if( (szHdr + nStr) > nKey1 ){
  74223. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  74224. return 0; /* Corruption */
  74225. }
  74226. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  74227. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  74228. if( res==0 ){
  74229. res = nStr - pPKey2->aMem[0].n;
  74230. if( res==0 ){
  74231. if( pPKey2->nField>1 ){
  74232. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  74233. }else{
  74234. res = pPKey2->default_rc;
  74235. pPKey2->eqSeen = 1;
  74236. }
  74237. }else if( res>0 ){
  74238. res = pPKey2->r2;
  74239. }else{
  74240. res = pPKey2->r1;
  74241. }
  74242. }else if( res>0 ){
  74243. res = pPKey2->r2;
  74244. }else{
  74245. res = pPKey2->r1;
  74246. }
  74247. }
  74248. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  74249. || CORRUPT_DB
  74250. || pPKey2->pKeyInfo->db->mallocFailed
  74251. );
  74252. return res;
  74253. }
  74254. /*
  74255. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  74256. ** suitable for comparing serialized records to the unpacked record passed
  74257. ** as the only argument.
  74258. */
  74259. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  74260. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  74261. ** that the size-of-header varint that occurs at the start of each record
  74262. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  74263. ** also assumes that it is safe to overread a buffer by at least the
  74264. ** maximum possible legal header size plus 8 bytes. Because there is
  74265. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  74266. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  74267. ** limit the size of the header to 64 bytes in cases where the first field
  74268. ** is an integer.
  74269. **
  74270. ** The easiest way to enforce this limit is to consider only records with
  74271. ** 13 fields or less. If the first field is an integer, the maximum legal
  74272. ** header size is (12*5 + 1 + 1) bytes. */
  74273. if( p->pKeyInfo->nAllField<=13 ){
  74274. int flags = p->aMem[0].flags;
  74275. if( p->pKeyInfo->aSortOrder[0] ){
  74276. p->r1 = 1;
  74277. p->r2 = -1;
  74278. }else{
  74279. p->r1 = -1;
  74280. p->r2 = 1;
  74281. }
  74282. if( (flags & MEM_Int) ){
  74283. return vdbeRecordCompareInt;
  74284. }
  74285. testcase( flags & MEM_Real );
  74286. testcase( flags & MEM_Null );
  74287. testcase( flags & MEM_Blob );
  74288. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  74289. assert( flags & MEM_Str );
  74290. return vdbeRecordCompareString;
  74291. }
  74292. }
  74293. return sqlite3VdbeRecordCompare;
  74294. }
  74295. /*
  74296. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  74297. ** Read the rowid (the last field in the record) and store it in *rowid.
  74298. ** Return SQLITE_OK if everything works, or an error code otherwise.
  74299. **
  74300. ** pCur might be pointing to text obtained from a corrupt database file.
  74301. ** So the content cannot be trusted. Do appropriate checks on the content.
  74302. */
  74303. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  74304. i64 nCellKey = 0;
  74305. int rc;
  74306. u32 szHdr; /* Size of the header */
  74307. u32 typeRowid; /* Serial type of the rowid */
  74308. u32 lenRowid; /* Size of the rowid */
  74309. Mem m, v;
  74310. /* Get the size of the index entry. Only indices entries of less
  74311. ** than 2GiB are support - anything large must be database corruption.
  74312. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  74313. ** this code can safely assume that nCellKey is 32-bits
  74314. */
  74315. assert( sqlite3BtreeCursorIsValid(pCur) );
  74316. nCellKey = sqlite3BtreePayloadSize(pCur);
  74317. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  74318. /* Read in the complete content of the index entry */
  74319. sqlite3VdbeMemInit(&m, db, 0);
  74320. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  74321. if( rc ){
  74322. return rc;
  74323. }
  74324. /* The index entry must begin with a header size */
  74325. (void)getVarint32((u8*)m.z, szHdr);
  74326. testcase( szHdr==3 );
  74327. testcase( szHdr==m.n );
  74328. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  74329. goto idx_rowid_corruption;
  74330. }
  74331. /* The last field of the index should be an integer - the ROWID.
  74332. ** Verify that the last entry really is an integer. */
  74333. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  74334. testcase( typeRowid==1 );
  74335. testcase( typeRowid==2 );
  74336. testcase( typeRowid==3 );
  74337. testcase( typeRowid==4 );
  74338. testcase( typeRowid==5 );
  74339. testcase( typeRowid==6 );
  74340. testcase( typeRowid==8 );
  74341. testcase( typeRowid==9 );
  74342. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  74343. goto idx_rowid_corruption;
  74344. }
  74345. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  74346. testcase( (u32)m.n==szHdr+lenRowid );
  74347. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  74348. goto idx_rowid_corruption;
  74349. }
  74350. /* Fetch the integer off the end of the index record */
  74351. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  74352. *rowid = v.u.i;
  74353. sqlite3VdbeMemRelease(&m);
  74354. return SQLITE_OK;
  74355. /* Jump here if database corruption is detected after m has been
  74356. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  74357. idx_rowid_corruption:
  74358. testcase( m.szMalloc!=0 );
  74359. sqlite3VdbeMemRelease(&m);
  74360. return SQLITE_CORRUPT_BKPT;
  74361. }
  74362. /*
  74363. ** Compare the key of the index entry that cursor pC is pointing to against
  74364. ** the key string in pUnpacked. Write into *pRes a number
  74365. ** that is negative, zero, or positive if pC is less than, equal to,
  74366. ** or greater than pUnpacked. Return SQLITE_OK on success.
  74367. **
  74368. ** pUnpacked is either created without a rowid or is truncated so that it
  74369. ** omits the rowid at the end. The rowid at the end of the index entry
  74370. ** is ignored as well. Hence, this routine only compares the prefixes
  74371. ** of the keys prior to the final rowid, not the entire key.
  74372. */
  74373. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  74374. sqlite3 *db, /* Database connection */
  74375. VdbeCursor *pC, /* The cursor to compare against */
  74376. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  74377. int *res /* Write the comparison result here */
  74378. ){
  74379. i64 nCellKey = 0;
  74380. int rc;
  74381. BtCursor *pCur;
  74382. Mem m;
  74383. assert( pC->eCurType==CURTYPE_BTREE );
  74384. pCur = pC->uc.pCursor;
  74385. assert( sqlite3BtreeCursorIsValid(pCur) );
  74386. nCellKey = sqlite3BtreePayloadSize(pCur);
  74387. /* nCellKey will always be between 0 and 0xffffffff because of the way
  74388. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  74389. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  74390. *res = 0;
  74391. return SQLITE_CORRUPT_BKPT;
  74392. }
  74393. sqlite3VdbeMemInit(&m, db, 0);
  74394. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  74395. if( rc ){
  74396. return rc;
  74397. }
  74398. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  74399. sqlite3VdbeMemRelease(&m);
  74400. return SQLITE_OK;
  74401. }
  74402. /*
  74403. ** This routine sets the value to be returned by subsequent calls to
  74404. ** sqlite3_changes() on the database handle 'db'.
  74405. */
  74406. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  74407. assert( sqlite3_mutex_held(db->mutex) );
  74408. db->nChange = nChange;
  74409. db->nTotalChange += nChange;
  74410. }
  74411. /*
  74412. ** Set a flag in the vdbe to update the change counter when it is finalised
  74413. ** or reset.
  74414. */
  74415. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  74416. v->changeCntOn = 1;
  74417. }
  74418. /*
  74419. ** Mark every prepared statement associated with a database connection
  74420. ** as expired.
  74421. **
  74422. ** An expired statement means that recompilation of the statement is
  74423. ** recommend. Statements expire when things happen that make their
  74424. ** programs obsolete. Removing user-defined functions or collating
  74425. ** sequences, or changing an authorization function are the types of
  74426. ** things that make prepared statements obsolete.
  74427. */
  74428. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  74429. Vdbe *p;
  74430. for(p = db->pVdbe; p; p=p->pNext){
  74431. p->expired = 1;
  74432. }
  74433. }
  74434. /*
  74435. ** Return the database associated with the Vdbe.
  74436. */
  74437. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  74438. return v->db;
  74439. }
  74440. /*
  74441. ** Return the SQLITE_PREPARE flags for a Vdbe.
  74442. */
  74443. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
  74444. return v->prepFlags;
  74445. }
  74446. /*
  74447. ** Return a pointer to an sqlite3_value structure containing the value bound
  74448. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  74449. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  74450. ** constants) to the value before returning it.
  74451. **
  74452. ** The returned value must be freed by the caller using sqlite3ValueFree().
  74453. */
  74454. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  74455. assert( iVar>0 );
  74456. if( v ){
  74457. Mem *pMem = &v->aVar[iVar-1];
  74458. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  74459. if( 0==(pMem->flags & MEM_Null) ){
  74460. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  74461. if( pRet ){
  74462. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  74463. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  74464. }
  74465. return pRet;
  74466. }
  74467. }
  74468. return 0;
  74469. }
  74470. /*
  74471. ** Configure SQL variable iVar so that binding a new value to it signals
  74472. ** to sqlite3_reoptimize() that re-preparing the statement may result
  74473. ** in a better query plan.
  74474. */
  74475. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  74476. assert( iVar>0 );
  74477. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  74478. if( iVar>=32 ){
  74479. v->expmask |= 0x80000000;
  74480. }else{
  74481. v->expmask |= ((u32)1 << (iVar-1));
  74482. }
  74483. }
  74484. /*
  74485. ** Cause a function to throw an error if it was call from OP_PureFunc
  74486. ** rather than OP_Function.
  74487. **
  74488. ** OP_PureFunc means that the function must be deterministic, and should
  74489. ** throw an error if it is given inputs that would make it non-deterministic.
  74490. ** This routine is invoked by date/time functions that use non-deterministic
  74491. ** features such as 'now'.
  74492. */
  74493. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
  74494. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  74495. if( pCtx->pVdbe==0 ) return 1;
  74496. #endif
  74497. if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
  74498. sqlite3_result_error(pCtx,
  74499. "non-deterministic function in index expression or CHECK constraint",
  74500. -1);
  74501. return 0;
  74502. }
  74503. return 1;
  74504. }
  74505. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74506. /*
  74507. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  74508. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  74509. ** in memory obtained from sqlite3DbMalloc).
  74510. */
  74511. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  74512. if( pVtab->zErrMsg ){
  74513. sqlite3 *db = p->db;
  74514. sqlite3DbFree(db, p->zErrMsg);
  74515. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  74516. sqlite3_free(pVtab->zErrMsg);
  74517. pVtab->zErrMsg = 0;
  74518. }
  74519. }
  74520. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74521. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  74522. /*
  74523. ** If the second argument is not NULL, release any allocations associated
  74524. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  74525. ** structure itself, using sqlite3DbFree().
  74526. **
  74527. ** This function is used to free UnpackedRecord structures allocated by
  74528. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  74529. */
  74530. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  74531. if( p ){
  74532. int i;
  74533. for(i=0; i<nField; i++){
  74534. Mem *pMem = &p->aMem[i];
  74535. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  74536. }
  74537. sqlite3DbFreeNN(db, p);
  74538. }
  74539. }
  74540. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  74541. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  74542. /*
  74543. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  74544. ** then cursor passed as the second argument should point to the row about
  74545. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  74546. ** the required value will be read from the row the cursor points to.
  74547. */
  74548. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  74549. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  74550. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  74551. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  74552. const char *zDb, /* Database name */
  74553. Table *pTab, /* Modified table */
  74554. i64 iKey1, /* Initial key value */
  74555. int iReg /* Register for new.* record */
  74556. ){
  74557. sqlite3 *db = v->db;
  74558. i64 iKey2;
  74559. PreUpdate preupdate;
  74560. const char *zTbl = pTab->zName;
  74561. static const u8 fakeSortOrder = 0;
  74562. assert( db->pPreUpdate==0 );
  74563. memset(&preupdate, 0, sizeof(PreUpdate));
  74564. if( HasRowid(pTab)==0 ){
  74565. iKey1 = iKey2 = 0;
  74566. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  74567. }else{
  74568. if( op==SQLITE_UPDATE ){
  74569. iKey2 = v->aMem[iReg].u.i;
  74570. }else{
  74571. iKey2 = iKey1;
  74572. }
  74573. }
  74574. assert( pCsr->nField==pTab->nCol
  74575. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  74576. );
  74577. preupdate.v = v;
  74578. preupdate.pCsr = pCsr;
  74579. preupdate.op = op;
  74580. preupdate.iNewReg = iReg;
  74581. preupdate.keyinfo.db = db;
  74582. preupdate.keyinfo.enc = ENC(db);
  74583. preupdate.keyinfo.nKeyField = pTab->nCol;
  74584. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  74585. preupdate.iKey1 = iKey1;
  74586. preupdate.iKey2 = iKey2;
  74587. preupdate.pTab = pTab;
  74588. db->pPreUpdate = &preupdate;
  74589. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  74590. db->pPreUpdate = 0;
  74591. sqlite3DbFree(db, preupdate.aRecord);
  74592. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
  74593. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
  74594. if( preupdate.aNew ){
  74595. int i;
  74596. for(i=0; i<pCsr->nField; i++){
  74597. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  74598. }
  74599. sqlite3DbFreeNN(db, preupdate.aNew);
  74600. }
  74601. }
  74602. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  74603. /************** End of vdbeaux.c *********************************************/
  74604. /************** Begin file vdbeapi.c *****************************************/
  74605. /*
  74606. ** 2004 May 26
  74607. **
  74608. ** The author disclaims copyright to this source code. In place of
  74609. ** a legal notice, here is a blessing:
  74610. **
  74611. ** May you do good and not evil.
  74612. ** May you find forgiveness for yourself and forgive others.
  74613. ** May you share freely, never taking more than you give.
  74614. **
  74615. *************************************************************************
  74616. **
  74617. ** This file contains code use to implement APIs that are part of the
  74618. ** VDBE.
  74619. */
  74620. /* #include "sqliteInt.h" */
  74621. /* #include "vdbeInt.h" */
  74622. #ifndef SQLITE_OMIT_DEPRECATED
  74623. /*
  74624. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  74625. ** to be recompiled. A statement needs to be recompiled whenever the
  74626. ** execution environment changes in a way that would alter the program
  74627. ** that sqlite3_prepare() generates. For example, if new functions or
  74628. ** collating sequences are registered or if an authorizer function is
  74629. ** added or changed.
  74630. */
  74631. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  74632. Vdbe *p = (Vdbe*)pStmt;
  74633. return p==0 || p->expired;
  74634. }
  74635. #endif
  74636. /*
  74637. ** Check on a Vdbe to make sure it has not been finalized. Log
  74638. ** an error and return true if it has been finalized (or is otherwise
  74639. ** invalid). Return false if it is ok.
  74640. */
  74641. static int vdbeSafety(Vdbe *p){
  74642. if( p->db==0 ){
  74643. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  74644. return 1;
  74645. }else{
  74646. return 0;
  74647. }
  74648. }
  74649. static int vdbeSafetyNotNull(Vdbe *p){
  74650. if( p==0 ){
  74651. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  74652. return 1;
  74653. }else{
  74654. return vdbeSafety(p);
  74655. }
  74656. }
  74657. #ifndef SQLITE_OMIT_TRACE
  74658. /*
  74659. ** Invoke the profile callback. This routine is only called if we already
  74660. ** know that the profile callback is defined and needs to be invoked.
  74661. */
  74662. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  74663. sqlite3_int64 iNow;
  74664. sqlite3_int64 iElapse;
  74665. assert( p->startTime>0 );
  74666. assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
  74667. assert( db->init.busy==0 );
  74668. assert( p->zSql!=0 );
  74669. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  74670. iElapse = (iNow - p->startTime)*1000000;
  74671. if( db->xProfile ){
  74672. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  74673. }
  74674. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  74675. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  74676. }
  74677. p->startTime = 0;
  74678. }
  74679. /*
  74680. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  74681. ** is needed, and it invokes the callback if it is needed.
  74682. */
  74683. # define checkProfileCallback(DB,P) \
  74684. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  74685. #else
  74686. # define checkProfileCallback(DB,P) /*no-op*/
  74687. #endif
  74688. /*
  74689. ** The following routine destroys a virtual machine that is created by
  74690. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  74691. ** success/failure code that describes the result of executing the virtual
  74692. ** machine.
  74693. **
  74694. ** This routine sets the error code and string returned by
  74695. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  74696. */
  74697. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  74698. int rc;
  74699. if( pStmt==0 ){
  74700. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  74701. ** pointer is a harmless no-op. */
  74702. rc = SQLITE_OK;
  74703. }else{
  74704. Vdbe *v = (Vdbe*)pStmt;
  74705. sqlite3 *db = v->db;
  74706. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  74707. sqlite3_mutex_enter(db->mutex);
  74708. checkProfileCallback(db, v);
  74709. rc = sqlite3VdbeFinalize(v);
  74710. rc = sqlite3ApiExit(db, rc);
  74711. sqlite3LeaveMutexAndCloseZombie(db);
  74712. }
  74713. return rc;
  74714. }
  74715. /*
  74716. ** Terminate the current execution of an SQL statement and reset it
  74717. ** back to its starting state so that it can be reused. A success code from
  74718. ** the prior execution is returned.
  74719. **
  74720. ** This routine sets the error code and string returned by
  74721. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  74722. */
  74723. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  74724. int rc;
  74725. if( pStmt==0 ){
  74726. rc = SQLITE_OK;
  74727. }else{
  74728. Vdbe *v = (Vdbe*)pStmt;
  74729. sqlite3 *db = v->db;
  74730. sqlite3_mutex_enter(db->mutex);
  74731. checkProfileCallback(db, v);
  74732. rc = sqlite3VdbeReset(v);
  74733. sqlite3VdbeRewind(v);
  74734. assert( (rc & (db->errMask))==rc );
  74735. rc = sqlite3ApiExit(db, rc);
  74736. sqlite3_mutex_leave(db->mutex);
  74737. }
  74738. return rc;
  74739. }
  74740. /*
  74741. ** Set all the parameters in the compiled SQL statement to NULL.
  74742. */
  74743. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  74744. int i;
  74745. int rc = SQLITE_OK;
  74746. Vdbe *p = (Vdbe*)pStmt;
  74747. #if SQLITE_THREADSAFE
  74748. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  74749. #endif
  74750. sqlite3_mutex_enter(mutex);
  74751. for(i=0; i<p->nVar; i++){
  74752. sqlite3VdbeMemRelease(&p->aVar[i]);
  74753. p->aVar[i].flags = MEM_Null;
  74754. }
  74755. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  74756. if( p->expmask ){
  74757. p->expired = 1;
  74758. }
  74759. sqlite3_mutex_leave(mutex);
  74760. return rc;
  74761. }
  74762. /**************************** sqlite3_value_ *******************************
  74763. ** The following routines extract information from a Mem or sqlite3_value
  74764. ** structure.
  74765. */
  74766. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  74767. Mem *p = (Mem*)pVal;
  74768. if( p->flags & (MEM_Blob|MEM_Str) ){
  74769. if( ExpandBlob(p)!=SQLITE_OK ){
  74770. assert( p->flags==MEM_Null && p->z==0 );
  74771. return 0;
  74772. }
  74773. p->flags |= MEM_Blob;
  74774. return p->n ? p->z : 0;
  74775. }else{
  74776. return sqlite3_value_text(pVal);
  74777. }
  74778. }
  74779. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  74780. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  74781. }
  74782. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  74783. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  74784. }
  74785. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  74786. return sqlite3VdbeRealValue((Mem*)pVal);
  74787. }
  74788. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  74789. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  74790. }
  74791. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  74792. return sqlite3VdbeIntValue((Mem*)pVal);
  74793. }
  74794. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  74795. Mem *pMem = (Mem*)pVal;
  74796. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  74797. }
  74798. SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
  74799. Mem *p = (Mem*)pVal;
  74800. if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
  74801. (MEM_Null|MEM_Term|MEM_Subtype)
  74802. && zPType!=0
  74803. && p->eSubtype=='p'
  74804. && strcmp(p->u.zPType, zPType)==0
  74805. ){
  74806. return (void*)p->z;
  74807. }else{
  74808. return 0;
  74809. }
  74810. }
  74811. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  74812. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  74813. }
  74814. #ifndef SQLITE_OMIT_UTF16
  74815. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  74816. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  74817. }
  74818. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  74819. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  74820. }
  74821. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  74822. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  74823. }
  74824. #endif /* SQLITE_OMIT_UTF16 */
  74825. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  74826. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  74827. ** point number string BLOB NULL
  74828. */
  74829. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  74830. static const u8 aType[] = {
  74831. SQLITE_BLOB, /* 0x00 */
  74832. SQLITE_NULL, /* 0x01 */
  74833. SQLITE_TEXT, /* 0x02 */
  74834. SQLITE_NULL, /* 0x03 */
  74835. SQLITE_INTEGER, /* 0x04 */
  74836. SQLITE_NULL, /* 0x05 */
  74837. SQLITE_INTEGER, /* 0x06 */
  74838. SQLITE_NULL, /* 0x07 */
  74839. SQLITE_FLOAT, /* 0x08 */
  74840. SQLITE_NULL, /* 0x09 */
  74841. SQLITE_FLOAT, /* 0x0a */
  74842. SQLITE_NULL, /* 0x0b */
  74843. SQLITE_INTEGER, /* 0x0c */
  74844. SQLITE_NULL, /* 0x0d */
  74845. SQLITE_INTEGER, /* 0x0e */
  74846. SQLITE_NULL, /* 0x0f */
  74847. SQLITE_BLOB, /* 0x10 */
  74848. SQLITE_NULL, /* 0x11 */
  74849. SQLITE_TEXT, /* 0x12 */
  74850. SQLITE_NULL, /* 0x13 */
  74851. SQLITE_INTEGER, /* 0x14 */
  74852. SQLITE_NULL, /* 0x15 */
  74853. SQLITE_INTEGER, /* 0x16 */
  74854. SQLITE_NULL, /* 0x17 */
  74855. SQLITE_FLOAT, /* 0x18 */
  74856. SQLITE_NULL, /* 0x19 */
  74857. SQLITE_FLOAT, /* 0x1a */
  74858. SQLITE_NULL, /* 0x1b */
  74859. SQLITE_INTEGER, /* 0x1c */
  74860. SQLITE_NULL, /* 0x1d */
  74861. SQLITE_INTEGER, /* 0x1e */
  74862. SQLITE_NULL, /* 0x1f */
  74863. };
  74864. return aType[pVal->flags&MEM_AffMask];
  74865. }
  74866. /* Return true if a parameter to xUpdate represents an unchanged column */
  74867. SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
  74868. return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
  74869. }
  74870. /* Make a copy of an sqlite3_value object
  74871. */
  74872. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  74873. sqlite3_value *pNew;
  74874. if( pOrig==0 ) return 0;
  74875. pNew = sqlite3_malloc( sizeof(*pNew) );
  74876. if( pNew==0 ) return 0;
  74877. memset(pNew, 0, sizeof(*pNew));
  74878. memcpy(pNew, pOrig, MEMCELLSIZE);
  74879. pNew->flags &= ~MEM_Dyn;
  74880. pNew->db = 0;
  74881. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  74882. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  74883. pNew->flags |= MEM_Ephem;
  74884. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  74885. sqlite3ValueFree(pNew);
  74886. pNew = 0;
  74887. }
  74888. }
  74889. return pNew;
  74890. }
  74891. /* Destroy an sqlite3_value object previously obtained from
  74892. ** sqlite3_value_dup().
  74893. */
  74894. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  74895. sqlite3ValueFree(pOld);
  74896. }
  74897. /**************************** sqlite3_result_ *******************************
  74898. ** The following routines are used by user-defined functions to specify
  74899. ** the function result.
  74900. **
  74901. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  74902. ** result as a string or blob but if the string or blob is too large, it
  74903. ** then sets the error code to SQLITE_TOOBIG
  74904. **
  74905. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  74906. ** on value P is not going to be used and need to be destroyed.
  74907. */
  74908. static void setResultStrOrError(
  74909. sqlite3_context *pCtx, /* Function context */
  74910. const char *z, /* String pointer */
  74911. int n, /* Bytes in string, or negative */
  74912. u8 enc, /* Encoding of z. 0 for BLOBs */
  74913. void (*xDel)(void*) /* Destructor function */
  74914. ){
  74915. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  74916. sqlite3_result_error_toobig(pCtx);
  74917. }
  74918. }
  74919. static int invokeValueDestructor(
  74920. const void *p, /* Value to destroy */
  74921. void (*xDel)(void*), /* The destructor */
  74922. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  74923. ){
  74924. assert( xDel!=SQLITE_DYNAMIC );
  74925. if( xDel==0 ){
  74926. /* noop */
  74927. }else if( xDel==SQLITE_TRANSIENT ){
  74928. /* noop */
  74929. }else{
  74930. xDel((void*)p);
  74931. }
  74932. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  74933. return SQLITE_TOOBIG;
  74934. }
  74935. SQLITE_API void sqlite3_result_blob(
  74936. sqlite3_context *pCtx,
  74937. const void *z,
  74938. int n,
  74939. void (*xDel)(void *)
  74940. ){
  74941. assert( n>=0 );
  74942. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74943. setResultStrOrError(pCtx, z, n, 0, xDel);
  74944. }
  74945. SQLITE_API void sqlite3_result_blob64(
  74946. sqlite3_context *pCtx,
  74947. const void *z,
  74948. sqlite3_uint64 n,
  74949. void (*xDel)(void *)
  74950. ){
  74951. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74952. assert( xDel!=SQLITE_DYNAMIC );
  74953. if( n>0x7fffffff ){
  74954. (void)invokeValueDestructor(z, xDel, pCtx);
  74955. }else{
  74956. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  74957. }
  74958. }
  74959. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  74960. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74961. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  74962. }
  74963. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  74964. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74965. pCtx->isError = SQLITE_ERROR;
  74966. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  74967. }
  74968. #ifndef SQLITE_OMIT_UTF16
  74969. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  74970. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74971. pCtx->isError = SQLITE_ERROR;
  74972. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  74973. }
  74974. #endif
  74975. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  74976. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74977. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  74978. }
  74979. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  74980. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74981. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  74982. }
  74983. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  74984. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74985. sqlite3VdbeMemSetNull(pCtx->pOut);
  74986. }
  74987. SQLITE_API void sqlite3_result_pointer(
  74988. sqlite3_context *pCtx,
  74989. void *pPtr,
  74990. const char *zPType,
  74991. void (*xDestructor)(void*)
  74992. ){
  74993. Mem *pOut = pCtx->pOut;
  74994. assert( sqlite3_mutex_held(pOut->db->mutex) );
  74995. sqlite3VdbeMemRelease(pOut);
  74996. pOut->flags = MEM_Null;
  74997. sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
  74998. }
  74999. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  75000. Mem *pOut = pCtx->pOut;
  75001. assert( sqlite3_mutex_held(pOut->db->mutex) );
  75002. pOut->eSubtype = eSubtype & 0xff;
  75003. pOut->flags |= MEM_Subtype;
  75004. }
  75005. SQLITE_API void sqlite3_result_text(
  75006. sqlite3_context *pCtx,
  75007. const char *z,
  75008. int n,
  75009. void (*xDel)(void *)
  75010. ){
  75011. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75012. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  75013. }
  75014. SQLITE_API void sqlite3_result_text64(
  75015. sqlite3_context *pCtx,
  75016. const char *z,
  75017. sqlite3_uint64 n,
  75018. void (*xDel)(void *),
  75019. unsigned char enc
  75020. ){
  75021. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75022. assert( xDel!=SQLITE_DYNAMIC );
  75023. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  75024. if( n>0x7fffffff ){
  75025. (void)invokeValueDestructor(z, xDel, pCtx);
  75026. }else{
  75027. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  75028. }
  75029. }
  75030. #ifndef SQLITE_OMIT_UTF16
  75031. SQLITE_API void sqlite3_result_text16(
  75032. sqlite3_context *pCtx,
  75033. const void *z,
  75034. int n,
  75035. void (*xDel)(void *)
  75036. ){
  75037. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75038. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  75039. }
  75040. SQLITE_API void sqlite3_result_text16be(
  75041. sqlite3_context *pCtx,
  75042. const void *z,
  75043. int n,
  75044. void (*xDel)(void *)
  75045. ){
  75046. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75047. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  75048. }
  75049. SQLITE_API void sqlite3_result_text16le(
  75050. sqlite3_context *pCtx,
  75051. const void *z,
  75052. int n,
  75053. void (*xDel)(void *)
  75054. ){
  75055. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75056. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  75057. }
  75058. #endif /* SQLITE_OMIT_UTF16 */
  75059. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  75060. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75061. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  75062. }
  75063. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  75064. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75065. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  75066. }
  75067. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  75068. Mem *pOut = pCtx->pOut;
  75069. assert( sqlite3_mutex_held(pOut->db->mutex) );
  75070. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  75071. return SQLITE_TOOBIG;
  75072. }
  75073. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  75074. return SQLITE_OK;
  75075. }
  75076. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  75077. pCtx->isError = errCode ? errCode : -1;
  75078. #ifdef SQLITE_DEBUG
  75079. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  75080. #endif
  75081. if( pCtx->pOut->flags & MEM_Null ){
  75082. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  75083. SQLITE_UTF8, SQLITE_STATIC);
  75084. }
  75085. }
  75086. /* Force an SQLITE_TOOBIG error. */
  75087. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  75088. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75089. pCtx->isError = SQLITE_TOOBIG;
  75090. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  75091. SQLITE_UTF8, SQLITE_STATIC);
  75092. }
  75093. /* An SQLITE_NOMEM error. */
  75094. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  75095. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75096. sqlite3VdbeMemSetNull(pCtx->pOut);
  75097. pCtx->isError = SQLITE_NOMEM_BKPT;
  75098. sqlite3OomFault(pCtx->pOut->db);
  75099. }
  75100. /*
  75101. ** This function is called after a transaction has been committed. It
  75102. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  75103. */
  75104. static int doWalCallbacks(sqlite3 *db){
  75105. int rc = SQLITE_OK;
  75106. #ifndef SQLITE_OMIT_WAL
  75107. int i;
  75108. for(i=0; i<db->nDb; i++){
  75109. Btree *pBt = db->aDb[i].pBt;
  75110. if( pBt ){
  75111. int nEntry;
  75112. sqlite3BtreeEnter(pBt);
  75113. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  75114. sqlite3BtreeLeave(pBt);
  75115. if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
  75116. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  75117. }
  75118. }
  75119. }
  75120. #endif
  75121. return rc;
  75122. }
  75123. /*
  75124. ** Execute the statement pStmt, either until a row of data is ready, the
  75125. ** statement is completely executed or an error occurs.
  75126. **
  75127. ** This routine implements the bulk of the logic behind the sqlite_step()
  75128. ** API. The only thing omitted is the automatic recompile if a
  75129. ** schema change has occurred. That detail is handled by the
  75130. ** outer sqlite3_step() wrapper procedure.
  75131. */
  75132. static int sqlite3Step(Vdbe *p){
  75133. sqlite3 *db;
  75134. int rc;
  75135. assert(p);
  75136. if( p->magic!=VDBE_MAGIC_RUN ){
  75137. /* We used to require that sqlite3_reset() be called before retrying
  75138. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  75139. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  75140. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  75141. ** This "automatic-reset" change is not technically an incompatibility,
  75142. ** since any application that receives an SQLITE_MISUSE is broken by
  75143. ** definition.
  75144. **
  75145. ** Nevertheless, some published applications that were originally written
  75146. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  75147. ** returns, and those were broken by the automatic-reset change. As a
  75148. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  75149. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  75150. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  75151. ** or SQLITE_BUSY error.
  75152. */
  75153. #ifdef SQLITE_OMIT_AUTORESET
  75154. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  75155. sqlite3_reset((sqlite3_stmt*)p);
  75156. }else{
  75157. return SQLITE_MISUSE_BKPT;
  75158. }
  75159. #else
  75160. sqlite3_reset((sqlite3_stmt*)p);
  75161. #endif
  75162. }
  75163. /* Check that malloc() has not failed. If it has, return early. */
  75164. db = p->db;
  75165. if( db->mallocFailed ){
  75166. p->rc = SQLITE_NOMEM;
  75167. return SQLITE_NOMEM_BKPT;
  75168. }
  75169. if( p->pc<=0 && p->expired ){
  75170. p->rc = SQLITE_SCHEMA;
  75171. rc = SQLITE_ERROR;
  75172. goto end_of_step;
  75173. }
  75174. if( p->pc<0 ){
  75175. /* If there are no other statements currently running, then
  75176. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  75177. ** from interrupting a statement that has not yet started.
  75178. */
  75179. if( db->nVdbeActive==0 ){
  75180. db->u1.isInterrupted = 0;
  75181. }
  75182. assert( db->nVdbeWrite>0 || db->autoCommit==0
  75183. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  75184. );
  75185. #ifndef SQLITE_OMIT_TRACE
  75186. if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
  75187. && !db->init.busy && p->zSql ){
  75188. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  75189. }else{
  75190. assert( p->startTime==0 );
  75191. }
  75192. #endif
  75193. db->nVdbeActive++;
  75194. if( p->readOnly==0 ) db->nVdbeWrite++;
  75195. if( p->bIsReader ) db->nVdbeRead++;
  75196. p->pc = 0;
  75197. }
  75198. #ifdef SQLITE_DEBUG
  75199. p->rcApp = SQLITE_OK;
  75200. #endif
  75201. #ifndef SQLITE_OMIT_EXPLAIN
  75202. if( p->explain ){
  75203. rc = sqlite3VdbeList(p);
  75204. }else
  75205. #endif /* SQLITE_OMIT_EXPLAIN */
  75206. {
  75207. db->nVdbeExec++;
  75208. rc = sqlite3VdbeExec(p);
  75209. db->nVdbeExec--;
  75210. }
  75211. #ifndef SQLITE_OMIT_TRACE
  75212. /* If the statement completed successfully, invoke the profile callback */
  75213. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  75214. #endif
  75215. if( rc==SQLITE_DONE && db->autoCommit ){
  75216. assert( p->rc==SQLITE_OK );
  75217. p->rc = doWalCallbacks(db);
  75218. if( p->rc!=SQLITE_OK ){
  75219. rc = SQLITE_ERROR;
  75220. }
  75221. }
  75222. db->errCode = rc;
  75223. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  75224. p->rc = SQLITE_NOMEM_BKPT;
  75225. }
  75226. end_of_step:
  75227. /* At this point local variable rc holds the value that should be
  75228. ** returned if this statement was compiled using the legacy
  75229. ** sqlite3_prepare() interface. According to the docs, this can only
  75230. ** be one of the values in the first assert() below. Variable p->rc
  75231. ** contains the value that would be returned if sqlite3_finalize()
  75232. ** were called on statement p.
  75233. */
  75234. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  75235. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  75236. );
  75237. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  75238. if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
  75239. && rc!=SQLITE_ROW
  75240. && rc!=SQLITE_DONE
  75241. ){
  75242. /* If this statement was prepared using saved SQL and an
  75243. ** error has occurred, then return the error code in p->rc to the
  75244. ** caller. Set the error code in the database handle to the same value.
  75245. */
  75246. rc = sqlite3VdbeTransferError(p);
  75247. }
  75248. return (rc&db->errMask);
  75249. }
  75250. /*
  75251. ** This is the top-level implementation of sqlite3_step(). Call
  75252. ** sqlite3Step() to do most of the work. If a schema error occurs,
  75253. ** call sqlite3Reprepare() and try again.
  75254. */
  75255. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  75256. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  75257. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  75258. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  75259. sqlite3 *db; /* The database connection */
  75260. if( vdbeSafetyNotNull(v) ){
  75261. return SQLITE_MISUSE_BKPT;
  75262. }
  75263. db = v->db;
  75264. sqlite3_mutex_enter(db->mutex);
  75265. v->doingRerun = 0;
  75266. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  75267. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  75268. int savedPc = v->pc;
  75269. rc = sqlite3Reprepare(v);
  75270. if( rc!=SQLITE_OK ){
  75271. /* This case occurs after failing to recompile an sql statement.
  75272. ** The error message from the SQL compiler has already been loaded
  75273. ** into the database handle. This block copies the error message
  75274. ** from the database handle into the statement and sets the statement
  75275. ** program counter to 0 to ensure that when the statement is
  75276. ** finalized or reset the parser error message is available via
  75277. ** sqlite3_errmsg() and sqlite3_errcode().
  75278. */
  75279. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  75280. sqlite3DbFree(db, v->zErrMsg);
  75281. if( !db->mallocFailed ){
  75282. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  75283. v->rc = rc = sqlite3ApiExit(db, rc);
  75284. } else {
  75285. v->zErrMsg = 0;
  75286. v->rc = rc = SQLITE_NOMEM_BKPT;
  75287. }
  75288. break;
  75289. }
  75290. sqlite3_reset(pStmt);
  75291. if( savedPc>=0 ) v->doingRerun = 1;
  75292. assert( v->expired==0 );
  75293. }
  75294. sqlite3_mutex_leave(db->mutex);
  75295. return rc;
  75296. }
  75297. /*
  75298. ** Extract the user data from a sqlite3_context structure and return a
  75299. ** pointer to it.
  75300. */
  75301. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  75302. assert( p && p->pFunc );
  75303. return p->pFunc->pUserData;
  75304. }
  75305. /*
  75306. ** Extract the user data from a sqlite3_context structure and return a
  75307. ** pointer to it.
  75308. **
  75309. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  75310. ** returns a copy of the pointer to the database connection (the 1st
  75311. ** parameter) of the sqlite3_create_function() and
  75312. ** sqlite3_create_function16() routines that originally registered the
  75313. ** application defined function.
  75314. */
  75315. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  75316. assert( p && p->pOut );
  75317. return p->pOut->db;
  75318. }
  75319. /*
  75320. ** If this routine is invoked from within an xColumn method of a virtual
  75321. ** table, then it returns true if and only if the the call is during an
  75322. ** UPDATE operation and the value of the column will not be modified
  75323. ** by the UPDATE.
  75324. **
  75325. ** If this routine is called from any context other than within the
  75326. ** xColumn method of a virtual table, then the return value is meaningless
  75327. ** and arbitrary.
  75328. **
  75329. ** Virtual table implements might use this routine to optimize their
  75330. ** performance by substituting a NULL result, or some other light-weight
  75331. ** value, as a signal to the xUpdate routine that the column is unchanged.
  75332. */
  75333. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
  75334. assert( p );
  75335. return sqlite3_value_nochange(p->pOut);
  75336. }
  75337. /*
  75338. ** Return the current time for a statement. If the current time
  75339. ** is requested more than once within the same run of a single prepared
  75340. ** statement, the exact same time is returned for each invocation regardless
  75341. ** of the amount of time that elapses between invocations. In other words,
  75342. ** the time returned is always the time of the first call.
  75343. */
  75344. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  75345. int rc;
  75346. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  75347. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  75348. assert( p->pVdbe!=0 );
  75349. #else
  75350. sqlite3_int64 iTime = 0;
  75351. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  75352. #endif
  75353. if( *piTime==0 ){
  75354. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  75355. if( rc ) *piTime = 0;
  75356. }
  75357. return *piTime;
  75358. }
  75359. /*
  75360. ** Create a new aggregate context for p and return a pointer to
  75361. ** its pMem->z element.
  75362. */
  75363. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  75364. Mem *pMem = p->pMem;
  75365. assert( (pMem->flags & MEM_Agg)==0 );
  75366. if( nByte<=0 ){
  75367. sqlite3VdbeMemSetNull(pMem);
  75368. pMem->z = 0;
  75369. }else{
  75370. sqlite3VdbeMemClearAndResize(pMem, nByte);
  75371. pMem->flags = MEM_Agg;
  75372. pMem->u.pDef = p->pFunc;
  75373. if( pMem->z ){
  75374. memset(pMem->z, 0, nByte);
  75375. }
  75376. }
  75377. return (void*)pMem->z;
  75378. }
  75379. /*
  75380. ** Allocate or return the aggregate context for a user function. A new
  75381. ** context is allocated on the first call. Subsequent calls return the
  75382. ** same context that was returned on prior calls.
  75383. */
  75384. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  75385. assert( p && p->pFunc && p->pFunc->xFinalize );
  75386. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  75387. testcase( nByte<0 );
  75388. if( (p->pMem->flags & MEM_Agg)==0 ){
  75389. return createAggContext(p, nByte);
  75390. }else{
  75391. return (void*)p->pMem->z;
  75392. }
  75393. }
  75394. /*
  75395. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  75396. ** the user-function defined by pCtx.
  75397. **
  75398. ** The left-most argument is 0.
  75399. **
  75400. ** Undocumented behavior: If iArg is negative then access a cache of
  75401. ** auxiliary data pointers that is available to all functions within a
  75402. ** single prepared statement. The iArg values must match.
  75403. */
  75404. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  75405. AuxData *pAuxData;
  75406. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75407. #if SQLITE_ENABLE_STAT3_OR_STAT4
  75408. if( pCtx->pVdbe==0 ) return 0;
  75409. #else
  75410. assert( pCtx->pVdbe!=0 );
  75411. #endif
  75412. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  75413. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  75414. return pAuxData->pAux;
  75415. }
  75416. }
  75417. return 0;
  75418. }
  75419. /*
  75420. ** Set the auxiliary data pointer and delete function, for the iArg'th
  75421. ** argument to the user-function defined by pCtx. Any previous value is
  75422. ** deleted by calling the delete function specified when it was set.
  75423. **
  75424. ** The left-most argument is 0.
  75425. **
  75426. ** Undocumented behavior: If iArg is negative then make the data available
  75427. ** to all functions within the current prepared statement using iArg as an
  75428. ** access code.
  75429. */
  75430. SQLITE_API void sqlite3_set_auxdata(
  75431. sqlite3_context *pCtx,
  75432. int iArg,
  75433. void *pAux,
  75434. void (*xDelete)(void*)
  75435. ){
  75436. AuxData *pAuxData;
  75437. Vdbe *pVdbe = pCtx->pVdbe;
  75438. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  75439. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  75440. if( pVdbe==0 ) goto failed;
  75441. #else
  75442. assert( pVdbe!=0 );
  75443. #endif
  75444. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  75445. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  75446. break;
  75447. }
  75448. }
  75449. if( pAuxData==0 ){
  75450. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  75451. if( !pAuxData ) goto failed;
  75452. pAuxData->iAuxOp = pCtx->iOp;
  75453. pAuxData->iAuxArg = iArg;
  75454. pAuxData->pNextAux = pVdbe->pAuxData;
  75455. pVdbe->pAuxData = pAuxData;
  75456. if( pCtx->isError==0 ) pCtx->isError = -1;
  75457. }else if( pAuxData->xDeleteAux ){
  75458. pAuxData->xDeleteAux(pAuxData->pAux);
  75459. }
  75460. pAuxData->pAux = pAux;
  75461. pAuxData->xDeleteAux = xDelete;
  75462. return;
  75463. failed:
  75464. if( xDelete ){
  75465. xDelete(pAux);
  75466. }
  75467. }
  75468. #ifndef SQLITE_OMIT_DEPRECATED
  75469. /*
  75470. ** Return the number of times the Step function of an aggregate has been
  75471. ** called.
  75472. **
  75473. ** This function is deprecated. Do not use it for new code. It is
  75474. ** provide only to avoid breaking legacy code. New aggregate function
  75475. ** implementations should keep their own counts within their aggregate
  75476. ** context.
  75477. */
  75478. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  75479. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  75480. return p->pMem->n;
  75481. }
  75482. #endif
  75483. /*
  75484. ** Return the number of columns in the result set for the statement pStmt.
  75485. */
  75486. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  75487. Vdbe *pVm = (Vdbe *)pStmt;
  75488. return pVm ? pVm->nResColumn : 0;
  75489. }
  75490. /*
  75491. ** Return the number of values available from the current row of the
  75492. ** currently executing statement pStmt.
  75493. */
  75494. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  75495. Vdbe *pVm = (Vdbe *)pStmt;
  75496. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  75497. return pVm->nResColumn;
  75498. }
  75499. /*
  75500. ** Return a pointer to static memory containing an SQL NULL value.
  75501. */
  75502. static const Mem *columnNullValue(void){
  75503. /* Even though the Mem structure contains an element
  75504. ** of type i64, on certain architectures (x86) with certain compiler
  75505. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  75506. ** instead of an 8-byte one. This all works fine, except that when
  75507. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  75508. ** that a Mem structure is located on an 8-byte boundary. To prevent
  75509. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  75510. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  75511. ** __attribute__((aligned(8))) macro. */
  75512. static const Mem nullMem
  75513. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  75514. __attribute__((aligned(8)))
  75515. #endif
  75516. = {
  75517. /* .u = */ {0},
  75518. /* .flags = */ (u16)MEM_Null,
  75519. /* .enc = */ (u8)0,
  75520. /* .eSubtype = */ (u8)0,
  75521. /* .n = */ (int)0,
  75522. /* .z = */ (char*)0,
  75523. /* .zMalloc = */ (char*)0,
  75524. /* .szMalloc = */ (int)0,
  75525. /* .uTemp = */ (u32)0,
  75526. /* .db = */ (sqlite3*)0,
  75527. /* .xDel = */ (void(*)(void*))0,
  75528. #ifdef SQLITE_DEBUG
  75529. /* .pScopyFrom = */ (Mem*)0,
  75530. /* .pFiller = */ (void*)0,
  75531. #endif
  75532. };
  75533. return &nullMem;
  75534. }
  75535. /*
  75536. ** Check to see if column iCol of the given statement is valid. If
  75537. ** it is, return a pointer to the Mem for the value of that column.
  75538. ** If iCol is not valid, return a pointer to a Mem which has a value
  75539. ** of NULL.
  75540. */
  75541. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  75542. Vdbe *pVm;
  75543. Mem *pOut;
  75544. pVm = (Vdbe *)pStmt;
  75545. if( pVm==0 ) return (Mem*)columnNullValue();
  75546. assert( pVm->db );
  75547. sqlite3_mutex_enter(pVm->db->mutex);
  75548. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  75549. pOut = &pVm->pResultSet[i];
  75550. }else{
  75551. sqlite3Error(pVm->db, SQLITE_RANGE);
  75552. pOut = (Mem*)columnNullValue();
  75553. }
  75554. return pOut;
  75555. }
  75556. /*
  75557. ** This function is called after invoking an sqlite3_value_XXX function on a
  75558. ** column value (i.e. a value returned by evaluating an SQL expression in the
  75559. ** select list of a SELECT statement) that may cause a malloc() failure. If
  75560. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  75561. ** code of statement pStmt set to SQLITE_NOMEM.
  75562. **
  75563. ** Specifically, this is called from within:
  75564. **
  75565. ** sqlite3_column_int()
  75566. ** sqlite3_column_int64()
  75567. ** sqlite3_column_text()
  75568. ** sqlite3_column_text16()
  75569. ** sqlite3_column_real()
  75570. ** sqlite3_column_bytes()
  75571. ** sqlite3_column_bytes16()
  75572. ** sqiite3_column_blob()
  75573. */
  75574. static void columnMallocFailure(sqlite3_stmt *pStmt)
  75575. {
  75576. /* If malloc() failed during an encoding conversion within an
  75577. ** sqlite3_column_XXX API, then set the return code of the statement to
  75578. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  75579. ** and _finalize() will return NOMEM.
  75580. */
  75581. Vdbe *p = (Vdbe *)pStmt;
  75582. if( p ){
  75583. assert( p->db!=0 );
  75584. assert( sqlite3_mutex_held(p->db->mutex) );
  75585. p->rc = sqlite3ApiExit(p->db, p->rc);
  75586. sqlite3_mutex_leave(p->db->mutex);
  75587. }
  75588. }
  75589. /**************************** sqlite3_column_ *******************************
  75590. ** The following routines are used to access elements of the current row
  75591. ** in the result set.
  75592. */
  75593. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  75594. const void *val;
  75595. val = sqlite3_value_blob( columnMem(pStmt,i) );
  75596. /* Even though there is no encoding conversion, value_blob() might
  75597. ** need to call malloc() to expand the result of a zeroblob()
  75598. ** expression.
  75599. */
  75600. columnMallocFailure(pStmt);
  75601. return val;
  75602. }
  75603. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  75604. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  75605. columnMallocFailure(pStmt);
  75606. return val;
  75607. }
  75608. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  75609. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  75610. columnMallocFailure(pStmt);
  75611. return val;
  75612. }
  75613. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  75614. double val = sqlite3_value_double( columnMem(pStmt,i) );
  75615. columnMallocFailure(pStmt);
  75616. return val;
  75617. }
  75618. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  75619. int val = sqlite3_value_int( columnMem(pStmt,i) );
  75620. columnMallocFailure(pStmt);
  75621. return val;
  75622. }
  75623. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  75624. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  75625. columnMallocFailure(pStmt);
  75626. return val;
  75627. }
  75628. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  75629. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  75630. columnMallocFailure(pStmt);
  75631. return val;
  75632. }
  75633. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  75634. Mem *pOut = columnMem(pStmt, i);
  75635. if( pOut->flags&MEM_Static ){
  75636. pOut->flags &= ~MEM_Static;
  75637. pOut->flags |= MEM_Ephem;
  75638. }
  75639. columnMallocFailure(pStmt);
  75640. return (sqlite3_value *)pOut;
  75641. }
  75642. #ifndef SQLITE_OMIT_UTF16
  75643. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  75644. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  75645. columnMallocFailure(pStmt);
  75646. return val;
  75647. }
  75648. #endif /* SQLITE_OMIT_UTF16 */
  75649. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  75650. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  75651. columnMallocFailure(pStmt);
  75652. return iType;
  75653. }
  75654. /*
  75655. ** Convert the N-th element of pStmt->pColName[] into a string using
  75656. ** xFunc() then return that string. If N is out of range, return 0.
  75657. **
  75658. ** There are up to 5 names for each column. useType determines which
  75659. ** name is returned. Here are the names:
  75660. **
  75661. ** 0 The column name as it should be displayed for output
  75662. ** 1 The datatype name for the column
  75663. ** 2 The name of the database that the column derives from
  75664. ** 3 The name of the table that the column derives from
  75665. ** 4 The name of the table column that the result column derives from
  75666. **
  75667. ** If the result is not a simple column reference (if it is an expression
  75668. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  75669. */
  75670. static const void *columnName(
  75671. sqlite3_stmt *pStmt,
  75672. int N,
  75673. const void *(*xFunc)(Mem*),
  75674. int useType
  75675. ){
  75676. const void *ret;
  75677. Vdbe *p;
  75678. int n;
  75679. sqlite3 *db;
  75680. #ifdef SQLITE_ENABLE_API_ARMOR
  75681. if( pStmt==0 ){
  75682. (void)SQLITE_MISUSE_BKPT;
  75683. return 0;
  75684. }
  75685. #endif
  75686. ret = 0;
  75687. p = (Vdbe *)pStmt;
  75688. db = p->db;
  75689. assert( db!=0 );
  75690. n = sqlite3_column_count(pStmt);
  75691. if( N<n && N>=0 ){
  75692. N += useType*n;
  75693. sqlite3_mutex_enter(db->mutex);
  75694. assert( db->mallocFailed==0 );
  75695. ret = xFunc(&p->aColName[N]);
  75696. /* A malloc may have failed inside of the xFunc() call. If this
  75697. ** is the case, clear the mallocFailed flag and return NULL.
  75698. */
  75699. if( db->mallocFailed ){
  75700. sqlite3OomClear(db);
  75701. ret = 0;
  75702. }
  75703. sqlite3_mutex_leave(db->mutex);
  75704. }
  75705. return ret;
  75706. }
  75707. /*
  75708. ** Return the name of the Nth column of the result set returned by SQL
  75709. ** statement pStmt.
  75710. */
  75711. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  75712. return columnName(
  75713. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  75714. }
  75715. #ifndef SQLITE_OMIT_UTF16
  75716. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  75717. return columnName(
  75718. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  75719. }
  75720. #endif
  75721. /*
  75722. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  75723. ** not define OMIT_DECLTYPE.
  75724. */
  75725. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  75726. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  75727. and SQLITE_ENABLE_COLUMN_METADATA"
  75728. #endif
  75729. #ifndef SQLITE_OMIT_DECLTYPE
  75730. /*
  75731. ** Return the column declaration type (if applicable) of the 'i'th column
  75732. ** of the result set of SQL statement pStmt.
  75733. */
  75734. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  75735. return columnName(
  75736. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  75737. }
  75738. #ifndef SQLITE_OMIT_UTF16
  75739. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  75740. return columnName(
  75741. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  75742. }
  75743. #endif /* SQLITE_OMIT_UTF16 */
  75744. #endif /* SQLITE_OMIT_DECLTYPE */
  75745. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  75746. /*
  75747. ** Return the name of the database from which a result column derives.
  75748. ** NULL is returned if the result column is an expression or constant or
  75749. ** anything else which is not an unambiguous reference to a database column.
  75750. */
  75751. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  75752. return columnName(
  75753. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  75754. }
  75755. #ifndef SQLITE_OMIT_UTF16
  75756. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  75757. return columnName(
  75758. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  75759. }
  75760. #endif /* SQLITE_OMIT_UTF16 */
  75761. /*
  75762. ** Return the name of the table from which a result column derives.
  75763. ** NULL is returned if the result column is an expression or constant or
  75764. ** anything else which is not an unambiguous reference to a database column.
  75765. */
  75766. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  75767. return columnName(
  75768. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  75769. }
  75770. #ifndef SQLITE_OMIT_UTF16
  75771. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  75772. return columnName(
  75773. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  75774. }
  75775. #endif /* SQLITE_OMIT_UTF16 */
  75776. /*
  75777. ** Return the name of the table column from which a result column derives.
  75778. ** NULL is returned if the result column is an expression or constant or
  75779. ** anything else which is not an unambiguous reference to a database column.
  75780. */
  75781. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  75782. return columnName(
  75783. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  75784. }
  75785. #ifndef SQLITE_OMIT_UTF16
  75786. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  75787. return columnName(
  75788. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  75789. }
  75790. #endif /* SQLITE_OMIT_UTF16 */
  75791. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  75792. /******************************* sqlite3_bind_ ***************************
  75793. **
  75794. ** Routines used to attach values to wildcards in a compiled SQL statement.
  75795. */
  75796. /*
  75797. ** Unbind the value bound to variable i in virtual machine p. This is the
  75798. ** the same as binding a NULL value to the column. If the "i" parameter is
  75799. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  75800. **
  75801. ** A successful evaluation of this routine acquires the mutex on p.
  75802. ** the mutex is released if any kind of error occurs.
  75803. **
  75804. ** The error code stored in database p->db is overwritten with the return
  75805. ** value in any case.
  75806. */
  75807. static int vdbeUnbind(Vdbe *p, int i){
  75808. Mem *pVar;
  75809. if( vdbeSafetyNotNull(p) ){
  75810. return SQLITE_MISUSE_BKPT;
  75811. }
  75812. sqlite3_mutex_enter(p->db->mutex);
  75813. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  75814. sqlite3Error(p->db, SQLITE_MISUSE);
  75815. sqlite3_mutex_leave(p->db->mutex);
  75816. sqlite3_log(SQLITE_MISUSE,
  75817. "bind on a busy prepared statement: [%s]", p->zSql);
  75818. return SQLITE_MISUSE_BKPT;
  75819. }
  75820. if( i<1 || i>p->nVar ){
  75821. sqlite3Error(p->db, SQLITE_RANGE);
  75822. sqlite3_mutex_leave(p->db->mutex);
  75823. return SQLITE_RANGE;
  75824. }
  75825. i--;
  75826. pVar = &p->aVar[i];
  75827. sqlite3VdbeMemRelease(pVar);
  75828. pVar->flags = MEM_Null;
  75829. sqlite3Error(p->db, SQLITE_OK);
  75830. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  75831. ** binding a new value to this variable invalidates the current query plan.
  75832. **
  75833. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  75834. ** parameter in the WHERE clause might influence the choice of query plan
  75835. ** for a statement, then the statement will be automatically recompiled,
  75836. ** as if there had been a schema change, on the first sqlite3_step() call
  75837. ** following any change to the bindings of that parameter.
  75838. */
  75839. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  75840. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  75841. p->expired = 1;
  75842. }
  75843. return SQLITE_OK;
  75844. }
  75845. /*
  75846. ** Bind a text or BLOB value.
  75847. */
  75848. static int bindText(
  75849. sqlite3_stmt *pStmt, /* The statement to bind against */
  75850. int i, /* Index of the parameter to bind */
  75851. const void *zData, /* Pointer to the data to be bound */
  75852. int nData, /* Number of bytes of data to be bound */
  75853. void (*xDel)(void*), /* Destructor for the data */
  75854. u8 encoding /* Encoding for the data */
  75855. ){
  75856. Vdbe *p = (Vdbe *)pStmt;
  75857. Mem *pVar;
  75858. int rc;
  75859. rc = vdbeUnbind(p, i);
  75860. if( rc==SQLITE_OK ){
  75861. if( zData!=0 ){
  75862. pVar = &p->aVar[i-1];
  75863. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  75864. if( rc==SQLITE_OK && encoding!=0 ){
  75865. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  75866. }
  75867. if( rc ){
  75868. sqlite3Error(p->db, rc);
  75869. rc = sqlite3ApiExit(p->db, rc);
  75870. }
  75871. }
  75872. sqlite3_mutex_leave(p->db->mutex);
  75873. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  75874. xDel((void*)zData);
  75875. }
  75876. return rc;
  75877. }
  75878. /*
  75879. ** Bind a blob value to an SQL statement variable.
  75880. */
  75881. SQLITE_API int sqlite3_bind_blob(
  75882. sqlite3_stmt *pStmt,
  75883. int i,
  75884. const void *zData,
  75885. int nData,
  75886. void (*xDel)(void*)
  75887. ){
  75888. #ifdef SQLITE_ENABLE_API_ARMOR
  75889. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  75890. #endif
  75891. return bindText(pStmt, i, zData, nData, xDel, 0);
  75892. }
  75893. SQLITE_API int sqlite3_bind_blob64(
  75894. sqlite3_stmt *pStmt,
  75895. int i,
  75896. const void *zData,
  75897. sqlite3_uint64 nData,
  75898. void (*xDel)(void*)
  75899. ){
  75900. assert( xDel!=SQLITE_DYNAMIC );
  75901. if( nData>0x7fffffff ){
  75902. return invokeValueDestructor(zData, xDel, 0);
  75903. }else{
  75904. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  75905. }
  75906. }
  75907. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  75908. int rc;
  75909. Vdbe *p = (Vdbe *)pStmt;
  75910. rc = vdbeUnbind(p, i);
  75911. if( rc==SQLITE_OK ){
  75912. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  75913. sqlite3_mutex_leave(p->db->mutex);
  75914. }
  75915. return rc;
  75916. }
  75917. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  75918. return sqlite3_bind_int64(p, i, (i64)iValue);
  75919. }
  75920. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  75921. int rc;
  75922. Vdbe *p = (Vdbe *)pStmt;
  75923. rc = vdbeUnbind(p, i);
  75924. if( rc==SQLITE_OK ){
  75925. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  75926. sqlite3_mutex_leave(p->db->mutex);
  75927. }
  75928. return rc;
  75929. }
  75930. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  75931. int rc;
  75932. Vdbe *p = (Vdbe*)pStmt;
  75933. rc = vdbeUnbind(p, i);
  75934. if( rc==SQLITE_OK ){
  75935. sqlite3_mutex_leave(p->db->mutex);
  75936. }
  75937. return rc;
  75938. }
  75939. SQLITE_API int sqlite3_bind_pointer(
  75940. sqlite3_stmt *pStmt,
  75941. int i,
  75942. void *pPtr,
  75943. const char *zPTtype,
  75944. void (*xDestructor)(void*)
  75945. ){
  75946. int rc;
  75947. Vdbe *p = (Vdbe*)pStmt;
  75948. rc = vdbeUnbind(p, i);
  75949. if( rc==SQLITE_OK ){
  75950. sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
  75951. sqlite3_mutex_leave(p->db->mutex);
  75952. }else if( xDestructor ){
  75953. xDestructor(pPtr);
  75954. }
  75955. return rc;
  75956. }
  75957. SQLITE_API int sqlite3_bind_text(
  75958. sqlite3_stmt *pStmt,
  75959. int i,
  75960. const char *zData,
  75961. int nData,
  75962. void (*xDel)(void*)
  75963. ){
  75964. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  75965. }
  75966. SQLITE_API int sqlite3_bind_text64(
  75967. sqlite3_stmt *pStmt,
  75968. int i,
  75969. const char *zData,
  75970. sqlite3_uint64 nData,
  75971. void (*xDel)(void*),
  75972. unsigned char enc
  75973. ){
  75974. assert( xDel!=SQLITE_DYNAMIC );
  75975. if( nData>0x7fffffff ){
  75976. return invokeValueDestructor(zData, xDel, 0);
  75977. }else{
  75978. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  75979. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  75980. }
  75981. }
  75982. #ifndef SQLITE_OMIT_UTF16
  75983. SQLITE_API int sqlite3_bind_text16(
  75984. sqlite3_stmt *pStmt,
  75985. int i,
  75986. const void *zData,
  75987. int nData,
  75988. void (*xDel)(void*)
  75989. ){
  75990. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  75991. }
  75992. #endif /* SQLITE_OMIT_UTF16 */
  75993. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  75994. int rc;
  75995. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  75996. case SQLITE_INTEGER: {
  75997. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  75998. break;
  75999. }
  76000. case SQLITE_FLOAT: {
  76001. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  76002. break;
  76003. }
  76004. case SQLITE_BLOB: {
  76005. if( pValue->flags & MEM_Zero ){
  76006. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  76007. }else{
  76008. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  76009. }
  76010. break;
  76011. }
  76012. case SQLITE_TEXT: {
  76013. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  76014. pValue->enc);
  76015. break;
  76016. }
  76017. default: {
  76018. rc = sqlite3_bind_null(pStmt, i);
  76019. break;
  76020. }
  76021. }
  76022. return rc;
  76023. }
  76024. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  76025. int rc;
  76026. Vdbe *p = (Vdbe *)pStmt;
  76027. rc = vdbeUnbind(p, i);
  76028. if( rc==SQLITE_OK ){
  76029. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  76030. sqlite3_mutex_leave(p->db->mutex);
  76031. }
  76032. return rc;
  76033. }
  76034. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  76035. int rc;
  76036. Vdbe *p = (Vdbe *)pStmt;
  76037. sqlite3_mutex_enter(p->db->mutex);
  76038. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76039. rc = SQLITE_TOOBIG;
  76040. }else{
  76041. assert( (n & 0x7FFFFFFF)==n );
  76042. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  76043. }
  76044. rc = sqlite3ApiExit(p->db, rc);
  76045. sqlite3_mutex_leave(p->db->mutex);
  76046. return rc;
  76047. }
  76048. /*
  76049. ** Return the number of wildcards that can be potentially bound to.
  76050. ** This routine is added to support DBD::SQLite.
  76051. */
  76052. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  76053. Vdbe *p = (Vdbe*)pStmt;
  76054. return p ? p->nVar : 0;
  76055. }
  76056. /*
  76057. ** Return the name of a wildcard parameter. Return NULL if the index
  76058. ** is out of range or if the wildcard is unnamed.
  76059. **
  76060. ** The result is always UTF-8.
  76061. */
  76062. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  76063. Vdbe *p = (Vdbe*)pStmt;
  76064. if( p==0 ) return 0;
  76065. return sqlite3VListNumToName(p->pVList, i);
  76066. }
  76067. /*
  76068. ** Given a wildcard parameter name, return the index of the variable
  76069. ** with that name. If there is no variable with the given name,
  76070. ** return 0.
  76071. */
  76072. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  76073. if( p==0 || zName==0 ) return 0;
  76074. return sqlite3VListNameToNum(p->pVList, zName, nName);
  76075. }
  76076. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  76077. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  76078. }
  76079. /*
  76080. ** Transfer all bindings from the first statement over to the second.
  76081. */
  76082. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  76083. Vdbe *pFrom = (Vdbe*)pFromStmt;
  76084. Vdbe *pTo = (Vdbe*)pToStmt;
  76085. int i;
  76086. assert( pTo->db==pFrom->db );
  76087. assert( pTo->nVar==pFrom->nVar );
  76088. sqlite3_mutex_enter(pTo->db->mutex);
  76089. for(i=0; i<pFrom->nVar; i++){
  76090. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  76091. }
  76092. sqlite3_mutex_leave(pTo->db->mutex);
  76093. return SQLITE_OK;
  76094. }
  76095. #ifndef SQLITE_OMIT_DEPRECATED
  76096. /*
  76097. ** Deprecated external interface. Internal/core SQLite code
  76098. ** should call sqlite3TransferBindings.
  76099. **
  76100. ** It is misuse to call this routine with statements from different
  76101. ** database connections. But as this is a deprecated interface, we
  76102. ** will not bother to check for that condition.
  76103. **
  76104. ** If the two statements contain a different number of bindings, then
  76105. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  76106. ** SQLITE_OK is returned.
  76107. */
  76108. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  76109. Vdbe *pFrom = (Vdbe*)pFromStmt;
  76110. Vdbe *pTo = (Vdbe*)pToStmt;
  76111. if( pFrom->nVar!=pTo->nVar ){
  76112. return SQLITE_ERROR;
  76113. }
  76114. assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
  76115. if( pTo->expmask ){
  76116. pTo->expired = 1;
  76117. }
  76118. assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
  76119. if( pFrom->expmask ){
  76120. pFrom->expired = 1;
  76121. }
  76122. return sqlite3TransferBindings(pFromStmt, pToStmt);
  76123. }
  76124. #endif
  76125. /*
  76126. ** Return the sqlite3* database handle to which the prepared statement given
  76127. ** in the argument belongs. This is the same database handle that was
  76128. ** the first argument to the sqlite3_prepare() that was used to create
  76129. ** the statement in the first place.
  76130. */
  76131. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  76132. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  76133. }
  76134. /*
  76135. ** Return true if the prepared statement is guaranteed to not modify the
  76136. ** database.
  76137. */
  76138. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  76139. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  76140. }
  76141. /*
  76142. ** Return true if the prepared statement is in need of being reset.
  76143. */
  76144. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  76145. Vdbe *v = (Vdbe*)pStmt;
  76146. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  76147. }
  76148. /*
  76149. ** Return a pointer to the next prepared statement after pStmt associated
  76150. ** with database connection pDb. If pStmt is NULL, return the first
  76151. ** prepared statement for the database connection. Return NULL if there
  76152. ** are no more.
  76153. */
  76154. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  76155. sqlite3_stmt *pNext;
  76156. #ifdef SQLITE_ENABLE_API_ARMOR
  76157. if( !sqlite3SafetyCheckOk(pDb) ){
  76158. (void)SQLITE_MISUSE_BKPT;
  76159. return 0;
  76160. }
  76161. #endif
  76162. sqlite3_mutex_enter(pDb->mutex);
  76163. if( pStmt==0 ){
  76164. pNext = (sqlite3_stmt*)pDb->pVdbe;
  76165. }else{
  76166. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  76167. }
  76168. sqlite3_mutex_leave(pDb->mutex);
  76169. return pNext;
  76170. }
  76171. /*
  76172. ** Return the value of a status counter for a prepared statement
  76173. */
  76174. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  76175. Vdbe *pVdbe = (Vdbe*)pStmt;
  76176. u32 v;
  76177. #ifdef SQLITE_ENABLE_API_ARMOR
  76178. if( !pStmt
  76179. || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
  76180. ){
  76181. (void)SQLITE_MISUSE_BKPT;
  76182. return 0;
  76183. }
  76184. #endif
  76185. if( op==SQLITE_STMTSTATUS_MEMUSED ){
  76186. sqlite3 *db = pVdbe->db;
  76187. sqlite3_mutex_enter(db->mutex);
  76188. v = 0;
  76189. db->pnBytesFreed = (int*)&v;
  76190. sqlite3VdbeClearObject(db, pVdbe);
  76191. sqlite3DbFree(db, pVdbe);
  76192. db->pnBytesFreed = 0;
  76193. sqlite3_mutex_leave(db->mutex);
  76194. }else{
  76195. v = pVdbe->aCounter[op];
  76196. if( resetFlag ) pVdbe->aCounter[op] = 0;
  76197. }
  76198. return (int)v;
  76199. }
  76200. /*
  76201. ** Return the SQL associated with a prepared statement
  76202. */
  76203. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  76204. Vdbe *p = (Vdbe *)pStmt;
  76205. return p ? p->zSql : 0;
  76206. }
  76207. /*
  76208. ** Return the SQL associated with a prepared statement with
  76209. ** bound parameters expanded. Space to hold the returned string is
  76210. ** obtained from sqlite3_malloc(). The caller is responsible for
  76211. ** freeing the returned string by passing it to sqlite3_free().
  76212. **
  76213. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  76214. ** expanded bound parameters.
  76215. */
  76216. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  76217. #ifdef SQLITE_OMIT_TRACE
  76218. return 0;
  76219. #else
  76220. char *z = 0;
  76221. const char *zSql = sqlite3_sql(pStmt);
  76222. if( zSql ){
  76223. Vdbe *p = (Vdbe *)pStmt;
  76224. sqlite3_mutex_enter(p->db->mutex);
  76225. z = sqlite3VdbeExpandSql(p, zSql);
  76226. sqlite3_mutex_leave(p->db->mutex);
  76227. }
  76228. return z;
  76229. #endif
  76230. }
  76231. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76232. /*
  76233. ** Allocate and populate an UnpackedRecord structure based on the serialized
  76234. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  76235. ** if successful, or a NULL pointer if an OOM error is encountered.
  76236. */
  76237. static UnpackedRecord *vdbeUnpackRecord(
  76238. KeyInfo *pKeyInfo,
  76239. int nKey,
  76240. const void *pKey
  76241. ){
  76242. UnpackedRecord *pRet; /* Return value */
  76243. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  76244. if( pRet ){
  76245. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
  76246. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  76247. }
  76248. return pRet;
  76249. }
  76250. /*
  76251. ** This function is called from within a pre-update callback to retrieve
  76252. ** a field of the row currently being updated or deleted.
  76253. */
  76254. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  76255. PreUpdate *p = db->pPreUpdate;
  76256. Mem *pMem;
  76257. int rc = SQLITE_OK;
  76258. /* Test that this call is being made from within an SQLITE_DELETE or
  76259. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  76260. if( !p || p->op==SQLITE_INSERT ){
  76261. rc = SQLITE_MISUSE_BKPT;
  76262. goto preupdate_old_out;
  76263. }
  76264. if( p->pPk ){
  76265. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  76266. }
  76267. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  76268. rc = SQLITE_RANGE;
  76269. goto preupdate_old_out;
  76270. }
  76271. /* If the old.* record has not yet been loaded into memory, do so now. */
  76272. if( p->pUnpacked==0 ){
  76273. u32 nRec;
  76274. u8 *aRec;
  76275. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  76276. aRec = sqlite3DbMallocRaw(db, nRec);
  76277. if( !aRec ) goto preupdate_old_out;
  76278. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  76279. if( rc==SQLITE_OK ){
  76280. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  76281. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  76282. }
  76283. if( rc!=SQLITE_OK ){
  76284. sqlite3DbFree(db, aRec);
  76285. goto preupdate_old_out;
  76286. }
  76287. p->aRecord = aRec;
  76288. }
  76289. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  76290. if( iIdx==p->pTab->iPKey ){
  76291. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  76292. }else if( iIdx>=p->pUnpacked->nField ){
  76293. *ppValue = (sqlite3_value *)columnNullValue();
  76294. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  76295. if( pMem->flags & MEM_Int ){
  76296. sqlite3VdbeMemRealify(pMem);
  76297. }
  76298. }
  76299. preupdate_old_out:
  76300. sqlite3Error(db, rc);
  76301. return sqlite3ApiExit(db, rc);
  76302. }
  76303. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76304. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76305. /*
  76306. ** This function is called from within a pre-update callback to retrieve
  76307. ** the number of columns in the row being updated, deleted or inserted.
  76308. */
  76309. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  76310. PreUpdate *p = db->pPreUpdate;
  76311. return (p ? p->keyinfo.nKeyField : 0);
  76312. }
  76313. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76314. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76315. /*
  76316. ** This function is designed to be called from within a pre-update callback
  76317. ** only. It returns zero if the change that caused the callback was made
  76318. ** immediately by a user SQL statement. Or, if the change was made by a
  76319. ** trigger program, it returns the number of trigger programs currently
  76320. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  76321. ** top-level trigger etc.).
  76322. **
  76323. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  76324. ** or SET DEFAULT action is considered a trigger.
  76325. */
  76326. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  76327. PreUpdate *p = db->pPreUpdate;
  76328. return (p ? p->v->nFrame : 0);
  76329. }
  76330. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76331. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76332. /*
  76333. ** This function is called from within a pre-update callback to retrieve
  76334. ** a field of the row currently being updated or inserted.
  76335. */
  76336. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  76337. PreUpdate *p = db->pPreUpdate;
  76338. int rc = SQLITE_OK;
  76339. Mem *pMem;
  76340. if( !p || p->op==SQLITE_DELETE ){
  76341. rc = SQLITE_MISUSE_BKPT;
  76342. goto preupdate_new_out;
  76343. }
  76344. if( p->pPk && p->op!=SQLITE_UPDATE ){
  76345. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  76346. }
  76347. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  76348. rc = SQLITE_RANGE;
  76349. goto preupdate_new_out;
  76350. }
  76351. if( p->op==SQLITE_INSERT ){
  76352. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  76353. ** that is being inserted. Deserialize it. */
  76354. UnpackedRecord *pUnpack = p->pNewUnpacked;
  76355. if( !pUnpack ){
  76356. Mem *pData = &p->v->aMem[p->iNewReg];
  76357. rc = ExpandBlob(pData);
  76358. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  76359. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  76360. if( !pUnpack ){
  76361. rc = SQLITE_NOMEM;
  76362. goto preupdate_new_out;
  76363. }
  76364. p->pNewUnpacked = pUnpack;
  76365. }
  76366. pMem = &pUnpack->aMem[iIdx];
  76367. if( iIdx==p->pTab->iPKey ){
  76368. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  76369. }else if( iIdx>=pUnpack->nField ){
  76370. pMem = (sqlite3_value *)columnNullValue();
  76371. }
  76372. }else{
  76373. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  76374. ** value. Make a copy of the cell contents and return a pointer to it.
  76375. ** It is not safe to return a pointer to the memory cell itself as the
  76376. ** caller may modify the value text encoding.
  76377. */
  76378. assert( p->op==SQLITE_UPDATE );
  76379. if( !p->aNew ){
  76380. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  76381. if( !p->aNew ){
  76382. rc = SQLITE_NOMEM;
  76383. goto preupdate_new_out;
  76384. }
  76385. }
  76386. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  76387. pMem = &p->aNew[iIdx];
  76388. if( pMem->flags==0 ){
  76389. if( iIdx==p->pTab->iPKey ){
  76390. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  76391. }else{
  76392. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  76393. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  76394. }
  76395. }
  76396. }
  76397. *ppValue = pMem;
  76398. preupdate_new_out:
  76399. sqlite3Error(db, rc);
  76400. return sqlite3ApiExit(db, rc);
  76401. }
  76402. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76403. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  76404. /*
  76405. ** Return status data for a single loop within query pStmt.
  76406. */
  76407. SQLITE_API int sqlite3_stmt_scanstatus(
  76408. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  76409. int idx, /* Index of loop to report on */
  76410. int iScanStatusOp, /* Which metric to return */
  76411. void *pOut /* OUT: Write the answer here */
  76412. ){
  76413. Vdbe *p = (Vdbe*)pStmt;
  76414. ScanStatus *pScan;
  76415. if( idx<0 || idx>=p->nScan ) return 1;
  76416. pScan = &p->aScan[idx];
  76417. switch( iScanStatusOp ){
  76418. case SQLITE_SCANSTAT_NLOOP: {
  76419. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  76420. break;
  76421. }
  76422. case SQLITE_SCANSTAT_NVISIT: {
  76423. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  76424. break;
  76425. }
  76426. case SQLITE_SCANSTAT_EST: {
  76427. double r = 1.0;
  76428. LogEst x = pScan->nEst;
  76429. while( x<100 ){
  76430. x += 10;
  76431. r *= 0.5;
  76432. }
  76433. *(double*)pOut = r*sqlite3LogEstToInt(x);
  76434. break;
  76435. }
  76436. case SQLITE_SCANSTAT_NAME: {
  76437. *(const char**)pOut = pScan->zName;
  76438. break;
  76439. }
  76440. case SQLITE_SCANSTAT_EXPLAIN: {
  76441. if( pScan->addrExplain ){
  76442. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  76443. }else{
  76444. *(const char**)pOut = 0;
  76445. }
  76446. break;
  76447. }
  76448. case SQLITE_SCANSTAT_SELECTID: {
  76449. if( pScan->addrExplain ){
  76450. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  76451. }else{
  76452. *(int*)pOut = -1;
  76453. }
  76454. break;
  76455. }
  76456. default: {
  76457. return 1;
  76458. }
  76459. }
  76460. return 0;
  76461. }
  76462. /*
  76463. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  76464. */
  76465. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  76466. Vdbe *p = (Vdbe*)pStmt;
  76467. memset(p->anExec, 0, p->nOp * sizeof(i64));
  76468. }
  76469. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  76470. /************** End of vdbeapi.c *********************************************/
  76471. /************** Begin file vdbetrace.c ***************************************/
  76472. /*
  76473. ** 2009 November 25
  76474. **
  76475. ** The author disclaims copyright to this source code. In place of
  76476. ** a legal notice, here is a blessing:
  76477. **
  76478. ** May you do good and not evil.
  76479. ** May you find forgiveness for yourself and forgive others.
  76480. ** May you share freely, never taking more than you give.
  76481. **
  76482. *************************************************************************
  76483. **
  76484. ** This file contains code used to insert the values of host parameters
  76485. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  76486. **
  76487. ** The Vdbe parse-tree explainer is also found here.
  76488. */
  76489. /* #include "sqliteInt.h" */
  76490. /* #include "vdbeInt.h" */
  76491. #ifndef SQLITE_OMIT_TRACE
  76492. /*
  76493. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  76494. ** bytes in this text up to but excluding the first character in
  76495. ** a host parameter. If the text contains no host parameters, return
  76496. ** the total number of bytes in the text.
  76497. */
  76498. static int findNextHostParameter(const char *zSql, int *pnToken){
  76499. int tokenType;
  76500. int nTotal = 0;
  76501. int n;
  76502. *pnToken = 0;
  76503. while( zSql[0] ){
  76504. n = sqlite3GetToken((u8*)zSql, &tokenType);
  76505. assert( n>0 && tokenType!=TK_ILLEGAL );
  76506. if( tokenType==TK_VARIABLE ){
  76507. *pnToken = n;
  76508. break;
  76509. }
  76510. nTotal += n;
  76511. zSql += n;
  76512. }
  76513. return nTotal;
  76514. }
  76515. /*
  76516. ** This function returns a pointer to a nul-terminated string in memory
  76517. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  76518. ** string contains a copy of zRawSql but with host parameters expanded to
  76519. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  76520. ** then the returned string holds a copy of zRawSql with "-- " prepended
  76521. ** to each line of text.
  76522. **
  76523. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  76524. ** then long strings and blobs are truncated to that many bytes. This
  76525. ** can be used to prevent unreasonably large trace strings when dealing
  76526. ** with large (multi-megabyte) strings and blobs.
  76527. **
  76528. ** The calling function is responsible for making sure the memory returned
  76529. ** is eventually freed.
  76530. **
  76531. ** ALGORITHM: Scan the input string looking for host parameters in any of
  76532. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  76533. ** string literals, quoted identifier names, and comments. For text forms,
  76534. ** the host parameter index is found by scanning the prepared
  76535. ** statement for the corresponding OP_Variable opcode. Once the host
  76536. ** parameter index is known, locate the value in p->aVar[]. Then render
  76537. ** the value as a literal in place of the host parameter name.
  76538. */
  76539. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  76540. Vdbe *p, /* The prepared statement being evaluated */
  76541. const char *zRawSql /* Raw text of the SQL statement */
  76542. ){
  76543. sqlite3 *db; /* The database connection */
  76544. int idx = 0; /* Index of a host parameter */
  76545. int nextIndex = 1; /* Index of next ? host parameter */
  76546. int n; /* Length of a token prefix */
  76547. int nToken; /* Length of the parameter token */
  76548. int i; /* Loop counter */
  76549. Mem *pVar; /* Value of a host parameter */
  76550. StrAccum out; /* Accumulate the output here */
  76551. #ifndef SQLITE_OMIT_UTF16
  76552. Mem utf8; /* Used to convert UTF16 into UTF8 for display */
  76553. #endif
  76554. char zBase[100]; /* Initial working space */
  76555. db = p->db;
  76556. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  76557. db->aLimit[SQLITE_LIMIT_LENGTH]);
  76558. if( db->nVdbeExec>1 ){
  76559. while( *zRawSql ){
  76560. const char *zStart = zRawSql;
  76561. while( *(zRawSql++)!='\n' && *zRawSql );
  76562. sqlite3_str_append(&out, "-- ", 3);
  76563. assert( (zRawSql - zStart) > 0 );
  76564. sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
  76565. }
  76566. }else if( p->nVar==0 ){
  76567. sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
  76568. }else{
  76569. while( zRawSql[0] ){
  76570. n = findNextHostParameter(zRawSql, &nToken);
  76571. assert( n>0 );
  76572. sqlite3_str_append(&out, zRawSql, n);
  76573. zRawSql += n;
  76574. assert( zRawSql[0] || nToken==0 );
  76575. if( nToken==0 ) break;
  76576. if( zRawSql[0]=='?' ){
  76577. if( nToken>1 ){
  76578. assert( sqlite3Isdigit(zRawSql[1]) );
  76579. sqlite3GetInt32(&zRawSql[1], &idx);
  76580. }else{
  76581. idx = nextIndex;
  76582. }
  76583. }else{
  76584. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  76585. zRawSql[0]=='@' || zRawSql[0]=='#' );
  76586. testcase( zRawSql[0]==':' );
  76587. testcase( zRawSql[0]=='$' );
  76588. testcase( zRawSql[0]=='@' );
  76589. testcase( zRawSql[0]=='#' );
  76590. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  76591. assert( idx>0 );
  76592. }
  76593. zRawSql += nToken;
  76594. nextIndex = idx + 1;
  76595. assert( idx>0 && idx<=p->nVar );
  76596. pVar = &p->aVar[idx-1];
  76597. if( pVar->flags & MEM_Null ){
  76598. sqlite3_str_append(&out, "NULL", 4);
  76599. }else if( pVar->flags & MEM_Int ){
  76600. sqlite3_str_appendf(&out, "%lld", pVar->u.i);
  76601. }else if( pVar->flags & MEM_Real ){
  76602. sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
  76603. }else if( pVar->flags & MEM_Str ){
  76604. int nOut; /* Number of bytes of the string text to include in output */
  76605. #ifndef SQLITE_OMIT_UTF16
  76606. u8 enc = ENC(db);
  76607. if( enc!=SQLITE_UTF8 ){
  76608. memset(&utf8, 0, sizeof(utf8));
  76609. utf8.db = db;
  76610. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  76611. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  76612. out.accError = SQLITE_NOMEM;
  76613. out.nAlloc = 0;
  76614. }
  76615. pVar = &utf8;
  76616. }
  76617. #endif
  76618. nOut = pVar->n;
  76619. #ifdef SQLITE_TRACE_SIZE_LIMIT
  76620. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  76621. nOut = SQLITE_TRACE_SIZE_LIMIT;
  76622. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  76623. }
  76624. #endif
  76625. sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
  76626. #ifdef SQLITE_TRACE_SIZE_LIMIT
  76627. if( nOut<pVar->n ){
  76628. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  76629. }
  76630. #endif
  76631. #ifndef SQLITE_OMIT_UTF16
  76632. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  76633. #endif
  76634. }else if( pVar->flags & MEM_Zero ){
  76635. sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
  76636. }else{
  76637. int nOut; /* Number of bytes of the blob to include in output */
  76638. assert( pVar->flags & MEM_Blob );
  76639. sqlite3_str_append(&out, "x'", 2);
  76640. nOut = pVar->n;
  76641. #ifdef SQLITE_TRACE_SIZE_LIMIT
  76642. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  76643. #endif
  76644. for(i=0; i<nOut; i++){
  76645. sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
  76646. }
  76647. sqlite3_str_append(&out, "'", 1);
  76648. #ifdef SQLITE_TRACE_SIZE_LIMIT
  76649. if( nOut<pVar->n ){
  76650. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  76651. }
  76652. #endif
  76653. }
  76654. }
  76655. }
  76656. if( out.accError ) sqlite3_str_reset(&out);
  76657. return sqlite3StrAccumFinish(&out);
  76658. }
  76659. #endif /* #ifndef SQLITE_OMIT_TRACE */
  76660. /************** End of vdbetrace.c *******************************************/
  76661. /************** Begin file vdbe.c ********************************************/
  76662. /*
  76663. ** 2001 September 15
  76664. **
  76665. ** The author disclaims copyright to this source code. In place of
  76666. ** a legal notice, here is a blessing:
  76667. **
  76668. ** May you do good and not evil.
  76669. ** May you find forgiveness for yourself and forgive others.
  76670. ** May you share freely, never taking more than you give.
  76671. **
  76672. *************************************************************************
  76673. ** The code in this file implements the function that runs the
  76674. ** bytecode of a prepared statement.
  76675. **
  76676. ** Various scripts scan this source file in order to generate HTML
  76677. ** documentation, headers files, or other derived files. The formatting
  76678. ** of the code in this file is, therefore, important. See other comments
  76679. ** in this file for details. If in doubt, do not deviate from existing
  76680. ** commenting and indentation practices when changing or adding code.
  76681. */
  76682. /* #include "sqliteInt.h" */
  76683. /* #include "vdbeInt.h" */
  76684. /*
  76685. ** Invoke this macro on memory cells just prior to changing the
  76686. ** value of the cell. This macro verifies that shallow copies are
  76687. ** not misused. A shallow copy of a string or blob just copies a
  76688. ** pointer to the string or blob, not the content. If the original
  76689. ** is changed while the copy is still in use, the string or blob might
  76690. ** be changed out from under the copy. This macro verifies that nothing
  76691. ** like that ever happens.
  76692. */
  76693. #ifdef SQLITE_DEBUG
  76694. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  76695. #else
  76696. # define memAboutToChange(P,M)
  76697. #endif
  76698. /*
  76699. ** The following global variable is incremented every time a cursor
  76700. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  76701. ** procedures use this information to make sure that indices are
  76702. ** working correctly. This variable has no function other than to
  76703. ** help verify the correct operation of the library.
  76704. */
  76705. #ifdef SQLITE_TEST
  76706. SQLITE_API int sqlite3_search_count = 0;
  76707. #endif
  76708. /*
  76709. ** When this global variable is positive, it gets decremented once before
  76710. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  76711. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  76712. **
  76713. ** This facility is used for testing purposes only. It does not function
  76714. ** in an ordinary build.
  76715. */
  76716. #ifdef SQLITE_TEST
  76717. SQLITE_API int sqlite3_interrupt_count = 0;
  76718. #endif
  76719. /*
  76720. ** The next global variable is incremented each type the OP_Sort opcode
  76721. ** is executed. The test procedures use this information to make sure that
  76722. ** sorting is occurring or not occurring at appropriate times. This variable
  76723. ** has no function other than to help verify the correct operation of the
  76724. ** library.
  76725. */
  76726. #ifdef SQLITE_TEST
  76727. SQLITE_API int sqlite3_sort_count = 0;
  76728. #endif
  76729. /*
  76730. ** The next global variable records the size of the largest MEM_Blob
  76731. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  76732. ** use this information to make sure that the zero-blob functionality
  76733. ** is working correctly. This variable has no function other than to
  76734. ** help verify the correct operation of the library.
  76735. */
  76736. #ifdef SQLITE_TEST
  76737. SQLITE_API int sqlite3_max_blobsize = 0;
  76738. static void updateMaxBlobsize(Mem *p){
  76739. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  76740. sqlite3_max_blobsize = p->n;
  76741. }
  76742. }
  76743. #endif
  76744. /*
  76745. ** This macro evaluates to true if either the update hook or the preupdate
  76746. ** hook are enabled for database connect DB.
  76747. */
  76748. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76749. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  76750. #else
  76751. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  76752. #endif
  76753. /*
  76754. ** The next global variable is incremented each time the OP_Found opcode
  76755. ** is executed. This is used to test whether or not the foreign key
  76756. ** operation implemented using OP_FkIsZero is working. This variable
  76757. ** has no function other than to help verify the correct operation of the
  76758. ** library.
  76759. */
  76760. #ifdef SQLITE_TEST
  76761. SQLITE_API int sqlite3_found_count = 0;
  76762. #endif
  76763. /*
  76764. ** Test a register to see if it exceeds the current maximum blob size.
  76765. ** If it does, record the new maximum blob size.
  76766. */
  76767. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  76768. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  76769. #else
  76770. # define UPDATE_MAX_BLOBSIZE(P)
  76771. #endif
  76772. /*
  76773. ** Invoke the VDBE coverage callback, if that callback is defined. This
  76774. ** feature is used for test suite validation only and does not appear an
  76775. ** production builds.
  76776. **
  76777. ** M is an integer, 2 or 3, that indices how many different ways the
  76778. ** branch can go. It is usually 2. "I" is the direction the branch
  76779. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  76780. ** second alternative branch is taken.
  76781. **
  76782. ** iSrcLine is the source code line (from the __LINE__ macro) that
  76783. ** generated the VDBE instruction. This instrumentation assumes that all
  76784. ** source code is in a single file (the amalgamation). Special values 1
  76785. ** and 2 for the iSrcLine parameter mean that this particular branch is
  76786. ** always taken or never taken, respectively.
  76787. */
  76788. #if !defined(SQLITE_VDBE_COVERAGE)
  76789. # define VdbeBranchTaken(I,M)
  76790. #else
  76791. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  76792. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  76793. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  76794. M = iSrcLine;
  76795. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  76796. ** VdbeCoverageNeverTaken() */
  76797. assert( (M & I)==I );
  76798. }else{
  76799. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  76800. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  76801. iSrcLine,I,M);
  76802. }
  76803. }
  76804. #endif
  76805. /*
  76806. ** Convert the given register into a string if it isn't one
  76807. ** already. Return non-zero if a malloc() fails.
  76808. */
  76809. #define Stringify(P, enc) \
  76810. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  76811. { goto no_mem; }
  76812. /*
  76813. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  76814. ** a pointer to a dynamically allocated string where some other entity
  76815. ** is responsible for deallocating that string. Because the register
  76816. ** does not control the string, it might be deleted without the register
  76817. ** knowing it.
  76818. **
  76819. ** This routine converts an ephemeral string into a dynamically allocated
  76820. ** string that the register itself controls. In other words, it
  76821. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  76822. */
  76823. #define Deephemeralize(P) \
  76824. if( ((P)->flags&MEM_Ephem)!=0 \
  76825. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  76826. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  76827. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  76828. /*
  76829. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  76830. ** if we run out of memory.
  76831. */
  76832. static VdbeCursor *allocateCursor(
  76833. Vdbe *p, /* The virtual machine */
  76834. int iCur, /* Index of the new VdbeCursor */
  76835. int nField, /* Number of fields in the table or index */
  76836. int iDb, /* Database the cursor belongs to, or -1 */
  76837. u8 eCurType /* Type of the new cursor */
  76838. ){
  76839. /* Find the memory cell that will be used to store the blob of memory
  76840. ** required for this VdbeCursor structure. It is convenient to use a
  76841. ** vdbe memory cell to manage the memory allocation required for a
  76842. ** VdbeCursor structure for the following reasons:
  76843. **
  76844. ** * Sometimes cursor numbers are used for a couple of different
  76845. ** purposes in a vdbe program. The different uses might require
  76846. ** different sized allocations. Memory cells provide growable
  76847. ** allocations.
  76848. **
  76849. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  76850. ** be freed lazily via the sqlite3_release_memory() API. This
  76851. ** minimizes the number of malloc calls made by the system.
  76852. **
  76853. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  76854. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  76855. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  76856. */
  76857. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  76858. int nByte;
  76859. VdbeCursor *pCx = 0;
  76860. nByte =
  76861. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  76862. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  76863. assert( iCur>=0 && iCur<p->nCursor );
  76864. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  76865. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  76866. p->apCsr[iCur] = 0;
  76867. }
  76868. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  76869. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  76870. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  76871. pCx->eCurType = eCurType;
  76872. pCx->iDb = iDb;
  76873. pCx->nField = nField;
  76874. pCx->aOffset = &pCx->aType[nField];
  76875. if( eCurType==CURTYPE_BTREE ){
  76876. pCx->uc.pCursor = (BtCursor*)
  76877. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  76878. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  76879. }
  76880. }
  76881. return pCx;
  76882. }
  76883. /*
  76884. ** Try to convert a value into a numeric representation if we can
  76885. ** do so without loss of information. In other words, if the string
  76886. ** looks like a number, convert it into a number. If it does not
  76887. ** look like a number, leave it alone.
  76888. **
  76889. ** If the bTryForInt flag is true, then extra effort is made to give
  76890. ** an integer representation. Strings that look like floating point
  76891. ** values but which have no fractional component (example: '48.00')
  76892. ** will have a MEM_Int representation when bTryForInt is true.
  76893. **
  76894. ** If bTryForInt is false, then if the input string contains a decimal
  76895. ** point or exponential notation, the result is only MEM_Real, even
  76896. ** if there is an exact integer representation of the quantity.
  76897. */
  76898. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  76899. double rValue;
  76900. i64 iValue;
  76901. u8 enc = pRec->enc;
  76902. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  76903. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  76904. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  76905. pRec->u.i = iValue;
  76906. pRec->flags |= MEM_Int;
  76907. }else{
  76908. pRec->u.r = rValue;
  76909. pRec->flags |= MEM_Real;
  76910. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  76911. }
  76912. /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
  76913. ** string representation after computing a numeric equivalent, because the
  76914. ** string representation might not be the canonical representation for the
  76915. ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
  76916. pRec->flags &= ~MEM_Str;
  76917. }
  76918. /*
  76919. ** Processing is determine by the affinity parameter:
  76920. **
  76921. ** SQLITE_AFF_INTEGER:
  76922. ** SQLITE_AFF_REAL:
  76923. ** SQLITE_AFF_NUMERIC:
  76924. ** Try to convert pRec to an integer representation or a
  76925. ** floating-point representation if an integer representation
  76926. ** is not possible. Note that the integer representation is
  76927. ** always preferred, even if the affinity is REAL, because
  76928. ** an integer representation is more space efficient on disk.
  76929. **
  76930. ** SQLITE_AFF_TEXT:
  76931. ** Convert pRec to a text representation.
  76932. **
  76933. ** SQLITE_AFF_BLOB:
  76934. ** No-op. pRec is unchanged.
  76935. */
  76936. static void applyAffinity(
  76937. Mem *pRec, /* The value to apply affinity to */
  76938. char affinity, /* The affinity to be applied */
  76939. u8 enc /* Use this text encoding */
  76940. ){
  76941. if( affinity>=SQLITE_AFF_NUMERIC ){
  76942. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  76943. || affinity==SQLITE_AFF_NUMERIC );
  76944. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  76945. if( (pRec->flags & MEM_Real)==0 ){
  76946. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  76947. }else{
  76948. sqlite3VdbeIntegerAffinity(pRec);
  76949. }
  76950. }
  76951. }else if( affinity==SQLITE_AFF_TEXT ){
  76952. /* Only attempt the conversion to TEXT if there is an integer or real
  76953. ** representation (blob and NULL do not get converted) but no string
  76954. ** representation. It would be harmless to repeat the conversion if
  76955. ** there is already a string rep, but it is pointless to waste those
  76956. ** CPU cycles. */
  76957. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  76958. if( (pRec->flags&(MEM_Real|MEM_Int)) ){
  76959. sqlite3VdbeMemStringify(pRec, enc, 1);
  76960. }
  76961. }
  76962. pRec->flags &= ~(MEM_Real|MEM_Int);
  76963. }
  76964. }
  76965. /*
  76966. ** Try to convert the type of a function argument or a result column
  76967. ** into a numeric representation. Use either INTEGER or REAL whichever
  76968. ** is appropriate. But only do the conversion if it is possible without
  76969. ** loss of information and return the revised type of the argument.
  76970. */
  76971. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  76972. int eType = sqlite3_value_type(pVal);
  76973. if( eType==SQLITE_TEXT ){
  76974. Mem *pMem = (Mem*)pVal;
  76975. applyNumericAffinity(pMem, 0);
  76976. eType = sqlite3_value_type(pVal);
  76977. }
  76978. return eType;
  76979. }
  76980. /*
  76981. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  76982. ** not the internal Mem* type.
  76983. */
  76984. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  76985. sqlite3_value *pVal,
  76986. u8 affinity,
  76987. u8 enc
  76988. ){
  76989. applyAffinity((Mem *)pVal, affinity, enc);
  76990. }
  76991. /*
  76992. ** pMem currently only holds a string type (or maybe a BLOB that we can
  76993. ** interpret as a string if we want to). Compute its corresponding
  76994. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  76995. ** accordingly.
  76996. */
  76997. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  76998. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  76999. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  77000. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  77001. return 0;
  77002. }
  77003. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
  77004. return MEM_Int;
  77005. }
  77006. return MEM_Real;
  77007. }
  77008. /*
  77009. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  77010. ** none.
  77011. **
  77012. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  77013. ** But it does set pMem->u.r and pMem->u.i appropriately.
  77014. */
  77015. static u16 numericType(Mem *pMem){
  77016. if( pMem->flags & (MEM_Int|MEM_Real) ){
  77017. return pMem->flags & (MEM_Int|MEM_Real);
  77018. }
  77019. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  77020. return computeNumericType(pMem);
  77021. }
  77022. return 0;
  77023. }
  77024. #ifdef SQLITE_DEBUG
  77025. /*
  77026. ** Write a nice string representation of the contents of cell pMem
  77027. ** into buffer zBuf, length nBuf.
  77028. */
  77029. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  77030. char *zCsr = zBuf;
  77031. int f = pMem->flags;
  77032. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  77033. if( f&MEM_Blob ){
  77034. int i;
  77035. char c;
  77036. if( f & MEM_Dyn ){
  77037. c = 'z';
  77038. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  77039. }else if( f & MEM_Static ){
  77040. c = 't';
  77041. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  77042. }else if( f & MEM_Ephem ){
  77043. c = 'e';
  77044. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  77045. }else{
  77046. c = 's';
  77047. }
  77048. *(zCsr++) = c;
  77049. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  77050. zCsr += sqlite3Strlen30(zCsr);
  77051. for(i=0; i<16 && i<pMem->n; i++){
  77052. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  77053. zCsr += sqlite3Strlen30(zCsr);
  77054. }
  77055. for(i=0; i<16 && i<pMem->n; i++){
  77056. char z = pMem->z[i];
  77057. if( z<32 || z>126 ) *zCsr++ = '.';
  77058. else *zCsr++ = z;
  77059. }
  77060. *(zCsr++) = ']';
  77061. if( f & MEM_Zero ){
  77062. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  77063. zCsr += sqlite3Strlen30(zCsr);
  77064. }
  77065. *zCsr = '\0';
  77066. }else if( f & MEM_Str ){
  77067. int j, k;
  77068. zBuf[0] = ' ';
  77069. if( f & MEM_Dyn ){
  77070. zBuf[1] = 'z';
  77071. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  77072. }else if( f & MEM_Static ){
  77073. zBuf[1] = 't';
  77074. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  77075. }else if( f & MEM_Ephem ){
  77076. zBuf[1] = 'e';
  77077. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  77078. }else{
  77079. zBuf[1] = 's';
  77080. }
  77081. k = 2;
  77082. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  77083. k += sqlite3Strlen30(&zBuf[k]);
  77084. zBuf[k++] = '[';
  77085. for(j=0; j<15 && j<pMem->n; j++){
  77086. u8 c = pMem->z[j];
  77087. if( c>=0x20 && c<0x7f ){
  77088. zBuf[k++] = c;
  77089. }else{
  77090. zBuf[k++] = '.';
  77091. }
  77092. }
  77093. zBuf[k++] = ']';
  77094. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  77095. k += sqlite3Strlen30(&zBuf[k]);
  77096. zBuf[k++] = 0;
  77097. }
  77098. }
  77099. #endif
  77100. #ifdef SQLITE_DEBUG
  77101. /*
  77102. ** Print the value of a register for tracing purposes:
  77103. */
  77104. static void memTracePrint(Mem *p){
  77105. if( p->flags & MEM_Undefined ){
  77106. printf(" undefined");
  77107. }else if( p->flags & MEM_Null ){
  77108. printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
  77109. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  77110. printf(" si:%lld", p->u.i);
  77111. }else if( p->flags & MEM_Int ){
  77112. printf(" i:%lld", p->u.i);
  77113. #ifndef SQLITE_OMIT_FLOATING_POINT
  77114. }else if( p->flags & MEM_Real ){
  77115. printf(" r:%g", p->u.r);
  77116. #endif
  77117. }else if( p->flags & MEM_RowSet ){
  77118. printf(" (rowset)");
  77119. }else{
  77120. char zBuf[200];
  77121. sqlite3VdbeMemPrettyPrint(p, zBuf);
  77122. printf(" %s", zBuf);
  77123. }
  77124. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  77125. }
  77126. static void registerTrace(int iReg, Mem *p){
  77127. printf("REG[%d] = ", iReg);
  77128. memTracePrint(p);
  77129. printf("\n");
  77130. sqlite3VdbeCheckMemInvariants(p);
  77131. }
  77132. #endif
  77133. #ifdef SQLITE_DEBUG
  77134. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  77135. #else
  77136. # define REGISTER_TRACE(R,M)
  77137. #endif
  77138. #ifdef VDBE_PROFILE
  77139. /*
  77140. ** hwtime.h contains inline assembler code for implementing
  77141. ** high-performance timing routines.
  77142. */
  77143. /************** Include hwtime.h in the middle of vdbe.c *********************/
  77144. /************** Begin file hwtime.h ******************************************/
  77145. /*
  77146. ** 2008 May 27
  77147. **
  77148. ** The author disclaims copyright to this source code. In place of
  77149. ** a legal notice, here is a blessing:
  77150. **
  77151. ** May you do good and not evil.
  77152. ** May you find forgiveness for yourself and forgive others.
  77153. ** May you share freely, never taking more than you give.
  77154. **
  77155. ******************************************************************************
  77156. **
  77157. ** This file contains inline asm code for retrieving "high-performance"
  77158. ** counters for x86 class CPUs.
  77159. */
  77160. #ifndef SQLITE_HWTIME_H
  77161. #define SQLITE_HWTIME_H
  77162. /*
  77163. ** The following routine only works on pentium-class (or newer) processors.
  77164. ** It uses the RDTSC opcode to read the cycle count value out of the
  77165. ** processor and returns that value. This can be used for high-res
  77166. ** profiling.
  77167. */
  77168. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  77169. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  77170. #if defined(__GNUC__)
  77171. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  77172. unsigned int lo, hi;
  77173. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  77174. return (sqlite_uint64)hi << 32 | lo;
  77175. }
  77176. #elif defined(_MSC_VER)
  77177. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  77178. __asm {
  77179. rdtsc
  77180. ret ; return value at EDX:EAX
  77181. }
  77182. }
  77183. #endif
  77184. #elif (defined(__GNUC__) && defined(__x86_64__))
  77185. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  77186. unsigned long val;
  77187. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  77188. return val;
  77189. }
  77190. #elif (defined(__GNUC__) && defined(__ppc__))
  77191. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  77192. unsigned long long retval;
  77193. unsigned long junk;
  77194. __asm__ __volatile__ ("\n\
  77195. 1: mftbu %1\n\
  77196. mftb %L0\n\
  77197. mftbu %0\n\
  77198. cmpw %0,%1\n\
  77199. bne 1b"
  77200. : "=r" (retval), "=r" (junk));
  77201. return retval;
  77202. }
  77203. #else
  77204. #error Need implementation of sqlite3Hwtime() for your platform.
  77205. /*
  77206. ** To compile without implementing sqlite3Hwtime() for your platform,
  77207. ** you can remove the above #error and use the following
  77208. ** stub function. You will lose timing support for many
  77209. ** of the debugging and testing utilities, but it should at
  77210. ** least compile and run.
  77211. */
  77212. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  77213. #endif
  77214. #endif /* !defined(SQLITE_HWTIME_H) */
  77215. /************** End of hwtime.h **********************************************/
  77216. /************** Continuing where we left off in vdbe.c ***********************/
  77217. #endif
  77218. #ifndef NDEBUG
  77219. /*
  77220. ** This function is only called from within an assert() expression. It
  77221. ** checks that the sqlite3.nTransaction variable is correctly set to
  77222. ** the number of non-transaction savepoints currently in the
  77223. ** linked list starting at sqlite3.pSavepoint.
  77224. **
  77225. ** Usage:
  77226. **
  77227. ** assert( checkSavepointCount(db) );
  77228. */
  77229. static int checkSavepointCount(sqlite3 *db){
  77230. int n = 0;
  77231. Savepoint *p;
  77232. for(p=db->pSavepoint; p; p=p->pNext) n++;
  77233. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  77234. return 1;
  77235. }
  77236. #endif
  77237. /*
  77238. ** Return the register of pOp->p2 after first preparing it to be
  77239. ** overwritten with an integer value.
  77240. */
  77241. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  77242. sqlite3VdbeMemSetNull(pOut);
  77243. pOut->flags = MEM_Int;
  77244. return pOut;
  77245. }
  77246. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  77247. Mem *pOut;
  77248. assert( pOp->p2>0 );
  77249. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  77250. pOut = &p->aMem[pOp->p2];
  77251. memAboutToChange(p, pOut);
  77252. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  77253. return out2PrereleaseWithClear(pOut);
  77254. }else{
  77255. pOut->flags = MEM_Int;
  77256. return pOut;
  77257. }
  77258. }
  77259. /*
  77260. ** Execute as much of a VDBE program as we can.
  77261. ** This is the core of sqlite3_step().
  77262. */
  77263. SQLITE_PRIVATE int sqlite3VdbeExec(
  77264. Vdbe *p /* The VDBE */
  77265. ){
  77266. Op *aOp = p->aOp; /* Copy of p->aOp */
  77267. Op *pOp = aOp; /* Current operation */
  77268. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  77269. Op *pOrigOp; /* Value of pOp at the top of the loop */
  77270. #endif
  77271. #ifdef SQLITE_DEBUG
  77272. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  77273. #endif
  77274. int rc = SQLITE_OK; /* Value to return */
  77275. sqlite3 *db = p->db; /* The database */
  77276. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  77277. u8 encoding = ENC(db); /* The database encoding */
  77278. int iCompare = 0; /* Result of last comparison */
  77279. unsigned nVmStep = 0; /* Number of virtual machine steps */
  77280. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  77281. unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
  77282. #endif
  77283. Mem *aMem = p->aMem; /* Copy of p->aMem */
  77284. Mem *pIn1 = 0; /* 1st input operand */
  77285. Mem *pIn2 = 0; /* 2nd input operand */
  77286. Mem *pIn3 = 0; /* 3rd input operand */
  77287. Mem *pOut = 0; /* Output operand */
  77288. #ifdef VDBE_PROFILE
  77289. u64 start; /* CPU clock count at start of opcode */
  77290. #endif
  77291. /*** INSERT STACK UNION HERE ***/
  77292. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  77293. sqlite3VdbeEnter(p);
  77294. if( p->rc==SQLITE_NOMEM ){
  77295. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  77296. ** sqlite3_column_text16() failed. */
  77297. goto no_mem;
  77298. }
  77299. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  77300. assert( p->bIsReader || p->readOnly!=0 );
  77301. p->iCurrentTime = 0;
  77302. assert( p->explain==0 );
  77303. p->pResultSet = 0;
  77304. db->busyHandler.nBusy = 0;
  77305. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  77306. sqlite3VdbeIOTraceSql(p);
  77307. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  77308. if( db->xProgress ){
  77309. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  77310. assert( 0 < db->nProgressOps );
  77311. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  77312. }else{
  77313. nProgressLimit = 0xffffffff;
  77314. }
  77315. #endif
  77316. #ifdef SQLITE_DEBUG
  77317. sqlite3BeginBenignMalloc();
  77318. if( p->pc==0
  77319. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  77320. ){
  77321. int i;
  77322. int once = 1;
  77323. sqlite3VdbePrintSql(p);
  77324. if( p->db->flags & SQLITE_VdbeListing ){
  77325. printf("VDBE Program Listing:\n");
  77326. for(i=0; i<p->nOp; i++){
  77327. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  77328. }
  77329. }
  77330. if( p->db->flags & SQLITE_VdbeEQP ){
  77331. for(i=0; i<p->nOp; i++){
  77332. if( aOp[i].opcode==OP_Explain ){
  77333. if( once ) printf("VDBE Query Plan:\n");
  77334. printf("%s\n", aOp[i].p4.z);
  77335. once = 0;
  77336. }
  77337. }
  77338. }
  77339. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  77340. }
  77341. sqlite3EndBenignMalloc();
  77342. #endif
  77343. for(pOp=&aOp[p->pc]; 1; pOp++){
  77344. /* Errors are detected by individual opcodes, with an immediate
  77345. ** jumps to abort_due_to_error. */
  77346. assert( rc==SQLITE_OK );
  77347. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  77348. #ifdef VDBE_PROFILE
  77349. start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  77350. #endif
  77351. nVmStep++;
  77352. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  77353. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  77354. #endif
  77355. /* Only allow tracing if SQLITE_DEBUG is defined.
  77356. */
  77357. #ifdef SQLITE_DEBUG
  77358. if( db->flags & SQLITE_VdbeTrace ){
  77359. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  77360. }
  77361. #endif
  77362. /* Check to see if we need to simulate an interrupt. This only happens
  77363. ** if we have a special test build.
  77364. */
  77365. #ifdef SQLITE_TEST
  77366. if( sqlite3_interrupt_count>0 ){
  77367. sqlite3_interrupt_count--;
  77368. if( sqlite3_interrupt_count==0 ){
  77369. sqlite3_interrupt(db);
  77370. }
  77371. }
  77372. #endif
  77373. /* Sanity checking on other operands */
  77374. #ifdef SQLITE_DEBUG
  77375. {
  77376. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  77377. if( (opProperty & OPFLG_IN1)!=0 ){
  77378. assert( pOp->p1>0 );
  77379. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  77380. assert( memIsValid(&aMem[pOp->p1]) );
  77381. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  77382. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  77383. }
  77384. if( (opProperty & OPFLG_IN2)!=0 ){
  77385. assert( pOp->p2>0 );
  77386. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  77387. assert( memIsValid(&aMem[pOp->p2]) );
  77388. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  77389. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  77390. }
  77391. if( (opProperty & OPFLG_IN3)!=0 ){
  77392. assert( pOp->p3>0 );
  77393. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77394. assert( memIsValid(&aMem[pOp->p3]) );
  77395. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  77396. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  77397. }
  77398. if( (opProperty & OPFLG_OUT2)!=0 ){
  77399. assert( pOp->p2>0 );
  77400. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  77401. memAboutToChange(p, &aMem[pOp->p2]);
  77402. }
  77403. if( (opProperty & OPFLG_OUT3)!=0 ){
  77404. assert( pOp->p3>0 );
  77405. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77406. memAboutToChange(p, &aMem[pOp->p3]);
  77407. }
  77408. }
  77409. #endif
  77410. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  77411. pOrigOp = pOp;
  77412. #endif
  77413. switch( pOp->opcode ){
  77414. /*****************************************************************************
  77415. ** What follows is a massive switch statement where each case implements a
  77416. ** separate instruction in the virtual machine. If we follow the usual
  77417. ** indentation conventions, each case should be indented by 6 spaces. But
  77418. ** that is a lot of wasted space on the left margin. So the code within
  77419. ** the switch statement will break with convention and be flush-left. Another
  77420. ** big comment (similar to this one) will mark the point in the code where
  77421. ** we transition back to normal indentation.
  77422. **
  77423. ** The formatting of each case is important. The makefile for SQLite
  77424. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  77425. ** file looking for lines that begin with "case OP_". The opcodes.h files
  77426. ** will be filled with #defines that give unique integer values to each
  77427. ** opcode and the opcodes.c file is filled with an array of strings where
  77428. ** each string is the symbolic name for the corresponding opcode. If the
  77429. ** case statement is followed by a comment of the form "/# same as ... #/"
  77430. ** that comment is used to determine the particular value of the opcode.
  77431. **
  77432. ** Other keywords in the comment that follows each case are used to
  77433. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  77434. ** Keywords include: in1, in2, in3, out2, out3. See
  77435. ** the mkopcodeh.awk script for additional information.
  77436. **
  77437. ** Documentation about VDBE opcodes is generated by scanning this file
  77438. ** for lines of that contain "Opcode:". That line and all subsequent
  77439. ** comment lines are used in the generation of the opcode.html documentation
  77440. ** file.
  77441. **
  77442. ** SUMMARY:
  77443. **
  77444. ** Formatting is important to scripts that scan this file.
  77445. ** Do not deviate from the formatting style currently in use.
  77446. **
  77447. *****************************************************************************/
  77448. /* Opcode: Goto * P2 * * *
  77449. **
  77450. ** An unconditional jump to address P2.
  77451. ** The next instruction executed will be
  77452. ** the one at index P2 from the beginning of
  77453. ** the program.
  77454. **
  77455. ** The P1 parameter is not actually used by this opcode. However, it
  77456. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  77457. ** that this Goto is the bottom of a loop and that the lines from P2 down
  77458. ** to the current line should be indented for EXPLAIN output.
  77459. */
  77460. case OP_Goto: { /* jump */
  77461. jump_to_p2_and_check_for_interrupt:
  77462. pOp = &aOp[pOp->p2 - 1];
  77463. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  77464. ** OP_VNext, or OP_SorterNext) all jump here upon
  77465. ** completion. Check to see if sqlite3_interrupt() has been called
  77466. ** or if the progress callback needs to be invoked.
  77467. **
  77468. ** This code uses unstructured "goto" statements and does not look clean.
  77469. ** But that is not due to sloppy coding habits. The code is written this
  77470. ** way for performance, to avoid having to run the interrupt and progress
  77471. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  77472. ** faster according to "valgrind --tool=cachegrind" */
  77473. check_for_interrupt:
  77474. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  77475. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  77476. /* Call the progress callback if it is configured and the required number
  77477. ** of VDBE ops have been executed (either since this invocation of
  77478. ** sqlite3VdbeExec() or since last time the progress callback was called).
  77479. ** If the progress callback returns non-zero, exit the virtual machine with
  77480. ** a return code SQLITE_ABORT.
  77481. */
  77482. if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  77483. assert( db->nProgressOps!=0 );
  77484. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  77485. if( db->xProgress(db->pProgressArg) ){
  77486. rc = SQLITE_INTERRUPT;
  77487. goto abort_due_to_error;
  77488. }
  77489. }
  77490. #endif
  77491. break;
  77492. }
  77493. /* Opcode: Gosub P1 P2 * * *
  77494. **
  77495. ** Write the current address onto register P1
  77496. ** and then jump to address P2.
  77497. */
  77498. case OP_Gosub: { /* jump */
  77499. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  77500. pIn1 = &aMem[pOp->p1];
  77501. assert( VdbeMemDynamic(pIn1)==0 );
  77502. memAboutToChange(p, pIn1);
  77503. pIn1->flags = MEM_Int;
  77504. pIn1->u.i = (int)(pOp-aOp);
  77505. REGISTER_TRACE(pOp->p1, pIn1);
  77506. /* Most jump operations do a goto to this spot in order to update
  77507. ** the pOp pointer. */
  77508. jump_to_p2:
  77509. pOp = &aOp[pOp->p2 - 1];
  77510. break;
  77511. }
  77512. /* Opcode: Return P1 * * * *
  77513. **
  77514. ** Jump to the next instruction after the address in register P1. After
  77515. ** the jump, register P1 becomes undefined.
  77516. */
  77517. case OP_Return: { /* in1 */
  77518. pIn1 = &aMem[pOp->p1];
  77519. assert( pIn1->flags==MEM_Int );
  77520. pOp = &aOp[pIn1->u.i];
  77521. pIn1->flags = MEM_Undefined;
  77522. break;
  77523. }
  77524. /* Opcode: InitCoroutine P1 P2 P3 * *
  77525. **
  77526. ** Set up register P1 so that it will Yield to the coroutine
  77527. ** located at address P3.
  77528. **
  77529. ** If P2!=0 then the coroutine implementation immediately follows
  77530. ** this opcode. So jump over the coroutine implementation to
  77531. ** address P2.
  77532. **
  77533. ** See also: EndCoroutine
  77534. */
  77535. case OP_InitCoroutine: { /* jump */
  77536. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  77537. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  77538. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  77539. pOut = &aMem[pOp->p1];
  77540. assert( !VdbeMemDynamic(pOut) );
  77541. pOut->u.i = pOp->p3 - 1;
  77542. pOut->flags = MEM_Int;
  77543. if( pOp->p2 ) goto jump_to_p2;
  77544. break;
  77545. }
  77546. /* Opcode: EndCoroutine P1 * * * *
  77547. **
  77548. ** The instruction at the address in register P1 is a Yield.
  77549. ** Jump to the P2 parameter of that Yield.
  77550. ** After the jump, register P1 becomes undefined.
  77551. **
  77552. ** See also: InitCoroutine
  77553. */
  77554. case OP_EndCoroutine: { /* in1 */
  77555. VdbeOp *pCaller;
  77556. pIn1 = &aMem[pOp->p1];
  77557. assert( pIn1->flags==MEM_Int );
  77558. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  77559. pCaller = &aOp[pIn1->u.i];
  77560. assert( pCaller->opcode==OP_Yield );
  77561. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  77562. pOp = &aOp[pCaller->p2 - 1];
  77563. pIn1->flags = MEM_Undefined;
  77564. break;
  77565. }
  77566. /* Opcode: Yield P1 P2 * * *
  77567. **
  77568. ** Swap the program counter with the value in register P1. This
  77569. ** has the effect of yielding to a coroutine.
  77570. **
  77571. ** If the coroutine that is launched by this instruction ends with
  77572. ** Yield or Return then continue to the next instruction. But if
  77573. ** the coroutine launched by this instruction ends with
  77574. ** EndCoroutine, then jump to P2 rather than continuing with the
  77575. ** next instruction.
  77576. **
  77577. ** See also: InitCoroutine
  77578. */
  77579. case OP_Yield: { /* in1, jump */
  77580. int pcDest;
  77581. pIn1 = &aMem[pOp->p1];
  77582. assert( VdbeMemDynamic(pIn1)==0 );
  77583. pIn1->flags = MEM_Int;
  77584. pcDest = (int)pIn1->u.i;
  77585. pIn1->u.i = (int)(pOp - aOp);
  77586. REGISTER_TRACE(pOp->p1, pIn1);
  77587. pOp = &aOp[pcDest];
  77588. break;
  77589. }
  77590. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  77591. ** Synopsis: if r[P3]=null halt
  77592. **
  77593. ** Check the value in register P3. If it is NULL then Halt using
  77594. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  77595. ** value in register P3 is not NULL, then this routine is a no-op.
  77596. ** The P5 parameter should be 1.
  77597. */
  77598. case OP_HaltIfNull: { /* in3 */
  77599. pIn3 = &aMem[pOp->p3];
  77600. #ifdef SQLITE_DEBUG
  77601. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  77602. #endif
  77603. if( (pIn3->flags & MEM_Null)==0 ) break;
  77604. /* Fall through into OP_Halt */
  77605. }
  77606. /* Opcode: Halt P1 P2 * P4 P5
  77607. **
  77608. ** Exit immediately. All open cursors, etc are closed
  77609. ** automatically.
  77610. **
  77611. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  77612. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  77613. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  77614. ** whether or not to rollback the current transaction. Do not rollback
  77615. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  77616. ** then back out all changes that have occurred during this execution of the
  77617. ** VDBE, but do not rollback the transaction.
  77618. **
  77619. ** If P4 is not null then it is an error message string.
  77620. **
  77621. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  77622. **
  77623. ** 0: (no change)
  77624. ** 1: NOT NULL contraint failed: P4
  77625. ** 2: UNIQUE constraint failed: P4
  77626. ** 3: CHECK constraint failed: P4
  77627. ** 4: FOREIGN KEY constraint failed: P4
  77628. **
  77629. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  77630. ** omitted.
  77631. **
  77632. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  77633. ** every program. So a jump past the last instruction of the program
  77634. ** is the same as executing Halt.
  77635. */
  77636. case OP_Halt: {
  77637. VdbeFrame *pFrame;
  77638. int pcx;
  77639. pcx = (int)(pOp - aOp);
  77640. #ifdef SQLITE_DEBUG
  77641. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  77642. #endif
  77643. if( pOp->p1==SQLITE_OK && p->pFrame ){
  77644. /* Halt the sub-program. Return control to the parent frame. */
  77645. pFrame = p->pFrame;
  77646. p->pFrame = pFrame->pParent;
  77647. p->nFrame--;
  77648. sqlite3VdbeSetChanges(db, p->nChange);
  77649. pcx = sqlite3VdbeFrameRestore(pFrame);
  77650. if( pOp->p2==OE_Ignore ){
  77651. /* Instruction pcx is the OP_Program that invoked the sub-program
  77652. ** currently being halted. If the p2 instruction of this OP_Halt
  77653. ** instruction is set to OE_Ignore, then the sub-program is throwing
  77654. ** an IGNORE exception. In this case jump to the address specified
  77655. ** as the p2 of the calling OP_Program. */
  77656. pcx = p->aOp[pcx].p2-1;
  77657. }
  77658. aOp = p->aOp;
  77659. aMem = p->aMem;
  77660. pOp = &aOp[pcx];
  77661. break;
  77662. }
  77663. p->rc = pOp->p1;
  77664. p->errorAction = (u8)pOp->p2;
  77665. p->pc = pcx;
  77666. assert( pOp->p5<=4 );
  77667. if( p->rc ){
  77668. if( pOp->p5 ){
  77669. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  77670. "FOREIGN KEY" };
  77671. testcase( pOp->p5==1 );
  77672. testcase( pOp->p5==2 );
  77673. testcase( pOp->p5==3 );
  77674. testcase( pOp->p5==4 );
  77675. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  77676. if( pOp->p4.z ){
  77677. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  77678. }
  77679. }else{
  77680. sqlite3VdbeError(p, "%s", pOp->p4.z);
  77681. }
  77682. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  77683. }
  77684. rc = sqlite3VdbeHalt(p);
  77685. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  77686. if( rc==SQLITE_BUSY ){
  77687. p->rc = SQLITE_BUSY;
  77688. }else{
  77689. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  77690. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  77691. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  77692. }
  77693. goto vdbe_return;
  77694. }
  77695. /* Opcode: Integer P1 P2 * * *
  77696. ** Synopsis: r[P2]=P1
  77697. **
  77698. ** The 32-bit integer value P1 is written into register P2.
  77699. */
  77700. case OP_Integer: { /* out2 */
  77701. pOut = out2Prerelease(p, pOp);
  77702. pOut->u.i = pOp->p1;
  77703. break;
  77704. }
  77705. /* Opcode: Int64 * P2 * P4 *
  77706. ** Synopsis: r[P2]=P4
  77707. **
  77708. ** P4 is a pointer to a 64-bit integer value.
  77709. ** Write that value into register P2.
  77710. */
  77711. case OP_Int64: { /* out2 */
  77712. pOut = out2Prerelease(p, pOp);
  77713. assert( pOp->p4.pI64!=0 );
  77714. pOut->u.i = *pOp->p4.pI64;
  77715. break;
  77716. }
  77717. #ifndef SQLITE_OMIT_FLOATING_POINT
  77718. /* Opcode: Real * P2 * P4 *
  77719. ** Synopsis: r[P2]=P4
  77720. **
  77721. ** P4 is a pointer to a 64-bit floating point value.
  77722. ** Write that value into register P2.
  77723. */
  77724. case OP_Real: { /* same as TK_FLOAT, out2 */
  77725. pOut = out2Prerelease(p, pOp);
  77726. pOut->flags = MEM_Real;
  77727. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  77728. pOut->u.r = *pOp->p4.pReal;
  77729. break;
  77730. }
  77731. #endif
  77732. /* Opcode: String8 * P2 * P4 *
  77733. ** Synopsis: r[P2]='P4'
  77734. **
  77735. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  77736. ** into a String opcode before it is executed for the first time. During
  77737. ** this transformation, the length of string P4 is computed and stored
  77738. ** as the P1 parameter.
  77739. */
  77740. case OP_String8: { /* same as TK_STRING, out2 */
  77741. assert( pOp->p4.z!=0 );
  77742. pOut = out2Prerelease(p, pOp);
  77743. pOp->opcode = OP_String;
  77744. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  77745. #ifndef SQLITE_OMIT_UTF16
  77746. if( encoding!=SQLITE_UTF8 ){
  77747. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  77748. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  77749. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  77750. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  77751. assert( VdbeMemDynamic(pOut)==0 );
  77752. pOut->szMalloc = 0;
  77753. pOut->flags |= MEM_Static;
  77754. if( pOp->p4type==P4_DYNAMIC ){
  77755. sqlite3DbFree(db, pOp->p4.z);
  77756. }
  77757. pOp->p4type = P4_DYNAMIC;
  77758. pOp->p4.z = pOut->z;
  77759. pOp->p1 = pOut->n;
  77760. }
  77761. testcase( rc==SQLITE_TOOBIG );
  77762. #endif
  77763. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77764. goto too_big;
  77765. }
  77766. assert( rc==SQLITE_OK );
  77767. /* Fall through to the next case, OP_String */
  77768. }
  77769. /* Opcode: String P1 P2 P3 P4 P5
  77770. ** Synopsis: r[P2]='P4' (len=P1)
  77771. **
  77772. ** The string value P4 of length P1 (bytes) is stored in register P2.
  77773. **
  77774. ** If P3 is not zero and the content of register P3 is equal to P5, then
  77775. ** the datatype of the register P2 is converted to BLOB. The content is
  77776. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  77777. ** of a string, as if it had been CAST. In other words:
  77778. **
  77779. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  77780. */
  77781. case OP_String: { /* out2 */
  77782. assert( pOp->p4.z!=0 );
  77783. pOut = out2Prerelease(p, pOp);
  77784. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  77785. pOut->z = pOp->p4.z;
  77786. pOut->n = pOp->p1;
  77787. pOut->enc = encoding;
  77788. UPDATE_MAX_BLOBSIZE(pOut);
  77789. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  77790. if( pOp->p3>0 ){
  77791. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77792. pIn3 = &aMem[pOp->p3];
  77793. assert( pIn3->flags & MEM_Int );
  77794. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  77795. }
  77796. #endif
  77797. break;
  77798. }
  77799. /* Opcode: Null P1 P2 P3 * *
  77800. ** Synopsis: r[P2..P3]=NULL
  77801. **
  77802. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  77803. ** NULL into register P3 and every register in between P2 and P3. If P3
  77804. ** is less than P2 (typically P3 is zero) then only register P2 is
  77805. ** set to NULL.
  77806. **
  77807. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  77808. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  77809. ** OP_Ne or OP_Eq.
  77810. */
  77811. case OP_Null: { /* out2 */
  77812. int cnt;
  77813. u16 nullFlag;
  77814. pOut = out2Prerelease(p, pOp);
  77815. cnt = pOp->p3-pOp->p2;
  77816. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77817. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  77818. pOut->n = 0;
  77819. while( cnt>0 ){
  77820. pOut++;
  77821. memAboutToChange(p, pOut);
  77822. sqlite3VdbeMemSetNull(pOut);
  77823. pOut->flags = nullFlag;
  77824. pOut->n = 0;
  77825. cnt--;
  77826. }
  77827. break;
  77828. }
  77829. /* Opcode: SoftNull P1 * * * *
  77830. ** Synopsis: r[P1]=NULL
  77831. **
  77832. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  77833. ** instruction, but do not free any string or blob memory associated with
  77834. ** the register, so that if the value was a string or blob that was
  77835. ** previously copied using OP_SCopy, the copies will continue to be valid.
  77836. */
  77837. case OP_SoftNull: {
  77838. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  77839. pOut = &aMem[pOp->p1];
  77840. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  77841. break;
  77842. }
  77843. /* Opcode: Blob P1 P2 * P4 *
  77844. ** Synopsis: r[P2]=P4 (len=P1)
  77845. **
  77846. ** P4 points to a blob of data P1 bytes long. Store this
  77847. ** blob in register P2.
  77848. */
  77849. case OP_Blob: { /* out2 */
  77850. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  77851. pOut = out2Prerelease(p, pOp);
  77852. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  77853. pOut->enc = encoding;
  77854. UPDATE_MAX_BLOBSIZE(pOut);
  77855. break;
  77856. }
  77857. /* Opcode: Variable P1 P2 * P4 *
  77858. ** Synopsis: r[P2]=parameter(P1,P4)
  77859. **
  77860. ** Transfer the values of bound parameter P1 into register P2
  77861. **
  77862. ** If the parameter is named, then its name appears in P4.
  77863. ** The P4 value is used by sqlite3_bind_parameter_name().
  77864. */
  77865. case OP_Variable: { /* out2 */
  77866. Mem *pVar; /* Value being transferred */
  77867. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  77868. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  77869. pVar = &p->aVar[pOp->p1 - 1];
  77870. if( sqlite3VdbeMemTooBig(pVar) ){
  77871. goto too_big;
  77872. }
  77873. pOut = &aMem[pOp->p2];
  77874. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  77875. UPDATE_MAX_BLOBSIZE(pOut);
  77876. break;
  77877. }
  77878. /* Opcode: Move P1 P2 P3 * *
  77879. ** Synopsis: r[P2@P3]=r[P1@P3]
  77880. **
  77881. ** Move the P3 values in register P1..P1+P3-1 over into
  77882. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  77883. ** left holding a NULL. It is an error for register ranges
  77884. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  77885. ** for P3 to be less than 1.
  77886. */
  77887. case OP_Move: {
  77888. int n; /* Number of registers left to copy */
  77889. int p1; /* Register to copy from */
  77890. int p2; /* Register to copy to */
  77891. n = pOp->p3;
  77892. p1 = pOp->p1;
  77893. p2 = pOp->p2;
  77894. assert( n>0 && p1>0 && p2>0 );
  77895. assert( p1+n<=p2 || p2+n<=p1 );
  77896. pIn1 = &aMem[p1];
  77897. pOut = &aMem[p2];
  77898. do{
  77899. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  77900. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  77901. assert( memIsValid(pIn1) );
  77902. memAboutToChange(p, pOut);
  77903. sqlite3VdbeMemMove(pOut, pIn1);
  77904. #ifdef SQLITE_DEBUG
  77905. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  77906. pOut->pScopyFrom += pOp->p2 - p1;
  77907. }
  77908. #endif
  77909. Deephemeralize(pOut);
  77910. REGISTER_TRACE(p2++, pOut);
  77911. pIn1++;
  77912. pOut++;
  77913. }while( --n );
  77914. break;
  77915. }
  77916. /* Opcode: Copy P1 P2 P3 * *
  77917. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  77918. **
  77919. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  77920. **
  77921. ** This instruction makes a deep copy of the value. A duplicate
  77922. ** is made of any string or blob constant. See also OP_SCopy.
  77923. */
  77924. case OP_Copy: {
  77925. int n;
  77926. n = pOp->p3;
  77927. pIn1 = &aMem[pOp->p1];
  77928. pOut = &aMem[pOp->p2];
  77929. assert( pOut!=pIn1 );
  77930. while( 1 ){
  77931. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  77932. Deephemeralize(pOut);
  77933. #ifdef SQLITE_DEBUG
  77934. pOut->pScopyFrom = 0;
  77935. #endif
  77936. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  77937. if( (n--)==0 ) break;
  77938. pOut++;
  77939. pIn1++;
  77940. }
  77941. break;
  77942. }
  77943. /* Opcode: SCopy P1 P2 * * *
  77944. ** Synopsis: r[P2]=r[P1]
  77945. **
  77946. ** Make a shallow copy of register P1 into register P2.
  77947. **
  77948. ** This instruction makes a shallow copy of the value. If the value
  77949. ** is a string or blob, then the copy is only a pointer to the
  77950. ** original and hence if the original changes so will the copy.
  77951. ** Worse, if the original is deallocated, the copy becomes invalid.
  77952. ** Thus the program must guarantee that the original will not change
  77953. ** during the lifetime of the copy. Use OP_Copy to make a complete
  77954. ** copy.
  77955. */
  77956. case OP_SCopy: { /* out2 */
  77957. pIn1 = &aMem[pOp->p1];
  77958. pOut = &aMem[pOp->p2];
  77959. assert( pOut!=pIn1 );
  77960. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  77961. #ifdef SQLITE_DEBUG
  77962. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  77963. #endif
  77964. break;
  77965. }
  77966. /* Opcode: IntCopy P1 P2 * * *
  77967. ** Synopsis: r[P2]=r[P1]
  77968. **
  77969. ** Transfer the integer value held in register P1 into register P2.
  77970. **
  77971. ** This is an optimized version of SCopy that works only for integer
  77972. ** values.
  77973. */
  77974. case OP_IntCopy: { /* out2 */
  77975. pIn1 = &aMem[pOp->p1];
  77976. assert( (pIn1->flags & MEM_Int)!=0 );
  77977. pOut = &aMem[pOp->p2];
  77978. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  77979. break;
  77980. }
  77981. /* Opcode: ResultRow P1 P2 * * *
  77982. ** Synopsis: output=r[P1@P2]
  77983. **
  77984. ** The registers P1 through P1+P2-1 contain a single row of
  77985. ** results. This opcode causes the sqlite3_step() call to terminate
  77986. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  77987. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  77988. ** the result row.
  77989. */
  77990. case OP_ResultRow: {
  77991. Mem *pMem;
  77992. int i;
  77993. assert( p->nResColumn==pOp->p2 );
  77994. assert( pOp->p1>0 );
  77995. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  77996. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  77997. /* Run the progress counter just before returning.
  77998. */
  77999. if( db->xProgress!=0
  78000. && nVmStep>=nProgressLimit
  78001. && db->xProgress(db->pProgressArg)!=0
  78002. ){
  78003. rc = SQLITE_INTERRUPT;
  78004. goto abort_due_to_error;
  78005. }
  78006. #endif
  78007. /* If this statement has violated immediate foreign key constraints, do
  78008. ** not return the number of rows modified. And do not RELEASE the statement
  78009. ** transaction. It needs to be rolled back. */
  78010. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  78011. assert( db->flags&SQLITE_CountRows );
  78012. assert( p->usesStmtJournal );
  78013. goto abort_due_to_error;
  78014. }
  78015. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  78016. ** DML statements invoke this opcode to return the number of rows
  78017. ** modified to the user. This is the only way that a VM that
  78018. ** opens a statement transaction may invoke this opcode.
  78019. **
  78020. ** In case this is such a statement, close any statement transaction
  78021. ** opened by this VM before returning control to the user. This is to
  78022. ** ensure that statement-transactions are always nested, not overlapping.
  78023. ** If the open statement-transaction is not closed here, then the user
  78024. ** may step another VM that opens its own statement transaction. This
  78025. ** may lead to overlapping statement transactions.
  78026. **
  78027. ** The statement transaction is never a top-level transaction. Hence
  78028. ** the RELEASE call below can never fail.
  78029. */
  78030. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  78031. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  78032. assert( rc==SQLITE_OK );
  78033. /* Invalidate all ephemeral cursor row caches */
  78034. p->cacheCtr = (p->cacheCtr + 2)|1;
  78035. /* Make sure the results of the current row are \000 terminated
  78036. ** and have an assigned type. The results are de-ephemeralized as
  78037. ** a side effect.
  78038. */
  78039. pMem = p->pResultSet = &aMem[pOp->p1];
  78040. for(i=0; i<pOp->p2; i++){
  78041. assert( memIsValid(&pMem[i]) );
  78042. Deephemeralize(&pMem[i]);
  78043. assert( (pMem[i].flags & MEM_Ephem)==0
  78044. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  78045. sqlite3VdbeMemNulTerminate(&pMem[i]);
  78046. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  78047. }
  78048. if( db->mallocFailed ) goto no_mem;
  78049. if( db->mTrace & SQLITE_TRACE_ROW ){
  78050. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  78051. }
  78052. /* Return SQLITE_ROW
  78053. */
  78054. p->pc = (int)(pOp - aOp) + 1;
  78055. rc = SQLITE_ROW;
  78056. goto vdbe_return;
  78057. }
  78058. /* Opcode: Concat P1 P2 P3 * *
  78059. ** Synopsis: r[P3]=r[P2]+r[P1]
  78060. **
  78061. ** Add the text in register P1 onto the end of the text in
  78062. ** register P2 and store the result in register P3.
  78063. ** If either the P1 or P2 text are NULL then store NULL in P3.
  78064. **
  78065. ** P3 = P2 || P1
  78066. **
  78067. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  78068. ** if P3 is the same register as P2, the implementation is able
  78069. ** to avoid a memcpy().
  78070. */
  78071. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  78072. i64 nByte;
  78073. pIn1 = &aMem[pOp->p1];
  78074. pIn2 = &aMem[pOp->p2];
  78075. pOut = &aMem[pOp->p3];
  78076. assert( pIn1!=pOut );
  78077. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  78078. sqlite3VdbeMemSetNull(pOut);
  78079. break;
  78080. }
  78081. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  78082. Stringify(pIn1, encoding);
  78083. Stringify(pIn2, encoding);
  78084. nByte = pIn1->n + pIn2->n;
  78085. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  78086. goto too_big;
  78087. }
  78088. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  78089. goto no_mem;
  78090. }
  78091. MemSetTypeFlag(pOut, MEM_Str);
  78092. if( pOut!=pIn2 ){
  78093. memcpy(pOut->z, pIn2->z, pIn2->n);
  78094. }
  78095. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  78096. pOut->z[nByte]=0;
  78097. pOut->z[nByte+1] = 0;
  78098. pOut->flags |= MEM_Term;
  78099. pOut->n = (int)nByte;
  78100. pOut->enc = encoding;
  78101. UPDATE_MAX_BLOBSIZE(pOut);
  78102. break;
  78103. }
  78104. /* Opcode: Add P1 P2 P3 * *
  78105. ** Synopsis: r[P3]=r[P1]+r[P2]
  78106. **
  78107. ** Add the value in register P1 to the value in register P2
  78108. ** and store the result in register P3.
  78109. ** If either input is NULL, the result is NULL.
  78110. */
  78111. /* Opcode: Multiply P1 P2 P3 * *
  78112. ** Synopsis: r[P3]=r[P1]*r[P2]
  78113. **
  78114. **
  78115. ** Multiply the value in register P1 by the value in register P2
  78116. ** and store the result in register P3.
  78117. ** If either input is NULL, the result is NULL.
  78118. */
  78119. /* Opcode: Subtract P1 P2 P3 * *
  78120. ** Synopsis: r[P3]=r[P2]-r[P1]
  78121. **
  78122. ** Subtract the value in register P1 from the value in register P2
  78123. ** and store the result in register P3.
  78124. ** If either input is NULL, the result is NULL.
  78125. */
  78126. /* Opcode: Divide P1 P2 P3 * *
  78127. ** Synopsis: r[P3]=r[P2]/r[P1]
  78128. **
  78129. ** Divide the value in register P1 by the value in register P2
  78130. ** and store the result in register P3 (P3=P2/P1). If the value in
  78131. ** register P1 is zero, then the result is NULL. If either input is
  78132. ** NULL, the result is NULL.
  78133. */
  78134. /* Opcode: Remainder P1 P2 P3 * *
  78135. ** Synopsis: r[P3]=r[P2]%r[P1]
  78136. **
  78137. ** Compute the remainder after integer register P2 is divided by
  78138. ** register P1 and store the result in register P3.
  78139. ** If the value in register P1 is zero the result is NULL.
  78140. ** If either operand is NULL, the result is NULL.
  78141. */
  78142. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  78143. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  78144. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  78145. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  78146. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  78147. char bIntint; /* Started out as two integer operands */
  78148. u16 flags; /* Combined MEM_* flags from both inputs */
  78149. u16 type1; /* Numeric type of left operand */
  78150. u16 type2; /* Numeric type of right operand */
  78151. i64 iA; /* Integer value of left operand */
  78152. i64 iB; /* Integer value of right operand */
  78153. double rA; /* Real value of left operand */
  78154. double rB; /* Real value of right operand */
  78155. pIn1 = &aMem[pOp->p1];
  78156. type1 = numericType(pIn1);
  78157. pIn2 = &aMem[pOp->p2];
  78158. type2 = numericType(pIn2);
  78159. pOut = &aMem[pOp->p3];
  78160. flags = pIn1->flags | pIn2->flags;
  78161. if( (type1 & type2 & MEM_Int)!=0 ){
  78162. iA = pIn1->u.i;
  78163. iB = pIn2->u.i;
  78164. bIntint = 1;
  78165. switch( pOp->opcode ){
  78166. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  78167. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  78168. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  78169. case OP_Divide: {
  78170. if( iA==0 ) goto arithmetic_result_is_null;
  78171. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  78172. iB /= iA;
  78173. break;
  78174. }
  78175. default: {
  78176. if( iA==0 ) goto arithmetic_result_is_null;
  78177. if( iA==-1 ) iA = 1;
  78178. iB %= iA;
  78179. break;
  78180. }
  78181. }
  78182. pOut->u.i = iB;
  78183. MemSetTypeFlag(pOut, MEM_Int);
  78184. }else if( (flags & MEM_Null)!=0 ){
  78185. goto arithmetic_result_is_null;
  78186. }else{
  78187. bIntint = 0;
  78188. fp_math:
  78189. rA = sqlite3VdbeRealValue(pIn1);
  78190. rB = sqlite3VdbeRealValue(pIn2);
  78191. switch( pOp->opcode ){
  78192. case OP_Add: rB += rA; break;
  78193. case OP_Subtract: rB -= rA; break;
  78194. case OP_Multiply: rB *= rA; break;
  78195. case OP_Divide: {
  78196. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  78197. if( rA==(double)0 ) goto arithmetic_result_is_null;
  78198. rB /= rA;
  78199. break;
  78200. }
  78201. default: {
  78202. iA = (i64)rA;
  78203. iB = (i64)rB;
  78204. if( iA==0 ) goto arithmetic_result_is_null;
  78205. if( iA==-1 ) iA = 1;
  78206. rB = (double)(iB % iA);
  78207. break;
  78208. }
  78209. }
  78210. #ifdef SQLITE_OMIT_FLOATING_POINT
  78211. pOut->u.i = rB;
  78212. MemSetTypeFlag(pOut, MEM_Int);
  78213. #else
  78214. if( sqlite3IsNaN(rB) ){
  78215. goto arithmetic_result_is_null;
  78216. }
  78217. pOut->u.r = rB;
  78218. MemSetTypeFlag(pOut, MEM_Real);
  78219. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  78220. sqlite3VdbeIntegerAffinity(pOut);
  78221. }
  78222. #endif
  78223. }
  78224. break;
  78225. arithmetic_result_is_null:
  78226. sqlite3VdbeMemSetNull(pOut);
  78227. break;
  78228. }
  78229. /* Opcode: CollSeq P1 * * P4
  78230. **
  78231. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  78232. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  78233. ** be returned. This is used by the built-in min(), max() and nullif()
  78234. ** functions.
  78235. **
  78236. ** If P1 is not zero, then it is a register that a subsequent min() or
  78237. ** max() aggregate will set to 1 if the current row is not the minimum or
  78238. ** maximum. The P1 register is initialized to 0 by this instruction.
  78239. **
  78240. ** The interface used by the implementation of the aforementioned functions
  78241. ** to retrieve the collation sequence set by this opcode is not available
  78242. ** publicly. Only built-in functions have access to this feature.
  78243. */
  78244. case OP_CollSeq: {
  78245. assert( pOp->p4type==P4_COLLSEQ );
  78246. if( pOp->p1 ){
  78247. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  78248. }
  78249. break;
  78250. }
  78251. /* Opcode: BitAnd P1 P2 P3 * *
  78252. ** Synopsis: r[P3]=r[P1]&r[P2]
  78253. **
  78254. ** Take the bit-wise AND of the values in register P1 and P2 and
  78255. ** store the result in register P3.
  78256. ** If either input is NULL, the result is NULL.
  78257. */
  78258. /* Opcode: BitOr P1 P2 P3 * *
  78259. ** Synopsis: r[P3]=r[P1]|r[P2]
  78260. **
  78261. ** Take the bit-wise OR of the values in register P1 and P2 and
  78262. ** store the result in register P3.
  78263. ** If either input is NULL, the result is NULL.
  78264. */
  78265. /* Opcode: ShiftLeft P1 P2 P3 * *
  78266. ** Synopsis: r[P3]=r[P2]<<r[P1]
  78267. **
  78268. ** Shift the integer value in register P2 to the left by the
  78269. ** number of bits specified by the integer in register P1.
  78270. ** Store the result in register P3.
  78271. ** If either input is NULL, the result is NULL.
  78272. */
  78273. /* Opcode: ShiftRight P1 P2 P3 * *
  78274. ** Synopsis: r[P3]=r[P2]>>r[P1]
  78275. **
  78276. ** Shift the integer value in register P2 to the right by the
  78277. ** number of bits specified by the integer in register P1.
  78278. ** Store the result in register P3.
  78279. ** If either input is NULL, the result is NULL.
  78280. */
  78281. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  78282. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  78283. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  78284. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  78285. i64 iA;
  78286. u64 uA;
  78287. i64 iB;
  78288. u8 op;
  78289. pIn1 = &aMem[pOp->p1];
  78290. pIn2 = &aMem[pOp->p2];
  78291. pOut = &aMem[pOp->p3];
  78292. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  78293. sqlite3VdbeMemSetNull(pOut);
  78294. break;
  78295. }
  78296. iA = sqlite3VdbeIntValue(pIn2);
  78297. iB = sqlite3VdbeIntValue(pIn1);
  78298. op = pOp->opcode;
  78299. if( op==OP_BitAnd ){
  78300. iA &= iB;
  78301. }else if( op==OP_BitOr ){
  78302. iA |= iB;
  78303. }else if( iB!=0 ){
  78304. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  78305. /* If shifting by a negative amount, shift in the other direction */
  78306. if( iB<0 ){
  78307. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  78308. op = 2*OP_ShiftLeft + 1 - op;
  78309. iB = iB>(-64) ? -iB : 64;
  78310. }
  78311. if( iB>=64 ){
  78312. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  78313. }else{
  78314. memcpy(&uA, &iA, sizeof(uA));
  78315. if( op==OP_ShiftLeft ){
  78316. uA <<= iB;
  78317. }else{
  78318. uA >>= iB;
  78319. /* Sign-extend on a right shift of a negative number */
  78320. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  78321. }
  78322. memcpy(&iA, &uA, sizeof(iA));
  78323. }
  78324. }
  78325. pOut->u.i = iA;
  78326. MemSetTypeFlag(pOut, MEM_Int);
  78327. break;
  78328. }
  78329. /* Opcode: AddImm P1 P2 * * *
  78330. ** Synopsis: r[P1]=r[P1]+P2
  78331. **
  78332. ** Add the constant P2 to the value in register P1.
  78333. ** The result is always an integer.
  78334. **
  78335. ** To force any register to be an integer, just add 0.
  78336. */
  78337. case OP_AddImm: { /* in1 */
  78338. pIn1 = &aMem[pOp->p1];
  78339. memAboutToChange(p, pIn1);
  78340. sqlite3VdbeMemIntegerify(pIn1);
  78341. pIn1->u.i += pOp->p2;
  78342. break;
  78343. }
  78344. /* Opcode: MustBeInt P1 P2 * * *
  78345. **
  78346. ** Force the value in register P1 to be an integer. If the value
  78347. ** in P1 is not an integer and cannot be converted into an integer
  78348. ** without data loss, then jump immediately to P2, or if P2==0
  78349. ** raise an SQLITE_MISMATCH exception.
  78350. */
  78351. case OP_MustBeInt: { /* jump, in1 */
  78352. pIn1 = &aMem[pOp->p1];
  78353. if( (pIn1->flags & MEM_Int)==0 ){
  78354. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  78355. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  78356. if( (pIn1->flags & MEM_Int)==0 ){
  78357. if( pOp->p2==0 ){
  78358. rc = SQLITE_MISMATCH;
  78359. goto abort_due_to_error;
  78360. }else{
  78361. goto jump_to_p2;
  78362. }
  78363. }
  78364. }
  78365. MemSetTypeFlag(pIn1, MEM_Int);
  78366. break;
  78367. }
  78368. #ifndef SQLITE_OMIT_FLOATING_POINT
  78369. /* Opcode: RealAffinity P1 * * * *
  78370. **
  78371. ** If register P1 holds an integer convert it to a real value.
  78372. **
  78373. ** This opcode is used when extracting information from a column that
  78374. ** has REAL affinity. Such column values may still be stored as
  78375. ** integers, for space efficiency, but after extraction we want them
  78376. ** to have only a real value.
  78377. */
  78378. case OP_RealAffinity: { /* in1 */
  78379. pIn1 = &aMem[pOp->p1];
  78380. if( pIn1->flags & MEM_Int ){
  78381. sqlite3VdbeMemRealify(pIn1);
  78382. }
  78383. break;
  78384. }
  78385. #endif
  78386. #ifndef SQLITE_OMIT_CAST
  78387. /* Opcode: Cast P1 P2 * * *
  78388. ** Synopsis: affinity(r[P1])
  78389. **
  78390. ** Force the value in register P1 to be the type defined by P2.
  78391. **
  78392. ** <ul>
  78393. ** <li> P2=='A' &rarr; BLOB
  78394. ** <li> P2=='B' &rarr; TEXT
  78395. ** <li> P2=='C' &rarr; NUMERIC
  78396. ** <li> P2=='D' &rarr; INTEGER
  78397. ** <li> P2=='E' &rarr; REAL
  78398. ** </ul>
  78399. **
  78400. ** A NULL value is not changed by this routine. It remains NULL.
  78401. */
  78402. case OP_Cast: { /* in1 */
  78403. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  78404. testcase( pOp->p2==SQLITE_AFF_TEXT );
  78405. testcase( pOp->p2==SQLITE_AFF_BLOB );
  78406. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  78407. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  78408. testcase( pOp->p2==SQLITE_AFF_REAL );
  78409. pIn1 = &aMem[pOp->p1];
  78410. memAboutToChange(p, pIn1);
  78411. rc = ExpandBlob(pIn1);
  78412. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  78413. UPDATE_MAX_BLOBSIZE(pIn1);
  78414. if( rc ) goto abort_due_to_error;
  78415. break;
  78416. }
  78417. #endif /* SQLITE_OMIT_CAST */
  78418. /* Opcode: Eq P1 P2 P3 P4 P5
  78419. ** Synopsis: IF r[P3]==r[P1]
  78420. **
  78421. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  78422. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  78423. ** store the result of comparison in register P2.
  78424. **
  78425. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  78426. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  78427. ** to coerce both inputs according to this affinity before the
  78428. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  78429. ** affinity is used. Note that the affinity conversions are stored
  78430. ** back into the input registers P1 and P3. So this opcode can cause
  78431. ** persistent changes to registers P1 and P3.
  78432. **
  78433. ** Once any conversions have taken place, and neither value is NULL,
  78434. ** the values are compared. If both values are blobs then memcmp() is
  78435. ** used to determine the results of the comparison. If both values
  78436. ** are text, then the appropriate collating function specified in
  78437. ** P4 is used to do the comparison. If P4 is not specified then
  78438. ** memcmp() is used to compare text string. If both values are
  78439. ** numeric, then a numeric comparison is used. If the two values
  78440. ** are of different types, then numbers are considered less than
  78441. ** strings and strings are considered less than blobs.
  78442. **
  78443. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  78444. ** true or false and is never NULL. If both operands are NULL then the result
  78445. ** of comparison is true. If either operand is NULL then the result is false.
  78446. ** If neither operand is NULL the result is the same as it would be if
  78447. ** the SQLITE_NULLEQ flag were omitted from P5.
  78448. **
  78449. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  78450. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  78451. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  78452. */
  78453. /* Opcode: Ne P1 P2 P3 P4 P5
  78454. ** Synopsis: IF r[P3]!=r[P1]
  78455. **
  78456. ** This works just like the Eq opcode except that the jump is taken if
  78457. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  78458. ** additional information.
  78459. **
  78460. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  78461. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  78462. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  78463. */
  78464. /* Opcode: Lt P1 P2 P3 P4 P5
  78465. ** Synopsis: IF r[P3]<r[P1]
  78466. **
  78467. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  78468. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  78469. ** the result of comparison (0 or 1 or NULL) into register P2.
  78470. **
  78471. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  78472. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  78473. ** bit is clear then fall through if either operand is NULL.
  78474. **
  78475. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  78476. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  78477. ** to coerce both inputs according to this affinity before the
  78478. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  78479. ** affinity is used. Note that the affinity conversions are stored
  78480. ** back into the input registers P1 and P3. So this opcode can cause
  78481. ** persistent changes to registers P1 and P3.
  78482. **
  78483. ** Once any conversions have taken place, and neither value is NULL,
  78484. ** the values are compared. If both values are blobs then memcmp() is
  78485. ** used to determine the results of the comparison. If both values
  78486. ** are text, then the appropriate collating function specified in
  78487. ** P4 is used to do the comparison. If P4 is not specified then
  78488. ** memcmp() is used to compare text string. If both values are
  78489. ** numeric, then a numeric comparison is used. If the two values
  78490. ** are of different types, then numbers are considered less than
  78491. ** strings and strings are considered less than blobs.
  78492. */
  78493. /* Opcode: Le P1 P2 P3 P4 P5
  78494. ** Synopsis: IF r[P3]<=r[P1]
  78495. **
  78496. ** This works just like the Lt opcode except that the jump is taken if
  78497. ** the content of register P3 is less than or equal to the content of
  78498. ** register P1. See the Lt opcode for additional information.
  78499. */
  78500. /* Opcode: Gt P1 P2 P3 P4 P5
  78501. ** Synopsis: IF r[P3]>r[P1]
  78502. **
  78503. ** This works just like the Lt opcode except that the jump is taken if
  78504. ** the content of register P3 is greater than the content of
  78505. ** register P1. See the Lt opcode for additional information.
  78506. */
  78507. /* Opcode: Ge P1 P2 P3 P4 P5
  78508. ** Synopsis: IF r[P3]>=r[P1]
  78509. **
  78510. ** This works just like the Lt opcode except that the jump is taken if
  78511. ** the content of register P3 is greater than or equal to the content of
  78512. ** register P1. See the Lt opcode for additional information.
  78513. */
  78514. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  78515. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  78516. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  78517. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  78518. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  78519. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  78520. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  78521. char affinity; /* Affinity to use for comparison */
  78522. u16 flags1; /* Copy of initial value of pIn1->flags */
  78523. u16 flags3; /* Copy of initial value of pIn3->flags */
  78524. pIn1 = &aMem[pOp->p1];
  78525. pIn3 = &aMem[pOp->p3];
  78526. flags1 = pIn1->flags;
  78527. flags3 = pIn3->flags;
  78528. if( (flags1 | flags3)&MEM_Null ){
  78529. /* One or both operands are NULL */
  78530. if( pOp->p5 & SQLITE_NULLEQ ){
  78531. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  78532. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  78533. ** or not both operands are null.
  78534. */
  78535. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  78536. assert( (flags1 & MEM_Cleared)==0 );
  78537. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  78538. if( (flags1&flags3&MEM_Null)!=0
  78539. && (flags3&MEM_Cleared)==0
  78540. ){
  78541. res = 0; /* Operands are equal */
  78542. }else{
  78543. res = 1; /* Operands are not equal */
  78544. }
  78545. }else{
  78546. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  78547. ** then the result is always NULL.
  78548. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  78549. */
  78550. if( pOp->p5 & SQLITE_STOREP2 ){
  78551. pOut = &aMem[pOp->p2];
  78552. iCompare = 1; /* Operands are not equal */
  78553. memAboutToChange(p, pOut);
  78554. MemSetTypeFlag(pOut, MEM_Null);
  78555. REGISTER_TRACE(pOp->p2, pOut);
  78556. }else{
  78557. VdbeBranchTaken(2,3);
  78558. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  78559. goto jump_to_p2;
  78560. }
  78561. }
  78562. break;
  78563. }
  78564. }else{
  78565. /* Neither operand is NULL. Do a comparison. */
  78566. affinity = pOp->p5 & SQLITE_AFF_MASK;
  78567. if( affinity>=SQLITE_AFF_NUMERIC ){
  78568. if( (flags1 | flags3)&MEM_Str ){
  78569. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  78570. applyNumericAffinity(pIn1,0);
  78571. testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
  78572. flags3 = pIn3->flags;
  78573. }
  78574. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  78575. applyNumericAffinity(pIn3,0);
  78576. }
  78577. }
  78578. /* Handle the common case of integer comparison here, as an
  78579. ** optimization, to avoid a call to sqlite3MemCompare() */
  78580. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  78581. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  78582. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  78583. res = 0;
  78584. goto compare_op;
  78585. }
  78586. }else if( affinity==SQLITE_AFF_TEXT ){
  78587. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  78588. testcase( pIn1->flags & MEM_Int );
  78589. testcase( pIn1->flags & MEM_Real );
  78590. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  78591. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  78592. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  78593. assert( pIn1!=pIn3 );
  78594. }
  78595. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  78596. testcase( pIn3->flags & MEM_Int );
  78597. testcase( pIn3->flags & MEM_Real );
  78598. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  78599. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  78600. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  78601. }
  78602. }
  78603. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  78604. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  78605. }
  78606. compare_op:
  78607. /* At this point, res is negative, zero, or positive if reg[P1] is
  78608. ** less than, equal to, or greater than reg[P3], respectively. Compute
  78609. ** the answer to this operator in res2, depending on what the comparison
  78610. ** operator actually is. The next block of code depends on the fact
  78611. ** that the 6 comparison operators are consecutive integers in this
  78612. ** order: NE, EQ, GT, LE, LT, GE */
  78613. assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
  78614. assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
  78615. if( res<0 ){ /* ne, eq, gt, le, lt, ge */
  78616. static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
  78617. res2 = aLTb[pOp->opcode - OP_Ne];
  78618. }else if( res==0 ){
  78619. static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
  78620. res2 = aEQb[pOp->opcode - OP_Ne];
  78621. }else{
  78622. static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
  78623. res2 = aGTb[pOp->opcode - OP_Ne];
  78624. }
  78625. /* Undo any changes made by applyAffinity() to the input registers. */
  78626. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  78627. pIn1->flags = flags1;
  78628. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  78629. pIn3->flags = flags3;
  78630. if( pOp->p5 & SQLITE_STOREP2 ){
  78631. pOut = &aMem[pOp->p2];
  78632. iCompare = res;
  78633. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  78634. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  78635. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  78636. ** is only used in contexts where either:
  78637. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  78638. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  78639. ** Therefore it is not necessary to check the content of r[P2] for
  78640. ** NULL. */
  78641. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  78642. assert( res2==0 || res2==1 );
  78643. testcase( res2==0 && pOp->opcode==OP_Eq );
  78644. testcase( res2==1 && pOp->opcode==OP_Eq );
  78645. testcase( res2==0 && pOp->opcode==OP_Ne );
  78646. testcase( res2==1 && pOp->opcode==OP_Ne );
  78647. if( (pOp->opcode==OP_Eq)==res2 ) break;
  78648. }
  78649. memAboutToChange(p, pOut);
  78650. MemSetTypeFlag(pOut, MEM_Int);
  78651. pOut->u.i = res2;
  78652. REGISTER_TRACE(pOp->p2, pOut);
  78653. }else{
  78654. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  78655. if( res2 ){
  78656. goto jump_to_p2;
  78657. }
  78658. }
  78659. break;
  78660. }
  78661. /* Opcode: ElseNotEq * P2 * * *
  78662. **
  78663. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  78664. ** If result of an OP_Eq comparison on the same two operands
  78665. ** would have be NULL or false (0), then then jump to P2.
  78666. ** If the result of an OP_Eq comparison on the two previous operands
  78667. ** would have been true (1), then fall through.
  78668. */
  78669. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  78670. assert( pOp>aOp );
  78671. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  78672. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  78673. VdbeBranchTaken(iCompare!=0, 2);
  78674. if( iCompare!=0 ) goto jump_to_p2;
  78675. break;
  78676. }
  78677. /* Opcode: Permutation * * * P4 *
  78678. **
  78679. ** Set the permutation used by the OP_Compare operator in the next
  78680. ** instruction. The permutation is stored in the P4 operand.
  78681. **
  78682. ** The permutation is only valid until the next OP_Compare that has
  78683. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  78684. ** occur immediately prior to the OP_Compare.
  78685. **
  78686. ** The first integer in the P4 integer array is the length of the array
  78687. ** and does not become part of the permutation.
  78688. */
  78689. case OP_Permutation: {
  78690. assert( pOp->p4type==P4_INTARRAY );
  78691. assert( pOp->p4.ai );
  78692. assert( pOp[1].opcode==OP_Compare );
  78693. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  78694. break;
  78695. }
  78696. /* Opcode: Compare P1 P2 P3 P4 P5
  78697. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  78698. **
  78699. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  78700. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  78701. ** the comparison for use by the next OP_Jump instruct.
  78702. **
  78703. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  78704. ** determined by the most recent OP_Permutation operator. If the
  78705. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  78706. ** order.
  78707. **
  78708. ** P4 is a KeyInfo structure that defines collating sequences and sort
  78709. ** orders for the comparison. The permutation applies to registers
  78710. ** only. The KeyInfo elements are used sequentially.
  78711. **
  78712. ** The comparison is a sort comparison, so NULLs compare equal,
  78713. ** NULLs are less than numbers, numbers are less than strings,
  78714. ** and strings are less than blobs.
  78715. */
  78716. case OP_Compare: {
  78717. int n;
  78718. int i;
  78719. int p1;
  78720. int p2;
  78721. const KeyInfo *pKeyInfo;
  78722. int idx;
  78723. CollSeq *pColl; /* Collating sequence to use on this term */
  78724. int bRev; /* True for DESCENDING sort order */
  78725. int *aPermute; /* The permutation */
  78726. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  78727. aPermute = 0;
  78728. }else{
  78729. assert( pOp>aOp );
  78730. assert( pOp[-1].opcode==OP_Permutation );
  78731. assert( pOp[-1].p4type==P4_INTARRAY );
  78732. aPermute = pOp[-1].p4.ai + 1;
  78733. assert( aPermute!=0 );
  78734. }
  78735. n = pOp->p3;
  78736. pKeyInfo = pOp->p4.pKeyInfo;
  78737. assert( n>0 );
  78738. assert( pKeyInfo!=0 );
  78739. p1 = pOp->p1;
  78740. p2 = pOp->p2;
  78741. #ifdef SQLITE_DEBUG
  78742. if( aPermute ){
  78743. int k, mx = 0;
  78744. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  78745. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  78746. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  78747. }else{
  78748. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  78749. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  78750. }
  78751. #endif /* SQLITE_DEBUG */
  78752. for(i=0; i<n; i++){
  78753. idx = aPermute ? aPermute[i] : i;
  78754. assert( memIsValid(&aMem[p1+idx]) );
  78755. assert( memIsValid(&aMem[p2+idx]) );
  78756. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  78757. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  78758. assert( i<pKeyInfo->nKeyField );
  78759. pColl = pKeyInfo->aColl[i];
  78760. bRev = pKeyInfo->aSortOrder[i];
  78761. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  78762. if( iCompare ){
  78763. if( bRev ) iCompare = -iCompare;
  78764. break;
  78765. }
  78766. }
  78767. break;
  78768. }
  78769. /* Opcode: Jump P1 P2 P3 * *
  78770. **
  78771. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  78772. ** in the most recent OP_Compare instruction the P1 vector was less than
  78773. ** equal to, or greater than the P2 vector, respectively.
  78774. */
  78775. case OP_Jump: { /* jump */
  78776. if( iCompare<0 ){
  78777. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  78778. }else if( iCompare==0 ){
  78779. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  78780. }else{
  78781. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  78782. }
  78783. break;
  78784. }
  78785. /* Opcode: And P1 P2 P3 * *
  78786. ** Synopsis: r[P3]=(r[P1] && r[P2])
  78787. **
  78788. ** Take the logical AND of the values in registers P1 and P2 and
  78789. ** write the result into register P3.
  78790. **
  78791. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  78792. ** the other input is NULL. A NULL and true or two NULLs give
  78793. ** a NULL output.
  78794. */
  78795. /* Opcode: Or P1 P2 P3 * *
  78796. ** Synopsis: r[P3]=(r[P1] || r[P2])
  78797. **
  78798. ** Take the logical OR of the values in register P1 and P2 and
  78799. ** store the answer in register P3.
  78800. **
  78801. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  78802. ** even if the other input is NULL. A NULL and false or two NULLs
  78803. ** give a NULL output.
  78804. */
  78805. case OP_And: /* same as TK_AND, in1, in2, out3 */
  78806. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  78807. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  78808. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  78809. v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
  78810. v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
  78811. if( pOp->opcode==OP_And ){
  78812. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  78813. v1 = and_logic[v1*3+v2];
  78814. }else{
  78815. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  78816. v1 = or_logic[v1*3+v2];
  78817. }
  78818. pOut = &aMem[pOp->p3];
  78819. if( v1==2 ){
  78820. MemSetTypeFlag(pOut, MEM_Null);
  78821. }else{
  78822. pOut->u.i = v1;
  78823. MemSetTypeFlag(pOut, MEM_Int);
  78824. }
  78825. break;
  78826. }
  78827. /* Opcode: IsTrue P1 P2 P3 P4 *
  78828. ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
  78829. **
  78830. ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
  78831. ** IS NOT FALSE operators.
  78832. **
  78833. ** Interpret the value in register P1 as a boolean value. Store that
  78834. ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
  78835. ** NULL, then the P3 is stored in register P2. Invert the answer if P4
  78836. ** is 1.
  78837. **
  78838. ** The logic is summarized like this:
  78839. **
  78840. ** <ul>
  78841. ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
  78842. ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
  78843. ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
  78844. ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
  78845. ** </ul>
  78846. */
  78847. case OP_IsTrue: { /* in1, out2 */
  78848. assert( pOp->p4type==P4_INT32 );
  78849. assert( pOp->p4.i==0 || pOp->p4.i==1 );
  78850. assert( pOp->p3==0 || pOp->p3==1 );
  78851. sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
  78852. sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
  78853. break;
  78854. }
  78855. /* Opcode: Not P1 P2 * * *
  78856. ** Synopsis: r[P2]= !r[P1]
  78857. **
  78858. ** Interpret the value in register P1 as a boolean value. Store the
  78859. ** boolean complement in register P2. If the value in register P1 is
  78860. ** NULL, then a NULL is stored in P2.
  78861. */
  78862. case OP_Not: { /* same as TK_NOT, in1, out2 */
  78863. pIn1 = &aMem[pOp->p1];
  78864. pOut = &aMem[pOp->p2];
  78865. if( (pIn1->flags & MEM_Null)==0 ){
  78866. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
  78867. }else{
  78868. sqlite3VdbeMemSetNull(pOut);
  78869. }
  78870. break;
  78871. }
  78872. /* Opcode: BitNot P1 P2 * * *
  78873. ** Synopsis: r[P1]= ~r[P1]
  78874. **
  78875. ** Interpret the content of register P1 as an integer. Store the
  78876. ** ones-complement of the P1 value into register P2. If P1 holds
  78877. ** a NULL then store a NULL in P2.
  78878. */
  78879. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  78880. pIn1 = &aMem[pOp->p1];
  78881. pOut = &aMem[pOp->p2];
  78882. sqlite3VdbeMemSetNull(pOut);
  78883. if( (pIn1->flags & MEM_Null)==0 ){
  78884. pOut->flags = MEM_Int;
  78885. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  78886. }
  78887. break;
  78888. }
  78889. /* Opcode: Once P1 P2 * * *
  78890. **
  78891. ** Fall through to the next instruction the first time this opcode is
  78892. ** encountered on each invocation of the byte-code program. Jump to P2
  78893. ** on the second and all subsequent encounters during the same invocation.
  78894. **
  78895. ** Top-level programs determine first invocation by comparing the P1
  78896. ** operand against the P1 operand on the OP_Init opcode at the beginning
  78897. ** of the program. If the P1 values differ, then fall through and make
  78898. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  78899. ** the same then take the jump.
  78900. **
  78901. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  78902. ** whether or not the jump should be taken. The bitmask is necessary
  78903. ** because the self-altering code trick does not work for recursive
  78904. ** triggers.
  78905. */
  78906. case OP_Once: { /* jump */
  78907. u32 iAddr; /* Address of this instruction */
  78908. assert( p->aOp[0].opcode==OP_Init );
  78909. if( p->pFrame ){
  78910. iAddr = (int)(pOp - p->aOp);
  78911. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  78912. VdbeBranchTaken(1, 2);
  78913. goto jump_to_p2;
  78914. }
  78915. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  78916. }else{
  78917. if( p->aOp[0].p1==pOp->p1 ){
  78918. VdbeBranchTaken(1, 2);
  78919. goto jump_to_p2;
  78920. }
  78921. }
  78922. VdbeBranchTaken(0, 2);
  78923. pOp->p1 = p->aOp[0].p1;
  78924. break;
  78925. }
  78926. /* Opcode: If P1 P2 P3 * *
  78927. **
  78928. ** Jump to P2 if the value in register P1 is true. The value
  78929. ** is considered true if it is numeric and non-zero. If the value
  78930. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  78931. */
  78932. case OP_If: { /* jump, in1 */
  78933. int c;
  78934. c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
  78935. VdbeBranchTaken(c!=0, 2);
  78936. if( c ) goto jump_to_p2;
  78937. break;
  78938. }
  78939. /* Opcode: IfNot P1 P2 P3 * *
  78940. **
  78941. ** Jump to P2 if the value in register P1 is False. The value
  78942. ** is considered false if it has a numeric value of zero. If the value
  78943. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  78944. */
  78945. case OP_IfNot: { /* jump, in1 */
  78946. int c;
  78947. c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
  78948. VdbeBranchTaken(c!=0, 2);
  78949. if( c ) goto jump_to_p2;
  78950. break;
  78951. }
  78952. /* Opcode: IsNull P1 P2 * * *
  78953. ** Synopsis: if r[P1]==NULL goto P2
  78954. **
  78955. ** Jump to P2 if the value in register P1 is NULL.
  78956. */
  78957. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  78958. pIn1 = &aMem[pOp->p1];
  78959. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  78960. if( (pIn1->flags & MEM_Null)!=0 ){
  78961. goto jump_to_p2;
  78962. }
  78963. break;
  78964. }
  78965. /* Opcode: NotNull P1 P2 * * *
  78966. ** Synopsis: if r[P1]!=NULL goto P2
  78967. **
  78968. ** Jump to P2 if the value in register P1 is not NULL.
  78969. */
  78970. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  78971. pIn1 = &aMem[pOp->p1];
  78972. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  78973. if( (pIn1->flags & MEM_Null)==0 ){
  78974. goto jump_to_p2;
  78975. }
  78976. break;
  78977. }
  78978. /* Opcode: IfNullRow P1 P2 P3 * *
  78979. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  78980. **
  78981. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  78982. ** If it is, then set register P3 to NULL and jump immediately to P2.
  78983. ** If P1 is not on a NULL row, then fall through without making any
  78984. ** changes.
  78985. */
  78986. case OP_IfNullRow: { /* jump */
  78987. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78988. assert( p->apCsr[pOp->p1]!=0 );
  78989. if( p->apCsr[pOp->p1]->nullRow ){
  78990. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  78991. goto jump_to_p2;
  78992. }
  78993. break;
  78994. }
  78995. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  78996. /* Opcode: Offset P1 P2 P3 * *
  78997. ** Synopsis: r[P3] = sqlite_offset(P1)
  78998. **
  78999. ** Store in register r[P3] the byte offset into the database file that is the
  79000. ** start of the payload for the record at which that cursor P1 is currently
  79001. ** pointing.
  79002. **
  79003. ** P2 is the column number for the argument to the sqlite_offset() function.
  79004. ** This opcode does not use P2 itself, but the P2 value is used by the
  79005. ** code generator. The P1, P2, and P3 operands to this opcode are the
  79006. ** same as for OP_Column.
  79007. **
  79008. ** This opcode is only available if SQLite is compiled with the
  79009. ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
  79010. */
  79011. case OP_Offset: { /* out3 */
  79012. VdbeCursor *pC; /* The VDBE cursor */
  79013. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79014. pC = p->apCsr[pOp->p1];
  79015. pOut = &p->aMem[pOp->p3];
  79016. if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
  79017. sqlite3VdbeMemSetNull(pOut);
  79018. }else{
  79019. sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
  79020. }
  79021. break;
  79022. }
  79023. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  79024. /* Opcode: Column P1 P2 P3 P4 P5
  79025. ** Synopsis: r[P3]=PX
  79026. **
  79027. ** Interpret the data that cursor P1 points to as a structure built using
  79028. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  79029. ** information about the format of the data.) Extract the P2-th column
  79030. ** from this record. If there are less that (P2+1)
  79031. ** values in the record, extract a NULL.
  79032. **
  79033. ** The value extracted is stored in register P3.
  79034. **
  79035. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  79036. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  79037. ** the result.
  79038. **
  79039. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  79040. ** then the cache of the cursor is reset prior to extracting the column.
  79041. ** The first OP_Column against a pseudo-table after the value of the content
  79042. ** register has changed should have this bit set.
  79043. **
  79044. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  79045. ** the result is guaranteed to only be used as the argument of a length()
  79046. ** or typeof() function, respectively. The loading of large blobs can be
  79047. ** skipped for length() and all content loading can be skipped for typeof().
  79048. */
  79049. case OP_Column: {
  79050. int p2; /* column number to retrieve */
  79051. VdbeCursor *pC; /* The VDBE cursor */
  79052. BtCursor *pCrsr; /* The BTree cursor */
  79053. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  79054. int len; /* The length of the serialized data for the column */
  79055. int i; /* Loop counter */
  79056. Mem *pDest; /* Where to write the extracted value */
  79057. Mem sMem; /* For storing the record being decoded */
  79058. const u8 *zData; /* Part of the record being decoded */
  79059. const u8 *zHdr; /* Next unparsed byte of the header */
  79060. const u8 *zEndHdr; /* Pointer to first byte after the header */
  79061. u64 offset64; /* 64-bit offset */
  79062. u32 t; /* A type code from the record header */
  79063. Mem *pReg; /* PseudoTable input register */
  79064. pC = p->apCsr[pOp->p1];
  79065. p2 = pOp->p2;
  79066. /* If the cursor cache is stale (meaning it is not currently point at
  79067. ** the correct row) then bring it up-to-date by doing the necessary
  79068. ** B-Tree seek. */
  79069. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  79070. if( rc ) goto abort_due_to_error;
  79071. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79072. pDest = &aMem[pOp->p3];
  79073. memAboutToChange(p, pDest);
  79074. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79075. assert( pC!=0 );
  79076. assert( p2<pC->nField );
  79077. aOffset = pC->aOffset;
  79078. assert( pC->eCurType!=CURTYPE_VTAB );
  79079. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  79080. assert( pC->eCurType!=CURTYPE_SORTER );
  79081. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  79082. if( pC->nullRow ){
  79083. if( pC->eCurType==CURTYPE_PSEUDO ){
  79084. /* For the special case of as pseudo-cursor, the seekResult field
  79085. ** identifies the register that holds the record */
  79086. assert( pC->seekResult>0 );
  79087. pReg = &aMem[pC->seekResult];
  79088. assert( pReg->flags & MEM_Blob );
  79089. assert( memIsValid(pReg) );
  79090. pC->payloadSize = pC->szRow = pReg->n;
  79091. pC->aRow = (u8*)pReg->z;
  79092. }else{
  79093. sqlite3VdbeMemSetNull(pDest);
  79094. goto op_column_out;
  79095. }
  79096. }else{
  79097. pCrsr = pC->uc.pCursor;
  79098. assert( pC->eCurType==CURTYPE_BTREE );
  79099. assert( pCrsr );
  79100. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  79101. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  79102. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
  79103. assert( pC->szRow<=pC->payloadSize );
  79104. assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
  79105. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  79106. goto too_big;
  79107. }
  79108. }
  79109. pC->cacheStatus = p->cacheCtr;
  79110. pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
  79111. pC->nHdrParsed = 0;
  79112. if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
  79113. /* pC->aRow does not have to hold the entire row, but it does at least
  79114. ** need to cover the header of the record. If pC->aRow does not contain
  79115. ** the complete header, then set it to zero, forcing the header to be
  79116. ** dynamically allocated. */
  79117. pC->aRow = 0;
  79118. pC->szRow = 0;
  79119. /* Make sure a corrupt database has not given us an oversize header.
  79120. ** Do this now to avoid an oversize memory allocation.
  79121. **
  79122. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  79123. ** types use so much data space that there can only be 4096 and 32 of
  79124. ** them, respectively. So the maximum header length results from a
  79125. ** 3-byte type for each of the maximum of 32768 columns plus three
  79126. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  79127. */
  79128. if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
  79129. goto op_column_corrupt;
  79130. }
  79131. }else{
  79132. /* This is an optimization. By skipping over the first few tests
  79133. ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
  79134. ** measurable performance gain.
  79135. **
  79136. ** This branch is taken even if aOffset[0]==0. Such a record is never
  79137. ** generated by SQLite, and could be considered corruption, but we
  79138. ** accept it for historical reasons. When aOffset[0]==0, the code this
  79139. ** branch jumps to reads past the end of the record, but never more
  79140. ** than a few bytes. Even if the record occurs at the end of the page
  79141. ** content area, the "page header" comes after the page content and so
  79142. ** this overread is harmless. Similar overreads can occur for a corrupt
  79143. ** database file.
  79144. */
  79145. zData = pC->aRow;
  79146. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  79147. testcase( aOffset[0]==0 );
  79148. goto op_column_read_header;
  79149. }
  79150. }
  79151. /* Make sure at least the first p2+1 entries of the header have been
  79152. ** parsed and valid information is in aOffset[] and pC->aType[].
  79153. */
  79154. if( pC->nHdrParsed<=p2 ){
  79155. /* If there is more header available for parsing in the record, try
  79156. ** to extract additional fields up through the p2+1-th field
  79157. */
  79158. if( pC->iHdrOffset<aOffset[0] ){
  79159. /* Make sure zData points to enough of the record to cover the header. */
  79160. if( pC->aRow==0 ){
  79161. memset(&sMem, 0, sizeof(sMem));
  79162. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  79163. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  79164. zData = (u8*)sMem.z;
  79165. }else{
  79166. zData = pC->aRow;
  79167. }
  79168. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  79169. op_column_read_header:
  79170. i = pC->nHdrParsed;
  79171. offset64 = aOffset[i];
  79172. zHdr = zData + pC->iHdrOffset;
  79173. zEndHdr = zData + aOffset[0];
  79174. testcase( zHdr>=zEndHdr );
  79175. do{
  79176. if( (t = zHdr[0])<0x80 ){
  79177. zHdr++;
  79178. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  79179. }else{
  79180. zHdr += sqlite3GetVarint32(zHdr, &t);
  79181. offset64 += sqlite3VdbeSerialTypeLen(t);
  79182. }
  79183. pC->aType[i++] = t;
  79184. aOffset[i] = (u32)(offset64 & 0xffffffff);
  79185. }while( i<=p2 && zHdr<zEndHdr );
  79186. /* The record is corrupt if any of the following are true:
  79187. ** (1) the bytes of the header extend past the declared header size
  79188. ** (2) the entire header was used but not all data was used
  79189. ** (3) the end of the data extends beyond the end of the record.
  79190. */
  79191. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  79192. || (offset64 > pC->payloadSize)
  79193. ){
  79194. if( aOffset[0]==0 ){
  79195. i = 0;
  79196. zHdr = zEndHdr;
  79197. }else{
  79198. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  79199. goto op_column_corrupt;
  79200. }
  79201. }
  79202. pC->nHdrParsed = i;
  79203. pC->iHdrOffset = (u32)(zHdr - zData);
  79204. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  79205. }else{
  79206. t = 0;
  79207. }
  79208. /* If after trying to extract new entries from the header, nHdrParsed is
  79209. ** still not up to p2, that means that the record has fewer than p2
  79210. ** columns. So the result will be either the default value or a NULL.
  79211. */
  79212. if( pC->nHdrParsed<=p2 ){
  79213. if( pOp->p4type==P4_MEM ){
  79214. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  79215. }else{
  79216. sqlite3VdbeMemSetNull(pDest);
  79217. }
  79218. goto op_column_out;
  79219. }
  79220. }else{
  79221. t = pC->aType[p2];
  79222. }
  79223. /* Extract the content for the p2+1-th column. Control can only
  79224. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  79225. ** all valid.
  79226. */
  79227. assert( p2<pC->nHdrParsed );
  79228. assert( rc==SQLITE_OK );
  79229. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  79230. if( VdbeMemDynamic(pDest) ){
  79231. sqlite3VdbeMemSetNull(pDest);
  79232. }
  79233. assert( t==pC->aType[p2] );
  79234. if( pC->szRow>=aOffset[p2+1] ){
  79235. /* This is the common case where the desired content fits on the original
  79236. ** page - where the content is not on an overflow page */
  79237. zData = pC->aRow + aOffset[p2];
  79238. if( t<12 ){
  79239. sqlite3VdbeSerialGet(zData, t, pDest);
  79240. }else{
  79241. /* If the column value is a string, we need a persistent value, not
  79242. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  79243. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  79244. */
  79245. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  79246. pDest->n = len = (t-12)/2;
  79247. pDest->enc = encoding;
  79248. if( pDest->szMalloc < len+2 ){
  79249. pDest->flags = MEM_Null;
  79250. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  79251. }else{
  79252. pDest->z = pDest->zMalloc;
  79253. }
  79254. memcpy(pDest->z, zData, len);
  79255. pDest->z[len] = 0;
  79256. pDest->z[len+1] = 0;
  79257. pDest->flags = aFlag[t&1];
  79258. }
  79259. }else{
  79260. pDest->enc = encoding;
  79261. /* This branch happens only when content is on overflow pages */
  79262. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  79263. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  79264. || (len = sqlite3VdbeSerialTypeLen(t))==0
  79265. ){
  79266. /* Content is irrelevant for
  79267. ** 1. the typeof() function,
  79268. ** 2. the length(X) function if X is a blob, and
  79269. ** 3. if the content length is zero.
  79270. ** So we might as well use bogus content rather than reading
  79271. ** content from disk.
  79272. **
  79273. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  79274. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  79275. ** read up to 16. So 16 bytes of bogus content is supplied.
  79276. */
  79277. static u8 aZero[16]; /* This is the bogus content */
  79278. sqlite3VdbeSerialGet(aZero, t, pDest);
  79279. }else{
  79280. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  79281. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  79282. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  79283. pDest->flags &= ~MEM_Ephem;
  79284. }
  79285. }
  79286. op_column_out:
  79287. UPDATE_MAX_BLOBSIZE(pDest);
  79288. REGISTER_TRACE(pOp->p3, pDest);
  79289. break;
  79290. op_column_corrupt:
  79291. if( aOp[0].p3>0 ){
  79292. pOp = &aOp[aOp[0].p3-1];
  79293. break;
  79294. }else{
  79295. rc = SQLITE_CORRUPT_BKPT;
  79296. goto abort_due_to_error;
  79297. }
  79298. }
  79299. /* Opcode: Affinity P1 P2 * P4 *
  79300. ** Synopsis: affinity(r[P1@P2])
  79301. **
  79302. ** Apply affinities to a range of P2 registers starting with P1.
  79303. **
  79304. ** P4 is a string that is P2 characters long. The N-th character of the
  79305. ** string indicates the column affinity that should be used for the N-th
  79306. ** memory cell in the range.
  79307. */
  79308. case OP_Affinity: {
  79309. const char *zAffinity; /* The affinity to be applied */
  79310. zAffinity = pOp->p4.z;
  79311. assert( zAffinity!=0 );
  79312. assert( pOp->p2>0 );
  79313. assert( zAffinity[pOp->p2]==0 );
  79314. pIn1 = &aMem[pOp->p1];
  79315. do{
  79316. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  79317. assert( memIsValid(pIn1) );
  79318. applyAffinity(pIn1, *(zAffinity++), encoding);
  79319. pIn1++;
  79320. }while( zAffinity[0] );
  79321. break;
  79322. }
  79323. /* Opcode: MakeRecord P1 P2 P3 P4 *
  79324. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  79325. **
  79326. ** Convert P2 registers beginning with P1 into the [record format]
  79327. ** use as a data record in a database table or as a key
  79328. ** in an index. The OP_Column opcode can decode the record later.
  79329. **
  79330. ** P4 may be a string that is P2 characters long. The N-th character of the
  79331. ** string indicates the column affinity that should be used for the N-th
  79332. ** field of the index key.
  79333. **
  79334. ** The mapping from character to affinity is given by the SQLITE_AFF_
  79335. ** macros defined in sqliteInt.h.
  79336. **
  79337. ** If P4 is NULL then all index fields have the affinity BLOB.
  79338. */
  79339. case OP_MakeRecord: {
  79340. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  79341. Mem *pRec; /* The new record */
  79342. u64 nData; /* Number of bytes of data space */
  79343. int nHdr; /* Number of bytes of header space */
  79344. i64 nByte; /* Data space required for this record */
  79345. i64 nZero; /* Number of zero bytes at the end of the record */
  79346. int nVarint; /* Number of bytes in a varint */
  79347. u32 serial_type; /* Type field */
  79348. Mem *pData0; /* First field to be combined into the record */
  79349. Mem *pLast; /* Last field of the record */
  79350. int nField; /* Number of fields in the record */
  79351. char *zAffinity; /* The affinity string for the record */
  79352. int file_format; /* File format to use for encoding */
  79353. int i; /* Space used in zNewRecord[] header */
  79354. int j; /* Space used in zNewRecord[] content */
  79355. u32 len; /* Length of a field */
  79356. /* Assuming the record contains N fields, the record format looks
  79357. ** like this:
  79358. **
  79359. ** ------------------------------------------------------------------------
  79360. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  79361. ** ------------------------------------------------------------------------
  79362. **
  79363. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  79364. ** and so forth.
  79365. **
  79366. ** Each type field is a varint representing the serial type of the
  79367. ** corresponding data element (see sqlite3VdbeSerialType()). The
  79368. ** hdr-size field is also a varint which is the offset from the beginning
  79369. ** of the record to data0.
  79370. */
  79371. nData = 0; /* Number of bytes of data space */
  79372. nHdr = 0; /* Number of bytes of header space */
  79373. nZero = 0; /* Number of zero bytes at the end of the record */
  79374. nField = pOp->p1;
  79375. zAffinity = pOp->p4.z;
  79376. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  79377. pData0 = &aMem[nField];
  79378. nField = pOp->p2;
  79379. pLast = &pData0[nField-1];
  79380. file_format = p->minWriteFileFormat;
  79381. /* Identify the output register */
  79382. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  79383. pOut = &aMem[pOp->p3];
  79384. memAboutToChange(p, pOut);
  79385. /* Apply the requested affinity to all inputs
  79386. */
  79387. assert( pData0<=pLast );
  79388. if( zAffinity ){
  79389. pRec = pData0;
  79390. do{
  79391. applyAffinity(pRec++, *(zAffinity++), encoding);
  79392. assert( zAffinity[0]==0 || pRec<=pLast );
  79393. }while( zAffinity[0] );
  79394. }
  79395. #ifdef SQLITE_ENABLE_NULL_TRIM
  79396. /* NULLs can be safely trimmed from the end of the record, as long as
  79397. ** as the schema format is 2 or more and none of the omitted columns
  79398. ** have a non-NULL default value. Also, the record must be left with
  79399. ** at least one field. If P5>0 then it will be one more than the
  79400. ** index of the right-most column with a non-NULL default value */
  79401. if( pOp->p5 ){
  79402. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  79403. pLast--;
  79404. nField--;
  79405. }
  79406. }
  79407. #endif
  79408. /* Loop through the elements that will make up the record to figure
  79409. ** out how much space is required for the new record.
  79410. */
  79411. pRec = pLast;
  79412. do{
  79413. assert( memIsValid(pRec) );
  79414. serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  79415. if( pRec->flags & MEM_Zero ){
  79416. if( serial_type==0 ){
  79417. /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
  79418. ** table methods that never invoke sqlite3_result_xxxxx() while
  79419. ** computing an unchanging column value in an UPDATE statement.
  79420. ** Give such values a special internal-use-only serial-type of 10
  79421. ** so that they can be passed through to xUpdate and have
  79422. ** a true sqlite3_value_nochange(). */
  79423. assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
  79424. serial_type = 10;
  79425. }else if( nData ){
  79426. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  79427. }else{
  79428. nZero += pRec->u.nZero;
  79429. len -= pRec->u.nZero;
  79430. }
  79431. }
  79432. nData += len;
  79433. testcase( serial_type==127 );
  79434. testcase( serial_type==128 );
  79435. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  79436. pRec->uTemp = serial_type;
  79437. if( pRec==pData0 ) break;
  79438. pRec--;
  79439. }while(1);
  79440. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  79441. ** which determines the total number of bytes in the header. The varint
  79442. ** value is the size of the header in bytes including the size varint
  79443. ** itself. */
  79444. testcase( nHdr==126 );
  79445. testcase( nHdr==127 );
  79446. if( nHdr<=126 ){
  79447. /* The common case */
  79448. nHdr += 1;
  79449. }else{
  79450. /* Rare case of a really large header */
  79451. nVarint = sqlite3VarintLen(nHdr);
  79452. nHdr += nVarint;
  79453. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  79454. }
  79455. nByte = nHdr+nData;
  79456. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  79457. goto too_big;
  79458. }
  79459. /* Make sure the output register has a buffer large enough to store
  79460. ** the new record. The output register (pOp->p3) is not allowed to
  79461. ** be one of the input registers (because the following call to
  79462. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  79463. */
  79464. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  79465. goto no_mem;
  79466. }
  79467. zNewRecord = (u8 *)pOut->z;
  79468. /* Write the record */
  79469. i = putVarint32(zNewRecord, nHdr);
  79470. j = nHdr;
  79471. assert( pData0<=pLast );
  79472. pRec = pData0;
  79473. do{
  79474. serial_type = pRec->uTemp;
  79475. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  79476. ** additional varints, one per column. */
  79477. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  79478. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  79479. ** immediately follow the header. */
  79480. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  79481. }while( (++pRec)<=pLast );
  79482. assert( i==nHdr );
  79483. assert( j==nByte );
  79484. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79485. pOut->n = (int)nByte;
  79486. pOut->flags = MEM_Blob;
  79487. if( nZero ){
  79488. pOut->u.nZero = nZero;
  79489. pOut->flags |= MEM_Zero;
  79490. }
  79491. REGISTER_TRACE(pOp->p3, pOut);
  79492. UPDATE_MAX_BLOBSIZE(pOut);
  79493. break;
  79494. }
  79495. /* Opcode: Count P1 P2 * * *
  79496. ** Synopsis: r[P2]=count()
  79497. **
  79498. ** Store the number of entries (an integer value) in the table or index
  79499. ** opened by cursor P1 in register P2
  79500. */
  79501. #ifndef SQLITE_OMIT_BTREECOUNT
  79502. case OP_Count: { /* out2 */
  79503. i64 nEntry;
  79504. BtCursor *pCrsr;
  79505. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  79506. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  79507. assert( pCrsr );
  79508. nEntry = 0; /* Not needed. Only used to silence a warning. */
  79509. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  79510. if( rc ) goto abort_due_to_error;
  79511. pOut = out2Prerelease(p, pOp);
  79512. pOut->u.i = nEntry;
  79513. break;
  79514. }
  79515. #endif
  79516. /* Opcode: Savepoint P1 * * P4 *
  79517. **
  79518. ** Open, release or rollback the savepoint named by parameter P4, depending
  79519. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  79520. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  79521. */
  79522. case OP_Savepoint: {
  79523. int p1; /* Value of P1 operand */
  79524. char *zName; /* Name of savepoint */
  79525. int nName;
  79526. Savepoint *pNew;
  79527. Savepoint *pSavepoint;
  79528. Savepoint *pTmp;
  79529. int iSavepoint;
  79530. int ii;
  79531. p1 = pOp->p1;
  79532. zName = pOp->p4.z;
  79533. /* Assert that the p1 parameter is valid. Also that if there is no open
  79534. ** transaction, then there cannot be any savepoints.
  79535. */
  79536. assert( db->pSavepoint==0 || db->autoCommit==0 );
  79537. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  79538. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  79539. assert( checkSavepointCount(db) );
  79540. assert( p->bIsReader );
  79541. if( p1==SAVEPOINT_BEGIN ){
  79542. if( db->nVdbeWrite>0 ){
  79543. /* A new savepoint cannot be created if there are active write
  79544. ** statements (i.e. open read/write incremental blob handles).
  79545. */
  79546. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  79547. rc = SQLITE_BUSY;
  79548. }else{
  79549. nName = sqlite3Strlen30(zName);
  79550. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79551. /* This call is Ok even if this savepoint is actually a transaction
  79552. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  79553. ** If this is a transaction savepoint being opened, it is guaranteed
  79554. ** that the db->aVTrans[] array is empty. */
  79555. assert( db->autoCommit==0 || db->nVTrans==0 );
  79556. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  79557. db->nStatement+db->nSavepoint);
  79558. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  79559. #endif
  79560. /* Create a new savepoint structure. */
  79561. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  79562. if( pNew ){
  79563. pNew->zName = (char *)&pNew[1];
  79564. memcpy(pNew->zName, zName, nName+1);
  79565. /* If there is no open transaction, then mark this as a special
  79566. ** "transaction savepoint". */
  79567. if( db->autoCommit ){
  79568. db->autoCommit = 0;
  79569. db->isTransactionSavepoint = 1;
  79570. }else{
  79571. db->nSavepoint++;
  79572. }
  79573. /* Link the new savepoint into the database handle's list. */
  79574. pNew->pNext = db->pSavepoint;
  79575. db->pSavepoint = pNew;
  79576. pNew->nDeferredCons = db->nDeferredCons;
  79577. pNew->nDeferredImmCons = db->nDeferredImmCons;
  79578. }
  79579. }
  79580. }else{
  79581. iSavepoint = 0;
  79582. /* Find the named savepoint. If there is no such savepoint, then an
  79583. ** an error is returned to the user. */
  79584. for(
  79585. pSavepoint = db->pSavepoint;
  79586. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  79587. pSavepoint = pSavepoint->pNext
  79588. ){
  79589. iSavepoint++;
  79590. }
  79591. if( !pSavepoint ){
  79592. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  79593. rc = SQLITE_ERROR;
  79594. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  79595. /* It is not possible to release (commit) a savepoint if there are
  79596. ** active write statements.
  79597. */
  79598. sqlite3VdbeError(p, "cannot release savepoint - "
  79599. "SQL statements in progress");
  79600. rc = SQLITE_BUSY;
  79601. }else{
  79602. /* Determine whether or not this is a transaction savepoint. If so,
  79603. ** and this is a RELEASE command, then the current transaction
  79604. ** is committed.
  79605. */
  79606. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  79607. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  79608. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  79609. goto vdbe_return;
  79610. }
  79611. db->autoCommit = 1;
  79612. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  79613. p->pc = (int)(pOp - aOp);
  79614. db->autoCommit = 0;
  79615. p->rc = rc = SQLITE_BUSY;
  79616. goto vdbe_return;
  79617. }
  79618. db->isTransactionSavepoint = 0;
  79619. rc = p->rc;
  79620. }else{
  79621. int isSchemaChange;
  79622. iSavepoint = db->nSavepoint - iSavepoint - 1;
  79623. if( p1==SAVEPOINT_ROLLBACK ){
  79624. isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
  79625. for(ii=0; ii<db->nDb; ii++){
  79626. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  79627. SQLITE_ABORT_ROLLBACK,
  79628. isSchemaChange==0);
  79629. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  79630. }
  79631. }else{
  79632. isSchemaChange = 0;
  79633. }
  79634. for(ii=0; ii<db->nDb; ii++){
  79635. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  79636. if( rc!=SQLITE_OK ){
  79637. goto abort_due_to_error;
  79638. }
  79639. }
  79640. if( isSchemaChange ){
  79641. sqlite3ExpirePreparedStatements(db);
  79642. sqlite3ResetAllSchemasOfConnection(db);
  79643. db->mDbFlags |= DBFLAG_SchemaChange;
  79644. }
  79645. }
  79646. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  79647. ** savepoints nested inside of the savepoint being operated on. */
  79648. while( db->pSavepoint!=pSavepoint ){
  79649. pTmp = db->pSavepoint;
  79650. db->pSavepoint = pTmp->pNext;
  79651. sqlite3DbFree(db, pTmp);
  79652. db->nSavepoint--;
  79653. }
  79654. /* If it is a RELEASE, then destroy the savepoint being operated on
  79655. ** too. If it is a ROLLBACK TO, then set the number of deferred
  79656. ** constraint violations present in the database to the value stored
  79657. ** when the savepoint was created. */
  79658. if( p1==SAVEPOINT_RELEASE ){
  79659. assert( pSavepoint==db->pSavepoint );
  79660. db->pSavepoint = pSavepoint->pNext;
  79661. sqlite3DbFree(db, pSavepoint);
  79662. if( !isTransaction ){
  79663. db->nSavepoint--;
  79664. }
  79665. }else{
  79666. db->nDeferredCons = pSavepoint->nDeferredCons;
  79667. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  79668. }
  79669. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  79670. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  79671. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  79672. }
  79673. }
  79674. }
  79675. if( rc ) goto abort_due_to_error;
  79676. break;
  79677. }
  79678. /* Opcode: AutoCommit P1 P2 * * *
  79679. **
  79680. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  79681. ** back any currently active btree transactions. If there are any active
  79682. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  79683. ** there are active writing VMs or active VMs that use shared cache.
  79684. **
  79685. ** This instruction causes the VM to halt.
  79686. */
  79687. case OP_AutoCommit: {
  79688. int desiredAutoCommit;
  79689. int iRollback;
  79690. desiredAutoCommit = pOp->p1;
  79691. iRollback = pOp->p2;
  79692. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  79693. assert( desiredAutoCommit==1 || iRollback==0 );
  79694. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  79695. assert( p->bIsReader );
  79696. if( desiredAutoCommit!=db->autoCommit ){
  79697. if( iRollback ){
  79698. assert( desiredAutoCommit==1 );
  79699. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  79700. db->autoCommit = 1;
  79701. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  79702. /* If this instruction implements a COMMIT and other VMs are writing
  79703. ** return an error indicating that the other VMs must complete first.
  79704. */
  79705. sqlite3VdbeError(p, "cannot commit transaction - "
  79706. "SQL statements in progress");
  79707. rc = SQLITE_BUSY;
  79708. goto abort_due_to_error;
  79709. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  79710. goto vdbe_return;
  79711. }else{
  79712. db->autoCommit = (u8)desiredAutoCommit;
  79713. }
  79714. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  79715. p->pc = (int)(pOp - aOp);
  79716. db->autoCommit = (u8)(1-desiredAutoCommit);
  79717. p->rc = rc = SQLITE_BUSY;
  79718. goto vdbe_return;
  79719. }
  79720. assert( db->nStatement==0 );
  79721. sqlite3CloseSavepoints(db);
  79722. if( p->rc==SQLITE_OK ){
  79723. rc = SQLITE_DONE;
  79724. }else{
  79725. rc = SQLITE_ERROR;
  79726. }
  79727. goto vdbe_return;
  79728. }else{
  79729. sqlite3VdbeError(p,
  79730. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  79731. (iRollback)?"cannot rollback - no transaction is active":
  79732. "cannot commit - no transaction is active"));
  79733. rc = SQLITE_ERROR;
  79734. goto abort_due_to_error;
  79735. }
  79736. break;
  79737. }
  79738. /* Opcode: Transaction P1 P2 P3 P4 P5
  79739. **
  79740. ** Begin a transaction on database P1 if a transaction is not already
  79741. ** active.
  79742. ** If P2 is non-zero, then a write-transaction is started, or if a
  79743. ** read-transaction is already active, it is upgraded to a write-transaction.
  79744. ** If P2 is zero, then a read-transaction is started.
  79745. **
  79746. ** P1 is the index of the database file on which the transaction is
  79747. ** started. Index 0 is the main database file and index 1 is the
  79748. ** file used for temporary tables. Indices of 2 or more are used for
  79749. ** attached databases.
  79750. **
  79751. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  79752. ** true (this flag is set if the Vdbe may modify more than one row and may
  79753. ** throw an ABORT exception), a statement transaction may also be opened.
  79754. ** More specifically, a statement transaction is opened iff the database
  79755. ** connection is currently not in autocommit mode, or if there are other
  79756. ** active statements. A statement transaction allows the changes made by this
  79757. ** VDBE to be rolled back after an error without having to roll back the
  79758. ** entire transaction. If no error is encountered, the statement transaction
  79759. ** will automatically commit when the VDBE halts.
  79760. **
  79761. ** If P5!=0 then this opcode also checks the schema cookie against P3
  79762. ** and the schema generation counter against P4.
  79763. ** The cookie changes its value whenever the database schema changes.
  79764. ** This operation is used to detect when that the cookie has changed
  79765. ** and that the current process needs to reread the schema. If the schema
  79766. ** cookie in P3 differs from the schema cookie in the database header or
  79767. ** if the schema generation counter in P4 differs from the current
  79768. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  79769. ** halts. The sqlite3_step() wrapper function might then reprepare the
  79770. ** statement and rerun it from the beginning.
  79771. */
  79772. case OP_Transaction: {
  79773. Btree *pBt;
  79774. int iMeta;
  79775. int iGen;
  79776. assert( p->bIsReader );
  79777. assert( p->readOnly==0 || pOp->p2==0 );
  79778. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79779. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  79780. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  79781. rc = SQLITE_READONLY;
  79782. goto abort_due_to_error;
  79783. }
  79784. pBt = db->aDb[pOp->p1].pBt;
  79785. if( pBt ){
  79786. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  79787. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  79788. testcase( rc==SQLITE_BUSY_RECOVERY );
  79789. if( rc!=SQLITE_OK ){
  79790. if( (rc&0xff)==SQLITE_BUSY ){
  79791. p->pc = (int)(pOp - aOp);
  79792. p->rc = rc;
  79793. goto vdbe_return;
  79794. }
  79795. goto abort_due_to_error;
  79796. }
  79797. if( pOp->p2 && p->usesStmtJournal
  79798. && (db->autoCommit==0 || db->nVdbeRead>1)
  79799. ){
  79800. assert( sqlite3BtreeIsInTrans(pBt) );
  79801. if( p->iStatement==0 ){
  79802. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  79803. db->nStatement++;
  79804. p->iStatement = db->nSavepoint + db->nStatement;
  79805. }
  79806. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  79807. if( rc==SQLITE_OK ){
  79808. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  79809. }
  79810. /* Store the current value of the database handles deferred constraint
  79811. ** counter. If the statement transaction needs to be rolled back,
  79812. ** the value of this counter needs to be restored too. */
  79813. p->nStmtDefCons = db->nDeferredCons;
  79814. p->nStmtDefImmCons = db->nDeferredImmCons;
  79815. }
  79816. /* Gather the schema version number for checking:
  79817. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  79818. ** version is checked to ensure that the schema has not changed since the
  79819. ** SQL statement was prepared.
  79820. */
  79821. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  79822. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  79823. }else{
  79824. iGen = iMeta = 0;
  79825. }
  79826. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  79827. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  79828. sqlite3DbFree(db, p->zErrMsg);
  79829. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  79830. /* If the schema-cookie from the database file matches the cookie
  79831. ** stored with the in-memory representation of the schema, do
  79832. ** not reload the schema from the database file.
  79833. **
  79834. ** If virtual-tables are in use, this is not just an optimization.
  79835. ** Often, v-tables store their data in other SQLite tables, which
  79836. ** are queried from within xNext() and other v-table methods using
  79837. ** prepared queries. If such a query is out-of-date, we do not want to
  79838. ** discard the database schema, as the user code implementing the
  79839. ** v-table would have to be ready for the sqlite3_vtab structure itself
  79840. ** to be invalidated whenever sqlite3_step() is called from within
  79841. ** a v-table method.
  79842. */
  79843. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  79844. sqlite3ResetOneSchema(db, pOp->p1);
  79845. }
  79846. p->expired = 1;
  79847. rc = SQLITE_SCHEMA;
  79848. }
  79849. if( rc ) goto abort_due_to_error;
  79850. break;
  79851. }
  79852. /* Opcode: ReadCookie P1 P2 P3 * *
  79853. **
  79854. ** Read cookie number P3 from database P1 and write it into register P2.
  79855. ** P3==1 is the schema version. P3==2 is the database format.
  79856. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  79857. ** the main database file and P1==1 is the database file used to store
  79858. ** temporary tables.
  79859. **
  79860. ** There must be a read-lock on the database (either a transaction
  79861. ** must be started or there must be an open cursor) before
  79862. ** executing this instruction.
  79863. */
  79864. case OP_ReadCookie: { /* out2 */
  79865. int iMeta;
  79866. int iDb;
  79867. int iCookie;
  79868. assert( p->bIsReader );
  79869. iDb = pOp->p1;
  79870. iCookie = pOp->p3;
  79871. assert( pOp->p3<SQLITE_N_BTREE_META );
  79872. assert( iDb>=0 && iDb<db->nDb );
  79873. assert( db->aDb[iDb].pBt!=0 );
  79874. assert( DbMaskTest(p->btreeMask, iDb) );
  79875. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  79876. pOut = out2Prerelease(p, pOp);
  79877. pOut->u.i = iMeta;
  79878. break;
  79879. }
  79880. /* Opcode: SetCookie P1 P2 P3 * *
  79881. **
  79882. ** Write the integer value P3 into cookie number P2 of database P1.
  79883. ** P2==1 is the schema version. P2==2 is the database format.
  79884. ** P2==3 is the recommended pager cache
  79885. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  79886. ** database file used to store temporary tables.
  79887. **
  79888. ** A transaction must be started before executing this opcode.
  79889. */
  79890. case OP_SetCookie: {
  79891. Db *pDb;
  79892. sqlite3VdbeIncrWriteCounter(p, 0);
  79893. assert( pOp->p2<SQLITE_N_BTREE_META );
  79894. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79895. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  79896. assert( p->readOnly==0 );
  79897. pDb = &db->aDb[pOp->p1];
  79898. assert( pDb->pBt!=0 );
  79899. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  79900. /* See note about index shifting on OP_ReadCookie */
  79901. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  79902. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  79903. /* When the schema cookie changes, record the new cookie internally */
  79904. pDb->pSchema->schema_cookie = pOp->p3;
  79905. db->mDbFlags |= DBFLAG_SchemaChange;
  79906. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  79907. /* Record changes in the file format */
  79908. pDb->pSchema->file_format = pOp->p3;
  79909. }
  79910. if( pOp->p1==1 ){
  79911. /* Invalidate all prepared statements whenever the TEMP database
  79912. ** schema is changed. Ticket #1644 */
  79913. sqlite3ExpirePreparedStatements(db);
  79914. p->expired = 0;
  79915. }
  79916. if( rc ) goto abort_due_to_error;
  79917. break;
  79918. }
  79919. /* Opcode: OpenRead P1 P2 P3 P4 P5
  79920. ** Synopsis: root=P2 iDb=P3
  79921. **
  79922. ** Open a read-only cursor for the database table whose root page is
  79923. ** P2 in a database file. The database file is determined by P3.
  79924. ** P3==0 means the main database, P3==1 means the database used for
  79925. ** temporary tables, and P3>1 means used the corresponding attached
  79926. ** database. Give the new cursor an identifier of P1. The P1
  79927. ** values need not be contiguous but all P1 values should be small integers.
  79928. ** It is an error for P1 to be negative.
  79929. **
  79930. ** If P5!=0 then use the content of register P2 as the root page, not
  79931. ** the value of P2 itself.
  79932. **
  79933. ** There will be a read lock on the database whenever there is an
  79934. ** open cursor. If the database was unlocked prior to this instruction
  79935. ** then a read lock is acquired as part of this instruction. A read
  79936. ** lock allows other processes to read the database but prohibits
  79937. ** any other process from modifying the database. The read lock is
  79938. ** released when all cursors are closed. If this instruction attempts
  79939. ** to get a read lock but fails, the script terminates with an
  79940. ** SQLITE_BUSY error code.
  79941. **
  79942. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  79943. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  79944. ** structure, then said structure defines the content and collating
  79945. ** sequence of the index being opened. Otherwise, if P4 is an integer
  79946. ** value, it is set to the number of columns in the table.
  79947. **
  79948. ** See also: OpenWrite, ReopenIdx
  79949. */
  79950. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  79951. ** Synopsis: root=P2 iDb=P3
  79952. **
  79953. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  79954. ** checks to see if the cursor on P1 is already open with a root page
  79955. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  79956. ** if the cursor is already open, do not reopen it.
  79957. **
  79958. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  79959. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  79960. ** every other ReopenIdx or OpenRead for the same cursor number.
  79961. **
  79962. ** See the OpenRead opcode documentation for additional information.
  79963. */
  79964. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  79965. ** Synopsis: root=P2 iDb=P3
  79966. **
  79967. ** Open a read/write cursor named P1 on the table or index whose root
  79968. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  79969. ** root page.
  79970. **
  79971. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  79972. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  79973. ** structure, then said structure defines the content and collating
  79974. ** sequence of the index being opened. Otherwise, if P4 is an integer
  79975. ** value, it is set to the number of columns in the table, or to the
  79976. ** largest index of any column of the table that is actually used.
  79977. **
  79978. ** This instruction works just like OpenRead except that it opens the cursor
  79979. ** in read/write mode. For a given table, there can be one or more read-only
  79980. ** cursors or a single read/write cursor but not both.
  79981. **
  79982. ** See also OpenRead.
  79983. */
  79984. case OP_ReopenIdx: {
  79985. int nField;
  79986. KeyInfo *pKeyInfo;
  79987. int p2;
  79988. int iDb;
  79989. int wrFlag;
  79990. Btree *pX;
  79991. VdbeCursor *pCur;
  79992. Db *pDb;
  79993. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  79994. assert( pOp->p4type==P4_KEYINFO );
  79995. pCur = p->apCsr[pOp->p1];
  79996. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  79997. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  79998. goto open_cursor_set_hints;
  79999. }
  80000. /* If the cursor is not currently open or is open on a different
  80001. ** index, then fall through into OP_OpenRead to force a reopen */
  80002. case OP_OpenRead:
  80003. case OP_OpenWrite:
  80004. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  80005. assert( p->bIsReader );
  80006. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  80007. || p->readOnly==0 );
  80008. if( p->expired ){
  80009. rc = SQLITE_ABORT_ROLLBACK;
  80010. goto abort_due_to_error;
  80011. }
  80012. nField = 0;
  80013. pKeyInfo = 0;
  80014. p2 = pOp->p2;
  80015. iDb = pOp->p3;
  80016. assert( iDb>=0 && iDb<db->nDb );
  80017. assert( DbMaskTest(p->btreeMask, iDb) );
  80018. pDb = &db->aDb[iDb];
  80019. pX = pDb->pBt;
  80020. assert( pX!=0 );
  80021. if( pOp->opcode==OP_OpenWrite ){
  80022. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  80023. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  80024. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80025. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  80026. p->minWriteFileFormat = pDb->pSchema->file_format;
  80027. }
  80028. }else{
  80029. wrFlag = 0;
  80030. }
  80031. if( pOp->p5 & OPFLAG_P2ISREG ){
  80032. assert( p2>0 );
  80033. assert( p2<=(p->nMem+1 - p->nCursor) );
  80034. pIn2 = &aMem[p2];
  80035. assert( memIsValid(pIn2) );
  80036. assert( (pIn2->flags & MEM_Int)!=0 );
  80037. sqlite3VdbeMemIntegerify(pIn2);
  80038. p2 = (int)pIn2->u.i;
  80039. /* The p2 value always comes from a prior OP_CreateBtree opcode and
  80040. ** that opcode will always set the p2 value to 2 or more or else fail.
  80041. ** If there were a failure, the prepared statement would have halted
  80042. ** before reaching this instruction. */
  80043. assert( p2>=2 );
  80044. }
  80045. if( pOp->p4type==P4_KEYINFO ){
  80046. pKeyInfo = pOp->p4.pKeyInfo;
  80047. assert( pKeyInfo->enc==ENC(db) );
  80048. assert( pKeyInfo->db==db );
  80049. nField = pKeyInfo->nAllField;
  80050. }else if( pOp->p4type==P4_INT32 ){
  80051. nField = pOp->p4.i;
  80052. }
  80053. assert( pOp->p1>=0 );
  80054. assert( nField>=0 );
  80055. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  80056. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  80057. if( pCur==0 ) goto no_mem;
  80058. pCur->nullRow = 1;
  80059. pCur->isOrdered = 1;
  80060. pCur->pgnoRoot = p2;
  80061. #ifdef SQLITE_DEBUG
  80062. pCur->wrFlag = wrFlag;
  80063. #endif
  80064. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  80065. pCur->pKeyInfo = pKeyInfo;
  80066. /* Set the VdbeCursor.isTable variable. Previous versions of
  80067. ** SQLite used to check if the root-page flags were sane at this point
  80068. ** and report database corruption if they were not, but this check has
  80069. ** since moved into the btree layer. */
  80070. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  80071. open_cursor_set_hints:
  80072. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  80073. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  80074. testcase( pOp->p5 & OPFLAG_BULKCSR );
  80075. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  80076. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  80077. #endif
  80078. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  80079. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  80080. if( rc ) goto abort_due_to_error;
  80081. break;
  80082. }
  80083. /* Opcode: OpenDup P1 P2 * * *
  80084. **
  80085. ** Open a new cursor P1 that points to the same ephemeral table as
  80086. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  80087. ** opcode. Only ephemeral cursors may be duplicated.
  80088. **
  80089. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  80090. */
  80091. case OP_OpenDup: {
  80092. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  80093. VdbeCursor *pCx; /* The new cursor */
  80094. pOrig = p->apCsr[pOp->p2];
  80095. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  80096. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  80097. if( pCx==0 ) goto no_mem;
  80098. pCx->nullRow = 1;
  80099. pCx->isEphemeral = 1;
  80100. pCx->pKeyInfo = pOrig->pKeyInfo;
  80101. pCx->isTable = pOrig->isTable;
  80102. rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
  80103. pCx->pKeyInfo, pCx->uc.pCursor);
  80104. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  80105. ** opened for a database. Since there is already an open cursor when this
  80106. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  80107. assert( rc==SQLITE_OK );
  80108. break;
  80109. }
  80110. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  80111. ** Synopsis: nColumn=P2
  80112. **
  80113. ** Open a new cursor P1 to a transient table.
  80114. ** The cursor is always opened read/write even if
  80115. ** the main database is read-only. The ephemeral
  80116. ** table is deleted automatically when the cursor is closed.
  80117. **
  80118. ** P2 is the number of columns in the ephemeral table.
  80119. ** The cursor points to a BTree table if P4==0 and to a BTree index
  80120. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  80121. ** that defines the format of keys in the index.
  80122. **
  80123. ** The P5 parameter can be a mask of the BTREE_* flags defined
  80124. ** in btree.h. These flags control aspects of the operation of
  80125. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  80126. ** added automatically.
  80127. */
  80128. /* Opcode: OpenAutoindex P1 P2 * P4 *
  80129. ** Synopsis: nColumn=P2
  80130. **
  80131. ** This opcode works the same as OP_OpenEphemeral. It has a
  80132. ** different name to distinguish its use. Tables created using
  80133. ** by this opcode will be used for automatically created transient
  80134. ** indices in joins.
  80135. */
  80136. case OP_OpenAutoindex:
  80137. case OP_OpenEphemeral: {
  80138. VdbeCursor *pCx;
  80139. KeyInfo *pKeyInfo;
  80140. static const int vfsFlags =
  80141. SQLITE_OPEN_READWRITE |
  80142. SQLITE_OPEN_CREATE |
  80143. SQLITE_OPEN_EXCLUSIVE |
  80144. SQLITE_OPEN_DELETEONCLOSE |
  80145. SQLITE_OPEN_TRANSIENT_DB;
  80146. assert( pOp->p1>=0 );
  80147. assert( pOp->p2>=0 );
  80148. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  80149. if( pCx==0 ) goto no_mem;
  80150. pCx->nullRow = 1;
  80151. pCx->isEphemeral = 1;
  80152. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  80153. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  80154. if( rc==SQLITE_OK ){
  80155. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
  80156. }
  80157. if( rc==SQLITE_OK ){
  80158. /* If a transient index is required, create it by calling
  80159. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  80160. ** opening it. If a transient table is required, just use the
  80161. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  80162. */
  80163. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  80164. int pgno;
  80165. assert( pOp->p4type==P4_KEYINFO );
  80166. rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
  80167. if( rc==SQLITE_OK ){
  80168. assert( pgno==MASTER_ROOT+1 );
  80169. assert( pKeyInfo->db==db );
  80170. assert( pKeyInfo->enc==ENC(db) );
  80171. rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
  80172. pKeyInfo, pCx->uc.pCursor);
  80173. }
  80174. pCx->isTable = 0;
  80175. }else{
  80176. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  80177. 0, pCx->uc.pCursor);
  80178. pCx->isTable = 1;
  80179. }
  80180. }
  80181. if( rc ) goto abort_due_to_error;
  80182. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  80183. break;
  80184. }
  80185. /* Opcode: SorterOpen P1 P2 P3 P4 *
  80186. **
  80187. ** This opcode works like OP_OpenEphemeral except that it opens
  80188. ** a transient index that is specifically designed to sort large
  80189. ** tables using an external merge-sort algorithm.
  80190. **
  80191. ** If argument P3 is non-zero, then it indicates that the sorter may
  80192. ** assume that a stable sort considering the first P3 fields of each
  80193. ** key is sufficient to produce the required results.
  80194. */
  80195. case OP_SorterOpen: {
  80196. VdbeCursor *pCx;
  80197. assert( pOp->p1>=0 );
  80198. assert( pOp->p2>=0 );
  80199. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  80200. if( pCx==0 ) goto no_mem;
  80201. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  80202. assert( pCx->pKeyInfo->db==db );
  80203. assert( pCx->pKeyInfo->enc==ENC(db) );
  80204. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  80205. if( rc ) goto abort_due_to_error;
  80206. break;
  80207. }
  80208. /* Opcode: SequenceTest P1 P2 * * *
  80209. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  80210. **
  80211. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  80212. ** to P2. Regardless of whether or not the jump is taken, increment the
  80213. ** the sequence value.
  80214. */
  80215. case OP_SequenceTest: {
  80216. VdbeCursor *pC;
  80217. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80218. pC = p->apCsr[pOp->p1];
  80219. assert( isSorter(pC) );
  80220. if( (pC->seqCount++)==0 ){
  80221. goto jump_to_p2;
  80222. }
  80223. break;
  80224. }
  80225. /* Opcode: OpenPseudo P1 P2 P3 * *
  80226. ** Synopsis: P3 columns in r[P2]
  80227. **
  80228. ** Open a new cursor that points to a fake table that contains a single
  80229. ** row of data. The content of that one row is the content of memory
  80230. ** register P2. In other words, cursor P1 becomes an alias for the
  80231. ** MEM_Blob content contained in register P2.
  80232. **
  80233. ** A pseudo-table created by this opcode is used to hold a single
  80234. ** row output from the sorter so that the row can be decomposed into
  80235. ** individual columns using the OP_Column opcode. The OP_Column opcode
  80236. ** is the only cursor opcode that works with a pseudo-table.
  80237. **
  80238. ** P3 is the number of fields in the records that will be stored by
  80239. ** the pseudo-table.
  80240. */
  80241. case OP_OpenPseudo: {
  80242. VdbeCursor *pCx;
  80243. assert( pOp->p1>=0 );
  80244. assert( pOp->p3>=0 );
  80245. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  80246. if( pCx==0 ) goto no_mem;
  80247. pCx->nullRow = 1;
  80248. pCx->seekResult = pOp->p2;
  80249. pCx->isTable = 1;
  80250. /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
  80251. ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
  80252. ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
  80253. ** which is a performance optimization */
  80254. pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
  80255. assert( pOp->p5==0 );
  80256. break;
  80257. }
  80258. /* Opcode: Close P1 * * * *
  80259. **
  80260. ** Close a cursor previously opened as P1. If P1 is not
  80261. ** currently open, this instruction is a no-op.
  80262. */
  80263. case OP_Close: {
  80264. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80265. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  80266. p->apCsr[pOp->p1] = 0;
  80267. break;
  80268. }
  80269. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  80270. /* Opcode: ColumnsUsed P1 * * P4 *
  80271. **
  80272. ** This opcode (which only exists if SQLite was compiled with
  80273. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  80274. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  80275. ** (P4_INT64) in which the first 63 bits are one for each of the
  80276. ** first 63 columns of the table or index that are actually used
  80277. ** by the cursor. The high-order bit is set if any column after
  80278. ** the 64th is used.
  80279. */
  80280. case OP_ColumnsUsed: {
  80281. VdbeCursor *pC;
  80282. pC = p->apCsr[pOp->p1];
  80283. assert( pC->eCurType==CURTYPE_BTREE );
  80284. pC->maskUsed = *(u64*)pOp->p4.pI64;
  80285. break;
  80286. }
  80287. #endif
  80288. /* Opcode: SeekGE P1 P2 P3 P4 *
  80289. ** Synopsis: key=r[P3@P4]
  80290. **
  80291. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  80292. ** use the value in register P3 as the key. If cursor P1 refers
  80293. ** to an SQL index, then P3 is the first in an array of P4 registers
  80294. ** that are used as an unpacked index key.
  80295. **
  80296. ** Reposition cursor P1 so that it points to the smallest entry that
  80297. ** is greater than or equal to the key value. If there are no records
  80298. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  80299. **
  80300. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  80301. ** opcode will always land on a record that equally equals the key, or
  80302. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  80303. ** opcode must be followed by an IdxLE opcode with the same arguments.
  80304. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  80305. ** IdxLE opcode will be used on subsequent loop iterations.
  80306. **
  80307. ** This opcode leaves the cursor configured to move in forward order,
  80308. ** from the beginning toward the end. In other words, the cursor is
  80309. ** configured to use Next, not Prev.
  80310. **
  80311. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  80312. */
  80313. /* Opcode: SeekGT P1 P2 P3 P4 *
  80314. ** Synopsis: key=r[P3@P4]
  80315. **
  80316. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  80317. ** use the value in register P3 as a key. If cursor P1 refers
  80318. ** to an SQL index, then P3 is the first in an array of P4 registers
  80319. ** that are used as an unpacked index key.
  80320. **
  80321. ** Reposition cursor P1 so that it points to the smallest entry that
  80322. ** is greater than the key value. If there are no records greater than
  80323. ** the key and P2 is not zero, then jump to P2.
  80324. **
  80325. ** This opcode leaves the cursor configured to move in forward order,
  80326. ** from the beginning toward the end. In other words, the cursor is
  80327. ** configured to use Next, not Prev.
  80328. **
  80329. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  80330. */
  80331. /* Opcode: SeekLT P1 P2 P3 P4 *
  80332. ** Synopsis: key=r[P3@P4]
  80333. **
  80334. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  80335. ** use the value in register P3 as a key. If cursor P1 refers
  80336. ** to an SQL index, then P3 is the first in an array of P4 registers
  80337. ** that are used as an unpacked index key.
  80338. **
  80339. ** Reposition cursor P1 so that it points to the largest entry that
  80340. ** is less than the key value. If there are no records less than
  80341. ** the key and P2 is not zero, then jump to P2.
  80342. **
  80343. ** This opcode leaves the cursor configured to move in reverse order,
  80344. ** from the end toward the beginning. In other words, the cursor is
  80345. ** configured to use Prev, not Next.
  80346. **
  80347. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  80348. */
  80349. /* Opcode: SeekLE P1 P2 P3 P4 *
  80350. ** Synopsis: key=r[P3@P4]
  80351. **
  80352. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  80353. ** use the value in register P3 as a key. If cursor P1 refers
  80354. ** to an SQL index, then P3 is the first in an array of P4 registers
  80355. ** that are used as an unpacked index key.
  80356. **
  80357. ** Reposition cursor P1 so that it points to the largest entry that
  80358. ** is less than or equal to the key value. If there are no records
  80359. ** less than or equal to the key and P2 is not zero, then jump to P2.
  80360. **
  80361. ** This opcode leaves the cursor configured to move in reverse order,
  80362. ** from the end toward the beginning. In other words, the cursor is
  80363. ** configured to use Prev, not Next.
  80364. **
  80365. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  80366. ** opcode will always land on a record that equally equals the key, or
  80367. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  80368. ** opcode must be followed by an IdxGE opcode with the same arguments.
  80369. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  80370. ** IdxGE opcode will be used on subsequent loop iterations.
  80371. **
  80372. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  80373. */
  80374. case OP_SeekLT: /* jump, in3 */
  80375. case OP_SeekLE: /* jump, in3 */
  80376. case OP_SeekGE: /* jump, in3 */
  80377. case OP_SeekGT: { /* jump, in3 */
  80378. int res; /* Comparison result */
  80379. int oc; /* Opcode */
  80380. VdbeCursor *pC; /* The cursor to seek */
  80381. UnpackedRecord r; /* The key to seek for */
  80382. int nField; /* Number of columns or fields in the key */
  80383. i64 iKey; /* The rowid we are to seek to */
  80384. int eqOnly; /* Only interested in == results */
  80385. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80386. assert( pOp->p2!=0 );
  80387. pC = p->apCsr[pOp->p1];
  80388. assert( pC!=0 );
  80389. assert( pC->eCurType==CURTYPE_BTREE );
  80390. assert( OP_SeekLE == OP_SeekLT+1 );
  80391. assert( OP_SeekGE == OP_SeekLT+2 );
  80392. assert( OP_SeekGT == OP_SeekLT+3 );
  80393. assert( pC->isOrdered );
  80394. assert( pC->uc.pCursor!=0 );
  80395. oc = pOp->opcode;
  80396. eqOnly = 0;
  80397. pC->nullRow = 0;
  80398. #ifdef SQLITE_DEBUG
  80399. pC->seekOp = pOp->opcode;
  80400. #endif
  80401. if( pC->isTable ){
  80402. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  80403. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  80404. || CORRUPT_DB );
  80405. /* The input value in P3 might be of any type: integer, real, string,
  80406. ** blob, or NULL. But it needs to be an integer before we can do
  80407. ** the seek, so convert it. */
  80408. pIn3 = &aMem[pOp->p3];
  80409. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  80410. applyNumericAffinity(pIn3, 0);
  80411. }
  80412. iKey = sqlite3VdbeIntValue(pIn3);
  80413. /* If the P3 value could not be converted into an integer without
  80414. ** loss of information, then special processing is required... */
  80415. if( (pIn3->flags & MEM_Int)==0 ){
  80416. if( (pIn3->flags & MEM_Real)==0 ){
  80417. /* If the P3 value cannot be converted into any kind of a number,
  80418. ** then the seek is not possible, so jump to P2 */
  80419. VdbeBranchTaken(1,2); goto jump_to_p2;
  80420. break;
  80421. }
  80422. /* If the approximation iKey is larger than the actual real search
  80423. ** term, substitute >= for > and < for <=. e.g. if the search term
  80424. ** is 4.9 and the integer approximation 5:
  80425. **
  80426. ** (x > 4.9) -> (x >= 5)
  80427. ** (x <= 4.9) -> (x < 5)
  80428. */
  80429. if( pIn3->u.r<(double)iKey ){
  80430. assert( OP_SeekGE==(OP_SeekGT-1) );
  80431. assert( OP_SeekLT==(OP_SeekLE-1) );
  80432. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  80433. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  80434. }
  80435. /* If the approximation iKey is smaller than the actual real search
  80436. ** term, substitute <= for < and > for >=. */
  80437. else if( pIn3->u.r>(double)iKey ){
  80438. assert( OP_SeekLE==(OP_SeekLT+1) );
  80439. assert( OP_SeekGT==(OP_SeekGE+1) );
  80440. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  80441. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  80442. }
  80443. }
  80444. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  80445. pC->movetoTarget = iKey; /* Used by OP_Delete */
  80446. if( rc!=SQLITE_OK ){
  80447. goto abort_due_to_error;
  80448. }
  80449. }else{
  80450. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  80451. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  80452. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  80453. */
  80454. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  80455. eqOnly = 1;
  80456. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  80457. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  80458. assert( pOp[1].p1==pOp[0].p1 );
  80459. assert( pOp[1].p2==pOp[0].p2 );
  80460. assert( pOp[1].p3==pOp[0].p3 );
  80461. assert( pOp[1].p4.i==pOp[0].p4.i );
  80462. }
  80463. nField = pOp->p4.i;
  80464. assert( pOp->p4type==P4_INT32 );
  80465. assert( nField>0 );
  80466. r.pKeyInfo = pC->pKeyInfo;
  80467. r.nField = (u16)nField;
  80468. /* The next line of code computes as follows, only faster:
  80469. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  80470. ** r.default_rc = -1;
  80471. ** }else{
  80472. ** r.default_rc = +1;
  80473. ** }
  80474. */
  80475. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  80476. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  80477. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  80478. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  80479. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  80480. r.aMem = &aMem[pOp->p3];
  80481. #ifdef SQLITE_DEBUG
  80482. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  80483. #endif
  80484. r.eqSeen = 0;
  80485. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  80486. if( rc!=SQLITE_OK ){
  80487. goto abort_due_to_error;
  80488. }
  80489. if( eqOnly && r.eqSeen==0 ){
  80490. assert( res!=0 );
  80491. goto seek_not_found;
  80492. }
  80493. }
  80494. pC->deferredMoveto = 0;
  80495. pC->cacheStatus = CACHE_STALE;
  80496. #ifdef SQLITE_TEST
  80497. sqlite3_search_count++;
  80498. #endif
  80499. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  80500. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  80501. res = 0;
  80502. rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
  80503. if( rc!=SQLITE_OK ){
  80504. if( rc==SQLITE_DONE ){
  80505. rc = SQLITE_OK;
  80506. res = 1;
  80507. }else{
  80508. goto abort_due_to_error;
  80509. }
  80510. }
  80511. }else{
  80512. res = 0;
  80513. }
  80514. }else{
  80515. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  80516. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  80517. res = 0;
  80518. rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
  80519. if( rc!=SQLITE_OK ){
  80520. if( rc==SQLITE_DONE ){
  80521. rc = SQLITE_OK;
  80522. res = 1;
  80523. }else{
  80524. goto abort_due_to_error;
  80525. }
  80526. }
  80527. }else{
  80528. /* res might be negative because the table is empty. Check to
  80529. ** see if this is the case.
  80530. */
  80531. res = sqlite3BtreeEof(pC->uc.pCursor);
  80532. }
  80533. }
  80534. seek_not_found:
  80535. assert( pOp->p2>0 );
  80536. VdbeBranchTaken(res!=0,2);
  80537. if( res ){
  80538. goto jump_to_p2;
  80539. }else if( eqOnly ){
  80540. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  80541. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  80542. }
  80543. break;
  80544. }
  80545. /* Opcode: Found P1 P2 P3 P4 *
  80546. ** Synopsis: key=r[P3@P4]
  80547. **
  80548. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  80549. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  80550. ** record.
  80551. **
  80552. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  80553. ** is a prefix of any entry in P1 then a jump is made to P2 and
  80554. ** P1 is left pointing at the matching entry.
  80555. **
  80556. ** This operation leaves the cursor in a state where it can be
  80557. ** advanced in the forward direction. The Next instruction will work,
  80558. ** but not the Prev instruction.
  80559. **
  80560. ** See also: NotFound, NoConflict, NotExists. SeekGe
  80561. */
  80562. /* Opcode: NotFound P1 P2 P3 P4 *
  80563. ** Synopsis: key=r[P3@P4]
  80564. **
  80565. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  80566. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  80567. ** record.
  80568. **
  80569. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  80570. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  80571. ** does contain an entry whose prefix matches the P3/P4 record then control
  80572. ** falls through to the next instruction and P1 is left pointing at the
  80573. ** matching entry.
  80574. **
  80575. ** This operation leaves the cursor in a state where it cannot be
  80576. ** advanced in either direction. In other words, the Next and Prev
  80577. ** opcodes do not work after this operation.
  80578. **
  80579. ** See also: Found, NotExists, NoConflict
  80580. */
  80581. /* Opcode: NoConflict P1 P2 P3 P4 *
  80582. ** Synopsis: key=r[P3@P4]
  80583. **
  80584. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  80585. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  80586. ** record.
  80587. **
  80588. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  80589. ** contains any NULL value, jump immediately to P2. If all terms of the
  80590. ** record are not-NULL then a check is done to determine if any row in the
  80591. ** P1 index btree has a matching key prefix. If there are no matches, jump
  80592. ** immediately to P2. If there is a match, fall through and leave the P1
  80593. ** cursor pointing to the matching row.
  80594. **
  80595. ** This opcode is similar to OP_NotFound with the exceptions that the
  80596. ** branch is always taken if any part of the search key input is NULL.
  80597. **
  80598. ** This operation leaves the cursor in a state where it cannot be
  80599. ** advanced in either direction. In other words, the Next and Prev
  80600. ** opcodes do not work after this operation.
  80601. **
  80602. ** See also: NotFound, Found, NotExists
  80603. */
  80604. case OP_NoConflict: /* jump, in3 */
  80605. case OP_NotFound: /* jump, in3 */
  80606. case OP_Found: { /* jump, in3 */
  80607. int alreadyExists;
  80608. int takeJump;
  80609. int ii;
  80610. VdbeCursor *pC;
  80611. int res;
  80612. UnpackedRecord *pFree;
  80613. UnpackedRecord *pIdxKey;
  80614. UnpackedRecord r;
  80615. #ifdef SQLITE_TEST
  80616. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  80617. #endif
  80618. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80619. assert( pOp->p4type==P4_INT32 );
  80620. pC = p->apCsr[pOp->p1];
  80621. assert( pC!=0 );
  80622. #ifdef SQLITE_DEBUG
  80623. pC->seekOp = pOp->opcode;
  80624. #endif
  80625. pIn3 = &aMem[pOp->p3];
  80626. assert( pC->eCurType==CURTYPE_BTREE );
  80627. assert( pC->uc.pCursor!=0 );
  80628. assert( pC->isTable==0 );
  80629. if( pOp->p4.i>0 ){
  80630. r.pKeyInfo = pC->pKeyInfo;
  80631. r.nField = (u16)pOp->p4.i;
  80632. r.aMem = pIn3;
  80633. #ifdef SQLITE_DEBUG
  80634. for(ii=0; ii<r.nField; ii++){
  80635. assert( memIsValid(&r.aMem[ii]) );
  80636. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  80637. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  80638. }
  80639. #endif
  80640. pIdxKey = &r;
  80641. pFree = 0;
  80642. }else{
  80643. assert( pIn3->flags & MEM_Blob );
  80644. rc = ExpandBlob(pIn3);
  80645. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  80646. if( rc ) goto no_mem;
  80647. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  80648. if( pIdxKey==0 ) goto no_mem;
  80649. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  80650. }
  80651. pIdxKey->default_rc = 0;
  80652. takeJump = 0;
  80653. if( pOp->opcode==OP_NoConflict ){
  80654. /* For the OP_NoConflict opcode, take the jump if any of the
  80655. ** input fields are NULL, since any key with a NULL will not
  80656. ** conflict */
  80657. for(ii=0; ii<pIdxKey->nField; ii++){
  80658. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  80659. takeJump = 1;
  80660. break;
  80661. }
  80662. }
  80663. }
  80664. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  80665. if( pFree ) sqlite3DbFreeNN(db, pFree);
  80666. if( rc!=SQLITE_OK ){
  80667. goto abort_due_to_error;
  80668. }
  80669. pC->seekResult = res;
  80670. alreadyExists = (res==0);
  80671. pC->nullRow = 1-alreadyExists;
  80672. pC->deferredMoveto = 0;
  80673. pC->cacheStatus = CACHE_STALE;
  80674. if( pOp->opcode==OP_Found ){
  80675. VdbeBranchTaken(alreadyExists!=0,2);
  80676. if( alreadyExists ) goto jump_to_p2;
  80677. }else{
  80678. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  80679. if( takeJump || !alreadyExists ) goto jump_to_p2;
  80680. }
  80681. break;
  80682. }
  80683. /* Opcode: SeekRowid P1 P2 P3 * *
  80684. ** Synopsis: intkey=r[P3]
  80685. **
  80686. ** P1 is the index of a cursor open on an SQL table btree (with integer
  80687. ** keys). If register P3 does not contain an integer or if P1 does not
  80688. ** contain a record with rowid P3 then jump immediately to P2.
  80689. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  80690. ** a record with rowid P3 then
  80691. ** leave the cursor pointing at that record and fall through to the next
  80692. ** instruction.
  80693. **
  80694. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  80695. ** the P3 register must be guaranteed to contain an integer value. With this
  80696. ** opcode, register P3 might not contain an integer.
  80697. **
  80698. ** The OP_NotFound opcode performs the same operation on index btrees
  80699. ** (with arbitrary multi-value keys).
  80700. **
  80701. ** This opcode leaves the cursor in a state where it cannot be advanced
  80702. ** in either direction. In other words, the Next and Prev opcodes will
  80703. ** not work following this opcode.
  80704. **
  80705. ** See also: Found, NotFound, NoConflict, SeekRowid
  80706. */
  80707. /* Opcode: NotExists P1 P2 P3 * *
  80708. ** Synopsis: intkey=r[P3]
  80709. **
  80710. ** P1 is the index of a cursor open on an SQL table btree (with integer
  80711. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  80712. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  80713. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  80714. ** leave the cursor pointing at that record and fall through to the next
  80715. ** instruction.
  80716. **
  80717. ** The OP_SeekRowid opcode performs the same operation but also allows the
  80718. ** P3 register to contain a non-integer value, in which case the jump is
  80719. ** always taken. This opcode requires that P3 always contain an integer.
  80720. **
  80721. ** The OP_NotFound opcode performs the same operation on index btrees
  80722. ** (with arbitrary multi-value keys).
  80723. **
  80724. ** This opcode leaves the cursor in a state where it cannot be advanced
  80725. ** in either direction. In other words, the Next and Prev opcodes will
  80726. ** not work following this opcode.
  80727. **
  80728. ** See also: Found, NotFound, NoConflict, SeekRowid
  80729. */
  80730. case OP_SeekRowid: { /* jump, in3 */
  80731. VdbeCursor *pC;
  80732. BtCursor *pCrsr;
  80733. int res;
  80734. u64 iKey;
  80735. pIn3 = &aMem[pOp->p3];
  80736. if( (pIn3->flags & MEM_Int)==0 ){
  80737. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  80738. if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
  80739. }
  80740. /* Fall through into OP_NotExists */
  80741. case OP_NotExists: /* jump, in3 */
  80742. pIn3 = &aMem[pOp->p3];
  80743. assert( pIn3->flags & MEM_Int );
  80744. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80745. pC = p->apCsr[pOp->p1];
  80746. assert( pC!=0 );
  80747. #ifdef SQLITE_DEBUG
  80748. pC->seekOp = 0;
  80749. #endif
  80750. assert( pC->isTable );
  80751. assert( pC->eCurType==CURTYPE_BTREE );
  80752. pCrsr = pC->uc.pCursor;
  80753. assert( pCrsr!=0 );
  80754. res = 0;
  80755. iKey = pIn3->u.i;
  80756. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  80757. assert( rc==SQLITE_OK || res==0 );
  80758. pC->movetoTarget = iKey; /* Used by OP_Delete */
  80759. pC->nullRow = 0;
  80760. pC->cacheStatus = CACHE_STALE;
  80761. pC->deferredMoveto = 0;
  80762. VdbeBranchTaken(res!=0,2);
  80763. pC->seekResult = res;
  80764. if( res!=0 ){
  80765. assert( rc==SQLITE_OK );
  80766. if( pOp->p2==0 ){
  80767. rc = SQLITE_CORRUPT_BKPT;
  80768. }else{
  80769. goto jump_to_p2;
  80770. }
  80771. }
  80772. if( rc ) goto abort_due_to_error;
  80773. break;
  80774. }
  80775. /* Opcode: Sequence P1 P2 * * *
  80776. ** Synopsis: r[P2]=cursor[P1].ctr++
  80777. **
  80778. ** Find the next available sequence number for cursor P1.
  80779. ** Write the sequence number into register P2.
  80780. ** The sequence number on the cursor is incremented after this
  80781. ** instruction.
  80782. */
  80783. case OP_Sequence: { /* out2 */
  80784. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80785. assert( p->apCsr[pOp->p1]!=0 );
  80786. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  80787. pOut = out2Prerelease(p, pOp);
  80788. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  80789. break;
  80790. }
  80791. /* Opcode: NewRowid P1 P2 P3 * *
  80792. ** Synopsis: r[P2]=rowid
  80793. **
  80794. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  80795. ** The record number is not previously used as a key in the database
  80796. ** table that cursor P1 points to. The new record number is written
  80797. ** written to register P2.
  80798. **
  80799. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  80800. ** the largest previously generated record number. No new record numbers are
  80801. ** allowed to be less than this value. When this value reaches its maximum,
  80802. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  80803. ** generated record number. This P3 mechanism is used to help implement the
  80804. ** AUTOINCREMENT feature.
  80805. */
  80806. case OP_NewRowid: { /* out2 */
  80807. i64 v; /* The new rowid */
  80808. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  80809. int res; /* Result of an sqlite3BtreeLast() */
  80810. int cnt; /* Counter to limit the number of searches */
  80811. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  80812. VdbeFrame *pFrame; /* Root frame of VDBE */
  80813. v = 0;
  80814. res = 0;
  80815. pOut = out2Prerelease(p, pOp);
  80816. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80817. pC = p->apCsr[pOp->p1];
  80818. assert( pC!=0 );
  80819. assert( pC->isTable );
  80820. assert( pC->eCurType==CURTYPE_BTREE );
  80821. assert( pC->uc.pCursor!=0 );
  80822. {
  80823. /* The next rowid or record number (different terms for the same
  80824. ** thing) is obtained in a two-step algorithm.
  80825. **
  80826. ** First we attempt to find the largest existing rowid and add one
  80827. ** to that. But if the largest existing rowid is already the maximum
  80828. ** positive integer, we have to fall through to the second
  80829. ** probabilistic algorithm
  80830. **
  80831. ** The second algorithm is to select a rowid at random and see if
  80832. ** it already exists in the table. If it does not exist, we have
  80833. ** succeeded. If the random rowid does exist, we select a new one
  80834. ** and try again, up to 100 times.
  80835. */
  80836. assert( pC->isTable );
  80837. #ifdef SQLITE_32BIT_ROWID
  80838. # define MAX_ROWID 0x7fffffff
  80839. #else
  80840. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  80841. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  80842. ** to provide the constant while making all compilers happy.
  80843. */
  80844. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  80845. #endif
  80846. if( !pC->useRandomRowid ){
  80847. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  80848. if( rc!=SQLITE_OK ){
  80849. goto abort_due_to_error;
  80850. }
  80851. if( res ){
  80852. v = 1; /* IMP: R-61914-48074 */
  80853. }else{
  80854. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  80855. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  80856. if( v>=MAX_ROWID ){
  80857. pC->useRandomRowid = 1;
  80858. }else{
  80859. v++; /* IMP: R-29538-34987 */
  80860. }
  80861. }
  80862. }
  80863. #ifndef SQLITE_OMIT_AUTOINCREMENT
  80864. if( pOp->p3 ){
  80865. /* Assert that P3 is a valid memory cell. */
  80866. assert( pOp->p3>0 );
  80867. if( p->pFrame ){
  80868. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  80869. /* Assert that P3 is a valid memory cell. */
  80870. assert( pOp->p3<=pFrame->nMem );
  80871. pMem = &pFrame->aMem[pOp->p3];
  80872. }else{
  80873. /* Assert that P3 is a valid memory cell. */
  80874. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  80875. pMem = &aMem[pOp->p3];
  80876. memAboutToChange(p, pMem);
  80877. }
  80878. assert( memIsValid(pMem) );
  80879. REGISTER_TRACE(pOp->p3, pMem);
  80880. sqlite3VdbeMemIntegerify(pMem);
  80881. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  80882. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  80883. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  80884. goto abort_due_to_error;
  80885. }
  80886. if( v<pMem->u.i+1 ){
  80887. v = pMem->u.i + 1;
  80888. }
  80889. pMem->u.i = v;
  80890. }
  80891. #endif
  80892. if( pC->useRandomRowid ){
  80893. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  80894. ** largest possible integer (9223372036854775807) then the database
  80895. ** engine starts picking positive candidate ROWIDs at random until
  80896. ** it finds one that is not previously used. */
  80897. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  80898. ** an AUTOINCREMENT table. */
  80899. cnt = 0;
  80900. do{
  80901. sqlite3_randomness(sizeof(v), &v);
  80902. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  80903. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  80904. 0, &res))==SQLITE_OK)
  80905. && (res==0)
  80906. && (++cnt<100));
  80907. if( rc ) goto abort_due_to_error;
  80908. if( res==0 ){
  80909. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  80910. goto abort_due_to_error;
  80911. }
  80912. assert( v>0 ); /* EV: R-40812-03570 */
  80913. }
  80914. pC->deferredMoveto = 0;
  80915. pC->cacheStatus = CACHE_STALE;
  80916. }
  80917. pOut->u.i = v;
  80918. break;
  80919. }
  80920. /* Opcode: Insert P1 P2 P3 P4 P5
  80921. ** Synopsis: intkey=r[P3] data=r[P2]
  80922. **
  80923. ** Write an entry into the table of cursor P1. A new entry is
  80924. ** created if it doesn't already exist or the data for an existing
  80925. ** entry is overwritten. The data is the value MEM_Blob stored in register
  80926. ** number P2. The key is stored in register P3. The key must
  80927. ** be a MEM_Int.
  80928. **
  80929. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  80930. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  80931. ** then rowid is stored for subsequent return by the
  80932. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  80933. **
  80934. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  80935. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  80936. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  80937. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  80938. **
  80939. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  80940. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  80941. ** is part of an INSERT operation. The difference is only important to
  80942. ** the update hook.
  80943. **
  80944. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  80945. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  80946. ** following a successful insert.
  80947. **
  80948. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  80949. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  80950. ** and register P2 becomes ephemeral. If the cursor is changed, the
  80951. ** value of register P2 will then change. Make sure this does not
  80952. ** cause any problems.)
  80953. **
  80954. ** This instruction only works on tables. The equivalent instruction
  80955. ** for indices is OP_IdxInsert.
  80956. */
  80957. /* Opcode: InsertInt P1 P2 P3 P4 P5
  80958. ** Synopsis: intkey=P3 data=r[P2]
  80959. **
  80960. ** This works exactly like OP_Insert except that the key is the
  80961. ** integer value P3, not the value of the integer stored in register P3.
  80962. */
  80963. case OP_Insert:
  80964. case OP_InsertInt: {
  80965. Mem *pData; /* MEM cell holding data for the record to be inserted */
  80966. Mem *pKey; /* MEM cell holding key for the record */
  80967. VdbeCursor *pC; /* Cursor to table into which insert is written */
  80968. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  80969. const char *zDb; /* database name - used by the update hook */
  80970. Table *pTab; /* Table structure - used by update and pre-update hooks */
  80971. BtreePayload x; /* Payload to be inserted */
  80972. pData = &aMem[pOp->p2];
  80973. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80974. assert( memIsValid(pData) );
  80975. pC = p->apCsr[pOp->p1];
  80976. assert( pC!=0 );
  80977. assert( pC->eCurType==CURTYPE_BTREE );
  80978. assert( pC->uc.pCursor!=0 );
  80979. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  80980. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  80981. REGISTER_TRACE(pOp->p2, pData);
  80982. sqlite3VdbeIncrWriteCounter(p, pC);
  80983. if( pOp->opcode==OP_Insert ){
  80984. pKey = &aMem[pOp->p3];
  80985. assert( pKey->flags & MEM_Int );
  80986. assert( memIsValid(pKey) );
  80987. REGISTER_TRACE(pOp->p3, pKey);
  80988. x.nKey = pKey->u.i;
  80989. }else{
  80990. assert( pOp->opcode==OP_InsertInt );
  80991. x.nKey = pOp->p3;
  80992. }
  80993. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  80994. assert( pC->iDb>=0 );
  80995. zDb = db->aDb[pC->iDb].zDbSName;
  80996. pTab = pOp->p4.pTab;
  80997. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  80998. }else{
  80999. pTab = 0;
  81000. zDb = 0; /* Not needed. Silence a compiler warning. */
  81001. }
  81002. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  81003. /* Invoke the pre-update hook, if any */
  81004. if( pTab ){
  81005. if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
  81006. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
  81007. }
  81008. if( db->xUpdateCallback==0 || pTab->aCol==0 ){
  81009. /* Prevent post-update hook from running in cases when it should not */
  81010. pTab = 0;
  81011. }
  81012. }
  81013. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  81014. #endif
  81015. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  81016. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  81017. assert( pData->flags & (MEM_Blob|MEM_Str) );
  81018. x.pData = pData->z;
  81019. x.nData = pData->n;
  81020. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  81021. if( pData->flags & MEM_Zero ){
  81022. x.nZero = pData->u.nZero;
  81023. }else{
  81024. x.nZero = 0;
  81025. }
  81026. x.pKey = 0;
  81027. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  81028. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  81029. );
  81030. pC->deferredMoveto = 0;
  81031. pC->cacheStatus = CACHE_STALE;
  81032. /* Invoke the update-hook if required. */
  81033. if( rc ) goto abort_due_to_error;
  81034. if( pTab ){
  81035. assert( db->xUpdateCallback!=0 );
  81036. assert( pTab->aCol!=0 );
  81037. db->xUpdateCallback(db->pUpdateArg,
  81038. (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
  81039. zDb, pTab->zName, x.nKey);
  81040. }
  81041. break;
  81042. }
  81043. /* Opcode: Delete P1 P2 P3 P4 P5
  81044. **
  81045. ** Delete the record at which the P1 cursor is currently pointing.
  81046. **
  81047. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  81048. ** the cursor will be left pointing at either the next or the previous
  81049. ** record in the table. If it is left pointing at the next record, then
  81050. ** the next Next instruction will be a no-op. As a result, in this case
  81051. ** it is ok to delete a record from within a Next loop. If
  81052. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  81053. ** left in an undefined state.
  81054. **
  81055. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  81056. ** delete one of several associated with deleting a table row and all its
  81057. ** associated index entries. Exactly one of those deletes is the "primary"
  81058. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  81059. ** marked with the AUXDELETE flag.
  81060. **
  81061. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  81062. ** change count is incremented (otherwise not).
  81063. **
  81064. ** P1 must not be pseudo-table. It has to be a real table with
  81065. ** multiple rows.
  81066. **
  81067. ** If P4 is not NULL then it points to a Table object. In this case either
  81068. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  81069. ** have been positioned using OP_NotFound prior to invoking this opcode in
  81070. ** this case. Specifically, if one is configured, the pre-update hook is
  81071. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  81072. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  81073. **
  81074. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  81075. ** of the memory cell that contains the value that the rowid of the row will
  81076. ** be set to by the update.
  81077. */
  81078. case OP_Delete: {
  81079. VdbeCursor *pC;
  81080. const char *zDb;
  81081. Table *pTab;
  81082. int opflags;
  81083. opflags = pOp->p2;
  81084. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81085. pC = p->apCsr[pOp->p1];
  81086. assert( pC!=0 );
  81087. assert( pC->eCurType==CURTYPE_BTREE );
  81088. assert( pC->uc.pCursor!=0 );
  81089. assert( pC->deferredMoveto==0 );
  81090. sqlite3VdbeIncrWriteCounter(p, pC);
  81091. #ifdef SQLITE_DEBUG
  81092. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  81093. /* If p5 is zero, the seek operation that positioned the cursor prior to
  81094. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  81095. ** the row that is being deleted */
  81096. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  81097. assert( pC->movetoTarget==iKey );
  81098. }
  81099. #endif
  81100. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  81101. ** the name of the db to pass as to it. Also set local pTab to a copy
  81102. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  81103. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  81104. ** VdbeCursor.movetoTarget to the current rowid. */
  81105. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  81106. assert( pC->iDb>=0 );
  81107. assert( pOp->p4.pTab!=0 );
  81108. zDb = db->aDb[pC->iDb].zDbSName;
  81109. pTab = pOp->p4.pTab;
  81110. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  81111. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  81112. }
  81113. }else{
  81114. zDb = 0; /* Not needed. Silence a compiler warning. */
  81115. pTab = 0; /* Not needed. Silence a compiler warning. */
  81116. }
  81117. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  81118. /* Invoke the pre-update-hook if required. */
  81119. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  81120. assert( !(opflags & OPFLAG_ISUPDATE)
  81121. || HasRowid(pTab)==0
  81122. || (aMem[pOp->p3].flags & MEM_Int)
  81123. );
  81124. sqlite3VdbePreUpdateHook(p, pC,
  81125. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  81126. zDb, pTab, pC->movetoTarget,
  81127. pOp->p3
  81128. );
  81129. }
  81130. if( opflags & OPFLAG_ISNOOP ) break;
  81131. #endif
  81132. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  81133. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  81134. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  81135. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  81136. #ifdef SQLITE_DEBUG
  81137. if( p->pFrame==0 ){
  81138. if( pC->isEphemeral==0
  81139. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  81140. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  81141. ){
  81142. nExtraDelete++;
  81143. }
  81144. if( pOp->p2 & OPFLAG_NCHANGE ){
  81145. nExtraDelete--;
  81146. }
  81147. }
  81148. #endif
  81149. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  81150. pC->cacheStatus = CACHE_STALE;
  81151. pC->seekResult = 0;
  81152. if( rc ) goto abort_due_to_error;
  81153. /* Invoke the update-hook if required. */
  81154. if( opflags & OPFLAG_NCHANGE ){
  81155. p->nChange++;
  81156. if( db->xUpdateCallback && HasRowid(pTab) ){
  81157. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  81158. pC->movetoTarget);
  81159. assert( pC->iDb>=0 );
  81160. }
  81161. }
  81162. break;
  81163. }
  81164. /* Opcode: ResetCount * * * * *
  81165. **
  81166. ** The value of the change counter is copied to the database handle
  81167. ** change counter (returned by subsequent calls to sqlite3_changes()).
  81168. ** Then the VMs internal change counter resets to 0.
  81169. ** This is used by trigger programs.
  81170. */
  81171. case OP_ResetCount: {
  81172. sqlite3VdbeSetChanges(db, p->nChange);
  81173. p->nChange = 0;
  81174. break;
  81175. }
  81176. /* Opcode: SorterCompare P1 P2 P3 P4
  81177. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  81178. **
  81179. ** P1 is a sorter cursor. This instruction compares a prefix of the
  81180. ** record blob in register P3 against a prefix of the entry that
  81181. ** the sorter cursor currently points to. Only the first P4 fields
  81182. ** of r[P3] and the sorter record are compared.
  81183. **
  81184. ** If either P3 or the sorter contains a NULL in one of their significant
  81185. ** fields (not counting the P4 fields at the end which are ignored) then
  81186. ** the comparison is assumed to be equal.
  81187. **
  81188. ** Fall through to next instruction if the two records compare equal to
  81189. ** each other. Jump to P2 if they are different.
  81190. */
  81191. case OP_SorterCompare: {
  81192. VdbeCursor *pC;
  81193. int res;
  81194. int nKeyCol;
  81195. pC = p->apCsr[pOp->p1];
  81196. assert( isSorter(pC) );
  81197. assert( pOp->p4type==P4_INT32 );
  81198. pIn3 = &aMem[pOp->p3];
  81199. nKeyCol = pOp->p4.i;
  81200. res = 0;
  81201. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  81202. VdbeBranchTaken(res!=0,2);
  81203. if( rc ) goto abort_due_to_error;
  81204. if( res ) goto jump_to_p2;
  81205. break;
  81206. };
  81207. /* Opcode: SorterData P1 P2 P3 * *
  81208. ** Synopsis: r[P2]=data
  81209. **
  81210. ** Write into register P2 the current sorter data for sorter cursor P1.
  81211. ** Then clear the column header cache on cursor P3.
  81212. **
  81213. ** This opcode is normally use to move a record out of the sorter and into
  81214. ** a register that is the source for a pseudo-table cursor created using
  81215. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  81216. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  81217. ** us from having to issue a separate NullRow instruction to clear that cache.
  81218. */
  81219. case OP_SorterData: {
  81220. VdbeCursor *pC;
  81221. pOut = &aMem[pOp->p2];
  81222. pC = p->apCsr[pOp->p1];
  81223. assert( isSorter(pC) );
  81224. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  81225. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  81226. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81227. if( rc ) goto abort_due_to_error;
  81228. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  81229. break;
  81230. }
  81231. /* Opcode: RowData P1 P2 P3 * *
  81232. ** Synopsis: r[P2]=data
  81233. **
  81234. ** Write into register P2 the complete row content for the row at
  81235. ** which cursor P1 is currently pointing.
  81236. ** There is no interpretation of the data.
  81237. ** It is just copied onto the P2 register exactly as
  81238. ** it is found in the database file.
  81239. **
  81240. ** If cursor P1 is an index, then the content is the key of the row.
  81241. ** If cursor P2 is a table, then the content extracted is the data.
  81242. **
  81243. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  81244. ** of a real table, not a pseudo-table.
  81245. **
  81246. ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
  81247. ** into the database page. That means that the content of the output
  81248. ** register will be invalidated as soon as the cursor moves - including
  81249. ** moves caused by other cursors that "save" the current cursors
  81250. ** position in order that they can write to the same table. If P3==0
  81251. ** then a copy of the data is made into memory. P3!=0 is faster, but
  81252. ** P3==0 is safer.
  81253. **
  81254. ** If P3!=0 then the content of the P2 register is unsuitable for use
  81255. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  81256. ** The P2 register content is invalidated by opcodes like OP_Function or
  81257. ** by any use of another cursor pointing to the same table.
  81258. */
  81259. case OP_RowData: {
  81260. VdbeCursor *pC;
  81261. BtCursor *pCrsr;
  81262. u32 n;
  81263. pOut = out2Prerelease(p, pOp);
  81264. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81265. pC = p->apCsr[pOp->p1];
  81266. assert( pC!=0 );
  81267. assert( pC->eCurType==CURTYPE_BTREE );
  81268. assert( isSorter(pC)==0 );
  81269. assert( pC->nullRow==0 );
  81270. assert( pC->uc.pCursor!=0 );
  81271. pCrsr = pC->uc.pCursor;
  81272. /* The OP_RowData opcodes always follow OP_NotExists or
  81273. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  81274. ** that might invalidate the cursor.
  81275. ** If this where not the case, on of the following assert()s
  81276. ** would fail. Should this ever change (because of changes in the code
  81277. ** generator) then the fix would be to insert a call to
  81278. ** sqlite3VdbeCursorMoveto().
  81279. */
  81280. assert( pC->deferredMoveto==0 );
  81281. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  81282. #if 0 /* Not required due to the previous to assert() statements */
  81283. rc = sqlite3VdbeCursorMoveto(pC);
  81284. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81285. #endif
  81286. n = sqlite3BtreePayloadSize(pCrsr);
  81287. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81288. goto too_big;
  81289. }
  81290. testcase( n==0 );
  81291. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  81292. if( rc ) goto abort_due_to_error;
  81293. if( !pOp->p3 ) Deephemeralize(pOut);
  81294. UPDATE_MAX_BLOBSIZE(pOut);
  81295. REGISTER_TRACE(pOp->p2, pOut);
  81296. break;
  81297. }
  81298. /* Opcode: Rowid P1 P2 * * *
  81299. ** Synopsis: r[P2]=rowid
  81300. **
  81301. ** Store in register P2 an integer which is the key of the table entry that
  81302. ** P1 is currently point to.
  81303. **
  81304. ** P1 can be either an ordinary table or a virtual table. There used to
  81305. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  81306. ** one opcode now works for both table types.
  81307. */
  81308. case OP_Rowid: { /* out2 */
  81309. VdbeCursor *pC;
  81310. i64 v;
  81311. sqlite3_vtab *pVtab;
  81312. const sqlite3_module *pModule;
  81313. pOut = out2Prerelease(p, pOp);
  81314. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81315. pC = p->apCsr[pOp->p1];
  81316. assert( pC!=0 );
  81317. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  81318. if( pC->nullRow ){
  81319. pOut->flags = MEM_Null;
  81320. break;
  81321. }else if( pC->deferredMoveto ){
  81322. v = pC->movetoTarget;
  81323. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81324. }else if( pC->eCurType==CURTYPE_VTAB ){
  81325. assert( pC->uc.pVCur!=0 );
  81326. pVtab = pC->uc.pVCur->pVtab;
  81327. pModule = pVtab->pModule;
  81328. assert( pModule->xRowid );
  81329. rc = pModule->xRowid(pC->uc.pVCur, &v);
  81330. sqlite3VtabImportErrmsg(p, pVtab);
  81331. if( rc ) goto abort_due_to_error;
  81332. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  81333. }else{
  81334. assert( pC->eCurType==CURTYPE_BTREE );
  81335. assert( pC->uc.pCursor!=0 );
  81336. rc = sqlite3VdbeCursorRestore(pC);
  81337. if( rc ) goto abort_due_to_error;
  81338. if( pC->nullRow ){
  81339. pOut->flags = MEM_Null;
  81340. break;
  81341. }
  81342. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  81343. }
  81344. pOut->u.i = v;
  81345. break;
  81346. }
  81347. /* Opcode: NullRow P1 * * * *
  81348. **
  81349. ** Move the cursor P1 to a null row. Any OP_Column operations
  81350. ** that occur while the cursor is on the null row will always
  81351. ** write a NULL.
  81352. */
  81353. case OP_NullRow: {
  81354. VdbeCursor *pC;
  81355. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81356. pC = p->apCsr[pOp->p1];
  81357. assert( pC!=0 );
  81358. pC->nullRow = 1;
  81359. pC->cacheStatus = CACHE_STALE;
  81360. if( pC->eCurType==CURTYPE_BTREE ){
  81361. assert( pC->uc.pCursor!=0 );
  81362. sqlite3BtreeClearCursor(pC->uc.pCursor);
  81363. }
  81364. break;
  81365. }
  81366. /* Opcode: SeekEnd P1 * * * *
  81367. **
  81368. ** Position cursor P1 at the end of the btree for the purpose of
  81369. ** appending a new entry onto the btree.
  81370. **
  81371. ** It is assumed that the cursor is used only for appending and so
  81372. ** if the cursor is valid, then the cursor must already be pointing
  81373. ** at the end of the btree and so no changes are made to
  81374. ** the cursor.
  81375. */
  81376. /* Opcode: Last P1 P2 * * *
  81377. **
  81378. ** The next use of the Rowid or Column or Prev instruction for P1
  81379. ** will refer to the last entry in the database table or index.
  81380. ** If the table or index is empty and P2>0, then jump immediately to P2.
  81381. ** If P2 is 0 or if the table or index is not empty, fall through
  81382. ** to the following instruction.
  81383. **
  81384. ** This opcode leaves the cursor configured to move in reverse order,
  81385. ** from the end toward the beginning. In other words, the cursor is
  81386. ** configured to use Prev, not Next.
  81387. */
  81388. case OP_SeekEnd:
  81389. case OP_Last: { /* jump */
  81390. VdbeCursor *pC;
  81391. BtCursor *pCrsr;
  81392. int res;
  81393. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81394. pC = p->apCsr[pOp->p1];
  81395. assert( pC!=0 );
  81396. assert( pC->eCurType==CURTYPE_BTREE );
  81397. pCrsr = pC->uc.pCursor;
  81398. res = 0;
  81399. assert( pCrsr!=0 );
  81400. #ifdef SQLITE_DEBUG
  81401. pC->seekOp = pOp->opcode;
  81402. #endif
  81403. if( pOp->opcode==OP_SeekEnd ){
  81404. assert( pOp->p2==0 );
  81405. pC->seekResult = -1;
  81406. if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
  81407. break;
  81408. }
  81409. }
  81410. rc = sqlite3BtreeLast(pCrsr, &res);
  81411. pC->nullRow = (u8)res;
  81412. pC->deferredMoveto = 0;
  81413. pC->cacheStatus = CACHE_STALE;
  81414. if( rc ) goto abort_due_to_error;
  81415. if( pOp->p2>0 ){
  81416. VdbeBranchTaken(res!=0,2);
  81417. if( res ) goto jump_to_p2;
  81418. }
  81419. break;
  81420. }
  81421. /* Opcode: IfSmaller P1 P2 P3 * *
  81422. **
  81423. ** Estimate the number of rows in the table P1. Jump to P2 if that
  81424. ** estimate is less than approximately 2**(0.1*P3).
  81425. */
  81426. case OP_IfSmaller: { /* jump */
  81427. VdbeCursor *pC;
  81428. BtCursor *pCrsr;
  81429. int res;
  81430. i64 sz;
  81431. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81432. pC = p->apCsr[pOp->p1];
  81433. assert( pC!=0 );
  81434. pCrsr = pC->uc.pCursor;
  81435. assert( pCrsr );
  81436. rc = sqlite3BtreeFirst(pCrsr, &res);
  81437. if( rc ) goto abort_due_to_error;
  81438. if( res==0 ){
  81439. sz = sqlite3BtreeRowCountEst(pCrsr);
  81440. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  81441. }
  81442. VdbeBranchTaken(res!=0,2);
  81443. if( res ) goto jump_to_p2;
  81444. break;
  81445. }
  81446. /* Opcode: SorterSort P1 P2 * * *
  81447. **
  81448. ** After all records have been inserted into the Sorter object
  81449. ** identified by P1, invoke this opcode to actually do the sorting.
  81450. ** Jump to P2 if there are no records to be sorted.
  81451. **
  81452. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  81453. ** for Sorter objects.
  81454. */
  81455. /* Opcode: Sort P1 P2 * * *
  81456. **
  81457. ** This opcode does exactly the same thing as OP_Rewind except that
  81458. ** it increments an undocumented global variable used for testing.
  81459. **
  81460. ** Sorting is accomplished by writing records into a sorting index,
  81461. ** then rewinding that index and playing it back from beginning to
  81462. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  81463. ** rewinding so that the global variable will be incremented and
  81464. ** regression tests can determine whether or not the optimizer is
  81465. ** correctly optimizing out sorts.
  81466. */
  81467. case OP_SorterSort: /* jump */
  81468. case OP_Sort: { /* jump */
  81469. #ifdef SQLITE_TEST
  81470. sqlite3_sort_count++;
  81471. sqlite3_search_count--;
  81472. #endif
  81473. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  81474. /* Fall through into OP_Rewind */
  81475. }
  81476. /* Opcode: Rewind P1 P2 * * *
  81477. **
  81478. ** The next use of the Rowid or Column or Next instruction for P1
  81479. ** will refer to the first entry in the database table or index.
  81480. ** If the table or index is empty, jump immediately to P2.
  81481. ** If the table or index is not empty, fall through to the following
  81482. ** instruction.
  81483. **
  81484. ** This opcode leaves the cursor configured to move in forward order,
  81485. ** from the beginning toward the end. In other words, the cursor is
  81486. ** configured to use Next, not Prev.
  81487. */
  81488. case OP_Rewind: { /* jump */
  81489. VdbeCursor *pC;
  81490. BtCursor *pCrsr;
  81491. int res;
  81492. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81493. pC = p->apCsr[pOp->p1];
  81494. assert( pC!=0 );
  81495. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  81496. res = 1;
  81497. #ifdef SQLITE_DEBUG
  81498. pC->seekOp = OP_Rewind;
  81499. #endif
  81500. if( isSorter(pC) ){
  81501. rc = sqlite3VdbeSorterRewind(pC, &res);
  81502. }else{
  81503. assert( pC->eCurType==CURTYPE_BTREE );
  81504. pCrsr = pC->uc.pCursor;
  81505. assert( pCrsr );
  81506. rc = sqlite3BtreeFirst(pCrsr, &res);
  81507. pC->deferredMoveto = 0;
  81508. pC->cacheStatus = CACHE_STALE;
  81509. }
  81510. if( rc ) goto abort_due_to_error;
  81511. pC->nullRow = (u8)res;
  81512. assert( pOp->p2>0 && pOp->p2<p->nOp );
  81513. VdbeBranchTaken(res!=0,2);
  81514. if( res ) goto jump_to_p2;
  81515. break;
  81516. }
  81517. /* Opcode: Next P1 P2 P3 P4 P5
  81518. **
  81519. ** Advance cursor P1 so that it points to the next key/data pair in its
  81520. ** table or index. If there are no more key/value pairs then fall through
  81521. ** to the following instruction. But if the cursor advance was successful,
  81522. ** jump immediately to P2.
  81523. **
  81524. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  81525. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  81526. ** to follow SeekLT, SeekLE, or OP_Last.
  81527. **
  81528. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  81529. ** been opened prior to this opcode or the program will segfault.
  81530. **
  81531. ** The P3 value is a hint to the btree implementation. If P3==1, that
  81532. ** means P1 is an SQL index and that this instruction could have been
  81533. ** omitted if that index had been unique. P3 is usually 0. P3 is
  81534. ** always either 0 or 1.
  81535. **
  81536. ** P4 is always of type P4_ADVANCE. The function pointer points to
  81537. ** sqlite3BtreeNext().
  81538. **
  81539. ** If P5 is positive and the jump is taken, then event counter
  81540. ** number P5-1 in the prepared statement is incremented.
  81541. **
  81542. ** See also: Prev, NextIfOpen
  81543. */
  81544. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  81545. **
  81546. ** This opcode works just like Next except that if cursor P1 is not
  81547. ** open it behaves a no-op.
  81548. */
  81549. /* Opcode: Prev P1 P2 P3 P4 P5
  81550. **
  81551. ** Back up cursor P1 so that it points to the previous key/data pair in its
  81552. ** table or index. If there is no previous key/value pairs then fall through
  81553. ** to the following instruction. But if the cursor backup was successful,
  81554. ** jump immediately to P2.
  81555. **
  81556. **
  81557. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  81558. ** OP_Last opcode used to position the cursor. Prev is not allowed
  81559. ** to follow SeekGT, SeekGE, or OP_Rewind.
  81560. **
  81561. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  81562. ** not open then the behavior is undefined.
  81563. **
  81564. ** The P3 value is a hint to the btree implementation. If P3==1, that
  81565. ** means P1 is an SQL index and that this instruction could have been
  81566. ** omitted if that index had been unique. P3 is usually 0. P3 is
  81567. ** always either 0 or 1.
  81568. **
  81569. ** P4 is always of type P4_ADVANCE. The function pointer points to
  81570. ** sqlite3BtreePrevious().
  81571. **
  81572. ** If P5 is positive and the jump is taken, then event counter
  81573. ** number P5-1 in the prepared statement is incremented.
  81574. */
  81575. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  81576. **
  81577. ** This opcode works just like Prev except that if cursor P1 is not
  81578. ** open it behaves a no-op.
  81579. */
  81580. /* Opcode: SorterNext P1 P2 * * P5
  81581. **
  81582. ** This opcode works just like OP_Next except that P1 must be a
  81583. ** sorter object for which the OP_SorterSort opcode has been
  81584. ** invoked. This opcode advances the cursor to the next sorted
  81585. ** record, or jumps to P2 if there are no more sorted records.
  81586. */
  81587. case OP_SorterNext: { /* jump */
  81588. VdbeCursor *pC;
  81589. pC = p->apCsr[pOp->p1];
  81590. assert( isSorter(pC) );
  81591. rc = sqlite3VdbeSorterNext(db, pC);
  81592. goto next_tail;
  81593. case OP_PrevIfOpen: /* jump */
  81594. case OP_NextIfOpen: /* jump */
  81595. if( p->apCsr[pOp->p1]==0 ) break;
  81596. /* Fall through */
  81597. case OP_Prev: /* jump */
  81598. case OP_Next: /* jump */
  81599. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81600. assert( pOp->p5<ArraySize(p->aCounter) );
  81601. pC = p->apCsr[pOp->p1];
  81602. assert( pC!=0 );
  81603. assert( pC->deferredMoveto==0 );
  81604. assert( pC->eCurType==CURTYPE_BTREE );
  81605. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  81606. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  81607. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  81608. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  81609. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  81610. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  81611. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  81612. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  81613. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  81614. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  81615. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  81616. || pC->seekOp==OP_Last );
  81617. rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
  81618. next_tail:
  81619. pC->cacheStatus = CACHE_STALE;
  81620. VdbeBranchTaken(rc==SQLITE_OK,2);
  81621. if( rc==SQLITE_OK ){
  81622. pC->nullRow = 0;
  81623. p->aCounter[pOp->p5]++;
  81624. #ifdef SQLITE_TEST
  81625. sqlite3_search_count++;
  81626. #endif
  81627. goto jump_to_p2_and_check_for_interrupt;
  81628. }
  81629. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  81630. rc = SQLITE_OK;
  81631. pC->nullRow = 1;
  81632. goto check_for_interrupt;
  81633. }
  81634. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  81635. ** Synopsis: key=r[P2]
  81636. **
  81637. ** Register P2 holds an SQL index key made using the
  81638. ** MakeRecord instructions. This opcode writes that key
  81639. ** into the index P1. Data for the entry is nil.
  81640. **
  81641. ** If P4 is not zero, then it is the number of values in the unpacked
  81642. ** key of reg(P2). In that case, P3 is the index of the first register
  81643. ** for the unpacked key. The availability of the unpacked key can sometimes
  81644. ** be an optimization.
  81645. **
  81646. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  81647. ** that this insert is likely to be an append.
  81648. **
  81649. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  81650. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  81651. ** then the change counter is unchanged.
  81652. **
  81653. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  81654. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  81655. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  81656. ** seeks on the cursor or if the most recent seek used a key equivalent
  81657. ** to P2.
  81658. **
  81659. ** This instruction only works for indices. The equivalent instruction
  81660. ** for tables is OP_Insert.
  81661. */
  81662. /* Opcode: SorterInsert P1 P2 * * *
  81663. ** Synopsis: key=r[P2]
  81664. **
  81665. ** Register P2 holds an SQL index key made using the
  81666. ** MakeRecord instructions. This opcode writes that key
  81667. ** into the sorter P1. Data for the entry is nil.
  81668. */
  81669. case OP_SorterInsert: /* in2 */
  81670. case OP_IdxInsert: { /* in2 */
  81671. VdbeCursor *pC;
  81672. BtreePayload x;
  81673. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81674. pC = p->apCsr[pOp->p1];
  81675. sqlite3VdbeIncrWriteCounter(p, pC);
  81676. assert( pC!=0 );
  81677. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  81678. pIn2 = &aMem[pOp->p2];
  81679. assert( pIn2->flags & MEM_Blob );
  81680. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  81681. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  81682. assert( pC->isTable==0 );
  81683. rc = ExpandBlob(pIn2);
  81684. if( rc ) goto abort_due_to_error;
  81685. if( pOp->opcode==OP_SorterInsert ){
  81686. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  81687. }else{
  81688. x.nKey = pIn2->n;
  81689. x.pKey = pIn2->z;
  81690. x.aMem = aMem + pOp->p3;
  81691. x.nMem = (u16)pOp->p4.i;
  81692. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  81693. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  81694. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  81695. );
  81696. assert( pC->deferredMoveto==0 );
  81697. pC->cacheStatus = CACHE_STALE;
  81698. }
  81699. if( rc) goto abort_due_to_error;
  81700. break;
  81701. }
  81702. /* Opcode: IdxDelete P1 P2 P3 * *
  81703. ** Synopsis: key=r[P2@P3]
  81704. **
  81705. ** The content of P3 registers starting at register P2 form
  81706. ** an unpacked index key. This opcode removes that entry from the
  81707. ** index opened by cursor P1.
  81708. */
  81709. case OP_IdxDelete: {
  81710. VdbeCursor *pC;
  81711. BtCursor *pCrsr;
  81712. int res;
  81713. UnpackedRecord r;
  81714. assert( pOp->p3>0 );
  81715. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  81716. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81717. pC = p->apCsr[pOp->p1];
  81718. assert( pC!=0 );
  81719. assert( pC->eCurType==CURTYPE_BTREE );
  81720. sqlite3VdbeIncrWriteCounter(p, pC);
  81721. pCrsr = pC->uc.pCursor;
  81722. assert( pCrsr!=0 );
  81723. assert( pOp->p5==0 );
  81724. r.pKeyInfo = pC->pKeyInfo;
  81725. r.nField = (u16)pOp->p3;
  81726. r.default_rc = 0;
  81727. r.aMem = &aMem[pOp->p2];
  81728. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  81729. if( rc ) goto abort_due_to_error;
  81730. if( res==0 ){
  81731. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  81732. if( rc ) goto abort_due_to_error;
  81733. }
  81734. assert( pC->deferredMoveto==0 );
  81735. pC->cacheStatus = CACHE_STALE;
  81736. pC->seekResult = 0;
  81737. break;
  81738. }
  81739. /* Opcode: DeferredSeek P1 * P3 P4 *
  81740. ** Synopsis: Move P3 to P1.rowid if needed
  81741. **
  81742. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  81743. ** table. This opcode does a deferred seek of the P3 table cursor
  81744. ** to the row that corresponds to the current row of P1.
  81745. **
  81746. ** This is a deferred seek. Nothing actually happens until
  81747. ** the cursor is used to read a record. That way, if no reads
  81748. ** occur, no unnecessary I/O happens.
  81749. **
  81750. ** P4 may be an array of integers (type P4_INTARRAY) containing
  81751. ** one entry for each column in the P3 table. If array entry a(i)
  81752. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  81753. ** equivalent to performing the deferred seek and then reading column i
  81754. ** from P1. This information is stored in P3 and used to redirect
  81755. ** reads against P3 over to P1, thus possibly avoiding the need to
  81756. ** seek and read cursor P3.
  81757. */
  81758. /* Opcode: IdxRowid P1 P2 * * *
  81759. ** Synopsis: r[P2]=rowid
  81760. **
  81761. ** Write into register P2 an integer which is the last entry in the record at
  81762. ** the end of the index key pointed to by cursor P1. This integer should be
  81763. ** the rowid of the table entry to which this index entry points.
  81764. **
  81765. ** See also: Rowid, MakeRecord.
  81766. */
  81767. case OP_DeferredSeek:
  81768. case OP_IdxRowid: { /* out2 */
  81769. VdbeCursor *pC; /* The P1 index cursor */
  81770. VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
  81771. i64 rowid; /* Rowid that P1 current points to */
  81772. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81773. pC = p->apCsr[pOp->p1];
  81774. assert( pC!=0 );
  81775. assert( pC->eCurType==CURTYPE_BTREE );
  81776. assert( pC->uc.pCursor!=0 );
  81777. assert( pC->isTable==0 );
  81778. assert( pC->deferredMoveto==0 );
  81779. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  81780. /* The IdxRowid and Seek opcodes are combined because of the commonality
  81781. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  81782. rc = sqlite3VdbeCursorRestore(pC);
  81783. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  81784. ** out from under the cursor. That will never happens for an IdxRowid
  81785. ** or Seek opcode */
  81786. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  81787. if( !pC->nullRow ){
  81788. rowid = 0; /* Not needed. Only used to silence a warning. */
  81789. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  81790. if( rc!=SQLITE_OK ){
  81791. goto abort_due_to_error;
  81792. }
  81793. if( pOp->opcode==OP_DeferredSeek ){
  81794. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  81795. pTabCur = p->apCsr[pOp->p3];
  81796. assert( pTabCur!=0 );
  81797. assert( pTabCur->eCurType==CURTYPE_BTREE );
  81798. assert( pTabCur->uc.pCursor!=0 );
  81799. assert( pTabCur->isTable );
  81800. pTabCur->nullRow = 0;
  81801. pTabCur->movetoTarget = rowid;
  81802. pTabCur->deferredMoveto = 1;
  81803. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  81804. pTabCur->aAltMap = pOp->p4.ai;
  81805. pTabCur->pAltCursor = pC;
  81806. }else{
  81807. pOut = out2Prerelease(p, pOp);
  81808. pOut->u.i = rowid;
  81809. }
  81810. }else{
  81811. assert( pOp->opcode==OP_IdxRowid );
  81812. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  81813. }
  81814. break;
  81815. }
  81816. /* Opcode: IdxGE P1 P2 P3 P4 P5
  81817. ** Synopsis: key=r[P3@P4]
  81818. **
  81819. ** The P4 register values beginning with P3 form an unpacked index
  81820. ** key that omits the PRIMARY KEY. Compare this key value against the index
  81821. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  81822. ** fields at the end.
  81823. **
  81824. ** If the P1 index entry is greater than or equal to the key value
  81825. ** then jump to P2. Otherwise fall through to the next instruction.
  81826. */
  81827. /* Opcode: IdxGT P1 P2 P3 P4 P5
  81828. ** Synopsis: key=r[P3@P4]
  81829. **
  81830. ** The P4 register values beginning with P3 form an unpacked index
  81831. ** key that omits the PRIMARY KEY. Compare this key value against the index
  81832. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  81833. ** fields at the end.
  81834. **
  81835. ** If the P1 index entry is greater than the key value
  81836. ** then jump to P2. Otherwise fall through to the next instruction.
  81837. */
  81838. /* Opcode: IdxLT P1 P2 P3 P4 P5
  81839. ** Synopsis: key=r[P3@P4]
  81840. **
  81841. ** The P4 register values beginning with P3 form an unpacked index
  81842. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  81843. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  81844. ** ROWID on the P1 index.
  81845. **
  81846. ** If the P1 index entry is less than the key value then jump to P2.
  81847. ** Otherwise fall through to the next instruction.
  81848. */
  81849. /* Opcode: IdxLE P1 P2 P3 P4 P5
  81850. ** Synopsis: key=r[P3@P4]
  81851. **
  81852. ** The P4 register values beginning with P3 form an unpacked index
  81853. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  81854. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  81855. ** ROWID on the P1 index.
  81856. **
  81857. ** If the P1 index entry is less than or equal to the key value then jump
  81858. ** to P2. Otherwise fall through to the next instruction.
  81859. */
  81860. case OP_IdxLE: /* jump */
  81861. case OP_IdxGT: /* jump */
  81862. case OP_IdxLT: /* jump */
  81863. case OP_IdxGE: { /* jump */
  81864. VdbeCursor *pC;
  81865. int res;
  81866. UnpackedRecord r;
  81867. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81868. pC = p->apCsr[pOp->p1];
  81869. assert( pC!=0 );
  81870. assert( pC->isOrdered );
  81871. assert( pC->eCurType==CURTYPE_BTREE );
  81872. assert( pC->uc.pCursor!=0);
  81873. assert( pC->deferredMoveto==0 );
  81874. assert( pOp->p5==0 || pOp->p5==1 );
  81875. assert( pOp->p4type==P4_INT32 );
  81876. r.pKeyInfo = pC->pKeyInfo;
  81877. r.nField = (u16)pOp->p4.i;
  81878. if( pOp->opcode<OP_IdxLT ){
  81879. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  81880. r.default_rc = -1;
  81881. }else{
  81882. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  81883. r.default_rc = 0;
  81884. }
  81885. r.aMem = &aMem[pOp->p3];
  81886. #ifdef SQLITE_DEBUG
  81887. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  81888. #endif
  81889. res = 0; /* Not needed. Only used to silence a warning. */
  81890. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  81891. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  81892. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  81893. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  81894. res = -res;
  81895. }else{
  81896. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  81897. res++;
  81898. }
  81899. VdbeBranchTaken(res>0,2);
  81900. if( rc ) goto abort_due_to_error;
  81901. if( res>0 ) goto jump_to_p2;
  81902. break;
  81903. }
  81904. /* Opcode: Destroy P1 P2 P3 * *
  81905. **
  81906. ** Delete an entire database table or index whose root page in the database
  81907. ** file is given by P1.
  81908. **
  81909. ** The table being destroyed is in the main database file if P3==0. If
  81910. ** P3==1 then the table to be clear is in the auxiliary database file
  81911. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  81912. **
  81913. ** If AUTOVACUUM is enabled then it is possible that another root page
  81914. ** might be moved into the newly deleted root page in order to keep all
  81915. ** root pages contiguous at the beginning of the database. The former
  81916. ** value of the root page that moved - its value before the move occurred -
  81917. ** is stored in register P2. If no page movement was required (because the
  81918. ** table being dropped was already the last one in the database) then a
  81919. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  81920. ** is stored in register P2.
  81921. **
  81922. ** This opcode throws an error if there are any active reader VMs when
  81923. ** it is invoked. This is done to avoid the difficulty associated with
  81924. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  81925. ** database. This error is thrown even if the database is not an AUTOVACUUM
  81926. ** db in order to avoid introducing an incompatibility between autovacuum
  81927. ** and non-autovacuum modes.
  81928. **
  81929. ** See also: Clear
  81930. */
  81931. case OP_Destroy: { /* out2 */
  81932. int iMoved;
  81933. int iDb;
  81934. sqlite3VdbeIncrWriteCounter(p, 0);
  81935. assert( p->readOnly==0 );
  81936. assert( pOp->p1>1 );
  81937. pOut = out2Prerelease(p, pOp);
  81938. pOut->flags = MEM_Null;
  81939. if( db->nVdbeRead > db->nVDestroy+1 ){
  81940. rc = SQLITE_LOCKED;
  81941. p->errorAction = OE_Abort;
  81942. goto abort_due_to_error;
  81943. }else{
  81944. iDb = pOp->p3;
  81945. assert( DbMaskTest(p->btreeMask, iDb) );
  81946. iMoved = 0; /* Not needed. Only to silence a warning. */
  81947. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  81948. pOut->flags = MEM_Int;
  81949. pOut->u.i = iMoved;
  81950. if( rc ) goto abort_due_to_error;
  81951. #ifndef SQLITE_OMIT_AUTOVACUUM
  81952. if( iMoved!=0 ){
  81953. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  81954. /* All OP_Destroy operations occur on the same btree */
  81955. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  81956. resetSchemaOnFault = iDb+1;
  81957. }
  81958. #endif
  81959. }
  81960. break;
  81961. }
  81962. /* Opcode: Clear P1 P2 P3
  81963. **
  81964. ** Delete all contents of the database table or index whose root page
  81965. ** in the database file is given by P1. But, unlike Destroy, do not
  81966. ** remove the table or index from the database file.
  81967. **
  81968. ** The table being clear is in the main database file if P2==0. If
  81969. ** P2==1 then the table to be clear is in the auxiliary database file
  81970. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  81971. **
  81972. ** If the P3 value is non-zero, then the table referred to must be an
  81973. ** intkey table (an SQL table, not an index). In this case the row change
  81974. ** count is incremented by the number of rows in the table being cleared.
  81975. ** If P3 is greater than zero, then the value stored in register P3 is
  81976. ** also incremented by the number of rows in the table being cleared.
  81977. **
  81978. ** See also: Destroy
  81979. */
  81980. case OP_Clear: {
  81981. int nChange;
  81982. sqlite3VdbeIncrWriteCounter(p, 0);
  81983. nChange = 0;
  81984. assert( p->readOnly==0 );
  81985. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  81986. rc = sqlite3BtreeClearTable(
  81987. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  81988. );
  81989. if( pOp->p3 ){
  81990. p->nChange += nChange;
  81991. if( pOp->p3>0 ){
  81992. assert( memIsValid(&aMem[pOp->p3]) );
  81993. memAboutToChange(p, &aMem[pOp->p3]);
  81994. aMem[pOp->p3].u.i += nChange;
  81995. }
  81996. }
  81997. if( rc ) goto abort_due_to_error;
  81998. break;
  81999. }
  82000. /* Opcode: ResetSorter P1 * * * *
  82001. **
  82002. ** Delete all contents from the ephemeral table or sorter
  82003. ** that is open on cursor P1.
  82004. **
  82005. ** This opcode only works for cursors used for sorting and
  82006. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  82007. */
  82008. case OP_ResetSorter: {
  82009. VdbeCursor *pC;
  82010. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82011. pC = p->apCsr[pOp->p1];
  82012. assert( pC!=0 );
  82013. if( isSorter(pC) ){
  82014. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  82015. }else{
  82016. assert( pC->eCurType==CURTYPE_BTREE );
  82017. assert( pC->isEphemeral );
  82018. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  82019. if( rc ) goto abort_due_to_error;
  82020. }
  82021. break;
  82022. }
  82023. /* Opcode: CreateBtree P1 P2 P3 * *
  82024. ** Synopsis: r[P2]=root iDb=P1 flags=P3
  82025. **
  82026. ** Allocate a new b-tree in the main database file if P1==0 or in the
  82027. ** TEMP database file if P1==1 or in an attached database if
  82028. ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
  82029. ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
  82030. ** The root page number of the new b-tree is stored in register P2.
  82031. */
  82032. case OP_CreateBtree: { /* out2 */
  82033. int pgno;
  82034. Db *pDb;
  82035. sqlite3VdbeIncrWriteCounter(p, 0);
  82036. pOut = out2Prerelease(p, pOp);
  82037. pgno = 0;
  82038. assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
  82039. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  82040. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  82041. assert( p->readOnly==0 );
  82042. pDb = &db->aDb[pOp->p1];
  82043. assert( pDb->pBt!=0 );
  82044. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
  82045. if( rc ) goto abort_due_to_error;
  82046. pOut->u.i = pgno;
  82047. break;
  82048. }
  82049. /* Opcode: SqlExec * * * P4 *
  82050. **
  82051. ** Run the SQL statement or statements specified in the P4 string.
  82052. */
  82053. case OP_SqlExec: {
  82054. sqlite3VdbeIncrWriteCounter(p, 0);
  82055. db->nSqlExec++;
  82056. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  82057. db->nSqlExec--;
  82058. if( rc ) goto abort_due_to_error;
  82059. break;
  82060. }
  82061. /* Opcode: ParseSchema P1 * * P4 *
  82062. **
  82063. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  82064. ** that match the WHERE clause P4.
  82065. **
  82066. ** This opcode invokes the parser to create a new virtual machine,
  82067. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  82068. */
  82069. case OP_ParseSchema: {
  82070. int iDb;
  82071. const char *zMaster;
  82072. char *zSql;
  82073. InitData initData;
  82074. /* Any prepared statement that invokes this opcode will hold mutexes
  82075. ** on every btree. This is a prerequisite for invoking
  82076. ** sqlite3InitCallback().
  82077. */
  82078. #ifdef SQLITE_DEBUG
  82079. for(iDb=0; iDb<db->nDb; iDb++){
  82080. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  82081. }
  82082. #endif
  82083. iDb = pOp->p1;
  82084. assert( iDb>=0 && iDb<db->nDb );
  82085. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  82086. /* Used to be a conditional */ {
  82087. zMaster = MASTER_NAME;
  82088. initData.db = db;
  82089. initData.iDb = pOp->p1;
  82090. initData.pzErrMsg = &p->zErrMsg;
  82091. zSql = sqlite3MPrintf(db,
  82092. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  82093. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  82094. if( zSql==0 ){
  82095. rc = SQLITE_NOMEM_BKPT;
  82096. }else{
  82097. assert( db->init.busy==0 );
  82098. db->init.busy = 1;
  82099. initData.rc = SQLITE_OK;
  82100. assert( !db->mallocFailed );
  82101. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  82102. if( rc==SQLITE_OK ) rc = initData.rc;
  82103. sqlite3DbFreeNN(db, zSql);
  82104. db->init.busy = 0;
  82105. }
  82106. }
  82107. if( rc ){
  82108. sqlite3ResetAllSchemasOfConnection(db);
  82109. if( rc==SQLITE_NOMEM ){
  82110. goto no_mem;
  82111. }
  82112. goto abort_due_to_error;
  82113. }
  82114. break;
  82115. }
  82116. #if !defined(SQLITE_OMIT_ANALYZE)
  82117. /* Opcode: LoadAnalysis P1 * * * *
  82118. **
  82119. ** Read the sqlite_stat1 table for database P1 and load the content
  82120. ** of that table into the internal index hash table. This will cause
  82121. ** the analysis to be used when preparing all subsequent queries.
  82122. */
  82123. case OP_LoadAnalysis: {
  82124. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  82125. rc = sqlite3AnalysisLoad(db, pOp->p1);
  82126. if( rc ) goto abort_due_to_error;
  82127. break;
  82128. }
  82129. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  82130. /* Opcode: DropTable P1 * * P4 *
  82131. **
  82132. ** Remove the internal (in-memory) data structures that describe
  82133. ** the table named P4 in database P1. This is called after a table
  82134. ** is dropped from disk (using the Destroy opcode) in order to keep
  82135. ** the internal representation of the
  82136. ** schema consistent with what is on disk.
  82137. */
  82138. case OP_DropTable: {
  82139. sqlite3VdbeIncrWriteCounter(p, 0);
  82140. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  82141. break;
  82142. }
  82143. /* Opcode: DropIndex P1 * * P4 *
  82144. **
  82145. ** Remove the internal (in-memory) data structures that describe
  82146. ** the index named P4 in database P1. This is called after an index
  82147. ** is dropped from disk (using the Destroy opcode)
  82148. ** in order to keep the internal representation of the
  82149. ** schema consistent with what is on disk.
  82150. */
  82151. case OP_DropIndex: {
  82152. sqlite3VdbeIncrWriteCounter(p, 0);
  82153. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  82154. break;
  82155. }
  82156. /* Opcode: DropTrigger P1 * * P4 *
  82157. **
  82158. ** Remove the internal (in-memory) data structures that describe
  82159. ** the trigger named P4 in database P1. This is called after a trigger
  82160. ** is dropped from disk (using the Destroy opcode) in order to keep
  82161. ** the internal representation of the
  82162. ** schema consistent with what is on disk.
  82163. */
  82164. case OP_DropTrigger: {
  82165. sqlite3VdbeIncrWriteCounter(p, 0);
  82166. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  82167. break;
  82168. }
  82169. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  82170. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  82171. **
  82172. ** Do an analysis of the currently open database. Store in
  82173. ** register P1 the text of an error message describing any problems.
  82174. ** If no problems are found, store a NULL in register P1.
  82175. **
  82176. ** The register P3 contains one less than the maximum number of allowed errors.
  82177. ** At most reg(P3) errors will be reported.
  82178. ** In other words, the analysis stops as soon as reg(P1) errors are
  82179. ** seen. Reg(P1) is updated with the number of errors remaining.
  82180. **
  82181. ** The root page numbers of all tables in the database are integers
  82182. ** stored in P4_INTARRAY argument.
  82183. **
  82184. ** If P5 is not zero, the check is done on the auxiliary database
  82185. ** file, not the main database file.
  82186. **
  82187. ** This opcode is used to implement the integrity_check pragma.
  82188. */
  82189. case OP_IntegrityCk: {
  82190. int nRoot; /* Number of tables to check. (Number of root pages.) */
  82191. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  82192. int nErr; /* Number of errors reported */
  82193. char *z; /* Text of the error report */
  82194. Mem *pnErr; /* Register keeping track of errors remaining */
  82195. assert( p->bIsReader );
  82196. nRoot = pOp->p2;
  82197. aRoot = pOp->p4.ai;
  82198. assert( nRoot>0 );
  82199. assert( aRoot[0]==nRoot );
  82200. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  82201. pnErr = &aMem[pOp->p3];
  82202. assert( (pnErr->flags & MEM_Int)!=0 );
  82203. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  82204. pIn1 = &aMem[pOp->p1];
  82205. assert( pOp->p5<db->nDb );
  82206. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  82207. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
  82208. (int)pnErr->u.i+1, &nErr);
  82209. sqlite3VdbeMemSetNull(pIn1);
  82210. if( nErr==0 ){
  82211. assert( z==0 );
  82212. }else if( z==0 ){
  82213. goto no_mem;
  82214. }else{
  82215. pnErr->u.i -= nErr-1;
  82216. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  82217. }
  82218. UPDATE_MAX_BLOBSIZE(pIn1);
  82219. sqlite3VdbeChangeEncoding(pIn1, encoding);
  82220. break;
  82221. }
  82222. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  82223. /* Opcode: RowSetAdd P1 P2 * * *
  82224. ** Synopsis: rowset(P1)=r[P2]
  82225. **
  82226. ** Insert the integer value held by register P2 into a RowSet object
  82227. ** held in register P1.
  82228. **
  82229. ** An assertion fails if P2 is not an integer.
  82230. */
  82231. case OP_RowSetAdd: { /* in1, in2 */
  82232. pIn1 = &aMem[pOp->p1];
  82233. pIn2 = &aMem[pOp->p2];
  82234. assert( (pIn2->flags & MEM_Int)!=0 );
  82235. if( (pIn1->flags & MEM_RowSet)==0 ){
  82236. sqlite3VdbeMemSetRowSet(pIn1);
  82237. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  82238. }
  82239. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  82240. break;
  82241. }
  82242. /* Opcode: RowSetRead P1 P2 P3 * *
  82243. ** Synopsis: r[P3]=rowset(P1)
  82244. **
  82245. ** Extract the smallest value from the RowSet object in P1
  82246. ** and put that value into register P3.
  82247. ** Or, if RowSet object P1 is initially empty, leave P3
  82248. ** unchanged and jump to instruction P2.
  82249. */
  82250. case OP_RowSetRead: { /* jump, in1, out3 */
  82251. i64 val;
  82252. pIn1 = &aMem[pOp->p1];
  82253. if( (pIn1->flags & MEM_RowSet)==0
  82254. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  82255. ){
  82256. /* The boolean index is empty */
  82257. sqlite3VdbeMemSetNull(pIn1);
  82258. VdbeBranchTaken(1,2);
  82259. goto jump_to_p2_and_check_for_interrupt;
  82260. }else{
  82261. /* A value was pulled from the index */
  82262. VdbeBranchTaken(0,2);
  82263. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  82264. }
  82265. goto check_for_interrupt;
  82266. }
  82267. /* Opcode: RowSetTest P1 P2 P3 P4
  82268. ** Synopsis: if r[P3] in rowset(P1) goto P2
  82269. **
  82270. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  82271. ** contains a RowSet object and that RowSet object contains
  82272. ** the value held in P3, jump to register P2. Otherwise, insert the
  82273. ** integer in P3 into the RowSet and continue on to the
  82274. ** next opcode.
  82275. **
  82276. ** The RowSet object is optimized for the case where sets of integers
  82277. ** are inserted in distinct phases, which each set contains no duplicates.
  82278. ** Each set is identified by a unique P4 value. The first set
  82279. ** must have P4==0, the final set must have P4==-1, and for all other sets
  82280. ** must have P4>0.
  82281. **
  82282. ** This allows optimizations: (a) when P4==0 there is no need to test
  82283. ** the RowSet object for P3, as it is guaranteed not to contain it,
  82284. ** (b) when P4==-1 there is no need to insert the value, as it will
  82285. ** never be tested for, and (c) when a value that is part of set X is
  82286. ** inserted, there is no need to search to see if the same value was
  82287. ** previously inserted as part of set X (only if it was previously
  82288. ** inserted as part of some other set).
  82289. */
  82290. case OP_RowSetTest: { /* jump, in1, in3 */
  82291. int iSet;
  82292. int exists;
  82293. pIn1 = &aMem[pOp->p1];
  82294. pIn3 = &aMem[pOp->p3];
  82295. iSet = pOp->p4.i;
  82296. assert( pIn3->flags&MEM_Int );
  82297. /* If there is anything other than a rowset object in memory cell P1,
  82298. ** delete it now and initialize P1 with an empty rowset
  82299. */
  82300. if( (pIn1->flags & MEM_RowSet)==0 ){
  82301. sqlite3VdbeMemSetRowSet(pIn1);
  82302. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  82303. }
  82304. assert( pOp->p4type==P4_INT32 );
  82305. assert( iSet==-1 || iSet>=0 );
  82306. if( iSet ){
  82307. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  82308. VdbeBranchTaken(exists!=0,2);
  82309. if( exists ) goto jump_to_p2;
  82310. }
  82311. if( iSet>=0 ){
  82312. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  82313. }
  82314. break;
  82315. }
  82316. #ifndef SQLITE_OMIT_TRIGGER
  82317. /* Opcode: Program P1 P2 P3 P4 P5
  82318. **
  82319. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  82320. **
  82321. ** P1 contains the address of the memory cell that contains the first memory
  82322. ** cell in an array of values used as arguments to the sub-program. P2
  82323. ** contains the address to jump to if the sub-program throws an IGNORE
  82324. ** exception using the RAISE() function. Register P3 contains the address
  82325. ** of a memory cell in this (the parent) VM that is used to allocate the
  82326. ** memory required by the sub-vdbe at runtime.
  82327. **
  82328. ** P4 is a pointer to the VM containing the trigger program.
  82329. **
  82330. ** If P5 is non-zero, then recursive program invocation is enabled.
  82331. */
  82332. case OP_Program: { /* jump */
  82333. int nMem; /* Number of memory registers for sub-program */
  82334. int nByte; /* Bytes of runtime space required for sub-program */
  82335. Mem *pRt; /* Register to allocate runtime space */
  82336. Mem *pMem; /* Used to iterate through memory cells */
  82337. Mem *pEnd; /* Last memory cell in new array */
  82338. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  82339. SubProgram *pProgram; /* Sub-program to execute */
  82340. void *t; /* Token identifying trigger */
  82341. pProgram = pOp->p4.pProgram;
  82342. pRt = &aMem[pOp->p3];
  82343. assert( pProgram->nOp>0 );
  82344. /* If the p5 flag is clear, then recursive invocation of triggers is
  82345. ** disabled for backwards compatibility (p5 is set if this sub-program
  82346. ** is really a trigger, not a foreign key action, and the flag set
  82347. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  82348. **
  82349. ** It is recursive invocation of triggers, at the SQL level, that is
  82350. ** disabled. In some cases a single trigger may generate more than one
  82351. ** SubProgram (if the trigger may be executed with more than one different
  82352. ** ON CONFLICT algorithm). SubProgram structures associated with a
  82353. ** single trigger all have the same value for the SubProgram.token
  82354. ** variable. */
  82355. if( pOp->p5 ){
  82356. t = pProgram->token;
  82357. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  82358. if( pFrame ) break;
  82359. }
  82360. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  82361. rc = SQLITE_ERROR;
  82362. sqlite3VdbeError(p, "too many levels of trigger recursion");
  82363. goto abort_due_to_error;
  82364. }
  82365. /* Register pRt is used to store the memory required to save the state
  82366. ** of the current program, and the memory required at runtime to execute
  82367. ** the trigger program. If this trigger has been fired before, then pRt
  82368. ** is already allocated. Otherwise, it must be initialized. */
  82369. if( (pRt->flags&MEM_Frame)==0 ){
  82370. /* SubProgram.nMem is set to the number of memory cells used by the
  82371. ** program stored in SubProgram.aOp. As well as these, one memory
  82372. ** cell is required for each cursor used by the program. Set local
  82373. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  82374. */
  82375. nMem = pProgram->nMem + pProgram->nCsr;
  82376. assert( nMem>0 );
  82377. if( pProgram->nCsr==0 ) nMem++;
  82378. nByte = ROUND8(sizeof(VdbeFrame))
  82379. + nMem * sizeof(Mem)
  82380. + pProgram->nCsr * sizeof(VdbeCursor*)
  82381. + (pProgram->nOp + 7)/8;
  82382. pFrame = sqlite3DbMallocZero(db, nByte);
  82383. if( !pFrame ){
  82384. goto no_mem;
  82385. }
  82386. sqlite3VdbeMemRelease(pRt);
  82387. pRt->flags = MEM_Frame;
  82388. pRt->u.pFrame = pFrame;
  82389. pFrame->v = p;
  82390. pFrame->nChildMem = nMem;
  82391. pFrame->nChildCsr = pProgram->nCsr;
  82392. pFrame->pc = (int)(pOp - aOp);
  82393. pFrame->aMem = p->aMem;
  82394. pFrame->nMem = p->nMem;
  82395. pFrame->apCsr = p->apCsr;
  82396. pFrame->nCursor = p->nCursor;
  82397. pFrame->aOp = p->aOp;
  82398. pFrame->nOp = p->nOp;
  82399. pFrame->token = pProgram->token;
  82400. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  82401. pFrame->anExec = p->anExec;
  82402. #endif
  82403. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  82404. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  82405. pMem->flags = MEM_Undefined;
  82406. pMem->db = db;
  82407. }
  82408. }else{
  82409. pFrame = pRt->u.pFrame;
  82410. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  82411. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  82412. assert( pProgram->nCsr==pFrame->nChildCsr );
  82413. assert( (int)(pOp - aOp)==pFrame->pc );
  82414. }
  82415. p->nFrame++;
  82416. pFrame->pParent = p->pFrame;
  82417. pFrame->lastRowid = db->lastRowid;
  82418. pFrame->nChange = p->nChange;
  82419. pFrame->nDbChange = p->db->nChange;
  82420. assert( pFrame->pAuxData==0 );
  82421. pFrame->pAuxData = p->pAuxData;
  82422. p->pAuxData = 0;
  82423. p->nChange = 0;
  82424. p->pFrame = pFrame;
  82425. p->aMem = aMem = VdbeFrameMem(pFrame);
  82426. p->nMem = pFrame->nChildMem;
  82427. p->nCursor = (u16)pFrame->nChildCsr;
  82428. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  82429. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  82430. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  82431. p->aOp = aOp = pProgram->aOp;
  82432. p->nOp = pProgram->nOp;
  82433. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  82434. p->anExec = 0;
  82435. #endif
  82436. pOp = &aOp[-1];
  82437. break;
  82438. }
  82439. /* Opcode: Param P1 P2 * * *
  82440. **
  82441. ** This opcode is only ever present in sub-programs called via the
  82442. ** OP_Program instruction. Copy a value currently stored in a memory
  82443. ** cell of the calling (parent) frame to cell P2 in the current frames
  82444. ** address space. This is used by trigger programs to access the new.*
  82445. ** and old.* values.
  82446. **
  82447. ** The address of the cell in the parent frame is determined by adding
  82448. ** the value of the P1 argument to the value of the P1 argument to the
  82449. ** calling OP_Program instruction.
  82450. */
  82451. case OP_Param: { /* out2 */
  82452. VdbeFrame *pFrame;
  82453. Mem *pIn;
  82454. pOut = out2Prerelease(p, pOp);
  82455. pFrame = p->pFrame;
  82456. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  82457. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  82458. break;
  82459. }
  82460. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  82461. #ifndef SQLITE_OMIT_FOREIGN_KEY
  82462. /* Opcode: FkCounter P1 P2 * * *
  82463. ** Synopsis: fkctr[P1]+=P2
  82464. **
  82465. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  82466. ** If P1 is non-zero, the database constraint counter is incremented
  82467. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  82468. ** statement counter is incremented (immediate foreign key constraints).
  82469. */
  82470. case OP_FkCounter: {
  82471. if( db->flags & SQLITE_DeferFKs ){
  82472. db->nDeferredImmCons += pOp->p2;
  82473. }else if( pOp->p1 ){
  82474. db->nDeferredCons += pOp->p2;
  82475. }else{
  82476. p->nFkConstraint += pOp->p2;
  82477. }
  82478. break;
  82479. }
  82480. /* Opcode: FkIfZero P1 P2 * * *
  82481. ** Synopsis: if fkctr[P1]==0 goto P2
  82482. **
  82483. ** This opcode tests if a foreign key constraint-counter is currently zero.
  82484. ** If so, jump to instruction P2. Otherwise, fall through to the next
  82485. ** instruction.
  82486. **
  82487. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  82488. ** is zero (the one that counts deferred constraint violations). If P1 is
  82489. ** zero, the jump is taken if the statement constraint-counter is zero
  82490. ** (immediate foreign key constraint violations).
  82491. */
  82492. case OP_FkIfZero: { /* jump */
  82493. if( pOp->p1 ){
  82494. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  82495. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  82496. }else{
  82497. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  82498. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  82499. }
  82500. break;
  82501. }
  82502. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  82503. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82504. /* Opcode: MemMax P1 P2 * * *
  82505. ** Synopsis: r[P1]=max(r[P1],r[P2])
  82506. **
  82507. ** P1 is a register in the root frame of this VM (the root frame is
  82508. ** different from the current frame if this instruction is being executed
  82509. ** within a sub-program). Set the value of register P1 to the maximum of
  82510. ** its current value and the value in register P2.
  82511. **
  82512. ** This instruction throws an error if the memory cell is not initially
  82513. ** an integer.
  82514. */
  82515. case OP_MemMax: { /* in2 */
  82516. VdbeFrame *pFrame;
  82517. if( p->pFrame ){
  82518. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  82519. pIn1 = &pFrame->aMem[pOp->p1];
  82520. }else{
  82521. pIn1 = &aMem[pOp->p1];
  82522. }
  82523. assert( memIsValid(pIn1) );
  82524. sqlite3VdbeMemIntegerify(pIn1);
  82525. pIn2 = &aMem[pOp->p2];
  82526. sqlite3VdbeMemIntegerify(pIn2);
  82527. if( pIn1->u.i<pIn2->u.i){
  82528. pIn1->u.i = pIn2->u.i;
  82529. }
  82530. break;
  82531. }
  82532. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  82533. /* Opcode: IfPos P1 P2 P3 * *
  82534. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  82535. **
  82536. ** Register P1 must contain an integer.
  82537. ** If the value of register P1 is 1 or greater, subtract P3 from the
  82538. ** value in P1 and jump to P2.
  82539. **
  82540. ** If the initial value of register P1 is less than 1, then the
  82541. ** value is unchanged and control passes through to the next instruction.
  82542. */
  82543. case OP_IfPos: { /* jump, in1 */
  82544. pIn1 = &aMem[pOp->p1];
  82545. assert( pIn1->flags&MEM_Int );
  82546. VdbeBranchTaken( pIn1->u.i>0, 2);
  82547. if( pIn1->u.i>0 ){
  82548. pIn1->u.i -= pOp->p3;
  82549. goto jump_to_p2;
  82550. }
  82551. break;
  82552. }
  82553. /* Opcode: OffsetLimit P1 P2 P3 * *
  82554. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  82555. **
  82556. ** This opcode performs a commonly used computation associated with
  82557. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  82558. ** holds the offset counter. The opcode computes the combined value
  82559. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  82560. ** value computed is the total number of rows that will need to be
  82561. ** visited in order to complete the query.
  82562. **
  82563. ** If r[P3] is zero or negative, that means there is no OFFSET
  82564. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  82565. **
  82566. ** if r[P1] is zero or negative, that means there is no LIMIT
  82567. ** and r[P2] is set to -1.
  82568. **
  82569. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  82570. */
  82571. case OP_OffsetLimit: { /* in1, out2, in3 */
  82572. i64 x;
  82573. pIn1 = &aMem[pOp->p1];
  82574. pIn3 = &aMem[pOp->p3];
  82575. pOut = out2Prerelease(p, pOp);
  82576. assert( pIn1->flags & MEM_Int );
  82577. assert( pIn3->flags & MEM_Int );
  82578. x = pIn1->u.i;
  82579. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  82580. /* If the LIMIT is less than or equal to zero, loop forever. This
  82581. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  82582. ** also loop forever. This is undocumented. In fact, one could argue
  82583. ** that the loop should terminate. But assuming 1 billion iterations
  82584. ** per second (far exceeding the capabilities of any current hardware)
  82585. ** it would take nearly 300 years to actually reach the limit. So
  82586. ** looping forever is a reasonable approximation. */
  82587. pOut->u.i = -1;
  82588. }else{
  82589. pOut->u.i = x;
  82590. }
  82591. break;
  82592. }
  82593. /* Opcode: IfNotZero P1 P2 * * *
  82594. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  82595. **
  82596. ** Register P1 must contain an integer. If the content of register P1 is
  82597. ** initially greater than zero, then decrement the value in register P1.
  82598. ** If it is non-zero (negative or positive) and then also jump to P2.
  82599. ** If register P1 is initially zero, leave it unchanged and fall through.
  82600. */
  82601. case OP_IfNotZero: { /* jump, in1 */
  82602. pIn1 = &aMem[pOp->p1];
  82603. assert( pIn1->flags&MEM_Int );
  82604. VdbeBranchTaken(pIn1->u.i<0, 2);
  82605. if( pIn1->u.i ){
  82606. if( pIn1->u.i>0 ) pIn1->u.i--;
  82607. goto jump_to_p2;
  82608. }
  82609. break;
  82610. }
  82611. /* Opcode: DecrJumpZero P1 P2 * * *
  82612. ** Synopsis: if (--r[P1])==0 goto P2
  82613. **
  82614. ** Register P1 must hold an integer. Decrement the value in P1
  82615. ** and jump to P2 if the new value is exactly zero.
  82616. */
  82617. case OP_DecrJumpZero: { /* jump, in1 */
  82618. pIn1 = &aMem[pOp->p1];
  82619. assert( pIn1->flags&MEM_Int );
  82620. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  82621. VdbeBranchTaken(pIn1->u.i==0, 2);
  82622. if( pIn1->u.i==0 ) goto jump_to_p2;
  82623. break;
  82624. }
  82625. /* Opcode: AggStep0 * P2 P3 P4 P5
  82626. ** Synopsis: accum=r[P3] step(r[P2@P5])
  82627. **
  82628. ** Execute the step function for an aggregate. The
  82629. ** function has P5 arguments. P4 is a pointer to the FuncDef
  82630. ** structure that specifies the function. Register P3 is the
  82631. ** accumulator.
  82632. **
  82633. ** The P5 arguments are taken from register P2 and its
  82634. ** successors.
  82635. */
  82636. /* Opcode: AggStep * P2 P3 P4 P5
  82637. ** Synopsis: accum=r[P3] step(r[P2@P5])
  82638. **
  82639. ** Execute the step function for an aggregate. The
  82640. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  82641. ** object that is used to run the function. Register P3 is
  82642. ** as the accumulator.
  82643. **
  82644. ** The P5 arguments are taken from register P2 and its
  82645. ** successors.
  82646. **
  82647. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  82648. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  82649. ** the opcode is changed. In this way, the initialization of the
  82650. ** sqlite3_context only happens once, instead of on each call to the
  82651. ** step function.
  82652. */
  82653. case OP_AggStep0: {
  82654. int n;
  82655. sqlite3_context *pCtx;
  82656. assert( pOp->p4type==P4_FUNCDEF );
  82657. n = pOp->p5;
  82658. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  82659. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  82660. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  82661. pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
  82662. (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
  82663. if( pCtx==0 ) goto no_mem;
  82664. pCtx->pMem = 0;
  82665. pCtx->pOut = (Mem*)&(pCtx->argv[n]);
  82666. sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
  82667. pCtx->pFunc = pOp->p4.pFunc;
  82668. pCtx->iOp = (int)(pOp - aOp);
  82669. pCtx->pVdbe = p;
  82670. pCtx->skipFlag = 0;
  82671. pCtx->isError = 0;
  82672. pCtx->argc = n;
  82673. pOp->p4type = P4_FUNCCTX;
  82674. pOp->p4.pCtx = pCtx;
  82675. pOp->opcode = OP_AggStep;
  82676. /* Fall through into OP_AggStep */
  82677. }
  82678. case OP_AggStep: {
  82679. int i;
  82680. sqlite3_context *pCtx;
  82681. Mem *pMem;
  82682. assert( pOp->p4type==P4_FUNCCTX );
  82683. pCtx = pOp->p4.pCtx;
  82684. pMem = &aMem[pOp->p3];
  82685. /* If this function is inside of a trigger, the register array in aMem[]
  82686. ** might change from one evaluation to the next. The next block of code
  82687. ** checks to see if the register array has changed, and if so it
  82688. ** reinitializes the relavant parts of the sqlite3_context object */
  82689. if( pCtx->pMem != pMem ){
  82690. pCtx->pMem = pMem;
  82691. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  82692. }
  82693. #ifdef SQLITE_DEBUG
  82694. for(i=0; i<pCtx->argc; i++){
  82695. assert( memIsValid(pCtx->argv[i]) );
  82696. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  82697. }
  82698. #endif
  82699. pMem->n++;
  82700. assert( pCtx->pOut->flags==MEM_Null );
  82701. assert( pCtx->isError==0 );
  82702. assert( pCtx->skipFlag==0 );
  82703. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  82704. if( pCtx->isError ){
  82705. if( pCtx->isError>0 ){
  82706. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  82707. rc = pCtx->isError;
  82708. }
  82709. if( pCtx->skipFlag ){
  82710. assert( pOp[-1].opcode==OP_CollSeq );
  82711. i = pOp[-1].p1;
  82712. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  82713. pCtx->skipFlag = 0;
  82714. }
  82715. sqlite3VdbeMemRelease(pCtx->pOut);
  82716. pCtx->pOut->flags = MEM_Null;
  82717. pCtx->isError = 0;
  82718. if( rc ) goto abort_due_to_error;
  82719. }
  82720. assert( pCtx->pOut->flags==MEM_Null );
  82721. assert( pCtx->skipFlag==0 );
  82722. break;
  82723. }
  82724. /* Opcode: AggFinal P1 P2 * P4 *
  82725. ** Synopsis: accum=r[P1] N=P2
  82726. **
  82727. ** Execute the finalizer function for an aggregate. P1 is
  82728. ** the memory location that is the accumulator for the aggregate.
  82729. **
  82730. ** P2 is the number of arguments that the step function takes and
  82731. ** P4 is a pointer to the FuncDef for this function. The P2
  82732. ** argument is not used by this opcode. It is only there to disambiguate
  82733. ** functions that can take varying numbers of arguments. The
  82734. ** P4 argument is only needed for the degenerate case where
  82735. ** the step function was not previously called.
  82736. */
  82737. case OP_AggFinal: {
  82738. Mem *pMem;
  82739. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  82740. pMem = &aMem[pOp->p1];
  82741. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  82742. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  82743. if( rc ){
  82744. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  82745. goto abort_due_to_error;
  82746. }
  82747. sqlite3VdbeChangeEncoding(pMem, encoding);
  82748. UPDATE_MAX_BLOBSIZE(pMem);
  82749. if( sqlite3VdbeMemTooBig(pMem) ){
  82750. goto too_big;
  82751. }
  82752. break;
  82753. }
  82754. #ifndef SQLITE_OMIT_WAL
  82755. /* Opcode: Checkpoint P1 P2 P3 * *
  82756. **
  82757. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  82758. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  82759. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  82760. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  82761. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  82762. ** in the WAL that have been checkpointed after the checkpoint
  82763. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  82764. ** mem[P3+2] are initialized to -1.
  82765. */
  82766. case OP_Checkpoint: {
  82767. int i; /* Loop counter */
  82768. int aRes[3]; /* Results */
  82769. Mem *pMem; /* Write results here */
  82770. assert( p->readOnly==0 );
  82771. aRes[0] = 0;
  82772. aRes[1] = aRes[2] = -1;
  82773. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  82774. || pOp->p2==SQLITE_CHECKPOINT_FULL
  82775. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  82776. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  82777. );
  82778. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  82779. if( rc ){
  82780. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  82781. rc = SQLITE_OK;
  82782. aRes[0] = 1;
  82783. }
  82784. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  82785. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  82786. }
  82787. break;
  82788. };
  82789. #endif
  82790. #ifndef SQLITE_OMIT_PRAGMA
  82791. /* Opcode: JournalMode P1 P2 P3 * *
  82792. **
  82793. ** Change the journal mode of database P1 to P3. P3 must be one of the
  82794. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  82795. ** modes (delete, truncate, persist, off and memory), this is a simple
  82796. ** operation. No IO is required.
  82797. **
  82798. ** If changing into or out of WAL mode the procedure is more complicated.
  82799. **
  82800. ** Write a string containing the final journal-mode to register P2.
  82801. */
  82802. case OP_JournalMode: { /* out2 */
  82803. Btree *pBt; /* Btree to change journal mode of */
  82804. Pager *pPager; /* Pager associated with pBt */
  82805. int eNew; /* New journal mode */
  82806. int eOld; /* The old journal mode */
  82807. #ifndef SQLITE_OMIT_WAL
  82808. const char *zFilename; /* Name of database file for pPager */
  82809. #endif
  82810. pOut = out2Prerelease(p, pOp);
  82811. eNew = pOp->p3;
  82812. assert( eNew==PAGER_JOURNALMODE_DELETE
  82813. || eNew==PAGER_JOURNALMODE_TRUNCATE
  82814. || eNew==PAGER_JOURNALMODE_PERSIST
  82815. || eNew==PAGER_JOURNALMODE_OFF
  82816. || eNew==PAGER_JOURNALMODE_MEMORY
  82817. || eNew==PAGER_JOURNALMODE_WAL
  82818. || eNew==PAGER_JOURNALMODE_QUERY
  82819. );
  82820. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  82821. assert( p->readOnly==0 );
  82822. pBt = db->aDb[pOp->p1].pBt;
  82823. pPager = sqlite3BtreePager(pBt);
  82824. eOld = sqlite3PagerGetJournalMode(pPager);
  82825. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  82826. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  82827. #ifndef SQLITE_OMIT_WAL
  82828. zFilename = sqlite3PagerFilename(pPager, 1);
  82829. /* Do not allow a transition to journal_mode=WAL for a database
  82830. ** in temporary storage or if the VFS does not support shared memory
  82831. */
  82832. if( eNew==PAGER_JOURNALMODE_WAL
  82833. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  82834. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  82835. ){
  82836. eNew = eOld;
  82837. }
  82838. if( (eNew!=eOld)
  82839. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  82840. ){
  82841. if( !db->autoCommit || db->nVdbeRead>1 ){
  82842. rc = SQLITE_ERROR;
  82843. sqlite3VdbeError(p,
  82844. "cannot change %s wal mode from within a transaction",
  82845. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  82846. );
  82847. goto abort_due_to_error;
  82848. }else{
  82849. if( eOld==PAGER_JOURNALMODE_WAL ){
  82850. /* If leaving WAL mode, close the log file. If successful, the call
  82851. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  82852. ** file. An EXCLUSIVE lock may still be held on the database file
  82853. ** after a successful return.
  82854. */
  82855. rc = sqlite3PagerCloseWal(pPager, db);
  82856. if( rc==SQLITE_OK ){
  82857. sqlite3PagerSetJournalMode(pPager, eNew);
  82858. }
  82859. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  82860. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  82861. ** as an intermediate */
  82862. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  82863. }
  82864. /* Open a transaction on the database file. Regardless of the journal
  82865. ** mode, this transaction always uses a rollback journal.
  82866. */
  82867. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  82868. if( rc==SQLITE_OK ){
  82869. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  82870. }
  82871. }
  82872. }
  82873. #endif /* ifndef SQLITE_OMIT_WAL */
  82874. if( rc ) eNew = eOld;
  82875. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  82876. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  82877. pOut->z = (char *)sqlite3JournalModename(eNew);
  82878. pOut->n = sqlite3Strlen30(pOut->z);
  82879. pOut->enc = SQLITE_UTF8;
  82880. sqlite3VdbeChangeEncoding(pOut, encoding);
  82881. if( rc ) goto abort_due_to_error;
  82882. break;
  82883. };
  82884. #endif /* SQLITE_OMIT_PRAGMA */
  82885. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  82886. /* Opcode: Vacuum P1 * * * *
  82887. **
  82888. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  82889. ** for an attached database. The "temp" database may not be vacuumed.
  82890. */
  82891. case OP_Vacuum: {
  82892. assert( p->readOnly==0 );
  82893. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
  82894. if( rc ) goto abort_due_to_error;
  82895. break;
  82896. }
  82897. #endif
  82898. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  82899. /* Opcode: IncrVacuum P1 P2 * * *
  82900. **
  82901. ** Perform a single step of the incremental vacuum procedure on
  82902. ** the P1 database. If the vacuum has finished, jump to instruction
  82903. ** P2. Otherwise, fall through to the next instruction.
  82904. */
  82905. case OP_IncrVacuum: { /* jump */
  82906. Btree *pBt;
  82907. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  82908. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  82909. assert( p->readOnly==0 );
  82910. pBt = db->aDb[pOp->p1].pBt;
  82911. rc = sqlite3BtreeIncrVacuum(pBt);
  82912. VdbeBranchTaken(rc==SQLITE_DONE,2);
  82913. if( rc ){
  82914. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  82915. rc = SQLITE_OK;
  82916. goto jump_to_p2;
  82917. }
  82918. break;
  82919. }
  82920. #endif
  82921. /* Opcode: Expire P1 * * * *
  82922. **
  82923. ** Cause precompiled statements to expire. When an expired statement
  82924. ** is executed using sqlite3_step() it will either automatically
  82925. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  82926. ** or it will fail with SQLITE_SCHEMA.
  82927. **
  82928. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  82929. ** then only the currently executing statement is expired.
  82930. */
  82931. case OP_Expire: {
  82932. if( !pOp->p1 ){
  82933. sqlite3ExpirePreparedStatements(db);
  82934. }else{
  82935. p->expired = 1;
  82936. }
  82937. break;
  82938. }
  82939. #ifndef SQLITE_OMIT_SHARED_CACHE
  82940. /* Opcode: TableLock P1 P2 P3 P4 *
  82941. ** Synopsis: iDb=P1 root=P2 write=P3
  82942. **
  82943. ** Obtain a lock on a particular table. This instruction is only used when
  82944. ** the shared-cache feature is enabled.
  82945. **
  82946. ** P1 is the index of the database in sqlite3.aDb[] of the database
  82947. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  82948. ** a write lock if P3==1.
  82949. **
  82950. ** P2 contains the root-page of the table to lock.
  82951. **
  82952. ** P4 contains a pointer to the name of the table being locked. This is only
  82953. ** used to generate an error message if the lock cannot be obtained.
  82954. */
  82955. case OP_TableLock: {
  82956. u8 isWriteLock = (u8)pOp->p3;
  82957. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
  82958. int p1 = pOp->p1;
  82959. assert( p1>=0 && p1<db->nDb );
  82960. assert( DbMaskTest(p->btreeMask, p1) );
  82961. assert( isWriteLock==0 || isWriteLock==1 );
  82962. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  82963. if( rc ){
  82964. if( (rc&0xFF)==SQLITE_LOCKED ){
  82965. const char *z = pOp->p4.z;
  82966. sqlite3VdbeError(p, "database table is locked: %s", z);
  82967. }
  82968. goto abort_due_to_error;
  82969. }
  82970. }
  82971. break;
  82972. }
  82973. #endif /* SQLITE_OMIT_SHARED_CACHE */
  82974. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82975. /* Opcode: VBegin * * * P4 *
  82976. **
  82977. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  82978. ** xBegin method for that table.
  82979. **
  82980. ** Also, whether or not P4 is set, check that this is not being called from
  82981. ** within a callback to a virtual table xSync() method. If it is, the error
  82982. ** code will be set to SQLITE_LOCKED.
  82983. */
  82984. case OP_VBegin: {
  82985. VTable *pVTab;
  82986. pVTab = pOp->p4.pVtab;
  82987. rc = sqlite3VtabBegin(db, pVTab);
  82988. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  82989. if( rc ) goto abort_due_to_error;
  82990. break;
  82991. }
  82992. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82993. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82994. /* Opcode: VCreate P1 P2 * * *
  82995. **
  82996. ** P2 is a register that holds the name of a virtual table in database
  82997. ** P1. Call the xCreate method for that table.
  82998. */
  82999. case OP_VCreate: {
  83000. Mem sMem; /* For storing the record being decoded */
  83001. const char *zTab; /* Name of the virtual table */
  83002. memset(&sMem, 0, sizeof(sMem));
  83003. sMem.db = db;
  83004. /* Because P2 is always a static string, it is impossible for the
  83005. ** sqlite3VdbeMemCopy() to fail */
  83006. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  83007. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  83008. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  83009. assert( rc==SQLITE_OK );
  83010. zTab = (const char*)sqlite3_value_text(&sMem);
  83011. assert( zTab || db->mallocFailed );
  83012. if( zTab ){
  83013. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  83014. }
  83015. sqlite3VdbeMemRelease(&sMem);
  83016. if( rc ) goto abort_due_to_error;
  83017. break;
  83018. }
  83019. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83020. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83021. /* Opcode: VDestroy P1 * * P4 *
  83022. **
  83023. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  83024. ** of that table.
  83025. */
  83026. case OP_VDestroy: {
  83027. db->nVDestroy++;
  83028. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  83029. db->nVDestroy--;
  83030. if( rc ) goto abort_due_to_error;
  83031. break;
  83032. }
  83033. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83034. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83035. /* Opcode: VOpen P1 * * P4 *
  83036. **
  83037. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  83038. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  83039. ** table and stores that cursor in P1.
  83040. */
  83041. case OP_VOpen: {
  83042. VdbeCursor *pCur;
  83043. sqlite3_vtab_cursor *pVCur;
  83044. sqlite3_vtab *pVtab;
  83045. const sqlite3_module *pModule;
  83046. assert( p->bIsReader );
  83047. pCur = 0;
  83048. pVCur = 0;
  83049. pVtab = pOp->p4.pVtab->pVtab;
  83050. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  83051. rc = SQLITE_LOCKED;
  83052. goto abort_due_to_error;
  83053. }
  83054. pModule = pVtab->pModule;
  83055. rc = pModule->xOpen(pVtab, &pVCur);
  83056. sqlite3VtabImportErrmsg(p, pVtab);
  83057. if( rc ) goto abort_due_to_error;
  83058. /* Initialize sqlite3_vtab_cursor base class */
  83059. pVCur->pVtab = pVtab;
  83060. /* Initialize vdbe cursor object */
  83061. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  83062. if( pCur ){
  83063. pCur->uc.pVCur = pVCur;
  83064. pVtab->nRef++;
  83065. }else{
  83066. assert( db->mallocFailed );
  83067. pModule->xClose(pVCur);
  83068. goto no_mem;
  83069. }
  83070. break;
  83071. }
  83072. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83073. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83074. /* Opcode: VFilter P1 P2 P3 P4 *
  83075. ** Synopsis: iplan=r[P3] zplan='P4'
  83076. **
  83077. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  83078. ** the filtered result set is empty.
  83079. **
  83080. ** P4 is either NULL or a string that was generated by the xBestIndex
  83081. ** method of the module. The interpretation of the P4 string is left
  83082. ** to the module implementation.
  83083. **
  83084. ** This opcode invokes the xFilter method on the virtual table specified
  83085. ** by P1. The integer query plan parameter to xFilter is stored in register
  83086. ** P3. Register P3+1 stores the argc parameter to be passed to the
  83087. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  83088. ** additional parameters which are passed to
  83089. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  83090. **
  83091. ** A jump is made to P2 if the result set after filtering would be empty.
  83092. */
  83093. case OP_VFilter: { /* jump */
  83094. int nArg;
  83095. int iQuery;
  83096. const sqlite3_module *pModule;
  83097. Mem *pQuery;
  83098. Mem *pArgc;
  83099. sqlite3_vtab_cursor *pVCur;
  83100. sqlite3_vtab *pVtab;
  83101. VdbeCursor *pCur;
  83102. int res;
  83103. int i;
  83104. Mem **apArg;
  83105. pQuery = &aMem[pOp->p3];
  83106. pArgc = &pQuery[1];
  83107. pCur = p->apCsr[pOp->p1];
  83108. assert( memIsValid(pQuery) );
  83109. REGISTER_TRACE(pOp->p3, pQuery);
  83110. assert( pCur->eCurType==CURTYPE_VTAB );
  83111. pVCur = pCur->uc.pVCur;
  83112. pVtab = pVCur->pVtab;
  83113. pModule = pVtab->pModule;
  83114. /* Grab the index number and argc parameters */
  83115. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  83116. nArg = (int)pArgc->u.i;
  83117. iQuery = (int)pQuery->u.i;
  83118. /* Invoke the xFilter method */
  83119. res = 0;
  83120. apArg = p->apArg;
  83121. for(i = 0; i<nArg; i++){
  83122. apArg[i] = &pArgc[i+1];
  83123. }
  83124. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  83125. sqlite3VtabImportErrmsg(p, pVtab);
  83126. if( rc ) goto abort_due_to_error;
  83127. res = pModule->xEof(pVCur);
  83128. pCur->nullRow = 0;
  83129. VdbeBranchTaken(res!=0,2);
  83130. if( res ) goto jump_to_p2;
  83131. break;
  83132. }
  83133. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83134. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83135. /* Opcode: VColumn P1 P2 P3 * P5
  83136. ** Synopsis: r[P3]=vcolumn(P2)
  83137. **
  83138. ** Store in register P3 the value of the P2-th column of
  83139. ** the current row of the virtual-table of cursor P1.
  83140. **
  83141. ** If the VColumn opcode is being used to fetch the value of
  83142. ** an unchanging column during an UPDATE operation, then the P5
  83143. ** value is 1. Otherwise, P5 is 0. The P5 value is returned
  83144. ** by sqlite3_vtab_nochange() routine and can be used
  83145. ** by virtual table implementations to return special "no-change"
  83146. ** marks which can be more efficient, depending on the virtual table.
  83147. */
  83148. case OP_VColumn: {
  83149. sqlite3_vtab *pVtab;
  83150. const sqlite3_module *pModule;
  83151. Mem *pDest;
  83152. sqlite3_context sContext;
  83153. VdbeCursor *pCur = p->apCsr[pOp->p1];
  83154. assert( pCur->eCurType==CURTYPE_VTAB );
  83155. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  83156. pDest = &aMem[pOp->p3];
  83157. memAboutToChange(p, pDest);
  83158. if( pCur->nullRow ){
  83159. sqlite3VdbeMemSetNull(pDest);
  83160. break;
  83161. }
  83162. pVtab = pCur->uc.pVCur->pVtab;
  83163. pModule = pVtab->pModule;
  83164. assert( pModule->xColumn );
  83165. memset(&sContext, 0, sizeof(sContext));
  83166. sContext.pOut = pDest;
  83167. if( pOp->p5 ){
  83168. sqlite3VdbeMemSetNull(pDest);
  83169. pDest->flags = MEM_Null|MEM_Zero;
  83170. pDest->u.nZero = 0;
  83171. }else{
  83172. MemSetTypeFlag(pDest, MEM_Null);
  83173. }
  83174. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  83175. sqlite3VtabImportErrmsg(p, pVtab);
  83176. if( sContext.isError>0 ){
  83177. sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
  83178. rc = sContext.isError;
  83179. }
  83180. sqlite3VdbeChangeEncoding(pDest, encoding);
  83181. REGISTER_TRACE(pOp->p3, pDest);
  83182. UPDATE_MAX_BLOBSIZE(pDest);
  83183. if( sqlite3VdbeMemTooBig(pDest) ){
  83184. goto too_big;
  83185. }
  83186. if( rc ) goto abort_due_to_error;
  83187. break;
  83188. }
  83189. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83190. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83191. /* Opcode: VNext P1 P2 * * *
  83192. **
  83193. ** Advance virtual table P1 to the next row in its result set and
  83194. ** jump to instruction P2. Or, if the virtual table has reached
  83195. ** the end of its result set, then fall through to the next instruction.
  83196. */
  83197. case OP_VNext: { /* jump */
  83198. sqlite3_vtab *pVtab;
  83199. const sqlite3_module *pModule;
  83200. int res;
  83201. VdbeCursor *pCur;
  83202. res = 0;
  83203. pCur = p->apCsr[pOp->p1];
  83204. assert( pCur->eCurType==CURTYPE_VTAB );
  83205. if( pCur->nullRow ){
  83206. break;
  83207. }
  83208. pVtab = pCur->uc.pVCur->pVtab;
  83209. pModule = pVtab->pModule;
  83210. assert( pModule->xNext );
  83211. /* Invoke the xNext() method of the module. There is no way for the
  83212. ** underlying implementation to return an error if one occurs during
  83213. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  83214. ** data is available) and the error code returned when xColumn or
  83215. ** some other method is next invoked on the save virtual table cursor.
  83216. */
  83217. rc = pModule->xNext(pCur->uc.pVCur);
  83218. sqlite3VtabImportErrmsg(p, pVtab);
  83219. if( rc ) goto abort_due_to_error;
  83220. res = pModule->xEof(pCur->uc.pVCur);
  83221. VdbeBranchTaken(!res,2);
  83222. if( !res ){
  83223. /* If there is data, jump to P2 */
  83224. goto jump_to_p2_and_check_for_interrupt;
  83225. }
  83226. goto check_for_interrupt;
  83227. }
  83228. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83229. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83230. /* Opcode: VRename P1 * * P4 *
  83231. **
  83232. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  83233. ** This opcode invokes the corresponding xRename method. The value
  83234. ** in register P1 is passed as the zName argument to the xRename method.
  83235. */
  83236. case OP_VRename: {
  83237. sqlite3_vtab *pVtab;
  83238. Mem *pName;
  83239. pVtab = pOp->p4.pVtab->pVtab;
  83240. pName = &aMem[pOp->p1];
  83241. assert( pVtab->pModule->xRename );
  83242. assert( memIsValid(pName) );
  83243. assert( p->readOnly==0 );
  83244. REGISTER_TRACE(pOp->p1, pName);
  83245. assert( pName->flags & MEM_Str );
  83246. testcase( pName->enc==SQLITE_UTF8 );
  83247. testcase( pName->enc==SQLITE_UTF16BE );
  83248. testcase( pName->enc==SQLITE_UTF16LE );
  83249. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  83250. if( rc ) goto abort_due_to_error;
  83251. rc = pVtab->pModule->xRename(pVtab, pName->z);
  83252. sqlite3VtabImportErrmsg(p, pVtab);
  83253. p->expired = 0;
  83254. if( rc ) goto abort_due_to_error;
  83255. break;
  83256. }
  83257. #endif
  83258. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83259. /* Opcode: VUpdate P1 P2 P3 P4 P5
  83260. ** Synopsis: data=r[P3@P2]
  83261. **
  83262. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  83263. ** This opcode invokes the corresponding xUpdate method. P2 values
  83264. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  83265. ** invocation. The value in register (P3+P2-1) corresponds to the
  83266. ** p2th element of the argv array passed to xUpdate.
  83267. **
  83268. ** The xUpdate method will do a DELETE or an INSERT or both.
  83269. ** The argv[0] element (which corresponds to memory cell P3)
  83270. ** is the rowid of a row to delete. If argv[0] is NULL then no
  83271. ** deletion occurs. The argv[1] element is the rowid of the new
  83272. ** row. This can be NULL to have the virtual table select the new
  83273. ** rowid for itself. The subsequent elements in the array are
  83274. ** the values of columns in the new row.
  83275. **
  83276. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  83277. ** a row to delete.
  83278. **
  83279. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  83280. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  83281. ** is set to the value of the rowid for the row just inserted.
  83282. **
  83283. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  83284. ** apply in the case of a constraint failure on an insert or update.
  83285. */
  83286. case OP_VUpdate: {
  83287. sqlite3_vtab *pVtab;
  83288. const sqlite3_module *pModule;
  83289. int nArg;
  83290. int i;
  83291. sqlite_int64 rowid;
  83292. Mem **apArg;
  83293. Mem *pX;
  83294. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  83295. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  83296. );
  83297. assert( p->readOnly==0 );
  83298. sqlite3VdbeIncrWriteCounter(p, 0);
  83299. pVtab = pOp->p4.pVtab->pVtab;
  83300. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  83301. rc = SQLITE_LOCKED;
  83302. goto abort_due_to_error;
  83303. }
  83304. pModule = pVtab->pModule;
  83305. nArg = pOp->p2;
  83306. assert( pOp->p4type==P4_VTAB );
  83307. if( ALWAYS(pModule->xUpdate) ){
  83308. u8 vtabOnConflict = db->vtabOnConflict;
  83309. apArg = p->apArg;
  83310. pX = &aMem[pOp->p3];
  83311. for(i=0; i<nArg; i++){
  83312. assert( memIsValid(pX) );
  83313. memAboutToChange(p, pX);
  83314. apArg[i] = pX;
  83315. pX++;
  83316. }
  83317. db->vtabOnConflict = pOp->p5;
  83318. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  83319. db->vtabOnConflict = vtabOnConflict;
  83320. sqlite3VtabImportErrmsg(p, pVtab);
  83321. if( rc==SQLITE_OK && pOp->p1 ){
  83322. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  83323. db->lastRowid = rowid;
  83324. }
  83325. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  83326. if( pOp->p5==OE_Ignore ){
  83327. rc = SQLITE_OK;
  83328. }else{
  83329. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  83330. }
  83331. }else{
  83332. p->nChange++;
  83333. }
  83334. if( rc ) goto abort_due_to_error;
  83335. }
  83336. break;
  83337. }
  83338. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83339. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  83340. /* Opcode: Pagecount P1 P2 * * *
  83341. **
  83342. ** Write the current number of pages in database P1 to memory cell P2.
  83343. */
  83344. case OP_Pagecount: { /* out2 */
  83345. pOut = out2Prerelease(p, pOp);
  83346. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  83347. break;
  83348. }
  83349. #endif
  83350. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  83351. /* Opcode: MaxPgcnt P1 P2 P3 * *
  83352. **
  83353. ** Try to set the maximum page count for database P1 to the value in P3.
  83354. ** Do not let the maximum page count fall below the current page count and
  83355. ** do not change the maximum page count value if P3==0.
  83356. **
  83357. ** Store the maximum page count after the change in register P2.
  83358. */
  83359. case OP_MaxPgcnt: { /* out2 */
  83360. unsigned int newMax;
  83361. Btree *pBt;
  83362. pOut = out2Prerelease(p, pOp);
  83363. pBt = db->aDb[pOp->p1].pBt;
  83364. newMax = 0;
  83365. if( pOp->p3 ){
  83366. newMax = sqlite3BtreeLastPage(pBt);
  83367. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  83368. }
  83369. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  83370. break;
  83371. }
  83372. #endif
  83373. /* Opcode: Function0 P1 P2 P3 P4 P5
  83374. ** Synopsis: r[P3]=func(r[P2@P5])
  83375. **
  83376. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  83377. ** defines the function) with P5 arguments taken from register P2 and
  83378. ** successors. The result of the function is stored in register P3.
  83379. ** Register P3 must not be one of the function inputs.
  83380. **
  83381. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  83382. ** function was determined to be constant at compile time. If the first
  83383. ** argument was constant then bit 0 of P1 is set. This is used to determine
  83384. ** whether meta data associated with a user function argument using the
  83385. ** sqlite3_set_auxdata() API may be safely retained until the next
  83386. ** invocation of this opcode.
  83387. **
  83388. ** See also: Function, AggStep, AggFinal
  83389. */
  83390. /* Opcode: Function P1 P2 P3 P4 P5
  83391. ** Synopsis: r[P3]=func(r[P2@P5])
  83392. **
  83393. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  83394. ** contains a pointer to the function to be run) with P5 arguments taken
  83395. ** from register P2 and successors. The result of the function is stored
  83396. ** in register P3. Register P3 must not be one of the function inputs.
  83397. **
  83398. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  83399. ** function was determined to be constant at compile time. If the first
  83400. ** argument was constant then bit 0 of P1 is set. This is used to determine
  83401. ** whether meta data associated with a user function argument using the
  83402. ** sqlite3_set_auxdata() API may be safely retained until the next
  83403. ** invocation of this opcode.
  83404. **
  83405. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  83406. ** to a FuncDef object. But on first evaluation, the P4 operand is
  83407. ** automatically converted into an sqlite3_context object and the operation
  83408. ** changed to this OP_Function opcode. In this way, the initialization of
  83409. ** the sqlite3_context object occurs only once, rather than once for each
  83410. ** evaluation of the function.
  83411. **
  83412. ** See also: Function0, AggStep, AggFinal
  83413. */
  83414. case OP_PureFunc0:
  83415. case OP_Function0: {
  83416. int n;
  83417. sqlite3_context *pCtx;
  83418. assert( pOp->p4type==P4_FUNCDEF );
  83419. n = pOp->p5;
  83420. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  83421. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  83422. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  83423. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  83424. if( pCtx==0 ) goto no_mem;
  83425. pCtx->pOut = 0;
  83426. pCtx->pFunc = pOp->p4.pFunc;
  83427. pCtx->iOp = (int)(pOp - aOp);
  83428. pCtx->pVdbe = p;
  83429. pCtx->isError = 0;
  83430. pCtx->argc = n;
  83431. pOp->p4type = P4_FUNCCTX;
  83432. pOp->p4.pCtx = pCtx;
  83433. assert( OP_PureFunc == OP_PureFunc0+2 );
  83434. assert( OP_Function == OP_Function0+2 );
  83435. pOp->opcode += 2;
  83436. /* Fall through into OP_Function */
  83437. }
  83438. case OP_PureFunc:
  83439. case OP_Function: {
  83440. int i;
  83441. sqlite3_context *pCtx;
  83442. assert( pOp->p4type==P4_FUNCCTX );
  83443. pCtx = pOp->p4.pCtx;
  83444. /* If this function is inside of a trigger, the register array in aMem[]
  83445. ** might change from one evaluation to the next. The next block of code
  83446. ** checks to see if the register array has changed, and if so it
  83447. ** reinitializes the relavant parts of the sqlite3_context object */
  83448. pOut = &aMem[pOp->p3];
  83449. if( pCtx->pOut != pOut ){
  83450. pCtx->pOut = pOut;
  83451. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  83452. }
  83453. memAboutToChange(p, pOut);
  83454. #ifdef SQLITE_DEBUG
  83455. for(i=0; i<pCtx->argc; i++){
  83456. assert( memIsValid(pCtx->argv[i]) );
  83457. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  83458. }
  83459. #endif
  83460. MemSetTypeFlag(pOut, MEM_Null);
  83461. assert( pCtx->isError==0 );
  83462. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  83463. /* If the function returned an error, throw an exception */
  83464. if( pCtx->isError ){
  83465. if( pCtx->isError>0 ){
  83466. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  83467. rc = pCtx->isError;
  83468. }
  83469. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  83470. pCtx->isError = 0;
  83471. if( rc ) goto abort_due_to_error;
  83472. }
  83473. /* Copy the result of the function into register P3 */
  83474. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  83475. sqlite3VdbeChangeEncoding(pOut, encoding);
  83476. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  83477. }
  83478. REGISTER_TRACE(pOp->p3, pOut);
  83479. UPDATE_MAX_BLOBSIZE(pOut);
  83480. break;
  83481. }
  83482. /* Opcode: Trace P1 P2 * P4 *
  83483. **
  83484. ** Write P4 on the statement trace output if statement tracing is
  83485. ** enabled.
  83486. **
  83487. ** Operand P1 must be 0x7fffffff and P2 must positive.
  83488. */
  83489. /* Opcode: Init P1 P2 P3 P4 *
  83490. ** Synopsis: Start at P2
  83491. **
  83492. ** Programs contain a single instance of this opcode as the very first
  83493. ** opcode.
  83494. **
  83495. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  83496. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  83497. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  83498. **
  83499. ** If P2 is not zero, jump to instruction P2.
  83500. **
  83501. ** Increment the value of P1 so that OP_Once opcodes will jump the
  83502. ** first time they are evaluated for this run.
  83503. **
  83504. ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
  83505. ** error is encountered.
  83506. */
  83507. case OP_Trace:
  83508. case OP_Init: { /* jump */
  83509. int i;
  83510. #ifndef SQLITE_OMIT_TRACE
  83511. char *zTrace;
  83512. #endif
  83513. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  83514. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  83515. **
  83516. ** This assert() provides evidence for:
  83517. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  83518. ** would have been returned by the legacy sqlite3_trace() interface by
  83519. ** using the X argument when X begins with "--" and invoking
  83520. ** sqlite3_expanded_sql(P) otherwise.
  83521. */
  83522. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  83523. /* OP_Init is always instruction 0 */
  83524. assert( pOp==p->aOp || pOp->opcode==OP_Trace );
  83525. #ifndef SQLITE_OMIT_TRACE
  83526. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  83527. && !p->doingRerun
  83528. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  83529. ){
  83530. #ifndef SQLITE_OMIT_DEPRECATED
  83531. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  83532. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  83533. char *z = sqlite3VdbeExpandSql(p, zTrace);
  83534. x(db->pTraceArg, z);
  83535. sqlite3_free(z);
  83536. }else
  83537. #endif
  83538. if( db->nVdbeExec>1 ){
  83539. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  83540. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  83541. sqlite3DbFree(db, z);
  83542. }else{
  83543. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  83544. }
  83545. }
  83546. #ifdef SQLITE_USE_FCNTL_TRACE
  83547. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  83548. if( zTrace ){
  83549. int j;
  83550. for(j=0; j<db->nDb; j++){
  83551. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  83552. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  83553. }
  83554. }
  83555. #endif /* SQLITE_USE_FCNTL_TRACE */
  83556. #ifdef SQLITE_DEBUG
  83557. if( (db->flags & SQLITE_SqlTrace)!=0
  83558. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  83559. ){
  83560. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  83561. }
  83562. #endif /* SQLITE_DEBUG */
  83563. #endif /* SQLITE_OMIT_TRACE */
  83564. assert( pOp->p2>0 );
  83565. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  83566. if( pOp->opcode==OP_Trace ) break;
  83567. for(i=1; i<p->nOp; i++){
  83568. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  83569. }
  83570. pOp->p1 = 0;
  83571. }
  83572. pOp->p1++;
  83573. p->aCounter[SQLITE_STMTSTATUS_RUN]++;
  83574. goto jump_to_p2;
  83575. }
  83576. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  83577. /* Opcode: CursorHint P1 * * P4 *
  83578. **
  83579. ** Provide a hint to cursor P1 that it only needs to return rows that
  83580. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  83581. ** to values currently held in registers. TK_COLUMN terms in the P4
  83582. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  83583. */
  83584. case OP_CursorHint: {
  83585. VdbeCursor *pC;
  83586. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83587. assert( pOp->p4type==P4_EXPR );
  83588. pC = p->apCsr[pOp->p1];
  83589. if( pC ){
  83590. assert( pC->eCurType==CURTYPE_BTREE );
  83591. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  83592. pOp->p4.pExpr, aMem);
  83593. }
  83594. break;
  83595. }
  83596. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  83597. #ifdef SQLITE_DEBUG
  83598. /* Opcode: Abortable * * * * *
  83599. **
  83600. ** Verify that an Abort can happen. Assert if an Abort at this point
  83601. ** might cause database corruption. This opcode only appears in debugging
  83602. ** builds.
  83603. **
  83604. ** An Abort is safe if either there have been no writes, or if there is
  83605. ** an active statement journal.
  83606. */
  83607. case OP_Abortable: {
  83608. sqlite3VdbeAssertAbortable(p);
  83609. break;
  83610. }
  83611. #endif
  83612. /* Opcode: Noop * * * * *
  83613. **
  83614. ** Do nothing. This instruction is often useful as a jump
  83615. ** destination.
  83616. */
  83617. /*
  83618. ** The magic Explain opcode are only inserted when explain==2 (which
  83619. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  83620. ** This opcode records information from the optimizer. It is the
  83621. ** the same as a no-op. This opcodesnever appears in a real VM program.
  83622. */
  83623. default: { /* This is really OP_Noop, OP_Explain */
  83624. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  83625. break;
  83626. }
  83627. /*****************************************************************************
  83628. ** The cases of the switch statement above this line should all be indented
  83629. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  83630. ** readability. From this point on down, the normal indentation rules are
  83631. ** restored.
  83632. *****************************************************************************/
  83633. }
  83634. #ifdef VDBE_PROFILE
  83635. {
  83636. u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  83637. if( endTime>start ) pOrigOp->cycles += endTime - start;
  83638. pOrigOp->cnt++;
  83639. }
  83640. #endif
  83641. /* The following code adds nothing to the actual functionality
  83642. ** of the program. It is only here for testing and debugging.
  83643. ** On the other hand, it does burn CPU cycles every time through
  83644. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  83645. */
  83646. #ifndef NDEBUG
  83647. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  83648. #ifdef SQLITE_DEBUG
  83649. if( db->flags & SQLITE_VdbeTrace ){
  83650. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  83651. if( rc!=0 ) printf("rc=%d\n",rc);
  83652. if( opProperty & (OPFLG_OUT2) ){
  83653. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  83654. }
  83655. if( opProperty & OPFLG_OUT3 ){
  83656. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  83657. }
  83658. }
  83659. #endif /* SQLITE_DEBUG */
  83660. #endif /* NDEBUG */
  83661. } /* The end of the for(;;) loop the loops through opcodes */
  83662. /* If we reach this point, it means that execution is finished with
  83663. ** an error of some kind.
  83664. */
  83665. abort_due_to_error:
  83666. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  83667. assert( rc );
  83668. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  83669. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  83670. }
  83671. p->rc = rc;
  83672. sqlite3SystemError(db, rc);
  83673. testcase( sqlite3GlobalConfig.xLog!=0 );
  83674. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  83675. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  83676. sqlite3VdbeHalt(p);
  83677. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  83678. rc = SQLITE_ERROR;
  83679. if( resetSchemaOnFault>0 ){
  83680. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  83681. }
  83682. /* This is the only way out of this procedure. We have to
  83683. ** release the mutexes on btrees that were acquired at the
  83684. ** top. */
  83685. vdbe_return:
  83686. testcase( nVmStep>0 );
  83687. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  83688. sqlite3VdbeLeave(p);
  83689. assert( rc!=SQLITE_OK || nExtraDelete==0
  83690. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  83691. );
  83692. return rc;
  83693. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  83694. ** is encountered.
  83695. */
  83696. too_big:
  83697. sqlite3VdbeError(p, "string or blob too big");
  83698. rc = SQLITE_TOOBIG;
  83699. goto abort_due_to_error;
  83700. /* Jump to here if a malloc() fails.
  83701. */
  83702. no_mem:
  83703. sqlite3OomFault(db);
  83704. sqlite3VdbeError(p, "out of memory");
  83705. rc = SQLITE_NOMEM_BKPT;
  83706. goto abort_due_to_error;
  83707. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  83708. ** flag.
  83709. */
  83710. abort_due_to_interrupt:
  83711. assert( db->u1.isInterrupted );
  83712. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  83713. p->rc = rc;
  83714. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  83715. goto abort_due_to_error;
  83716. }
  83717. /************** End of vdbe.c ************************************************/
  83718. /************** Begin file vdbeblob.c ****************************************/
  83719. /*
  83720. ** 2007 May 1
  83721. **
  83722. ** The author disclaims copyright to this source code. In place of
  83723. ** a legal notice, here is a blessing:
  83724. **
  83725. ** May you do good and not evil.
  83726. ** May you find forgiveness for yourself and forgive others.
  83727. ** May you share freely, never taking more than you give.
  83728. **
  83729. *************************************************************************
  83730. **
  83731. ** This file contains code used to implement incremental BLOB I/O.
  83732. */
  83733. /* #include "sqliteInt.h" */
  83734. /* #include "vdbeInt.h" */
  83735. #ifndef SQLITE_OMIT_INCRBLOB
  83736. /*
  83737. ** Valid sqlite3_blob* handles point to Incrblob structures.
  83738. */
  83739. typedef struct Incrblob Incrblob;
  83740. struct Incrblob {
  83741. int nByte; /* Size of open blob, in bytes */
  83742. int iOffset; /* Byte offset of blob in cursor data */
  83743. u16 iCol; /* Table column this handle is open on */
  83744. BtCursor *pCsr; /* Cursor pointing at blob row */
  83745. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  83746. sqlite3 *db; /* The associated database */
  83747. char *zDb; /* Database name */
  83748. Table *pTab; /* Table object */
  83749. };
  83750. /*
  83751. ** This function is used by both blob_open() and blob_reopen(). It seeks
  83752. ** the b-tree cursor associated with blob handle p to point to row iRow.
  83753. ** If successful, SQLITE_OK is returned and subsequent calls to
  83754. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  83755. **
  83756. ** If an error occurs, or if the specified row does not exist or does not
  83757. ** contain a value of type TEXT or BLOB in the column nominated when the
  83758. ** blob handle was opened, then an error code is returned and *pzErr may
  83759. ** be set to point to a buffer containing an error message. It is the
  83760. ** responsibility of the caller to free the error message buffer using
  83761. ** sqlite3DbFree().
  83762. **
  83763. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  83764. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  83765. ** immediately return SQLITE_ABORT.
  83766. */
  83767. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  83768. int rc; /* Error code */
  83769. char *zErr = 0; /* Error message */
  83770. Vdbe *v = (Vdbe *)p->pStmt;
  83771. /* Set the value of register r[1] in the SQL statement to integer iRow.
  83772. ** This is done directly as a performance optimization
  83773. */
  83774. v->aMem[1].flags = MEM_Int;
  83775. v->aMem[1].u.i = iRow;
  83776. /* If the statement has been run before (and is paused at the OP_ResultRow)
  83777. ** then back it up to the point where it does the OP_NotExists. This could
  83778. ** have been down with an extra OP_Goto, but simply setting the program
  83779. ** counter is faster. */
  83780. if( v->pc>4 ){
  83781. v->pc = 4;
  83782. assert( v->aOp[v->pc].opcode==OP_NotExists );
  83783. rc = sqlite3VdbeExec(v);
  83784. }else{
  83785. rc = sqlite3_step(p->pStmt);
  83786. }
  83787. if( rc==SQLITE_ROW ){
  83788. VdbeCursor *pC = v->apCsr[0];
  83789. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  83790. testcase( pC->nHdrParsed==p->iCol );
  83791. testcase( pC->nHdrParsed==p->iCol+1 );
  83792. if( type<12 ){
  83793. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  83794. type==0?"null": type==7?"real": "integer"
  83795. );
  83796. rc = SQLITE_ERROR;
  83797. sqlite3_finalize(p->pStmt);
  83798. p->pStmt = 0;
  83799. }else{
  83800. p->iOffset = pC->aType[p->iCol + pC->nField];
  83801. p->nByte = sqlite3VdbeSerialTypeLen(type);
  83802. p->pCsr = pC->uc.pCursor;
  83803. sqlite3BtreeIncrblobCursor(p->pCsr);
  83804. }
  83805. }
  83806. if( rc==SQLITE_ROW ){
  83807. rc = SQLITE_OK;
  83808. }else if( p->pStmt ){
  83809. rc = sqlite3_finalize(p->pStmt);
  83810. p->pStmt = 0;
  83811. if( rc==SQLITE_OK ){
  83812. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  83813. rc = SQLITE_ERROR;
  83814. }else{
  83815. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  83816. }
  83817. }
  83818. assert( rc!=SQLITE_OK || zErr==0 );
  83819. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  83820. *pzErr = zErr;
  83821. return rc;
  83822. }
  83823. /*
  83824. ** Open a blob handle.
  83825. */
  83826. SQLITE_API int sqlite3_blob_open(
  83827. sqlite3* db, /* The database connection */
  83828. const char *zDb, /* The attached database containing the blob */
  83829. const char *zTable, /* The table containing the blob */
  83830. const char *zColumn, /* The column containing the blob */
  83831. sqlite_int64 iRow, /* The row containing the glob */
  83832. int wrFlag, /* True -> read/write access, false -> read-only */
  83833. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  83834. ){
  83835. int nAttempt = 0;
  83836. int iCol; /* Index of zColumn in row-record */
  83837. int rc = SQLITE_OK;
  83838. char *zErr = 0;
  83839. Table *pTab;
  83840. Incrblob *pBlob = 0;
  83841. Parse sParse;
  83842. #ifdef SQLITE_ENABLE_API_ARMOR
  83843. if( ppBlob==0 ){
  83844. return SQLITE_MISUSE_BKPT;
  83845. }
  83846. #endif
  83847. *ppBlob = 0;
  83848. #ifdef SQLITE_ENABLE_API_ARMOR
  83849. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  83850. return SQLITE_MISUSE_BKPT;
  83851. }
  83852. #endif
  83853. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  83854. sqlite3_mutex_enter(db->mutex);
  83855. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  83856. do {
  83857. memset(&sParse, 0, sizeof(Parse));
  83858. if( !pBlob ) goto blob_open_out;
  83859. sParse.db = db;
  83860. sqlite3DbFree(db, zErr);
  83861. zErr = 0;
  83862. sqlite3BtreeEnterAll(db);
  83863. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  83864. if( pTab && IsVirtual(pTab) ){
  83865. pTab = 0;
  83866. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  83867. }
  83868. if( pTab && !HasRowid(pTab) ){
  83869. pTab = 0;
  83870. sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
  83871. }
  83872. #ifndef SQLITE_OMIT_VIEW
  83873. if( pTab && pTab->pSelect ){
  83874. pTab = 0;
  83875. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  83876. }
  83877. #endif
  83878. if( !pTab ){
  83879. if( sParse.zErrMsg ){
  83880. sqlite3DbFree(db, zErr);
  83881. zErr = sParse.zErrMsg;
  83882. sParse.zErrMsg = 0;
  83883. }
  83884. rc = SQLITE_ERROR;
  83885. sqlite3BtreeLeaveAll(db);
  83886. goto blob_open_out;
  83887. }
  83888. pBlob->pTab = pTab;
  83889. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  83890. /* Now search pTab for the exact column. */
  83891. for(iCol=0; iCol<pTab->nCol; iCol++) {
  83892. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  83893. break;
  83894. }
  83895. }
  83896. if( iCol==pTab->nCol ){
  83897. sqlite3DbFree(db, zErr);
  83898. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  83899. rc = SQLITE_ERROR;
  83900. sqlite3BtreeLeaveAll(db);
  83901. goto blob_open_out;
  83902. }
  83903. /* If the value is being opened for writing, check that the
  83904. ** column is not indexed, and that it is not part of a foreign key.
  83905. */
  83906. if( wrFlag ){
  83907. const char *zFault = 0;
  83908. Index *pIdx;
  83909. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83910. if( db->flags&SQLITE_ForeignKeys ){
  83911. /* Check that the column is not part of an FK child key definition. It
  83912. ** is not necessary to check if it is part of a parent key, as parent
  83913. ** key columns must be indexed. The check below will pick up this
  83914. ** case. */
  83915. FKey *pFKey;
  83916. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  83917. int j;
  83918. for(j=0; j<pFKey->nCol; j++){
  83919. if( pFKey->aCol[j].iFrom==iCol ){
  83920. zFault = "foreign key";
  83921. }
  83922. }
  83923. }
  83924. }
  83925. #endif
  83926. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83927. int j;
  83928. for(j=0; j<pIdx->nKeyCol; j++){
  83929. /* FIXME: Be smarter about indexes that use expressions */
  83930. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  83931. zFault = "indexed";
  83932. }
  83933. }
  83934. }
  83935. if( zFault ){
  83936. sqlite3DbFree(db, zErr);
  83937. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  83938. rc = SQLITE_ERROR;
  83939. sqlite3BtreeLeaveAll(db);
  83940. goto blob_open_out;
  83941. }
  83942. }
  83943. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
  83944. assert( pBlob->pStmt || db->mallocFailed );
  83945. if( pBlob->pStmt ){
  83946. /* This VDBE program seeks a btree cursor to the identified
  83947. ** db/table/row entry. The reason for using a vdbe program instead
  83948. ** of writing code to use the b-tree layer directly is that the
  83949. ** vdbe program will take advantage of the various transaction,
  83950. ** locking and error handling infrastructure built into the vdbe.
  83951. **
  83952. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  83953. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  83954. ** uses it to implement the blob_read(), blob_write() and
  83955. ** blob_bytes() functions.
  83956. **
  83957. ** The sqlite3_blob_close() function finalizes the vdbe program,
  83958. ** which closes the b-tree cursor and (possibly) commits the
  83959. ** transaction.
  83960. */
  83961. static const int iLn = VDBE_OFFSET_LINENO(2);
  83962. static const VdbeOpList openBlob[] = {
  83963. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  83964. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  83965. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  83966. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  83967. {OP_Column, 0, 0, 1}, /* 3 */
  83968. {OP_ResultRow, 1, 0, 0}, /* 4 */
  83969. {OP_Halt, 0, 0, 0}, /* 5 */
  83970. };
  83971. Vdbe *v = (Vdbe *)pBlob->pStmt;
  83972. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83973. VdbeOp *aOp;
  83974. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  83975. pTab->pSchema->schema_cookie,
  83976. pTab->pSchema->iGeneration);
  83977. sqlite3VdbeChangeP5(v, 1);
  83978. assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
  83979. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  83980. /* Make sure a mutex is held on the table to be accessed */
  83981. sqlite3VdbeUsesBtree(v, iDb);
  83982. if( db->mallocFailed==0 ){
  83983. assert( aOp!=0 );
  83984. /* Configure the OP_TableLock instruction */
  83985. #ifdef SQLITE_OMIT_SHARED_CACHE
  83986. aOp[0].opcode = OP_Noop;
  83987. #else
  83988. aOp[0].p1 = iDb;
  83989. aOp[0].p2 = pTab->tnum;
  83990. aOp[0].p3 = wrFlag;
  83991. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  83992. }
  83993. if( db->mallocFailed==0 ){
  83994. #endif
  83995. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  83996. ** parameter of the other to pTab->tnum. */
  83997. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  83998. aOp[1].p2 = pTab->tnum;
  83999. aOp[1].p3 = iDb;
  84000. /* Configure the number of columns. Configure the cursor to
  84001. ** think that the table has one more column than it really
  84002. ** does. An OP_Column to retrieve this imaginary column will
  84003. ** always return an SQL NULL. This is useful because it means
  84004. ** we can invoke OP_Column to fill in the vdbe cursors type
  84005. ** and offset cache without causing any IO.
  84006. */
  84007. aOp[1].p4type = P4_INT32;
  84008. aOp[1].p4.i = pTab->nCol+1;
  84009. aOp[3].p2 = pTab->nCol;
  84010. sParse.nVar = 0;
  84011. sParse.nMem = 1;
  84012. sParse.nTab = 1;
  84013. sqlite3VdbeMakeReady(v, &sParse);
  84014. }
  84015. }
  84016. pBlob->iCol = iCol;
  84017. pBlob->db = db;
  84018. sqlite3BtreeLeaveAll(db);
  84019. if( db->mallocFailed ){
  84020. goto blob_open_out;
  84021. }
  84022. rc = blobSeekToRow(pBlob, iRow, &zErr);
  84023. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  84024. blob_open_out:
  84025. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  84026. *ppBlob = (sqlite3_blob *)pBlob;
  84027. }else{
  84028. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  84029. sqlite3DbFree(db, pBlob);
  84030. }
  84031. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  84032. sqlite3DbFree(db, zErr);
  84033. sqlite3ParserReset(&sParse);
  84034. rc = sqlite3ApiExit(db, rc);
  84035. sqlite3_mutex_leave(db->mutex);
  84036. return rc;
  84037. }
  84038. /*
  84039. ** Close a blob handle that was previously created using
  84040. ** sqlite3_blob_open().
  84041. */
  84042. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  84043. Incrblob *p = (Incrblob *)pBlob;
  84044. int rc;
  84045. sqlite3 *db;
  84046. if( p ){
  84047. db = p->db;
  84048. sqlite3_mutex_enter(db->mutex);
  84049. rc = sqlite3_finalize(p->pStmt);
  84050. sqlite3DbFree(db, p);
  84051. sqlite3_mutex_leave(db->mutex);
  84052. }else{
  84053. rc = SQLITE_OK;
  84054. }
  84055. return rc;
  84056. }
  84057. /*
  84058. ** Perform a read or write operation on a blob
  84059. */
  84060. static int blobReadWrite(
  84061. sqlite3_blob *pBlob,
  84062. void *z,
  84063. int n,
  84064. int iOffset,
  84065. int (*xCall)(BtCursor*, u32, u32, void*)
  84066. ){
  84067. int rc;
  84068. Incrblob *p = (Incrblob *)pBlob;
  84069. Vdbe *v;
  84070. sqlite3 *db;
  84071. if( p==0 ) return SQLITE_MISUSE_BKPT;
  84072. db = p->db;
  84073. sqlite3_mutex_enter(db->mutex);
  84074. v = (Vdbe*)p->pStmt;
  84075. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  84076. /* Request is out of range. Return a transient error. */
  84077. rc = SQLITE_ERROR;
  84078. }else if( v==0 ){
  84079. /* If there is no statement handle, then the blob-handle has
  84080. ** already been invalidated. Return SQLITE_ABORT in this case.
  84081. */
  84082. rc = SQLITE_ABORT;
  84083. }else{
  84084. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  84085. ** returned, clean-up the statement handle.
  84086. */
  84087. assert( db == v->db );
  84088. sqlite3BtreeEnterCursor(p->pCsr);
  84089. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  84090. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  84091. /* If a pre-update hook is registered and this is a write cursor,
  84092. ** invoke it here.
  84093. **
  84094. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  84095. ** operation should really be an SQLITE_UPDATE. This is probably
  84096. ** incorrect, but is convenient because at this point the new.* values
  84097. ** are not easily obtainable. And for the sessions module, an
  84098. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  84099. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  84100. ** slightly more efficient). Since you cannot write to a PK column
  84101. ** using the incremental-blob API, this works. For the sessions module
  84102. ** anyhow.
  84103. */
  84104. sqlite3_int64 iKey;
  84105. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  84106. sqlite3VdbePreUpdateHook(
  84107. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  84108. );
  84109. }
  84110. #endif
  84111. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  84112. sqlite3BtreeLeaveCursor(p->pCsr);
  84113. if( rc==SQLITE_ABORT ){
  84114. sqlite3VdbeFinalize(v);
  84115. p->pStmt = 0;
  84116. }else{
  84117. v->rc = rc;
  84118. }
  84119. }
  84120. sqlite3Error(db, rc);
  84121. rc = sqlite3ApiExit(db, rc);
  84122. sqlite3_mutex_leave(db->mutex);
  84123. return rc;
  84124. }
  84125. /*
  84126. ** Read data from a blob handle.
  84127. */
  84128. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  84129. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  84130. }
  84131. /*
  84132. ** Write data to a blob handle.
  84133. */
  84134. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  84135. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  84136. }
  84137. /*
  84138. ** Query a blob handle for the size of the data.
  84139. **
  84140. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  84141. ** so no mutex is required for access.
  84142. */
  84143. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  84144. Incrblob *p = (Incrblob *)pBlob;
  84145. return (p && p->pStmt) ? p->nByte : 0;
  84146. }
  84147. /*
  84148. ** Move an existing blob handle to point to a different row of the same
  84149. ** database table.
  84150. **
  84151. ** If an error occurs, or if the specified row does not exist or does not
  84152. ** contain a blob or text value, then an error code is returned and the
  84153. ** database handle error code and message set. If this happens, then all
  84154. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  84155. ** immediately return SQLITE_ABORT.
  84156. */
  84157. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  84158. int rc;
  84159. Incrblob *p = (Incrblob *)pBlob;
  84160. sqlite3 *db;
  84161. if( p==0 ) return SQLITE_MISUSE_BKPT;
  84162. db = p->db;
  84163. sqlite3_mutex_enter(db->mutex);
  84164. if( p->pStmt==0 ){
  84165. /* If there is no statement handle, then the blob-handle has
  84166. ** already been invalidated. Return SQLITE_ABORT in this case.
  84167. */
  84168. rc = SQLITE_ABORT;
  84169. }else{
  84170. char *zErr;
  84171. rc = blobSeekToRow(p, iRow, &zErr);
  84172. if( rc!=SQLITE_OK ){
  84173. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  84174. sqlite3DbFree(db, zErr);
  84175. }
  84176. assert( rc!=SQLITE_SCHEMA );
  84177. }
  84178. rc = sqlite3ApiExit(db, rc);
  84179. assert( rc==SQLITE_OK || p->pStmt==0 );
  84180. sqlite3_mutex_leave(db->mutex);
  84181. return rc;
  84182. }
  84183. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  84184. /************** End of vdbeblob.c ********************************************/
  84185. /************** Begin file vdbesort.c ****************************************/
  84186. /*
  84187. ** 2011-07-09
  84188. **
  84189. ** The author disclaims copyright to this source code. In place of
  84190. ** a legal notice, here is a blessing:
  84191. **
  84192. ** May you do good and not evil.
  84193. ** May you find forgiveness for yourself and forgive others.
  84194. ** May you share freely, never taking more than you give.
  84195. **
  84196. *************************************************************************
  84197. ** This file contains code for the VdbeSorter object, used in concert with
  84198. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  84199. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  84200. ** using indexes and without LIMIT clauses.
  84201. **
  84202. ** The VdbeSorter object implements a multi-threaded external merge sort
  84203. ** algorithm that is efficient even if the number of elements being sorted
  84204. ** exceeds the available memory.
  84205. **
  84206. ** Here is the (internal, non-API) interface between this module and the
  84207. ** rest of the SQLite system:
  84208. **
  84209. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  84210. **
  84211. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  84212. ** object. The row is a binary blob in the
  84213. ** OP_MakeRecord format that contains both
  84214. ** the ORDER BY key columns and result columns
  84215. ** in the case of a SELECT w/ ORDER BY, or
  84216. ** the complete record for an index entry
  84217. ** in the case of a CREATE INDEX.
  84218. **
  84219. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  84220. ** Position the read cursor on the
  84221. ** first sorted element.
  84222. **
  84223. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  84224. ** element.
  84225. **
  84226. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  84227. ** row currently under the read cursor.
  84228. **
  84229. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  84230. ** currently under the read cursor against
  84231. ** another binary blob X and report if
  84232. ** X is strictly less than the read cursor.
  84233. ** Used to enforce uniqueness in a
  84234. ** CREATE UNIQUE INDEX statement.
  84235. **
  84236. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  84237. ** all resources.
  84238. **
  84239. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  84240. ** is like Close() followed by Init() only
  84241. ** much faster.
  84242. **
  84243. ** The interfaces above must be called in a particular order. Write() can
  84244. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  84245. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  84246. **
  84247. ** Init()
  84248. ** for each record: Write()
  84249. ** Rewind()
  84250. ** Rowkey()/Compare()
  84251. ** Next()
  84252. ** Close()
  84253. **
  84254. ** Algorithm:
  84255. **
  84256. ** Records passed to the sorter via calls to Write() are initially held
  84257. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  84258. ** a threshold, when Rewind() is called the set of records is sorted using
  84259. ** an in-memory merge sort. In this case, no temporary files are required
  84260. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  84261. ** directly from main memory.
  84262. **
  84263. ** If the amount of space used to store records in main memory exceeds the
  84264. ** threshold, then the set of records currently in memory are sorted and
  84265. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  84266. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  84267. ** of PMAs may be created by merging existing PMAs together - for example
  84268. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  84269. **
  84270. ** The threshold for the amount of main memory to use before flushing
  84271. ** records to a PMA is roughly the same as the limit configured for the
  84272. ** page-cache of the main database. Specifically, the threshold is set to
  84273. ** the value returned by "PRAGMA main.page_size" multipled by
  84274. ** that returned by "PRAGMA main.cache_size", in bytes.
  84275. **
  84276. ** If the sorter is running in single-threaded mode, then all PMAs generated
  84277. ** are appended to a single temporary file. Or, if the sorter is running in
  84278. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  84279. ** N is the configured number of worker threads. In this case, instead of
  84280. ** sorting the records and writing the PMA to a temporary file itself, the
  84281. ** calling thread usually launches a worker thread to do so. Except, if
  84282. ** there are already N worker threads running, the main thread does the work
  84283. ** itself.
  84284. **
  84285. ** The sorter is running in multi-threaded mode if (a) the library was built
  84286. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  84287. ** than zero, and (b) worker threads have been enabled at runtime by calling
  84288. ** "PRAGMA threads=N" with some value of N greater than 0.
  84289. **
  84290. ** When Rewind() is called, any data remaining in memory is flushed to a
  84291. ** final PMA. So at this point the data is stored in some number of sorted
  84292. ** PMAs within temporary files on disk.
  84293. **
  84294. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  84295. ** sorter is running in single-threaded mode, then these PMAs are merged
  84296. ** incrementally as keys are retreived from the sorter by the VDBE. The
  84297. ** MergeEngine object, described in further detail below, performs this
  84298. ** merge.
  84299. **
  84300. ** Or, if running in multi-threaded mode, then a background thread is
  84301. ** launched to merge the existing PMAs. Once the background thread has
  84302. ** merged T bytes of data into a single sorted PMA, the main thread
  84303. ** begins reading keys from that PMA while the background thread proceeds
  84304. ** with merging the next T bytes of data. And so on.
  84305. **
  84306. ** Parameter T is set to half the value of the memory threshold used
  84307. ** by Write() above to determine when to create a new PMA.
  84308. **
  84309. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  84310. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  84311. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  84312. ** disk are merged together. Then T bytes of data from the second set, and
  84313. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  84314. ** PMAs at a time. This done is to improve locality.
  84315. **
  84316. ** If running in multi-threaded mode and there are more than
  84317. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  84318. ** than one background thread may be created. Specifically, there may be
  84319. ** one background thread for each temporary file on disk, and one background
  84320. ** thread to merge the output of each of the others to a single PMA for
  84321. ** the main thread to read from.
  84322. */
  84323. /* #include "sqliteInt.h" */
  84324. /* #include "vdbeInt.h" */
  84325. /*
  84326. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  84327. ** messages to stderr that may be helpful in understanding the performance
  84328. ** characteristics of the sorter in multi-threaded mode.
  84329. */
  84330. #if 0
  84331. # define SQLITE_DEBUG_SORTER_THREADS 1
  84332. #endif
  84333. /*
  84334. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  84335. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  84336. ** overflows. 512MiB.
  84337. */
  84338. #define SQLITE_MAX_PMASZ (1<<29)
  84339. /*
  84340. ** Private objects used by the sorter
  84341. */
  84342. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  84343. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  84344. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  84345. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  84346. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  84347. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  84348. typedef struct SorterList SorterList; /* In-memory list of records */
  84349. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  84350. /*
  84351. ** A container for a temp file handle and the current amount of data
  84352. ** stored in the file.
  84353. */
  84354. struct SorterFile {
  84355. sqlite3_file *pFd; /* File handle */
  84356. i64 iEof; /* Bytes of data stored in pFd */
  84357. };
  84358. /*
  84359. ** An in-memory list of objects to be sorted.
  84360. **
  84361. ** If aMemory==0 then each object is allocated separately and the objects
  84362. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  84363. ** are stored in the aMemory[] bulk memory, one right after the other, and
  84364. ** are connected using SorterRecord.u.iNext.
  84365. */
  84366. struct SorterList {
  84367. SorterRecord *pList; /* Linked list of records */
  84368. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  84369. int szPMA; /* Size of pList as PMA in bytes */
  84370. };
  84371. /*
  84372. ** The MergeEngine object is used to combine two or more smaller PMAs into
  84373. ** one big PMA using a merge operation. Separate PMAs all need to be
  84374. ** combined into one big PMA in order to be able to step through the sorted
  84375. ** records in order.
  84376. **
  84377. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  84378. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  84379. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  84380. ** For the purposes of the paragraphs below, we assume that the array is
  84381. ** actually N elements in size, where N is the smallest power of 2 greater
  84382. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  84383. ** are treated as if they are empty (always at EOF).
  84384. **
  84385. ** The aTree[] array is also N elements in size. The value of N is stored in
  84386. ** the MergeEngine.nTree variable.
  84387. **
  84388. ** The final (N/2) elements of aTree[] contain the results of comparing
  84389. ** pairs of PMA keys together. Element i contains the result of
  84390. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  84391. ** aTree element is set to the index of it.
  84392. **
  84393. ** For the purposes of this comparison, EOF is considered greater than any
  84394. ** other key value. If the keys are equal (only possible with two EOF
  84395. ** values), it doesn't matter which index is stored.
  84396. **
  84397. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  84398. ** above contains the index of the smallest of each block of 4 PmaReaders
  84399. ** And so on. So that aTree[1] contains the index of the PmaReader that
  84400. ** currently points to the smallest key value. aTree[0] is unused.
  84401. **
  84402. ** Example:
  84403. **
  84404. ** aReadr[0] -> Banana
  84405. ** aReadr[1] -> Feijoa
  84406. ** aReadr[2] -> Elderberry
  84407. ** aReadr[3] -> Currant
  84408. ** aReadr[4] -> Grapefruit
  84409. ** aReadr[5] -> Apple
  84410. ** aReadr[6] -> Durian
  84411. ** aReadr[7] -> EOF
  84412. **
  84413. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  84414. **
  84415. ** The current element is "Apple" (the value of the key indicated by
  84416. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  84417. ** be advanced to the next key in its segment. Say the next key is
  84418. ** "Eggplant":
  84419. **
  84420. ** aReadr[5] -> Eggplant
  84421. **
  84422. ** The contents of aTree[] are updated first by comparing the new PmaReader
  84423. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  84424. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  84425. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  84426. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  84427. ** so the value written into element 1 of the array is 0. As follows:
  84428. **
  84429. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  84430. **
  84431. ** In other words, each time we advance to the next sorter element, log2(N)
  84432. ** key comparison operations are required, where N is the number of segments
  84433. ** being merged (rounded up to the next power of 2).
  84434. */
  84435. struct MergeEngine {
  84436. int nTree; /* Used size of aTree/aReadr (power of 2) */
  84437. SortSubtask *pTask; /* Used by this thread only */
  84438. int *aTree; /* Current state of incremental merge */
  84439. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  84440. };
  84441. /*
  84442. ** This object represents a single thread of control in a sort operation.
  84443. ** Exactly VdbeSorter.nTask instances of this object are allocated
  84444. ** as part of each VdbeSorter object. Instances are never allocated any
  84445. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  84446. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  84447. ** single-threaded operation, there is exactly one instance of this object
  84448. ** and for multi-threaded operation there are two or more instances.
  84449. **
  84450. ** Essentially, this structure contains all those fields of the VdbeSorter
  84451. ** structure for which each thread requires a separate instance. For example,
  84452. ** each thread requries its own UnpackedRecord object to unpack records in
  84453. ** as part of comparison operations.
  84454. **
  84455. ** Before a background thread is launched, variable bDone is set to 0. Then,
  84456. ** right before it exits, the thread itself sets bDone to 1. This is used for
  84457. ** two purposes:
  84458. **
  84459. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  84460. ** attempt to select a SortSubtask for which there is not already an
  84461. ** active background thread (since doing so causes the main thread
  84462. ** to block until it finishes).
  84463. **
  84464. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  84465. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  84466. ** block provoke debugging output.
  84467. **
  84468. ** In both cases, the effects of the main thread seeing (bDone==0) even
  84469. ** after the thread has finished are not dire. So we don't worry about
  84470. ** memory barriers and such here.
  84471. */
  84472. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  84473. struct SortSubtask {
  84474. SQLiteThread *pThread; /* Background thread, if any */
  84475. int bDone; /* Set if thread is finished but not joined */
  84476. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  84477. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  84478. SorterList list; /* List for thread to write to a PMA */
  84479. int nPMA; /* Number of PMAs currently in file */
  84480. SorterCompare xCompare; /* Compare function to use */
  84481. SorterFile file; /* Temp file for level-0 PMAs */
  84482. SorterFile file2; /* Space for other PMAs */
  84483. };
  84484. /*
  84485. ** Main sorter structure. A single instance of this is allocated for each
  84486. ** sorter cursor created by the VDBE.
  84487. **
  84488. ** mxKeysize:
  84489. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  84490. ** this variable is updated so as to be set to the size on disk of the
  84491. ** largest record in the sorter.
  84492. */
  84493. struct VdbeSorter {
  84494. int mnPmaSize; /* Minimum PMA size, in bytes */
  84495. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  84496. int mxKeysize; /* Largest serialized key seen so far */
  84497. int pgsz; /* Main database page size */
  84498. PmaReader *pReader; /* Readr data from here after Rewind() */
  84499. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  84500. sqlite3 *db; /* Database connection */
  84501. KeyInfo *pKeyInfo; /* How to compare records */
  84502. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  84503. SorterList list; /* List of in-memory records */
  84504. int iMemory; /* Offset of free space in list.aMemory */
  84505. int nMemory; /* Size of list.aMemory allocation in bytes */
  84506. u8 bUsePMA; /* True if one or more PMAs created */
  84507. u8 bUseThreads; /* True to use background threads */
  84508. u8 iPrev; /* Previous thread used to flush PMA */
  84509. u8 nTask; /* Size of aTask[] array */
  84510. u8 typeMask;
  84511. SortSubtask aTask[1]; /* One or more subtasks */
  84512. };
  84513. #define SORTER_TYPE_INTEGER 0x01
  84514. #define SORTER_TYPE_TEXT 0x02
  84515. /*
  84516. ** An instance of the following object is used to read records out of a
  84517. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  84518. ** aKey might point into aMap or into aBuffer. If neither of those locations
  84519. ** contain a contiguous representation of the key, then aAlloc is allocated
  84520. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  84521. **
  84522. ** pFd==0 at EOF.
  84523. */
  84524. struct PmaReader {
  84525. i64 iReadOff; /* Current read offset */
  84526. i64 iEof; /* 1 byte past EOF for this PmaReader */
  84527. int nAlloc; /* Bytes of space at aAlloc */
  84528. int nKey; /* Number of bytes in key */
  84529. sqlite3_file *pFd; /* File handle we are reading from */
  84530. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  84531. u8 *aKey; /* Pointer to current key */
  84532. u8 *aBuffer; /* Current read buffer */
  84533. int nBuffer; /* Size of read buffer in bytes */
  84534. u8 *aMap; /* Pointer to mapping of entire file */
  84535. IncrMerger *pIncr; /* Incremental merger */
  84536. };
  84537. /*
  84538. ** Normally, a PmaReader object iterates through an existing PMA stored
  84539. ** within a temp file. However, if the PmaReader.pIncr variable points to
  84540. ** an object of the following type, it may be used to iterate/merge through
  84541. ** multiple PMAs simultaneously.
  84542. **
  84543. ** There are two types of IncrMerger object - single (bUseThread==0) and
  84544. ** multi-threaded (bUseThread==1).
  84545. **
  84546. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  84547. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  84548. ** size. When the IncrMerger is initialized, it reads enough data from
  84549. ** pMerger to populate aFile[0]. It then sets variables within the
  84550. ** corresponding PmaReader object to read from that file and kicks off
  84551. ** a background thread to populate aFile[1] with the next mxSz bytes of
  84552. ** sorted record data from pMerger.
  84553. **
  84554. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  84555. ** background thread has finished populating aFile[1]. It then exchanges
  84556. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  84557. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  84558. ** another background thread to populate the new aFile[1]. And so on, until
  84559. ** the contents of pMerger are exhausted.
  84560. **
  84561. ** A single-threaded IncrMerger does not open any temporary files of its
  84562. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  84563. ** at offset iStartOff of file pTask->file2. And instead of using a
  84564. ** background thread to prepare data for the PmaReader, with a single
  84565. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  84566. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  84567. ** of data.
  84568. */
  84569. struct IncrMerger {
  84570. SortSubtask *pTask; /* Task that owns this merger */
  84571. MergeEngine *pMerger; /* Merge engine thread reads data from */
  84572. i64 iStartOff; /* Offset to start writing file at */
  84573. int mxSz; /* Maximum bytes of data to store */
  84574. int bEof; /* Set to true when merge is finished */
  84575. int bUseThread; /* True to use a bg thread for this object */
  84576. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  84577. };
  84578. /*
  84579. ** An instance of this object is used for writing a PMA.
  84580. **
  84581. ** The PMA is written one record at a time. Each record is of an arbitrary
  84582. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  84583. ** each block is aligned on a page boundary. This object caches writes to
  84584. ** the PMA so that aligned, page-size blocks are written.
  84585. */
  84586. struct PmaWriter {
  84587. int eFWErr; /* Non-zero if in an error state */
  84588. u8 *aBuffer; /* Pointer to write buffer */
  84589. int nBuffer; /* Size of write buffer in bytes */
  84590. int iBufStart; /* First byte of buffer to write */
  84591. int iBufEnd; /* Last byte of buffer to write */
  84592. i64 iWriteOff; /* Offset of start of buffer in file */
  84593. sqlite3_file *pFd; /* File handle to write to */
  84594. };
  84595. /*
  84596. ** This object is the header on a single record while that record is being
  84597. ** held in memory and prior to being written out as part of a PMA.
  84598. **
  84599. ** How the linked list is connected depends on how memory is being managed
  84600. ** by this module. If using a separate allocation for each in-memory record
  84601. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  84602. ** SorterRecord.u.pNext pointers.
  84603. **
  84604. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  84605. ** then while records are being accumulated the list is linked using the
  84606. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  84607. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  84608. ** has finished passing records to the sorter, or when the in-memory buffer
  84609. ** is full, the list is sorted. As part of the sorting process, it is
  84610. ** converted to use the SorterRecord.u.pNext pointers. See function
  84611. ** vdbeSorterSort() for details.
  84612. */
  84613. struct SorterRecord {
  84614. int nVal; /* Size of the record in bytes */
  84615. union {
  84616. SorterRecord *pNext; /* Pointer to next record in list */
  84617. int iNext; /* Offset within aMemory of next record */
  84618. } u;
  84619. /* The data for the record immediately follows this header */
  84620. };
  84621. /* Return a pointer to the buffer containing the record data for SorterRecord
  84622. ** object p. Should be used as if:
  84623. **
  84624. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  84625. */
  84626. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  84627. /* Maximum number of PMAs that a single MergeEngine can merge */
  84628. #define SORTER_MAX_MERGE_COUNT 16
  84629. static int vdbeIncrSwap(IncrMerger*);
  84630. static void vdbeIncrFree(IncrMerger *);
  84631. /*
  84632. ** Free all memory belonging to the PmaReader object passed as the
  84633. ** argument. All structure fields are set to zero before returning.
  84634. */
  84635. static void vdbePmaReaderClear(PmaReader *pReadr){
  84636. sqlite3_free(pReadr->aAlloc);
  84637. sqlite3_free(pReadr->aBuffer);
  84638. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  84639. vdbeIncrFree(pReadr->pIncr);
  84640. memset(pReadr, 0, sizeof(PmaReader));
  84641. }
  84642. /*
  84643. ** Read the next nByte bytes of data from the PMA p.
  84644. ** If successful, set *ppOut to point to a buffer containing the data
  84645. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  84646. ** error code.
  84647. **
  84648. ** The buffer returned in *ppOut is only valid until the
  84649. ** next call to this function.
  84650. */
  84651. static int vdbePmaReadBlob(
  84652. PmaReader *p, /* PmaReader from which to take the blob */
  84653. int nByte, /* Bytes of data to read */
  84654. u8 **ppOut /* OUT: Pointer to buffer containing data */
  84655. ){
  84656. int iBuf; /* Offset within buffer to read from */
  84657. int nAvail; /* Bytes of data available in buffer */
  84658. if( p->aMap ){
  84659. *ppOut = &p->aMap[p->iReadOff];
  84660. p->iReadOff += nByte;
  84661. return SQLITE_OK;
  84662. }
  84663. assert( p->aBuffer );
  84664. /* If there is no more data to be read from the buffer, read the next
  84665. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  84666. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  84667. iBuf = p->iReadOff % p->nBuffer;
  84668. if( iBuf==0 ){
  84669. int nRead; /* Bytes to read from disk */
  84670. int rc; /* sqlite3OsRead() return code */
  84671. /* Determine how many bytes of data to read. */
  84672. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  84673. nRead = p->nBuffer;
  84674. }else{
  84675. nRead = (int)(p->iEof - p->iReadOff);
  84676. }
  84677. assert( nRead>0 );
  84678. /* Readr data from the file. Return early if an error occurs. */
  84679. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  84680. assert( rc!=SQLITE_IOERR_SHORT_READ );
  84681. if( rc!=SQLITE_OK ) return rc;
  84682. }
  84683. nAvail = p->nBuffer - iBuf;
  84684. if( nByte<=nAvail ){
  84685. /* The requested data is available in the in-memory buffer. In this
  84686. ** case there is no need to make a copy of the data, just return a
  84687. ** pointer into the buffer to the caller. */
  84688. *ppOut = &p->aBuffer[iBuf];
  84689. p->iReadOff += nByte;
  84690. }else{
  84691. /* The requested data is not all available in the in-memory buffer.
  84692. ** In this case, allocate space at p->aAlloc[] to copy the requested
  84693. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  84694. int nRem; /* Bytes remaining to copy */
  84695. /* Extend the p->aAlloc[] allocation if required. */
  84696. if( p->nAlloc<nByte ){
  84697. u8 *aNew;
  84698. int nNew = MAX(128, p->nAlloc*2);
  84699. while( nByte>nNew ) nNew = nNew*2;
  84700. aNew = sqlite3Realloc(p->aAlloc, nNew);
  84701. if( !aNew ) return SQLITE_NOMEM_BKPT;
  84702. p->nAlloc = nNew;
  84703. p->aAlloc = aNew;
  84704. }
  84705. /* Copy as much data as is available in the buffer into the start of
  84706. ** p->aAlloc[]. */
  84707. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  84708. p->iReadOff += nAvail;
  84709. nRem = nByte - nAvail;
  84710. /* The following loop copies up to p->nBuffer bytes per iteration into
  84711. ** the p->aAlloc[] buffer. */
  84712. while( nRem>0 ){
  84713. int rc; /* vdbePmaReadBlob() return code */
  84714. int nCopy; /* Number of bytes to copy */
  84715. u8 *aNext; /* Pointer to buffer to copy data from */
  84716. nCopy = nRem;
  84717. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  84718. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  84719. if( rc!=SQLITE_OK ) return rc;
  84720. assert( aNext!=p->aAlloc );
  84721. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  84722. nRem -= nCopy;
  84723. }
  84724. *ppOut = p->aAlloc;
  84725. }
  84726. return SQLITE_OK;
  84727. }
  84728. /*
  84729. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  84730. ** the value read.
  84731. */
  84732. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  84733. int iBuf;
  84734. if( p->aMap ){
  84735. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  84736. }else{
  84737. iBuf = p->iReadOff % p->nBuffer;
  84738. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  84739. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  84740. }else{
  84741. u8 aVarint[16], *a;
  84742. int i = 0, rc;
  84743. do{
  84744. rc = vdbePmaReadBlob(p, 1, &a);
  84745. if( rc ) return rc;
  84746. aVarint[(i++)&0xf] = a[0];
  84747. }while( (a[0]&0x80)!=0 );
  84748. sqlite3GetVarint(aVarint, pnOut);
  84749. }
  84750. }
  84751. return SQLITE_OK;
  84752. }
  84753. /*
  84754. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  84755. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  84756. ** (because the file is too large or the VFS layer is configured not to use
  84757. ** mmap), return SQLITE_OK and set *pp to NULL.
  84758. **
  84759. ** Or, if an error occurs, return an SQLite error code. The final value of
  84760. ** *pp is undefined in this case.
  84761. */
  84762. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  84763. int rc = SQLITE_OK;
  84764. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  84765. sqlite3_file *pFd = pFile->pFd;
  84766. if( pFd->pMethods->iVersion>=3 ){
  84767. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  84768. testcase( rc!=SQLITE_OK );
  84769. }
  84770. }
  84771. return rc;
  84772. }
  84773. /*
  84774. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  84775. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  84776. ** if successful, or an SQLite error code if an error occurs.
  84777. */
  84778. static int vdbePmaReaderSeek(
  84779. SortSubtask *pTask, /* Task context */
  84780. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  84781. SorterFile *pFile, /* Sorter file to read from */
  84782. i64 iOff /* Offset in pFile */
  84783. ){
  84784. int rc = SQLITE_OK;
  84785. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  84786. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  84787. if( pReadr->aMap ){
  84788. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  84789. pReadr->aMap = 0;
  84790. }
  84791. pReadr->iReadOff = iOff;
  84792. pReadr->iEof = pFile->iEof;
  84793. pReadr->pFd = pFile->pFd;
  84794. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  84795. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  84796. int pgsz = pTask->pSorter->pgsz;
  84797. int iBuf = pReadr->iReadOff % pgsz;
  84798. if( pReadr->aBuffer==0 ){
  84799. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  84800. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  84801. pReadr->nBuffer = pgsz;
  84802. }
  84803. if( rc==SQLITE_OK && iBuf ){
  84804. int nRead = pgsz - iBuf;
  84805. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  84806. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  84807. }
  84808. rc = sqlite3OsRead(
  84809. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  84810. );
  84811. testcase( rc!=SQLITE_OK );
  84812. }
  84813. }
  84814. return rc;
  84815. }
  84816. /*
  84817. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  84818. ** no error occurs, or an SQLite error code if one does.
  84819. */
  84820. static int vdbePmaReaderNext(PmaReader *pReadr){
  84821. int rc = SQLITE_OK; /* Return Code */
  84822. u64 nRec = 0; /* Size of record in bytes */
  84823. if( pReadr->iReadOff>=pReadr->iEof ){
  84824. IncrMerger *pIncr = pReadr->pIncr;
  84825. int bEof = 1;
  84826. if( pIncr ){
  84827. rc = vdbeIncrSwap(pIncr);
  84828. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  84829. rc = vdbePmaReaderSeek(
  84830. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  84831. );
  84832. bEof = 0;
  84833. }
  84834. }
  84835. if( bEof ){
  84836. /* This is an EOF condition */
  84837. vdbePmaReaderClear(pReadr);
  84838. testcase( rc!=SQLITE_OK );
  84839. return rc;
  84840. }
  84841. }
  84842. if( rc==SQLITE_OK ){
  84843. rc = vdbePmaReadVarint(pReadr, &nRec);
  84844. }
  84845. if( rc==SQLITE_OK ){
  84846. pReadr->nKey = (int)nRec;
  84847. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  84848. testcase( rc!=SQLITE_OK );
  84849. }
  84850. return rc;
  84851. }
  84852. /*
  84853. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  84854. ** starting at offset iStart and ending at offset iEof-1. This function
  84855. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  84856. ** PMA is empty).
  84857. **
  84858. ** If the pnByte parameter is NULL, then it is assumed that the file
  84859. ** contains a single PMA, and that that PMA omits the initial length varint.
  84860. */
  84861. static int vdbePmaReaderInit(
  84862. SortSubtask *pTask, /* Task context */
  84863. SorterFile *pFile, /* Sorter file to read from */
  84864. i64 iStart, /* Start offset in pFile */
  84865. PmaReader *pReadr, /* PmaReader to populate */
  84866. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  84867. ){
  84868. int rc;
  84869. assert( pFile->iEof>iStart );
  84870. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  84871. assert( pReadr->aBuffer==0 );
  84872. assert( pReadr->aMap==0 );
  84873. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  84874. if( rc==SQLITE_OK ){
  84875. u64 nByte = 0; /* Size of PMA in bytes */
  84876. rc = vdbePmaReadVarint(pReadr, &nByte);
  84877. pReadr->iEof = pReadr->iReadOff + nByte;
  84878. *pnByte += nByte;
  84879. }
  84880. if( rc==SQLITE_OK ){
  84881. rc = vdbePmaReaderNext(pReadr);
  84882. }
  84883. return rc;
  84884. }
  84885. /*
  84886. ** A version of vdbeSorterCompare() that assumes that it has already been
  84887. ** determined that the first field of key1 is equal to the first field of
  84888. ** key2.
  84889. */
  84890. static int vdbeSorterCompareTail(
  84891. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84892. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84893. const void *pKey1, int nKey1, /* Left side of comparison */
  84894. const void *pKey2, int nKey2 /* Right side of comparison */
  84895. ){
  84896. UnpackedRecord *r2 = pTask->pUnpacked;
  84897. if( *pbKey2Cached==0 ){
  84898. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  84899. *pbKey2Cached = 1;
  84900. }
  84901. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  84902. }
  84903. /*
  84904. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  84905. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  84906. ** used by the comparison. Return the result of the comparison.
  84907. **
  84908. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  84909. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  84910. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  84911. ** version of key2 and *pbKey2Cached set to true before returning.
  84912. **
  84913. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  84914. ** to SQLITE_NOMEM.
  84915. */
  84916. static int vdbeSorterCompare(
  84917. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84918. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84919. const void *pKey1, int nKey1, /* Left side of comparison */
  84920. const void *pKey2, int nKey2 /* Right side of comparison */
  84921. ){
  84922. UnpackedRecord *r2 = pTask->pUnpacked;
  84923. if( !*pbKey2Cached ){
  84924. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  84925. *pbKey2Cached = 1;
  84926. }
  84927. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  84928. }
  84929. /*
  84930. ** A specially optimized version of vdbeSorterCompare() that assumes that
  84931. ** the first field of each key is a TEXT value and that the collation
  84932. ** sequence to compare them with is BINARY.
  84933. */
  84934. static int vdbeSorterCompareText(
  84935. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84936. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84937. const void *pKey1, int nKey1, /* Left side of comparison */
  84938. const void *pKey2, int nKey2 /* Right side of comparison */
  84939. ){
  84940. const u8 * const p1 = (const u8 * const)pKey1;
  84941. const u8 * const p2 = (const u8 * const)pKey2;
  84942. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  84943. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  84944. int n1;
  84945. int n2;
  84946. int res;
  84947. getVarint32(&p1[1], n1);
  84948. getVarint32(&p2[1], n2);
  84949. res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
  84950. if( res==0 ){
  84951. res = n1 - n2;
  84952. }
  84953. if( res==0 ){
  84954. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  84955. res = vdbeSorterCompareTail(
  84956. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  84957. );
  84958. }
  84959. }else{
  84960. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  84961. res = res * -1;
  84962. }
  84963. }
  84964. return res;
  84965. }
  84966. /*
  84967. ** A specially optimized version of vdbeSorterCompare() that assumes that
  84968. ** the first field of each key is an INTEGER value.
  84969. */
  84970. static int vdbeSorterCompareInt(
  84971. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84972. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84973. const void *pKey1, int nKey1, /* Left side of comparison */
  84974. const void *pKey2, int nKey2 /* Right side of comparison */
  84975. ){
  84976. const u8 * const p1 = (const u8 * const)pKey1;
  84977. const u8 * const p2 = (const u8 * const)pKey2;
  84978. const int s1 = p1[1]; /* Left hand serial type */
  84979. const int s2 = p2[1]; /* Right hand serial type */
  84980. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  84981. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  84982. int res; /* Return value */
  84983. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  84984. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  84985. if( s1==s2 ){
  84986. /* The two values have the same sign. Compare using memcmp(). */
  84987. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  84988. const u8 n = aLen[s1];
  84989. int i;
  84990. res = 0;
  84991. for(i=0; i<n; i++){
  84992. if( (res = v1[i] - v2[i])!=0 ){
  84993. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  84994. res = v1[0] & 0x80 ? -1 : +1;
  84995. }
  84996. break;
  84997. }
  84998. }
  84999. }else if( s1>7 && s2>7 ){
  85000. res = s1 - s2;
  85001. }else{
  85002. if( s2>7 ){
  85003. res = +1;
  85004. }else if( s1>7 ){
  85005. res = -1;
  85006. }else{
  85007. res = s1 - s2;
  85008. }
  85009. assert( res!=0 );
  85010. if( res>0 ){
  85011. if( *v1 & 0x80 ) res = -1;
  85012. }else{
  85013. if( *v2 & 0x80 ) res = +1;
  85014. }
  85015. }
  85016. if( res==0 ){
  85017. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  85018. res = vdbeSorterCompareTail(
  85019. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  85020. );
  85021. }
  85022. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  85023. res = res * -1;
  85024. }
  85025. return res;
  85026. }
  85027. /*
  85028. ** Initialize the temporary index cursor just opened as a sorter cursor.
  85029. **
  85030. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
  85031. ** to determine the number of fields that should be compared from the
  85032. ** records being sorted. However, if the value passed as argument nField
  85033. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  85034. ** is used instead. This is used when sorting records for a CREATE INDEX
  85035. ** statement. In this case, keys are always delivered to the sorter in
  85036. ** order of the primary key, which happens to be make up the final part
  85037. ** of the records being sorted. So if the sort is stable, there is never
  85038. ** any reason to compare PK fields and they can be ignored for a small
  85039. ** performance boost.
  85040. **
  85041. ** The sorter can guarantee a stable sort when running in single-threaded
  85042. ** mode, but not in multi-threaded mode.
  85043. **
  85044. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  85045. */
  85046. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  85047. sqlite3 *db, /* Database connection (for malloc()) */
  85048. int nField, /* Number of key fields in each record */
  85049. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  85050. ){
  85051. int pgsz; /* Page size of main database */
  85052. int i; /* Used to iterate through aTask[] */
  85053. VdbeSorter *pSorter; /* The new sorter */
  85054. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  85055. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  85056. int sz; /* Size of pSorter in bytes */
  85057. int rc = SQLITE_OK;
  85058. #if SQLITE_MAX_WORKER_THREADS==0
  85059. # define nWorker 0
  85060. #else
  85061. int nWorker;
  85062. #endif
  85063. /* Initialize the upper limit on the number of worker threads */
  85064. #if SQLITE_MAX_WORKER_THREADS>0
  85065. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  85066. nWorker = 0;
  85067. }else{
  85068. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  85069. }
  85070. #endif
  85071. /* Do not allow the total number of threads (main thread + all workers)
  85072. ** to exceed the maximum merge count */
  85073. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  85074. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  85075. nWorker = SORTER_MAX_MERGE_COUNT-1;
  85076. }
  85077. #endif
  85078. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  85079. assert( pCsr->eCurType==CURTYPE_SORTER );
  85080. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
  85081. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  85082. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  85083. pCsr->uc.pSorter = pSorter;
  85084. if( pSorter==0 ){
  85085. rc = SQLITE_NOMEM_BKPT;
  85086. }else{
  85087. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  85088. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  85089. pKeyInfo->db = 0;
  85090. if( nField && nWorker==0 ){
  85091. pKeyInfo->nKeyField = nField;
  85092. }
  85093. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  85094. pSorter->nTask = nWorker + 1;
  85095. pSorter->iPrev = (u8)(nWorker - 1);
  85096. pSorter->bUseThreads = (pSorter->nTask>1);
  85097. pSorter->db = db;
  85098. for(i=0; i<pSorter->nTask; i++){
  85099. SortSubtask *pTask = &pSorter->aTask[i];
  85100. pTask->pSorter = pSorter;
  85101. }
  85102. if( !sqlite3TempInMemory(db) ){
  85103. i64 mxCache; /* Cache size in bytes*/
  85104. u32 szPma = sqlite3GlobalConfig.szPma;
  85105. pSorter->mnPmaSize = szPma * pgsz;
  85106. mxCache = db->aDb[0].pSchema->cache_size;
  85107. if( mxCache<0 ){
  85108. /* A negative cache-size value C indicates that the cache is abs(C)
  85109. ** KiB in size. */
  85110. mxCache = mxCache * -1024;
  85111. }else{
  85112. mxCache = mxCache * pgsz;
  85113. }
  85114. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  85115. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  85116. /* Avoid large memory allocations if the application has requested
  85117. ** SQLITE_CONFIG_SMALL_MALLOC. */
  85118. if( sqlite3GlobalConfig.bSmallMalloc==0 ){
  85119. assert( pSorter->iMemory==0 );
  85120. pSorter->nMemory = pgsz;
  85121. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  85122. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  85123. }
  85124. }
  85125. if( pKeyInfo->nAllField<13
  85126. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  85127. ){
  85128. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  85129. }
  85130. }
  85131. return rc;
  85132. }
  85133. #undef nWorker /* Defined at the top of this function */
  85134. /*
  85135. ** Free the list of sorted records starting at pRecord.
  85136. */
  85137. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  85138. SorterRecord *p;
  85139. SorterRecord *pNext;
  85140. for(p=pRecord; p; p=pNext){
  85141. pNext = p->u.pNext;
  85142. sqlite3DbFree(db, p);
  85143. }
  85144. }
  85145. /*
  85146. ** Free all resources owned by the object indicated by argument pTask. All
  85147. ** fields of *pTask are zeroed before returning.
  85148. */
  85149. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  85150. sqlite3DbFree(db, pTask->pUnpacked);
  85151. #if SQLITE_MAX_WORKER_THREADS>0
  85152. /* pTask->list.aMemory can only be non-zero if it was handed memory
  85153. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  85154. if( pTask->list.aMemory ){
  85155. sqlite3_free(pTask->list.aMemory);
  85156. }else
  85157. #endif
  85158. {
  85159. assert( pTask->list.aMemory==0 );
  85160. vdbeSorterRecordFree(0, pTask->list.pList);
  85161. }
  85162. if( pTask->file.pFd ){
  85163. sqlite3OsCloseFree(pTask->file.pFd);
  85164. }
  85165. if( pTask->file2.pFd ){
  85166. sqlite3OsCloseFree(pTask->file2.pFd);
  85167. }
  85168. memset(pTask, 0, sizeof(SortSubtask));
  85169. }
  85170. #ifdef SQLITE_DEBUG_SORTER_THREADS
  85171. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  85172. i64 t;
  85173. int iTask = (pTask - pTask->pSorter->aTask);
  85174. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  85175. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  85176. }
  85177. static void vdbeSorterRewindDebug(const char *zEvent){
  85178. i64 t;
  85179. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  85180. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  85181. }
  85182. static void vdbeSorterPopulateDebug(
  85183. SortSubtask *pTask,
  85184. const char *zEvent
  85185. ){
  85186. i64 t;
  85187. int iTask = (pTask - pTask->pSorter->aTask);
  85188. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  85189. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  85190. }
  85191. static void vdbeSorterBlockDebug(
  85192. SortSubtask *pTask,
  85193. int bBlocked,
  85194. const char *zEvent
  85195. ){
  85196. if( bBlocked ){
  85197. i64 t;
  85198. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  85199. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  85200. }
  85201. }
  85202. #else
  85203. # define vdbeSorterWorkDebug(x,y)
  85204. # define vdbeSorterRewindDebug(y)
  85205. # define vdbeSorterPopulateDebug(x,y)
  85206. # define vdbeSorterBlockDebug(x,y,z)
  85207. #endif
  85208. #if SQLITE_MAX_WORKER_THREADS>0
  85209. /*
  85210. ** Join thread pTask->thread.
  85211. */
  85212. static int vdbeSorterJoinThread(SortSubtask *pTask){
  85213. int rc = SQLITE_OK;
  85214. if( pTask->pThread ){
  85215. #ifdef SQLITE_DEBUG_SORTER_THREADS
  85216. int bDone = pTask->bDone;
  85217. #endif
  85218. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  85219. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  85220. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  85221. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  85222. rc = SQLITE_PTR_TO_INT(pRet);
  85223. assert( pTask->bDone==1 );
  85224. pTask->bDone = 0;
  85225. pTask->pThread = 0;
  85226. }
  85227. return rc;
  85228. }
  85229. /*
  85230. ** Launch a background thread to run xTask(pIn).
  85231. */
  85232. static int vdbeSorterCreateThread(
  85233. SortSubtask *pTask, /* Thread will use this task object */
  85234. void *(*xTask)(void*), /* Routine to run in a separate thread */
  85235. void *pIn /* Argument passed into xTask() */
  85236. ){
  85237. assert( pTask->pThread==0 && pTask->bDone==0 );
  85238. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  85239. }
  85240. /*
  85241. ** Join all outstanding threads launched by SorterWrite() to create
  85242. ** level-0 PMAs.
  85243. */
  85244. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  85245. int rc = rcin;
  85246. int i;
  85247. /* This function is always called by the main user thread.
  85248. **
  85249. ** If this function is being called after SorterRewind() has been called,
  85250. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  85251. ** is currently attempt to join one of the other threads. To avoid a race
  85252. ** condition where this thread also attempts to join the same object, join
  85253. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  85254. for(i=pSorter->nTask-1; i>=0; i--){
  85255. SortSubtask *pTask = &pSorter->aTask[i];
  85256. int rc2 = vdbeSorterJoinThread(pTask);
  85257. if( rc==SQLITE_OK ) rc = rc2;
  85258. }
  85259. return rc;
  85260. }
  85261. #else
  85262. # define vdbeSorterJoinAll(x,rcin) (rcin)
  85263. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  85264. #endif
  85265. /*
  85266. ** Allocate a new MergeEngine object capable of handling up to
  85267. ** nReader PmaReader inputs.
  85268. **
  85269. ** nReader is automatically rounded up to the next power of two.
  85270. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  85271. */
  85272. static MergeEngine *vdbeMergeEngineNew(int nReader){
  85273. int N = 2; /* Smallest power of two >= nReader */
  85274. int nByte; /* Total bytes of space to allocate */
  85275. MergeEngine *pNew; /* Pointer to allocated object to return */
  85276. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  85277. while( N<nReader ) N += N;
  85278. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  85279. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  85280. if( pNew ){
  85281. pNew->nTree = N;
  85282. pNew->pTask = 0;
  85283. pNew->aReadr = (PmaReader*)&pNew[1];
  85284. pNew->aTree = (int*)&pNew->aReadr[N];
  85285. }
  85286. return pNew;
  85287. }
  85288. /*
  85289. ** Free the MergeEngine object passed as the only argument.
  85290. */
  85291. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  85292. int i;
  85293. if( pMerger ){
  85294. for(i=0; i<pMerger->nTree; i++){
  85295. vdbePmaReaderClear(&pMerger->aReadr[i]);
  85296. }
  85297. }
  85298. sqlite3_free(pMerger);
  85299. }
  85300. /*
  85301. ** Free all resources associated with the IncrMerger object indicated by
  85302. ** the first argument.
  85303. */
  85304. static void vdbeIncrFree(IncrMerger *pIncr){
  85305. if( pIncr ){
  85306. #if SQLITE_MAX_WORKER_THREADS>0
  85307. if( pIncr->bUseThread ){
  85308. vdbeSorterJoinThread(pIncr->pTask);
  85309. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  85310. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  85311. }
  85312. #endif
  85313. vdbeMergeEngineFree(pIncr->pMerger);
  85314. sqlite3_free(pIncr);
  85315. }
  85316. }
  85317. /*
  85318. ** Reset a sorting cursor back to its original empty state.
  85319. */
  85320. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  85321. int i;
  85322. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  85323. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  85324. #if SQLITE_MAX_WORKER_THREADS>0
  85325. if( pSorter->pReader ){
  85326. vdbePmaReaderClear(pSorter->pReader);
  85327. sqlite3DbFree(db, pSorter->pReader);
  85328. pSorter->pReader = 0;
  85329. }
  85330. #endif
  85331. vdbeMergeEngineFree(pSorter->pMerger);
  85332. pSorter->pMerger = 0;
  85333. for(i=0; i<pSorter->nTask; i++){
  85334. SortSubtask *pTask = &pSorter->aTask[i];
  85335. vdbeSortSubtaskCleanup(db, pTask);
  85336. pTask->pSorter = pSorter;
  85337. }
  85338. if( pSorter->list.aMemory==0 ){
  85339. vdbeSorterRecordFree(0, pSorter->list.pList);
  85340. }
  85341. pSorter->list.pList = 0;
  85342. pSorter->list.szPMA = 0;
  85343. pSorter->bUsePMA = 0;
  85344. pSorter->iMemory = 0;
  85345. pSorter->mxKeysize = 0;
  85346. sqlite3DbFree(db, pSorter->pUnpacked);
  85347. pSorter->pUnpacked = 0;
  85348. }
  85349. /*
  85350. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  85351. */
  85352. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  85353. VdbeSorter *pSorter;
  85354. assert( pCsr->eCurType==CURTYPE_SORTER );
  85355. pSorter = pCsr->uc.pSorter;
  85356. if( pSorter ){
  85357. sqlite3VdbeSorterReset(db, pSorter);
  85358. sqlite3_free(pSorter->list.aMemory);
  85359. sqlite3DbFree(db, pSorter);
  85360. pCsr->uc.pSorter = 0;
  85361. }
  85362. }
  85363. #if SQLITE_MAX_MMAP_SIZE>0
  85364. /*
  85365. ** The first argument is a file-handle open on a temporary file. The file
  85366. ** is guaranteed to be nByte bytes or smaller in size. This function
  85367. ** attempts to extend the file to nByte bytes in size and to ensure that
  85368. ** the VFS has memory mapped it.
  85369. **
  85370. ** Whether or not the file does end up memory mapped of course depends on
  85371. ** the specific VFS implementation.
  85372. */
  85373. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  85374. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  85375. void *p = 0;
  85376. int chunksize = 4*1024;
  85377. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  85378. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  85379. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  85380. sqlite3OsUnfetch(pFd, 0, p);
  85381. }
  85382. }
  85383. #else
  85384. # define vdbeSorterExtendFile(x,y,z)
  85385. #endif
  85386. /*
  85387. ** Allocate space for a file-handle and open a temporary file. If successful,
  85388. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  85389. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  85390. */
  85391. static int vdbeSorterOpenTempFile(
  85392. sqlite3 *db, /* Database handle doing sort */
  85393. i64 nExtend, /* Attempt to extend file to this size */
  85394. sqlite3_file **ppFd
  85395. ){
  85396. int rc;
  85397. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  85398. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  85399. SQLITE_OPEN_TEMP_JOURNAL |
  85400. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  85401. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  85402. );
  85403. if( rc==SQLITE_OK ){
  85404. i64 max = SQLITE_MAX_MMAP_SIZE;
  85405. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  85406. if( nExtend>0 ){
  85407. vdbeSorterExtendFile(db, *ppFd, nExtend);
  85408. }
  85409. }
  85410. return rc;
  85411. }
  85412. /*
  85413. ** If it has not already been allocated, allocate the UnpackedRecord
  85414. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  85415. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  85416. */
  85417. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  85418. if( pTask->pUnpacked==0 ){
  85419. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  85420. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  85421. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
  85422. pTask->pUnpacked->errCode = 0;
  85423. }
  85424. return SQLITE_OK;
  85425. }
  85426. /*
  85427. ** Merge the two sorted lists p1 and p2 into a single list.
  85428. */
  85429. static SorterRecord *vdbeSorterMerge(
  85430. SortSubtask *pTask, /* Calling thread context */
  85431. SorterRecord *p1, /* First list to merge */
  85432. SorterRecord *p2 /* Second list to merge */
  85433. ){
  85434. SorterRecord *pFinal = 0;
  85435. SorterRecord **pp = &pFinal;
  85436. int bCached = 0;
  85437. assert( p1!=0 && p2!=0 );
  85438. for(;;){
  85439. int res;
  85440. res = pTask->xCompare(
  85441. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  85442. );
  85443. if( res<=0 ){
  85444. *pp = p1;
  85445. pp = &p1->u.pNext;
  85446. p1 = p1->u.pNext;
  85447. if( p1==0 ){
  85448. *pp = p2;
  85449. break;
  85450. }
  85451. }else{
  85452. *pp = p2;
  85453. pp = &p2->u.pNext;
  85454. p2 = p2->u.pNext;
  85455. bCached = 0;
  85456. if( p2==0 ){
  85457. *pp = p1;
  85458. break;
  85459. }
  85460. }
  85461. }
  85462. return pFinal;
  85463. }
  85464. /*
  85465. ** Return the SorterCompare function to compare values collected by the
  85466. ** sorter object passed as the only argument.
  85467. */
  85468. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  85469. if( p->typeMask==SORTER_TYPE_INTEGER ){
  85470. return vdbeSorterCompareInt;
  85471. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  85472. return vdbeSorterCompareText;
  85473. }
  85474. return vdbeSorterCompare;
  85475. }
  85476. /*
  85477. ** Sort the linked list of records headed at pTask->pList. Return
  85478. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  85479. ** an error occurs.
  85480. */
  85481. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  85482. int i;
  85483. SorterRecord **aSlot;
  85484. SorterRecord *p;
  85485. int rc;
  85486. rc = vdbeSortAllocUnpacked(pTask);
  85487. if( rc!=SQLITE_OK ) return rc;
  85488. p = pList->pList;
  85489. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  85490. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  85491. if( !aSlot ){
  85492. return SQLITE_NOMEM_BKPT;
  85493. }
  85494. while( p ){
  85495. SorterRecord *pNext;
  85496. if( pList->aMemory ){
  85497. if( (u8*)p==pList->aMemory ){
  85498. pNext = 0;
  85499. }else{
  85500. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  85501. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  85502. }
  85503. }else{
  85504. pNext = p->u.pNext;
  85505. }
  85506. p->u.pNext = 0;
  85507. for(i=0; aSlot[i]; i++){
  85508. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  85509. aSlot[i] = 0;
  85510. }
  85511. aSlot[i] = p;
  85512. p = pNext;
  85513. }
  85514. p = 0;
  85515. for(i=0; i<64; i++){
  85516. if( aSlot[i]==0 ) continue;
  85517. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  85518. }
  85519. pList->pList = p;
  85520. sqlite3_free(aSlot);
  85521. assert( pTask->pUnpacked->errCode==SQLITE_OK
  85522. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  85523. );
  85524. return pTask->pUnpacked->errCode;
  85525. }
  85526. /*
  85527. ** Initialize a PMA-writer object.
  85528. */
  85529. static void vdbePmaWriterInit(
  85530. sqlite3_file *pFd, /* File handle to write to */
  85531. PmaWriter *p, /* Object to populate */
  85532. int nBuf, /* Buffer size */
  85533. i64 iStart /* Offset of pFd to begin writing at */
  85534. ){
  85535. memset(p, 0, sizeof(PmaWriter));
  85536. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  85537. if( !p->aBuffer ){
  85538. p->eFWErr = SQLITE_NOMEM_BKPT;
  85539. }else{
  85540. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  85541. p->iWriteOff = iStart - p->iBufStart;
  85542. p->nBuffer = nBuf;
  85543. p->pFd = pFd;
  85544. }
  85545. }
  85546. /*
  85547. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  85548. ** if successful, or an SQLite error code if an error occurs.
  85549. */
  85550. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  85551. int nRem = nData;
  85552. while( nRem>0 && p->eFWErr==0 ){
  85553. int nCopy = nRem;
  85554. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  85555. nCopy = p->nBuffer - p->iBufEnd;
  85556. }
  85557. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  85558. p->iBufEnd += nCopy;
  85559. if( p->iBufEnd==p->nBuffer ){
  85560. p->eFWErr = sqlite3OsWrite(p->pFd,
  85561. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  85562. p->iWriteOff + p->iBufStart
  85563. );
  85564. p->iBufStart = p->iBufEnd = 0;
  85565. p->iWriteOff += p->nBuffer;
  85566. }
  85567. assert( p->iBufEnd<p->nBuffer );
  85568. nRem -= nCopy;
  85569. }
  85570. }
  85571. /*
  85572. ** Flush any buffered data to disk and clean up the PMA-writer object.
  85573. ** The results of using the PMA-writer after this call are undefined.
  85574. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  85575. ** required. Otherwise, return an SQLite error code.
  85576. **
  85577. ** Before returning, set *piEof to the offset immediately following the
  85578. ** last byte written to the file.
  85579. */
  85580. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  85581. int rc;
  85582. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  85583. p->eFWErr = sqlite3OsWrite(p->pFd,
  85584. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  85585. p->iWriteOff + p->iBufStart
  85586. );
  85587. }
  85588. *piEof = (p->iWriteOff + p->iBufEnd);
  85589. sqlite3_free(p->aBuffer);
  85590. rc = p->eFWErr;
  85591. memset(p, 0, sizeof(PmaWriter));
  85592. return rc;
  85593. }
  85594. /*
  85595. ** Write value iVal encoded as a varint to the PMA. Return
  85596. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  85597. */
  85598. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  85599. int nByte;
  85600. u8 aByte[10];
  85601. nByte = sqlite3PutVarint(aByte, iVal);
  85602. vdbePmaWriteBlob(p, aByte, nByte);
  85603. }
  85604. /*
  85605. ** Write the current contents of in-memory linked-list pList to a level-0
  85606. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  85607. ** successful, or an SQLite error code otherwise.
  85608. **
  85609. ** The format of a PMA is:
  85610. **
  85611. ** * A varint. This varint contains the total number of bytes of content
  85612. ** in the PMA (not including the varint itself).
  85613. **
  85614. ** * One or more records packed end-to-end in order of ascending keys.
  85615. ** Each record consists of a varint followed by a blob of data (the
  85616. ** key). The varint is the number of bytes in the blob of data.
  85617. */
  85618. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  85619. sqlite3 *db = pTask->pSorter->db;
  85620. int rc = SQLITE_OK; /* Return code */
  85621. PmaWriter writer; /* Object used to write to the file */
  85622. #ifdef SQLITE_DEBUG
  85623. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  85624. ** This is used by an assert() statement at the end of this function. */
  85625. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  85626. #endif
  85627. vdbeSorterWorkDebug(pTask, "enter");
  85628. memset(&writer, 0, sizeof(PmaWriter));
  85629. assert( pList->szPMA>0 );
  85630. /* If the first temporary PMA file has not been opened, open it now. */
  85631. if( pTask->file.pFd==0 ){
  85632. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  85633. assert( rc!=SQLITE_OK || pTask->file.pFd );
  85634. assert( pTask->file.iEof==0 );
  85635. assert( pTask->nPMA==0 );
  85636. }
  85637. /* Try to get the file to memory map */
  85638. if( rc==SQLITE_OK ){
  85639. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  85640. }
  85641. /* Sort the list */
  85642. if( rc==SQLITE_OK ){
  85643. rc = vdbeSorterSort(pTask, pList);
  85644. }
  85645. if( rc==SQLITE_OK ){
  85646. SorterRecord *p;
  85647. SorterRecord *pNext = 0;
  85648. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  85649. pTask->file.iEof);
  85650. pTask->nPMA++;
  85651. vdbePmaWriteVarint(&writer, pList->szPMA);
  85652. for(p=pList->pList; p; p=pNext){
  85653. pNext = p->u.pNext;
  85654. vdbePmaWriteVarint(&writer, p->nVal);
  85655. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  85656. if( pList->aMemory==0 ) sqlite3_free(p);
  85657. }
  85658. pList->pList = p;
  85659. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  85660. }
  85661. vdbeSorterWorkDebug(pTask, "exit");
  85662. assert( rc!=SQLITE_OK || pList->pList==0 );
  85663. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  85664. return rc;
  85665. }
  85666. /*
  85667. ** Advance the MergeEngine to its next entry.
  85668. ** Set *pbEof to true there is no next entry because
  85669. ** the MergeEngine has reached the end of all its inputs.
  85670. **
  85671. ** Return SQLITE_OK if successful or an error code if an error occurs.
  85672. */
  85673. static int vdbeMergeEngineStep(
  85674. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  85675. int *pbEof /* Set TRUE at EOF. Set false for more content */
  85676. ){
  85677. int rc;
  85678. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  85679. SortSubtask *pTask = pMerger->pTask;
  85680. /* Advance the current PmaReader */
  85681. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  85682. /* Update contents of aTree[] */
  85683. if( rc==SQLITE_OK ){
  85684. int i; /* Index of aTree[] to recalculate */
  85685. PmaReader *pReadr1; /* First PmaReader to compare */
  85686. PmaReader *pReadr2; /* Second PmaReader to compare */
  85687. int bCached = 0;
  85688. /* Find the first two PmaReaders to compare. The one that was just
  85689. ** advanced (iPrev) and the one next to it in the array. */
  85690. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  85691. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  85692. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  85693. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  85694. int iRes;
  85695. if( pReadr1->pFd==0 ){
  85696. iRes = +1;
  85697. }else if( pReadr2->pFd==0 ){
  85698. iRes = -1;
  85699. }else{
  85700. iRes = pTask->xCompare(pTask, &bCached,
  85701. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  85702. );
  85703. }
  85704. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  85705. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  85706. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  85707. ** pKey2 to point to the record belonging to pReadr2.
  85708. **
  85709. ** Alternatively, if pReadr2 contains the smaller of the two values,
  85710. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  85711. ** was actually called above, then pTask->pUnpacked now contains
  85712. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  85713. ** vdbeSorterCompare() from decoding pReadr2 again.
  85714. **
  85715. ** If the two values were equal, then the value from the oldest
  85716. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  85717. ** is sorted from oldest to newest, so pReadr1 contains older values
  85718. ** than pReadr2 iff (pReadr1<pReadr2). */
  85719. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  85720. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  85721. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  85722. bCached = 0;
  85723. }else{
  85724. if( pReadr1->pFd ) bCached = 0;
  85725. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  85726. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  85727. }
  85728. }
  85729. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  85730. }
  85731. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  85732. }
  85733. #if SQLITE_MAX_WORKER_THREADS>0
  85734. /*
  85735. ** The main routine for background threads that write level-0 PMAs.
  85736. */
  85737. static void *vdbeSorterFlushThread(void *pCtx){
  85738. SortSubtask *pTask = (SortSubtask*)pCtx;
  85739. int rc; /* Return code */
  85740. assert( pTask->bDone==0 );
  85741. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  85742. pTask->bDone = 1;
  85743. return SQLITE_INT_TO_PTR(rc);
  85744. }
  85745. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  85746. /*
  85747. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  85748. ** using a background thread.
  85749. */
  85750. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  85751. #if SQLITE_MAX_WORKER_THREADS==0
  85752. pSorter->bUsePMA = 1;
  85753. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  85754. #else
  85755. int rc = SQLITE_OK;
  85756. int i;
  85757. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  85758. int nWorker = (pSorter->nTask-1);
  85759. /* Set the flag to indicate that at least one PMA has been written.
  85760. ** Or will be, anyhow. */
  85761. pSorter->bUsePMA = 1;
  85762. /* Select a sub-task to sort and flush the current list of in-memory
  85763. ** records to disk. If the sorter is running in multi-threaded mode,
  85764. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  85765. ** the background thread from a sub-tasks previous turn is still running,
  85766. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  85767. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  85768. ** sub-tasks are prefered as they use background threads - the final
  85769. ** sub-task uses the main thread. */
  85770. for(i=0; i<nWorker; i++){
  85771. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  85772. pTask = &pSorter->aTask[iTest];
  85773. if( pTask->bDone ){
  85774. rc = vdbeSorterJoinThread(pTask);
  85775. }
  85776. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  85777. }
  85778. if( rc==SQLITE_OK ){
  85779. if( i==nWorker ){
  85780. /* Use the foreground thread for this operation */
  85781. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  85782. }else{
  85783. /* Launch a background thread for this operation */
  85784. u8 *aMem = pTask->list.aMemory;
  85785. void *pCtx = (void*)pTask;
  85786. assert( pTask->pThread==0 && pTask->bDone==0 );
  85787. assert( pTask->list.pList==0 );
  85788. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  85789. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  85790. pTask->list = pSorter->list;
  85791. pSorter->list.pList = 0;
  85792. pSorter->list.szPMA = 0;
  85793. if( aMem ){
  85794. pSorter->list.aMemory = aMem;
  85795. pSorter->nMemory = sqlite3MallocSize(aMem);
  85796. }else if( pSorter->list.aMemory ){
  85797. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  85798. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  85799. }
  85800. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  85801. }
  85802. }
  85803. return rc;
  85804. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  85805. }
  85806. /*
  85807. ** Add a record to the sorter.
  85808. */
  85809. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  85810. const VdbeCursor *pCsr, /* Sorter cursor */
  85811. Mem *pVal /* Memory cell containing record */
  85812. ){
  85813. VdbeSorter *pSorter;
  85814. int rc = SQLITE_OK; /* Return Code */
  85815. SorterRecord *pNew; /* New list element */
  85816. int bFlush; /* True to flush contents of memory to PMA */
  85817. int nReq; /* Bytes of memory required */
  85818. int nPMA; /* Bytes of PMA space required */
  85819. int t; /* serial type of first record field */
  85820. assert( pCsr->eCurType==CURTYPE_SORTER );
  85821. pSorter = pCsr->uc.pSorter;
  85822. getVarint32((const u8*)&pVal->z[1], t);
  85823. if( t>0 && t<10 && t!=7 ){
  85824. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  85825. }else if( t>10 && (t & 0x01) ){
  85826. pSorter->typeMask &= SORTER_TYPE_TEXT;
  85827. }else{
  85828. pSorter->typeMask = 0;
  85829. }
  85830. assert( pSorter );
  85831. /* Figure out whether or not the current contents of memory should be
  85832. ** flushed to a PMA before continuing. If so, do so.
  85833. **
  85834. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  85835. ** flush the contents of memory to a new PMA if (a) at least one value is
  85836. ** already in memory and (b) the new value will not fit in memory.
  85837. **
  85838. ** Or, if using separate allocations for each record, flush the contents
  85839. ** of memory to a PMA if either of the following are true:
  85840. **
  85841. ** * The total memory allocated for the in-memory list is greater
  85842. ** than (page-size * cache-size), or
  85843. **
  85844. ** * The total memory allocated for the in-memory list is greater
  85845. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  85846. */
  85847. nReq = pVal->n + sizeof(SorterRecord);
  85848. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  85849. if( pSorter->mxPmaSize ){
  85850. if( pSorter->list.aMemory ){
  85851. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  85852. }else{
  85853. bFlush = (
  85854. (pSorter->list.szPMA > pSorter->mxPmaSize)
  85855. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  85856. );
  85857. }
  85858. if( bFlush ){
  85859. rc = vdbeSorterFlushPMA(pSorter);
  85860. pSorter->list.szPMA = 0;
  85861. pSorter->iMemory = 0;
  85862. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  85863. }
  85864. }
  85865. pSorter->list.szPMA += nPMA;
  85866. if( nPMA>pSorter->mxKeysize ){
  85867. pSorter->mxKeysize = nPMA;
  85868. }
  85869. if( pSorter->list.aMemory ){
  85870. int nMin = pSorter->iMemory + nReq;
  85871. if( nMin>pSorter->nMemory ){
  85872. u8 *aNew;
  85873. int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  85874. int nNew = pSorter->nMemory * 2;
  85875. while( nNew < nMin ) nNew = nNew*2;
  85876. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  85877. if( nNew < nMin ) nNew = nMin;
  85878. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  85879. if( !aNew ) return SQLITE_NOMEM_BKPT;
  85880. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  85881. pSorter->list.aMemory = aNew;
  85882. pSorter->nMemory = nNew;
  85883. }
  85884. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  85885. pSorter->iMemory += ROUND8(nReq);
  85886. if( pSorter->list.pList ){
  85887. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  85888. }
  85889. }else{
  85890. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  85891. if( pNew==0 ){
  85892. return SQLITE_NOMEM_BKPT;
  85893. }
  85894. pNew->u.pNext = pSorter->list.pList;
  85895. }
  85896. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  85897. pNew->nVal = pVal->n;
  85898. pSorter->list.pList = pNew;
  85899. return rc;
  85900. }
  85901. /*
  85902. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  85903. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  85904. ** except that the number-of-bytes varint is omitted from the start.
  85905. */
  85906. static int vdbeIncrPopulate(IncrMerger *pIncr){
  85907. int rc = SQLITE_OK;
  85908. int rc2;
  85909. i64 iStart = pIncr->iStartOff;
  85910. SorterFile *pOut = &pIncr->aFile[1];
  85911. SortSubtask *pTask = pIncr->pTask;
  85912. MergeEngine *pMerger = pIncr->pMerger;
  85913. PmaWriter writer;
  85914. assert( pIncr->bEof==0 );
  85915. vdbeSorterPopulateDebug(pTask, "enter");
  85916. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  85917. while( rc==SQLITE_OK ){
  85918. int dummy;
  85919. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  85920. int nKey = pReader->nKey;
  85921. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  85922. /* Check if the output file is full or if the input has been exhausted.
  85923. ** In either case exit the loop. */
  85924. if( pReader->pFd==0 ) break;
  85925. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  85926. /* Write the next key to the output. */
  85927. vdbePmaWriteVarint(&writer, nKey);
  85928. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  85929. assert( pIncr->pMerger->pTask==pTask );
  85930. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  85931. }
  85932. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  85933. if( rc==SQLITE_OK ) rc = rc2;
  85934. vdbeSorterPopulateDebug(pTask, "exit");
  85935. return rc;
  85936. }
  85937. #if SQLITE_MAX_WORKER_THREADS>0
  85938. /*
  85939. ** The main routine for background threads that populate aFile[1] of
  85940. ** multi-threaded IncrMerger objects.
  85941. */
  85942. static void *vdbeIncrPopulateThread(void *pCtx){
  85943. IncrMerger *pIncr = (IncrMerger*)pCtx;
  85944. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  85945. pIncr->pTask->bDone = 1;
  85946. return pRet;
  85947. }
  85948. /*
  85949. ** Launch a background thread to populate aFile[1] of pIncr.
  85950. */
  85951. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  85952. void *p = (void*)pIncr;
  85953. assert( pIncr->bUseThread );
  85954. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  85955. }
  85956. #endif
  85957. /*
  85958. ** This function is called when the PmaReader corresponding to pIncr has
  85959. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  85960. ** aFile[0] such that the PmaReader should start rereading it from the
  85961. ** beginning.
  85962. **
  85963. ** For single-threaded objects, this is accomplished by literally reading
  85964. ** keys from pIncr->pMerger and repopulating aFile[0].
  85965. **
  85966. ** For multi-threaded objects, all that is required is to wait until the
  85967. ** background thread is finished (if it is not already) and then swap
  85968. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  85969. ** been exhausted, this function also launches a new background thread
  85970. ** to populate the new aFile[1].
  85971. **
  85972. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  85973. */
  85974. static int vdbeIncrSwap(IncrMerger *pIncr){
  85975. int rc = SQLITE_OK;
  85976. #if SQLITE_MAX_WORKER_THREADS>0
  85977. if( pIncr->bUseThread ){
  85978. rc = vdbeSorterJoinThread(pIncr->pTask);
  85979. if( rc==SQLITE_OK ){
  85980. SorterFile f0 = pIncr->aFile[0];
  85981. pIncr->aFile[0] = pIncr->aFile[1];
  85982. pIncr->aFile[1] = f0;
  85983. }
  85984. if( rc==SQLITE_OK ){
  85985. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  85986. pIncr->bEof = 1;
  85987. }else{
  85988. rc = vdbeIncrBgPopulate(pIncr);
  85989. }
  85990. }
  85991. }else
  85992. #endif
  85993. {
  85994. rc = vdbeIncrPopulate(pIncr);
  85995. pIncr->aFile[0] = pIncr->aFile[1];
  85996. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  85997. pIncr->bEof = 1;
  85998. }
  85999. }
  86000. return rc;
  86001. }
  86002. /*
  86003. ** Allocate and return a new IncrMerger object to read data from pMerger.
  86004. **
  86005. ** If an OOM condition is encountered, return NULL. In this case free the
  86006. ** pMerger argument before returning.
  86007. */
  86008. static int vdbeIncrMergerNew(
  86009. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  86010. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  86011. IncrMerger **ppOut /* Write the new IncrMerger here */
  86012. ){
  86013. int rc = SQLITE_OK;
  86014. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  86015. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  86016. if( pIncr ){
  86017. pIncr->pMerger = pMerger;
  86018. pIncr->pTask = pTask;
  86019. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  86020. pTask->file2.iEof += pIncr->mxSz;
  86021. }else{
  86022. vdbeMergeEngineFree(pMerger);
  86023. rc = SQLITE_NOMEM_BKPT;
  86024. }
  86025. return rc;
  86026. }
  86027. #if SQLITE_MAX_WORKER_THREADS>0
  86028. /*
  86029. ** Set the "use-threads" flag on object pIncr.
  86030. */
  86031. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  86032. pIncr->bUseThread = 1;
  86033. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  86034. }
  86035. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  86036. /*
  86037. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  86038. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  86039. ** are advanced. This routine merely does the comparison.
  86040. */
  86041. static void vdbeMergeEngineCompare(
  86042. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  86043. int iOut /* Store the result in pMerger->aTree[iOut] */
  86044. ){
  86045. int i1;
  86046. int i2;
  86047. int iRes;
  86048. PmaReader *p1;
  86049. PmaReader *p2;
  86050. assert( iOut<pMerger->nTree && iOut>0 );
  86051. if( iOut>=(pMerger->nTree/2) ){
  86052. i1 = (iOut - pMerger->nTree/2) * 2;
  86053. i2 = i1 + 1;
  86054. }else{
  86055. i1 = pMerger->aTree[iOut*2];
  86056. i2 = pMerger->aTree[iOut*2+1];
  86057. }
  86058. p1 = &pMerger->aReadr[i1];
  86059. p2 = &pMerger->aReadr[i2];
  86060. if( p1->pFd==0 ){
  86061. iRes = i2;
  86062. }else if( p2->pFd==0 ){
  86063. iRes = i1;
  86064. }else{
  86065. SortSubtask *pTask = pMerger->pTask;
  86066. int bCached = 0;
  86067. int res;
  86068. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  86069. res = pTask->xCompare(
  86070. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  86071. );
  86072. if( res<=0 ){
  86073. iRes = i1;
  86074. }else{
  86075. iRes = i2;
  86076. }
  86077. }
  86078. pMerger->aTree[iOut] = iRes;
  86079. }
  86080. /*
  86081. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  86082. ** and vdbePmaReaderIncrMergeInit().
  86083. **
  86084. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  86085. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  86086. ** when there exists one or more separate worker threads.
  86087. */
  86088. #define INCRINIT_NORMAL 0
  86089. #define INCRINIT_TASK 1
  86090. #define INCRINIT_ROOT 2
  86091. /*
  86092. ** Forward reference required as the vdbeIncrMergeInit() and
  86093. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  86094. ** building a merge tree.
  86095. */
  86096. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  86097. /*
  86098. ** Initialize the MergeEngine object passed as the second argument. Once this
  86099. ** function returns, the first key of merged data may be read from the
  86100. ** MergeEngine object in the usual fashion.
  86101. **
  86102. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  86103. ** objects attached to the PmaReader objects that the merger reads from have
  86104. ** already been populated, but that they have not yet populated aFile[0] and
  86105. ** set the PmaReader objects up to read from it. In this case all that is
  86106. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  86107. ** its first key.
  86108. **
  86109. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  86110. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  86111. ** to pMerger.
  86112. **
  86113. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  86114. */
  86115. static int vdbeMergeEngineInit(
  86116. SortSubtask *pTask, /* Thread that will run pMerger */
  86117. MergeEngine *pMerger, /* MergeEngine to initialize */
  86118. int eMode /* One of the INCRINIT_XXX constants */
  86119. ){
  86120. int rc = SQLITE_OK; /* Return code */
  86121. int i; /* For looping over PmaReader objects */
  86122. int nTree = pMerger->nTree;
  86123. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  86124. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  86125. /* Verify that the MergeEngine is assigned to a single thread */
  86126. assert( pMerger->pTask==0 );
  86127. pMerger->pTask = pTask;
  86128. for(i=0; i<nTree; i++){
  86129. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  86130. /* PmaReaders should be normally initialized in order, as if they are
  86131. ** reading from the same temp file this makes for more linear file IO.
  86132. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  86133. ** in use it will block the vdbePmaReaderNext() call while it uses
  86134. ** the main thread to fill its buffer. So calling PmaReaderNext()
  86135. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  86136. ** better advantage of multi-processor hardware. */
  86137. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  86138. }else{
  86139. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  86140. }
  86141. if( rc!=SQLITE_OK ) return rc;
  86142. }
  86143. for(i=pMerger->nTree-1; i>0; i--){
  86144. vdbeMergeEngineCompare(pMerger, i);
  86145. }
  86146. return pTask->pUnpacked->errCode;
  86147. }
  86148. /*
  86149. ** The PmaReader passed as the first argument is guaranteed to be an
  86150. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  86151. ** and/or initialize the temp file related fields of the IncrMerge
  86152. ** object at (pReadr->pIncr).
  86153. **
  86154. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  86155. ** in the sub-tree headed by pReadr are also initialized. Data is then
  86156. ** loaded into the buffers belonging to pReadr and it is set to point to
  86157. ** the first key in its range.
  86158. **
  86159. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  86160. ** to be a multi-threaded PmaReader and this function is being called in a
  86161. ** background thread. In this case all PmaReaders in the sub-tree are
  86162. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  86163. ** pReadr is populated. However, pReadr itself is not set up to point
  86164. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  86165. ** that.
  86166. **
  86167. ** The reason this function does not call vdbePmaReaderNext() immediately
  86168. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  86169. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  86170. ** this entire function is being run by thread (pTask->thread), that will
  86171. ** lead to the current background thread attempting to join itself.
  86172. **
  86173. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  86174. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  86175. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  86176. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  86177. ** the current PmaReader set to point to the first key in its range.
  86178. **
  86179. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  86180. */
  86181. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  86182. int rc = SQLITE_OK;
  86183. IncrMerger *pIncr = pReadr->pIncr;
  86184. SortSubtask *pTask = pIncr->pTask;
  86185. sqlite3 *db = pTask->pSorter->db;
  86186. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  86187. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  86188. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  86189. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  86190. ** requires two temp files to itself, whereas a single-threaded object
  86191. ** only requires a region of pTask->file2. */
  86192. if( rc==SQLITE_OK ){
  86193. int mxSz = pIncr->mxSz;
  86194. #if SQLITE_MAX_WORKER_THREADS>0
  86195. if( pIncr->bUseThread ){
  86196. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  86197. if( rc==SQLITE_OK ){
  86198. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  86199. }
  86200. }else
  86201. #endif
  86202. /*if( !pIncr->bUseThread )*/{
  86203. if( pTask->file2.pFd==0 ){
  86204. assert( pTask->file2.iEof>0 );
  86205. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  86206. pTask->file2.iEof = 0;
  86207. }
  86208. if( rc==SQLITE_OK ){
  86209. pIncr->aFile[1].pFd = pTask->file2.pFd;
  86210. pIncr->iStartOff = pTask->file2.iEof;
  86211. pTask->file2.iEof += mxSz;
  86212. }
  86213. }
  86214. }
  86215. #if SQLITE_MAX_WORKER_THREADS>0
  86216. if( rc==SQLITE_OK && pIncr->bUseThread ){
  86217. /* Use the current thread to populate aFile[1], even though this
  86218. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  86219. ** then this function is already running in background thread
  86220. ** pIncr->pTask->thread.
  86221. **
  86222. ** If this is the INCRINIT_ROOT object, then it is running in the
  86223. ** main VDBE thread. But that is Ok, as that thread cannot return
  86224. ** control to the VDBE or proceed with anything useful until the
  86225. ** first results are ready from this merger object anyway.
  86226. */
  86227. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  86228. rc = vdbeIncrPopulate(pIncr);
  86229. }
  86230. #endif
  86231. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  86232. rc = vdbePmaReaderNext(pReadr);
  86233. }
  86234. return rc;
  86235. }
  86236. #if SQLITE_MAX_WORKER_THREADS>0
  86237. /*
  86238. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  86239. ** background threads.
  86240. */
  86241. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  86242. PmaReader *pReader = (PmaReader*)pCtx;
  86243. void *pRet = SQLITE_INT_TO_PTR(
  86244. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  86245. );
  86246. pReader->pIncr->pTask->bDone = 1;
  86247. return pRet;
  86248. }
  86249. #endif
  86250. /*
  86251. ** If the PmaReader passed as the first argument is not an incremental-reader
  86252. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  86253. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  86254. ** this routine to initialize the incremental merge.
  86255. **
  86256. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  86257. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  86258. ** Or, if the IncrMerger is single threaded, the same function is called
  86259. ** using the current thread.
  86260. */
  86261. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  86262. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  86263. int rc = SQLITE_OK; /* Return code */
  86264. if( pIncr ){
  86265. #if SQLITE_MAX_WORKER_THREADS>0
  86266. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  86267. if( pIncr->bUseThread ){
  86268. void *pCtx = (void*)pReadr;
  86269. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  86270. }else
  86271. #endif
  86272. {
  86273. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  86274. }
  86275. }
  86276. return rc;
  86277. }
  86278. /*
  86279. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  86280. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  86281. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  86282. ** to NULL and return an SQLite error code.
  86283. **
  86284. ** When this function is called, *piOffset is set to the offset of the
  86285. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  86286. ** set to the offset immediately following the last byte of the last
  86287. ** PMA before returning. If an error does occur, then the final value of
  86288. ** *piOffset is undefined.
  86289. */
  86290. static int vdbeMergeEngineLevel0(
  86291. SortSubtask *pTask, /* Sorter task to read from */
  86292. int nPMA, /* Number of PMAs to read */
  86293. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  86294. MergeEngine **ppOut /* OUT: New merge-engine */
  86295. ){
  86296. MergeEngine *pNew; /* Merge engine to return */
  86297. i64 iOff = *piOffset;
  86298. int i;
  86299. int rc = SQLITE_OK;
  86300. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  86301. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  86302. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  86303. i64 nDummy = 0;
  86304. PmaReader *pReadr = &pNew->aReadr[i];
  86305. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  86306. iOff = pReadr->iEof;
  86307. }
  86308. if( rc!=SQLITE_OK ){
  86309. vdbeMergeEngineFree(pNew);
  86310. *ppOut = 0;
  86311. }
  86312. *piOffset = iOff;
  86313. return rc;
  86314. }
  86315. /*
  86316. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  86317. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  86318. **
  86319. ** i.e.
  86320. **
  86321. ** nPMA<=16 -> TreeDepth() == 0
  86322. ** nPMA<=256 -> TreeDepth() == 1
  86323. ** nPMA<=65536 -> TreeDepth() == 2
  86324. */
  86325. static int vdbeSorterTreeDepth(int nPMA){
  86326. int nDepth = 0;
  86327. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  86328. while( nDiv < (i64)nPMA ){
  86329. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  86330. nDepth++;
  86331. }
  86332. return nDepth;
  86333. }
  86334. /*
  86335. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  86336. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  86337. ** tree, counting from zero. This function adds pLeaf to the tree.
  86338. **
  86339. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  86340. ** code is returned and pLeaf is freed.
  86341. */
  86342. static int vdbeSorterAddToTree(
  86343. SortSubtask *pTask, /* Task context */
  86344. int nDepth, /* Depth of tree according to TreeDepth() */
  86345. int iSeq, /* Sequence number of leaf within tree */
  86346. MergeEngine *pRoot, /* Root of tree */
  86347. MergeEngine *pLeaf /* Leaf to add to tree */
  86348. ){
  86349. int rc = SQLITE_OK;
  86350. int nDiv = 1;
  86351. int i;
  86352. MergeEngine *p = pRoot;
  86353. IncrMerger *pIncr;
  86354. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  86355. for(i=1; i<nDepth; i++){
  86356. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  86357. }
  86358. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  86359. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  86360. PmaReader *pReadr = &p->aReadr[iIter];
  86361. if( pReadr->pIncr==0 ){
  86362. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  86363. if( pNew==0 ){
  86364. rc = SQLITE_NOMEM_BKPT;
  86365. }else{
  86366. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  86367. }
  86368. }
  86369. if( rc==SQLITE_OK ){
  86370. p = pReadr->pIncr->pMerger;
  86371. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  86372. }
  86373. }
  86374. if( rc==SQLITE_OK ){
  86375. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  86376. }else{
  86377. vdbeIncrFree(pIncr);
  86378. }
  86379. return rc;
  86380. }
  86381. /*
  86382. ** This function is called as part of a SorterRewind() operation on a sorter
  86383. ** that has already written two or more level-0 PMAs to one or more temp
  86384. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  86385. ** can be used to incrementally merge all PMAs on disk.
  86386. **
  86387. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  86388. ** MergeEngine object at the root of the tree before returning. Or, if an
  86389. ** error occurs, an SQLite error code is returned and the final value
  86390. ** of *ppOut is undefined.
  86391. */
  86392. static int vdbeSorterMergeTreeBuild(
  86393. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  86394. MergeEngine **ppOut /* Write the MergeEngine here */
  86395. ){
  86396. MergeEngine *pMain = 0;
  86397. int rc = SQLITE_OK;
  86398. int iTask;
  86399. #if SQLITE_MAX_WORKER_THREADS>0
  86400. /* If the sorter uses more than one task, then create the top-level
  86401. ** MergeEngine here. This MergeEngine will read data from exactly
  86402. ** one PmaReader per sub-task. */
  86403. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  86404. if( pSorter->nTask>1 ){
  86405. pMain = vdbeMergeEngineNew(pSorter->nTask);
  86406. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  86407. }
  86408. #endif
  86409. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  86410. SortSubtask *pTask = &pSorter->aTask[iTask];
  86411. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  86412. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  86413. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  86414. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  86415. i64 iReadOff = 0;
  86416. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  86417. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  86418. }else{
  86419. int i;
  86420. int iSeq = 0;
  86421. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  86422. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  86423. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  86424. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  86425. int nReader; /* Number of level-0 PMAs to merge */
  86426. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  86427. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  86428. if( rc==SQLITE_OK ){
  86429. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  86430. }
  86431. }
  86432. }
  86433. if( rc==SQLITE_OK ){
  86434. #if SQLITE_MAX_WORKER_THREADS>0
  86435. if( pMain!=0 ){
  86436. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  86437. }else
  86438. #endif
  86439. {
  86440. assert( pMain==0 );
  86441. pMain = pRoot;
  86442. }
  86443. }else{
  86444. vdbeMergeEngineFree(pRoot);
  86445. }
  86446. }
  86447. }
  86448. if( rc!=SQLITE_OK ){
  86449. vdbeMergeEngineFree(pMain);
  86450. pMain = 0;
  86451. }
  86452. *ppOut = pMain;
  86453. return rc;
  86454. }
  86455. /*
  86456. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  86457. ** on a sorter that has written two or more PMAs to temporary files. It sets
  86458. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  86459. ** (for multi-threaded sorters) so that it can be used to iterate through
  86460. ** all records stored in the sorter.
  86461. **
  86462. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  86463. */
  86464. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  86465. int rc; /* Return code */
  86466. SortSubtask *pTask0 = &pSorter->aTask[0];
  86467. MergeEngine *pMain = 0;
  86468. #if SQLITE_MAX_WORKER_THREADS
  86469. sqlite3 *db = pTask0->pSorter->db;
  86470. int i;
  86471. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  86472. for(i=0; i<pSorter->nTask; i++){
  86473. pSorter->aTask[i].xCompare = xCompare;
  86474. }
  86475. #endif
  86476. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  86477. if( rc==SQLITE_OK ){
  86478. #if SQLITE_MAX_WORKER_THREADS
  86479. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  86480. if( pSorter->bUseThreads ){
  86481. int iTask;
  86482. PmaReader *pReadr = 0;
  86483. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  86484. rc = vdbeSortAllocUnpacked(pLast);
  86485. if( rc==SQLITE_OK ){
  86486. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  86487. pSorter->pReader = pReadr;
  86488. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  86489. }
  86490. if( rc==SQLITE_OK ){
  86491. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  86492. if( rc==SQLITE_OK ){
  86493. vdbeIncrMergerSetThreads(pReadr->pIncr);
  86494. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  86495. IncrMerger *pIncr;
  86496. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  86497. vdbeIncrMergerSetThreads(pIncr);
  86498. assert( pIncr->pTask!=pLast );
  86499. }
  86500. }
  86501. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  86502. /* Check that:
  86503. **
  86504. ** a) The incremental merge object is configured to use the
  86505. ** right task, and
  86506. ** b) If it is using task (nTask-1), it is configured to run
  86507. ** in single-threaded mode. This is important, as the
  86508. ** root merge (INCRINIT_ROOT) will be using the same task
  86509. ** object.
  86510. */
  86511. PmaReader *p = &pMain->aReadr[iTask];
  86512. assert( p->pIncr==0 || (
  86513. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  86514. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  86515. ));
  86516. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  86517. }
  86518. }
  86519. pMain = 0;
  86520. }
  86521. if( rc==SQLITE_OK ){
  86522. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  86523. }
  86524. }else
  86525. #endif
  86526. {
  86527. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  86528. pSorter->pMerger = pMain;
  86529. pMain = 0;
  86530. }
  86531. }
  86532. if( rc!=SQLITE_OK ){
  86533. vdbeMergeEngineFree(pMain);
  86534. }
  86535. return rc;
  86536. }
  86537. /*
  86538. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  86539. ** this function is called to prepare for iterating through the records
  86540. ** in sorted order.
  86541. */
  86542. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  86543. VdbeSorter *pSorter;
  86544. int rc = SQLITE_OK; /* Return code */
  86545. assert( pCsr->eCurType==CURTYPE_SORTER );
  86546. pSorter = pCsr->uc.pSorter;
  86547. assert( pSorter );
  86548. /* If no data has been written to disk, then do not do so now. Instead,
  86549. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  86550. ** from the in-memory list. */
  86551. if( pSorter->bUsePMA==0 ){
  86552. if( pSorter->list.pList ){
  86553. *pbEof = 0;
  86554. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  86555. }else{
  86556. *pbEof = 1;
  86557. }
  86558. return rc;
  86559. }
  86560. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  86561. ** function flushes the contents of memory to disk, it immediately always
  86562. ** creates a new list consisting of a single key immediately afterwards.
  86563. ** So the list is never empty at this point. */
  86564. assert( pSorter->list.pList );
  86565. rc = vdbeSorterFlushPMA(pSorter);
  86566. /* Join all threads */
  86567. rc = vdbeSorterJoinAll(pSorter, rc);
  86568. vdbeSorterRewindDebug("rewind");
  86569. /* Assuming no errors have occurred, set up a merger structure to
  86570. ** incrementally read and merge all remaining PMAs. */
  86571. assert( pSorter->pReader==0 );
  86572. if( rc==SQLITE_OK ){
  86573. rc = vdbeSorterSetupMerge(pSorter);
  86574. *pbEof = 0;
  86575. }
  86576. vdbeSorterRewindDebug("rewinddone");
  86577. return rc;
  86578. }
  86579. /*
  86580. ** Advance to the next element in the sorter. Return value:
  86581. **
  86582. ** SQLITE_OK success
  86583. ** SQLITE_DONE end of data
  86584. ** otherwise some kind of error.
  86585. */
  86586. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
  86587. VdbeSorter *pSorter;
  86588. int rc; /* Return code */
  86589. assert( pCsr->eCurType==CURTYPE_SORTER );
  86590. pSorter = pCsr->uc.pSorter;
  86591. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  86592. if( pSorter->bUsePMA ){
  86593. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  86594. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  86595. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  86596. #if SQLITE_MAX_WORKER_THREADS>0
  86597. if( pSorter->bUseThreads ){
  86598. rc = vdbePmaReaderNext(pSorter->pReader);
  86599. if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
  86600. }else
  86601. #endif
  86602. /*if( !pSorter->bUseThreads )*/ {
  86603. int res = 0;
  86604. assert( pSorter->pMerger!=0 );
  86605. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  86606. rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
  86607. if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
  86608. }
  86609. }else{
  86610. SorterRecord *pFree = pSorter->list.pList;
  86611. pSorter->list.pList = pFree->u.pNext;
  86612. pFree->u.pNext = 0;
  86613. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  86614. rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
  86615. }
  86616. return rc;
  86617. }
  86618. /*
  86619. ** Return a pointer to a buffer owned by the sorter that contains the
  86620. ** current key.
  86621. */
  86622. static void *vdbeSorterRowkey(
  86623. const VdbeSorter *pSorter, /* Sorter object */
  86624. int *pnKey /* OUT: Size of current key in bytes */
  86625. ){
  86626. void *pKey;
  86627. if( pSorter->bUsePMA ){
  86628. PmaReader *pReader;
  86629. #if SQLITE_MAX_WORKER_THREADS>0
  86630. if( pSorter->bUseThreads ){
  86631. pReader = pSorter->pReader;
  86632. }else
  86633. #endif
  86634. /*if( !pSorter->bUseThreads )*/{
  86635. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  86636. }
  86637. *pnKey = pReader->nKey;
  86638. pKey = pReader->aKey;
  86639. }else{
  86640. *pnKey = pSorter->list.pList->nVal;
  86641. pKey = SRVAL(pSorter->list.pList);
  86642. }
  86643. return pKey;
  86644. }
  86645. /*
  86646. ** Copy the current sorter key into the memory cell pOut.
  86647. */
  86648. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  86649. VdbeSorter *pSorter;
  86650. void *pKey; int nKey; /* Sorter key to copy into pOut */
  86651. assert( pCsr->eCurType==CURTYPE_SORTER );
  86652. pSorter = pCsr->uc.pSorter;
  86653. pKey = vdbeSorterRowkey(pSorter, &nKey);
  86654. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  86655. return SQLITE_NOMEM_BKPT;
  86656. }
  86657. pOut->n = nKey;
  86658. MemSetTypeFlag(pOut, MEM_Blob);
  86659. memcpy(pOut->z, pKey, nKey);
  86660. return SQLITE_OK;
  86661. }
  86662. /*
  86663. ** Compare the key in memory cell pVal with the key that the sorter cursor
  86664. ** passed as the first argument currently points to. For the purposes of
  86665. ** the comparison, ignore the rowid field at the end of each record.
  86666. **
  86667. ** If the sorter cursor key contains any NULL values, consider it to be
  86668. ** less than pVal. Even if pVal also contains NULL values.
  86669. **
  86670. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  86671. ** Otherwise, set *pRes to a negative, zero or positive value if the
  86672. ** key in pVal is smaller than, equal to or larger than the current sorter
  86673. ** key.
  86674. **
  86675. ** This routine forms the core of the OP_SorterCompare opcode, which in
  86676. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  86677. */
  86678. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  86679. const VdbeCursor *pCsr, /* Sorter cursor */
  86680. Mem *pVal, /* Value to compare to current sorter key */
  86681. int nKeyCol, /* Compare this many columns */
  86682. int *pRes /* OUT: Result of comparison */
  86683. ){
  86684. VdbeSorter *pSorter;
  86685. UnpackedRecord *r2;
  86686. KeyInfo *pKeyInfo;
  86687. int i;
  86688. void *pKey; int nKey; /* Sorter key to compare pVal with */
  86689. assert( pCsr->eCurType==CURTYPE_SORTER );
  86690. pSorter = pCsr->uc.pSorter;
  86691. r2 = pSorter->pUnpacked;
  86692. pKeyInfo = pCsr->pKeyInfo;
  86693. if( r2==0 ){
  86694. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  86695. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  86696. r2->nField = nKeyCol;
  86697. }
  86698. assert( r2->nField==nKeyCol );
  86699. pKey = vdbeSorterRowkey(pSorter, &nKey);
  86700. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  86701. for(i=0; i<nKeyCol; i++){
  86702. if( r2->aMem[i].flags & MEM_Null ){
  86703. *pRes = -1;
  86704. return SQLITE_OK;
  86705. }
  86706. }
  86707. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  86708. return SQLITE_OK;
  86709. }
  86710. /************** End of vdbesort.c ********************************************/
  86711. /************** Begin file memjournal.c **************************************/
  86712. /*
  86713. ** 2008 October 7
  86714. **
  86715. ** The author disclaims copyright to this source code. In place of
  86716. ** a legal notice, here is a blessing:
  86717. **
  86718. ** May you do good and not evil.
  86719. ** May you find forgiveness for yourself and forgive others.
  86720. ** May you share freely, never taking more than you give.
  86721. **
  86722. *************************************************************************
  86723. **
  86724. ** This file contains code use to implement an in-memory rollback journal.
  86725. ** The in-memory rollback journal is used to journal transactions for
  86726. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  86727. **
  86728. ** Update: The in-memory journal is also used to temporarily cache
  86729. ** smaller journals that are not critical for power-loss recovery.
  86730. ** For example, statement journals that are not too big will be held
  86731. ** entirely in memory, thus reducing the number of file I/O calls, and
  86732. ** more importantly, reducing temporary file creation events. If these
  86733. ** journals become too large for memory, they are spilled to disk. But
  86734. ** in the common case, they are usually small and no file I/O needs to
  86735. ** occur.
  86736. */
  86737. /* #include "sqliteInt.h" */
  86738. /* Forward references to internal structures */
  86739. typedef struct MemJournal MemJournal;
  86740. typedef struct FilePoint FilePoint;
  86741. typedef struct FileChunk FileChunk;
  86742. /*
  86743. ** The rollback journal is composed of a linked list of these structures.
  86744. **
  86745. ** The zChunk array is always at least 8 bytes in size - usually much more.
  86746. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  86747. */
  86748. struct FileChunk {
  86749. FileChunk *pNext; /* Next chunk in the journal */
  86750. u8 zChunk[8]; /* Content of this chunk */
  86751. };
  86752. /*
  86753. ** By default, allocate this many bytes of memory for each FileChunk object.
  86754. */
  86755. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  86756. /*
  86757. ** For chunk size nChunkSize, return the number of bytes that should
  86758. ** be allocated for each FileChunk structure.
  86759. */
  86760. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  86761. /*
  86762. ** An instance of this object serves as a cursor into the rollback journal.
  86763. ** The cursor can be either for reading or writing.
  86764. */
  86765. struct FilePoint {
  86766. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  86767. FileChunk *pChunk; /* Specific chunk into which cursor points */
  86768. };
  86769. /*
  86770. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  86771. ** is an instance of this class.
  86772. */
  86773. struct MemJournal {
  86774. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  86775. int nChunkSize; /* In-memory chunk-size */
  86776. int nSpill; /* Bytes of data before flushing */
  86777. int nSize; /* Bytes of data currently in memory */
  86778. FileChunk *pFirst; /* Head of in-memory chunk-list */
  86779. FilePoint endpoint; /* Pointer to the end of the file */
  86780. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  86781. int flags; /* xOpen flags */
  86782. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  86783. const char *zJournal; /* Name of the journal file */
  86784. };
  86785. /*
  86786. ** Read data from the in-memory journal file. This is the implementation
  86787. ** of the sqlite3_vfs.xRead method.
  86788. */
  86789. static int memjrnlRead(
  86790. sqlite3_file *pJfd, /* The journal file from which to read */
  86791. void *zBuf, /* Put the results here */
  86792. int iAmt, /* Number of bytes to read */
  86793. sqlite_int64 iOfst /* Begin reading at this offset */
  86794. ){
  86795. MemJournal *p = (MemJournal *)pJfd;
  86796. u8 *zOut = zBuf;
  86797. int nRead = iAmt;
  86798. int iChunkOffset;
  86799. FileChunk *pChunk;
  86800. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  86801. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  86802. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  86803. return SQLITE_IOERR_SHORT_READ;
  86804. }
  86805. #endif
  86806. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  86807. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  86808. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  86809. sqlite3_int64 iOff = 0;
  86810. for(pChunk=p->pFirst;
  86811. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  86812. pChunk=pChunk->pNext
  86813. ){
  86814. iOff += p->nChunkSize;
  86815. }
  86816. }else{
  86817. pChunk = p->readpoint.pChunk;
  86818. assert( pChunk!=0 );
  86819. }
  86820. iChunkOffset = (int)(iOfst%p->nChunkSize);
  86821. do {
  86822. int iSpace = p->nChunkSize - iChunkOffset;
  86823. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  86824. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  86825. zOut += nCopy;
  86826. nRead -= iSpace;
  86827. iChunkOffset = 0;
  86828. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  86829. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  86830. p->readpoint.pChunk = pChunk;
  86831. return SQLITE_OK;
  86832. }
  86833. /*
  86834. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  86835. */
  86836. static void memjrnlFreeChunks(MemJournal *p){
  86837. FileChunk *pIter;
  86838. FileChunk *pNext;
  86839. for(pIter=p->pFirst; pIter; pIter=pNext){
  86840. pNext = pIter->pNext;
  86841. sqlite3_free(pIter);
  86842. }
  86843. p->pFirst = 0;
  86844. }
  86845. /*
  86846. ** Flush the contents of memory to a real file on disk.
  86847. */
  86848. static int memjrnlCreateFile(MemJournal *p){
  86849. int rc;
  86850. sqlite3_file *pReal = (sqlite3_file*)p;
  86851. MemJournal copy = *p;
  86852. memset(p, 0, sizeof(MemJournal));
  86853. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  86854. if( rc==SQLITE_OK ){
  86855. int nChunk = copy.nChunkSize;
  86856. i64 iOff = 0;
  86857. FileChunk *pIter;
  86858. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  86859. if( iOff + nChunk > copy.endpoint.iOffset ){
  86860. nChunk = copy.endpoint.iOffset - iOff;
  86861. }
  86862. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  86863. if( rc ) break;
  86864. iOff += nChunk;
  86865. }
  86866. if( rc==SQLITE_OK ){
  86867. /* No error has occurred. Free the in-memory buffers. */
  86868. memjrnlFreeChunks(&copy);
  86869. }
  86870. }
  86871. if( rc!=SQLITE_OK ){
  86872. /* If an error occurred while creating or writing to the file, restore
  86873. ** the original before returning. This way, SQLite uses the in-memory
  86874. ** journal data to roll back changes made to the internal page-cache
  86875. ** before this function was called. */
  86876. sqlite3OsClose(pReal);
  86877. *p = copy;
  86878. }
  86879. return rc;
  86880. }
  86881. /*
  86882. ** Write data to the file.
  86883. */
  86884. static int memjrnlWrite(
  86885. sqlite3_file *pJfd, /* The journal file into which to write */
  86886. const void *zBuf, /* Take data to be written from here */
  86887. int iAmt, /* Number of bytes to write */
  86888. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  86889. ){
  86890. MemJournal *p = (MemJournal *)pJfd;
  86891. int nWrite = iAmt;
  86892. u8 *zWrite = (u8 *)zBuf;
  86893. /* If the file should be created now, create it and write the new data
  86894. ** into the file on disk. */
  86895. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  86896. int rc = memjrnlCreateFile(p);
  86897. if( rc==SQLITE_OK ){
  86898. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  86899. }
  86900. return rc;
  86901. }
  86902. /* If the contents of this write should be stored in memory */
  86903. else{
  86904. /* An in-memory journal file should only ever be appended to. Random
  86905. ** access writes are not required. The only exception to this is when
  86906. ** the in-memory journal is being used by a connection using the
  86907. ** atomic-write optimization. In this case the first 28 bytes of the
  86908. ** journal file may be written as part of committing the transaction. */
  86909. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  86910. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  86911. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  86912. if( iOfst==0 && p->pFirst ){
  86913. assert( p->nChunkSize>iAmt );
  86914. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  86915. }else
  86916. #else
  86917. assert( iOfst>0 || p->pFirst==0 );
  86918. #endif
  86919. {
  86920. while( nWrite>0 ){
  86921. FileChunk *pChunk = p->endpoint.pChunk;
  86922. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  86923. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  86924. if( iChunkOffset==0 ){
  86925. /* New chunk is required to extend the file. */
  86926. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  86927. if( !pNew ){
  86928. return SQLITE_IOERR_NOMEM_BKPT;
  86929. }
  86930. pNew->pNext = 0;
  86931. if( pChunk ){
  86932. assert( p->pFirst );
  86933. pChunk->pNext = pNew;
  86934. }else{
  86935. assert( !p->pFirst );
  86936. p->pFirst = pNew;
  86937. }
  86938. p->endpoint.pChunk = pNew;
  86939. }
  86940. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  86941. zWrite += iSpace;
  86942. nWrite -= iSpace;
  86943. p->endpoint.iOffset += iSpace;
  86944. }
  86945. p->nSize = iAmt + iOfst;
  86946. }
  86947. }
  86948. return SQLITE_OK;
  86949. }
  86950. /*
  86951. ** Truncate the file.
  86952. **
  86953. ** If the journal file is already on disk, truncate it there. Or, if it
  86954. ** is still in main memory but is being truncated to zero bytes in size,
  86955. ** ignore
  86956. */
  86957. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  86958. MemJournal *p = (MemJournal *)pJfd;
  86959. if( ALWAYS(size==0) ){
  86960. memjrnlFreeChunks(p);
  86961. p->nSize = 0;
  86962. p->endpoint.pChunk = 0;
  86963. p->endpoint.iOffset = 0;
  86964. p->readpoint.pChunk = 0;
  86965. p->readpoint.iOffset = 0;
  86966. }
  86967. return SQLITE_OK;
  86968. }
  86969. /*
  86970. ** Close the file.
  86971. */
  86972. static int memjrnlClose(sqlite3_file *pJfd){
  86973. MemJournal *p = (MemJournal *)pJfd;
  86974. memjrnlFreeChunks(p);
  86975. return SQLITE_OK;
  86976. }
  86977. /*
  86978. ** Sync the file.
  86979. **
  86980. ** If the real file has been created, call its xSync method. Otherwise,
  86981. ** syncing an in-memory journal is a no-op.
  86982. */
  86983. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  86984. UNUSED_PARAMETER2(pJfd, flags);
  86985. return SQLITE_OK;
  86986. }
  86987. /*
  86988. ** Query the size of the file in bytes.
  86989. */
  86990. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  86991. MemJournal *p = (MemJournal *)pJfd;
  86992. *pSize = (sqlite_int64) p->endpoint.iOffset;
  86993. return SQLITE_OK;
  86994. }
  86995. /*
  86996. ** Table of methods for MemJournal sqlite3_file object.
  86997. */
  86998. static const struct sqlite3_io_methods MemJournalMethods = {
  86999. 1, /* iVersion */
  87000. memjrnlClose, /* xClose */
  87001. memjrnlRead, /* xRead */
  87002. memjrnlWrite, /* xWrite */
  87003. memjrnlTruncate, /* xTruncate */
  87004. memjrnlSync, /* xSync */
  87005. memjrnlFileSize, /* xFileSize */
  87006. 0, /* xLock */
  87007. 0, /* xUnlock */
  87008. 0, /* xCheckReservedLock */
  87009. 0, /* xFileControl */
  87010. 0, /* xSectorSize */
  87011. 0, /* xDeviceCharacteristics */
  87012. 0, /* xShmMap */
  87013. 0, /* xShmLock */
  87014. 0, /* xShmBarrier */
  87015. 0, /* xShmUnmap */
  87016. 0, /* xFetch */
  87017. 0 /* xUnfetch */
  87018. };
  87019. /*
  87020. ** Open a journal file.
  87021. **
  87022. ** The behaviour of the journal file depends on the value of parameter
  87023. ** nSpill. If nSpill is 0, then the journal file is always create and
  87024. ** accessed using the underlying VFS. If nSpill is less than zero, then
  87025. ** all content is always stored in main-memory. Finally, if nSpill is a
  87026. ** positive value, then the journal file is initially created in-memory
  87027. ** but may be flushed to disk later on. In this case the journal file is
  87028. ** flushed to disk either when it grows larger than nSpill bytes in size,
  87029. ** or when sqlite3JournalCreate() is called.
  87030. */
  87031. SQLITE_PRIVATE int sqlite3JournalOpen(
  87032. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  87033. const char *zName, /* Name of the journal file */
  87034. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  87035. int flags, /* Opening flags */
  87036. int nSpill /* Bytes buffered before opening the file */
  87037. ){
  87038. MemJournal *p = (MemJournal*)pJfd;
  87039. /* Zero the file-handle object. If nSpill was passed zero, initialize
  87040. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  87041. ** case none of the code in this module is executed as a result of calls
  87042. ** made on the journal file-handle. */
  87043. memset(p, 0, sizeof(MemJournal));
  87044. if( nSpill==0 ){
  87045. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  87046. }
  87047. if( nSpill>0 ){
  87048. p->nChunkSize = nSpill;
  87049. }else{
  87050. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  87051. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  87052. }
  87053. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  87054. p->nSpill = nSpill;
  87055. p->flags = flags;
  87056. p->zJournal = zName;
  87057. p->pVfs = pVfs;
  87058. return SQLITE_OK;
  87059. }
  87060. /*
  87061. ** Open an in-memory journal file.
  87062. */
  87063. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  87064. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  87065. }
  87066. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  87067. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  87068. /*
  87069. ** If the argument p points to a MemJournal structure that is not an
  87070. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  87071. ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
  87072. ** file has not yet been created, create it now.
  87073. */
  87074. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
  87075. int rc = SQLITE_OK;
  87076. MemJournal *p = (MemJournal*)pJfd;
  87077. if( p->pMethod==&MemJournalMethods && (
  87078. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  87079. p->nSpill>0
  87080. #else
  87081. /* While this appears to not be possible without ATOMIC_WRITE, the
  87082. ** paths are complex, so it seems prudent to leave the test in as
  87083. ** a NEVER(), in case our analysis is subtly flawed. */
  87084. NEVER(p->nSpill>0)
  87085. #endif
  87086. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  87087. || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
  87088. #endif
  87089. )){
  87090. rc = memjrnlCreateFile(p);
  87091. }
  87092. return rc;
  87093. }
  87094. #endif
  87095. /*
  87096. ** The file-handle passed as the only argument is open on a journal file.
  87097. ** Return true if this "journal file" is currently stored in heap memory,
  87098. ** or false otherwise.
  87099. */
  87100. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  87101. return p->pMethods==&MemJournalMethods;
  87102. }
  87103. /*
  87104. ** Return the number of bytes required to store a JournalFile that uses vfs
  87105. ** pVfs to create the underlying on-disk files.
  87106. */
  87107. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  87108. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  87109. }
  87110. /************** End of memjournal.c ******************************************/
  87111. /************** Begin file walker.c ******************************************/
  87112. /*
  87113. ** 2008 August 16
  87114. **
  87115. ** The author disclaims copyright to this source code. In place of
  87116. ** a legal notice, here is a blessing:
  87117. **
  87118. ** May you do good and not evil.
  87119. ** May you find forgiveness for yourself and forgive others.
  87120. ** May you share freely, never taking more than you give.
  87121. **
  87122. *************************************************************************
  87123. ** This file contains routines used for walking the parser tree for
  87124. ** an SQL statement.
  87125. */
  87126. /* #include "sqliteInt.h" */
  87127. /* #include <stdlib.h> */
  87128. /* #include <string.h> */
  87129. /*
  87130. ** Walk an expression tree. Invoke the callback once for each node
  87131. ** of the expression, while descending. (In other words, the callback
  87132. ** is invoked before visiting children.)
  87133. **
  87134. ** The return value from the callback should be one of the WRC_*
  87135. ** constants to specify how to proceed with the walk.
  87136. **
  87137. ** WRC_Continue Continue descending down the tree.
  87138. **
  87139. ** WRC_Prune Do not descend into child nodes, but allow
  87140. ** the walk to continue with sibling nodes.
  87141. **
  87142. ** WRC_Abort Do no more callbacks. Unwind the stack and
  87143. ** return from the top-level walk call.
  87144. **
  87145. ** The return value from this routine is WRC_Abort to abandon the tree walk
  87146. ** and WRC_Continue to continue.
  87147. */
  87148. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  87149. int rc;
  87150. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  87151. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  87152. while(1){
  87153. rc = pWalker->xExprCallback(pWalker, pExpr);
  87154. if( rc ) return rc & WRC_Abort;
  87155. if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  87156. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  87157. assert( pExpr->x.pList==0 || pExpr->pRight==0 );
  87158. if( pExpr->pRight ){
  87159. pExpr = pExpr->pRight;
  87160. continue;
  87161. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  87162. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  87163. }else if( pExpr->x.pList ){
  87164. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  87165. }
  87166. }
  87167. break;
  87168. }
  87169. return WRC_Continue;
  87170. }
  87171. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  87172. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  87173. }
  87174. /*
  87175. ** Call sqlite3WalkExpr() for every expression in list p or until
  87176. ** an abort request is seen.
  87177. */
  87178. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  87179. int i;
  87180. struct ExprList_item *pItem;
  87181. if( p ){
  87182. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  87183. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  87184. }
  87185. }
  87186. return WRC_Continue;
  87187. }
  87188. /*
  87189. ** Walk all expressions associated with SELECT statement p. Do
  87190. ** not invoke the SELECT callback on p, but do (of course) invoke
  87191. ** any expr callbacks and SELECT callbacks that come from subqueries.
  87192. ** Return WRC_Abort or WRC_Continue.
  87193. */
  87194. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  87195. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  87196. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  87197. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  87198. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  87199. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  87200. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  87201. return WRC_Continue;
  87202. }
  87203. /*
  87204. ** Walk the parse trees associated with all subqueries in the
  87205. ** FROM clause of SELECT statement p. Do not invoke the select
  87206. ** callback on p, but do invoke it on each FROM clause subquery
  87207. ** and on any subqueries further down in the tree. Return
  87208. ** WRC_Abort or WRC_Continue;
  87209. */
  87210. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  87211. SrcList *pSrc;
  87212. int i;
  87213. struct SrcList_item *pItem;
  87214. pSrc = p->pSrc;
  87215. assert( pSrc!=0 );
  87216. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  87217. if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  87218. return WRC_Abort;
  87219. }
  87220. if( pItem->fg.isTabFunc
  87221. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  87222. ){
  87223. return WRC_Abort;
  87224. }
  87225. }
  87226. return WRC_Continue;
  87227. }
  87228. /*
  87229. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  87230. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  87231. ** on the compound select chain, p->pPrior.
  87232. **
  87233. ** If it is not NULL, the xSelectCallback() callback is invoked before
  87234. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  87235. ** method is invoked following the walk of the expressions and FROM clause,
  87236. ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
  87237. ** and if the expressions and FROM clause both return WRC_Continue;
  87238. **
  87239. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  87240. ** there is an abort request.
  87241. **
  87242. ** If the Walker does not have an xSelectCallback() then this routine
  87243. ** is a no-op returning WRC_Continue.
  87244. */
  87245. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  87246. int rc;
  87247. if( p==0 ) return WRC_Continue;
  87248. if( pWalker->xSelectCallback==0 ) return WRC_Continue;
  87249. do{
  87250. rc = pWalker->xSelectCallback(pWalker, p);
  87251. if( rc ) return rc & WRC_Abort;
  87252. if( sqlite3WalkSelectExpr(pWalker, p)
  87253. || sqlite3WalkSelectFrom(pWalker, p)
  87254. ){
  87255. return WRC_Abort;
  87256. }
  87257. if( pWalker->xSelectCallback2 ){
  87258. pWalker->xSelectCallback2(pWalker, p);
  87259. }
  87260. p = p->pPrior;
  87261. }while( p!=0 );
  87262. return WRC_Continue;
  87263. }
  87264. /************** End of walker.c **********************************************/
  87265. /************** Begin file resolve.c *****************************************/
  87266. /*
  87267. ** 2008 August 18
  87268. **
  87269. ** The author disclaims copyright to this source code. In place of
  87270. ** a legal notice, here is a blessing:
  87271. **
  87272. ** May you do good and not evil.
  87273. ** May you find forgiveness for yourself and forgive others.
  87274. ** May you share freely, never taking more than you give.
  87275. **
  87276. *************************************************************************
  87277. **
  87278. ** This file contains routines used for walking the parser tree and
  87279. ** resolve all identifiers by associating them with a particular
  87280. ** table and column.
  87281. */
  87282. /* #include "sqliteInt.h" */
  87283. /*
  87284. ** Walk the expression tree pExpr and increase the aggregate function
  87285. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  87286. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  87287. ** outer query into an inner subquery.
  87288. **
  87289. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  87290. ** is a helper function - a callback for the tree walker.
  87291. */
  87292. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  87293. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  87294. return WRC_Continue;
  87295. }
  87296. static void incrAggFunctionDepth(Expr *pExpr, int N){
  87297. if( N>0 ){
  87298. Walker w;
  87299. memset(&w, 0, sizeof(w));
  87300. w.xExprCallback = incrAggDepth;
  87301. w.u.n = N;
  87302. sqlite3WalkExpr(&w, pExpr);
  87303. }
  87304. }
  87305. /*
  87306. ** Turn the pExpr expression into an alias for the iCol-th column of the
  87307. ** result set in pEList.
  87308. **
  87309. ** If the reference is followed by a COLLATE operator, then make sure
  87310. ** the COLLATE operator is preserved. For example:
  87311. **
  87312. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  87313. **
  87314. ** Should be transformed into:
  87315. **
  87316. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  87317. **
  87318. ** The nSubquery parameter specifies how many levels of subquery the
  87319. ** alias is removed from the original expression. The usual value is
  87320. ** zero but it might be more if the alias is contained within a subquery
  87321. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  87322. ** structures must be increased by the nSubquery amount.
  87323. */
  87324. static void resolveAlias(
  87325. Parse *pParse, /* Parsing context */
  87326. ExprList *pEList, /* A result set */
  87327. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  87328. Expr *pExpr, /* Transform this into an alias to the result set */
  87329. const char *zType, /* "GROUP" or "ORDER" or "" */
  87330. int nSubquery /* Number of subqueries that the label is moving */
  87331. ){
  87332. Expr *pOrig; /* The iCol-th column of the result set */
  87333. Expr *pDup; /* Copy of pOrig */
  87334. sqlite3 *db; /* The database connection */
  87335. assert( iCol>=0 && iCol<pEList->nExpr );
  87336. pOrig = pEList->a[iCol].pExpr;
  87337. assert( pOrig!=0 );
  87338. db = pParse->db;
  87339. pDup = sqlite3ExprDup(db, pOrig, 0);
  87340. if( pDup!=0 ){
  87341. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  87342. if( pExpr->op==TK_COLLATE ){
  87343. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  87344. }
  87345. ExprSetProperty(pDup, EP_Alias);
  87346. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  87347. ** prevents ExprDelete() from deleting the Expr structure itself,
  87348. ** allowing it to be repopulated by the memcpy() on the following line.
  87349. ** The pExpr->u.zToken might point into memory that will be freed by the
  87350. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  87351. ** make a copy of the token before doing the sqlite3DbFree().
  87352. */
  87353. ExprSetProperty(pExpr, EP_Static);
  87354. sqlite3ExprDelete(db, pExpr);
  87355. memcpy(pExpr, pDup, sizeof(*pExpr));
  87356. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  87357. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  87358. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  87359. pExpr->flags |= EP_MemToken;
  87360. }
  87361. sqlite3DbFree(db, pDup);
  87362. }
  87363. ExprSetProperty(pExpr, EP_Alias);
  87364. }
  87365. /*
  87366. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  87367. **
  87368. ** Return FALSE if the USING clause is NULL or if it does not contain
  87369. ** zCol.
  87370. */
  87371. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  87372. if( pUsing ){
  87373. int k;
  87374. for(k=0; k<pUsing->nId; k++){
  87375. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  87376. }
  87377. }
  87378. return 0;
  87379. }
  87380. /*
  87381. ** Subqueries stores the original database, table and column names for their
  87382. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  87383. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  87384. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  87385. ** match anything.
  87386. */
  87387. SQLITE_PRIVATE int sqlite3MatchSpanName(
  87388. const char *zSpan,
  87389. const char *zCol,
  87390. const char *zTab,
  87391. const char *zDb
  87392. ){
  87393. int n;
  87394. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  87395. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  87396. return 0;
  87397. }
  87398. zSpan += n+1;
  87399. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  87400. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  87401. return 0;
  87402. }
  87403. zSpan += n+1;
  87404. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  87405. return 0;
  87406. }
  87407. return 1;
  87408. }
  87409. /*
  87410. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  87411. ** that name in the set of source tables in pSrcList and make the pExpr
  87412. ** expression node refer back to that source column. The following changes
  87413. ** are made to pExpr:
  87414. **
  87415. ** pExpr->iDb Set the index in db->aDb[] of the database X
  87416. ** (even if X is implied).
  87417. ** pExpr->iTable Set to the cursor number for the table obtained
  87418. ** from pSrcList.
  87419. ** pExpr->pTab Points to the Table structure of X.Y (even if
  87420. ** X and/or Y are implied.)
  87421. ** pExpr->iColumn Set to the column number within the table.
  87422. ** pExpr->op Set to TK_COLUMN.
  87423. ** pExpr->pLeft Any expression this points to is deleted
  87424. ** pExpr->pRight Any expression this points to is deleted.
  87425. **
  87426. ** The zDb variable is the name of the database (the "X"). This value may be
  87427. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  87428. ** can be used. The zTable variable is the name of the table (the "Y"). This
  87429. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  87430. ** means that the form of the name is Z and that columns from any table
  87431. ** can be used.
  87432. **
  87433. ** If the name cannot be resolved unambiguously, leave an error message
  87434. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  87435. */
  87436. static int lookupName(
  87437. Parse *pParse, /* The parsing context */
  87438. const char *zDb, /* Name of the database containing table, or NULL */
  87439. const char *zTab, /* Name of table containing column, or NULL */
  87440. const char *zCol, /* Name of the column. */
  87441. NameContext *pNC, /* The name context used to resolve the name */
  87442. Expr *pExpr /* Make this EXPR node point to the selected column */
  87443. ){
  87444. int i, j; /* Loop counters */
  87445. int cnt = 0; /* Number of matching column names */
  87446. int cntTab = 0; /* Number of matching table names */
  87447. int nSubquery = 0; /* How many levels of subquery */
  87448. sqlite3 *db = pParse->db; /* The database connection */
  87449. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  87450. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  87451. NameContext *pTopNC = pNC; /* First namecontext in the list */
  87452. Schema *pSchema = 0; /* Schema of the expression */
  87453. int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
  87454. Table *pTab = 0; /* Table hold the row */
  87455. Column *pCol; /* A column of pTab */
  87456. assert( pNC ); /* the name context cannot be NULL. */
  87457. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  87458. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  87459. /* Initialize the node to no-match */
  87460. pExpr->iTable = -1;
  87461. pExpr->pTab = 0;
  87462. ExprSetVVAProperty(pExpr, EP_NoReduce);
  87463. /* Translate the schema name in zDb into a pointer to the corresponding
  87464. ** schema. If not found, pSchema will remain NULL and nothing will match
  87465. ** resulting in an appropriate error message toward the end of this routine
  87466. */
  87467. if( zDb ){
  87468. testcase( pNC->ncFlags & NC_PartIdx );
  87469. testcase( pNC->ncFlags & NC_IsCheck );
  87470. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  87471. /* Silently ignore database qualifiers inside CHECK constraints and
  87472. ** partial indices. Do not raise errors because that might break
  87473. ** legacy and because it does not hurt anything to just ignore the
  87474. ** database name. */
  87475. zDb = 0;
  87476. }else{
  87477. for(i=0; i<db->nDb; i++){
  87478. assert( db->aDb[i].zDbSName );
  87479. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  87480. pSchema = db->aDb[i].pSchema;
  87481. break;
  87482. }
  87483. }
  87484. }
  87485. }
  87486. /* Start at the inner-most context and move outward until a match is found */
  87487. assert( pNC && cnt==0 );
  87488. do{
  87489. ExprList *pEList;
  87490. SrcList *pSrcList = pNC->pSrcList;
  87491. if( pSrcList ){
  87492. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  87493. pTab = pItem->pTab;
  87494. assert( pTab!=0 && pTab->zName!=0 );
  87495. assert( pTab->nCol>0 );
  87496. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  87497. int hit = 0;
  87498. pEList = pItem->pSelect->pEList;
  87499. for(j=0; j<pEList->nExpr; j++){
  87500. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  87501. cnt++;
  87502. cntTab = 2;
  87503. pMatch = pItem;
  87504. pExpr->iColumn = j;
  87505. hit = 1;
  87506. }
  87507. }
  87508. if( hit || zTab==0 ) continue;
  87509. }
  87510. if( zDb && pTab->pSchema!=pSchema ){
  87511. continue;
  87512. }
  87513. if( zTab ){
  87514. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  87515. assert( zTabName!=0 );
  87516. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  87517. continue;
  87518. }
  87519. }
  87520. if( 0==(cntTab++) ){
  87521. pMatch = pItem;
  87522. }
  87523. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  87524. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  87525. /* If there has been exactly one prior match and this match
  87526. ** is for the right-hand table of a NATURAL JOIN or is in a
  87527. ** USING clause, then skip this match.
  87528. */
  87529. if( cnt==1 ){
  87530. if( pItem->fg.jointype & JT_NATURAL ) continue;
  87531. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  87532. }
  87533. cnt++;
  87534. pMatch = pItem;
  87535. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  87536. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  87537. break;
  87538. }
  87539. }
  87540. }
  87541. if( pMatch ){
  87542. pExpr->iTable = pMatch->iCursor;
  87543. pExpr->pTab = pMatch->pTab;
  87544. /* RIGHT JOIN not (yet) supported */
  87545. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  87546. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  87547. ExprSetProperty(pExpr, EP_CanBeNull);
  87548. }
  87549. pSchema = pExpr->pTab->pSchema;
  87550. }
  87551. } /* if( pSrcList ) */
  87552. #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
  87553. /* If we have not already resolved the name, then maybe
  87554. ** it is a new.* or old.* trigger argument reference. Or
  87555. ** maybe it is an excluded.* from an upsert.
  87556. */
  87557. if( zDb==0 && zTab!=0 && cntTab==0 ){
  87558. pTab = 0;
  87559. #ifndef SQLITE_OMIT_TRIGGER
  87560. if( pParse->pTriggerTab!=0 ){
  87561. int op = pParse->eTriggerOp;
  87562. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  87563. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  87564. pExpr->iTable = 1;
  87565. pTab = pParse->pTriggerTab;
  87566. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  87567. pExpr->iTable = 0;
  87568. pTab = pParse->pTriggerTab;
  87569. }
  87570. }
  87571. #endif /* SQLITE_OMIT_TRIGGER */
  87572. #ifndef SQLITE_OMIT_UPSERT
  87573. if( (pNC->ncFlags & NC_UUpsert)!=0 ){
  87574. Upsert *pUpsert = pNC->uNC.pUpsert;
  87575. if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
  87576. pTab = pUpsert->pUpsertSrc->a[0].pTab;
  87577. pExpr->iTable = 2;
  87578. }
  87579. }
  87580. #endif /* SQLITE_OMIT_UPSERT */
  87581. if( pTab ){
  87582. int iCol;
  87583. pSchema = pTab->pSchema;
  87584. cntTab++;
  87585. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  87586. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  87587. if( iCol==pTab->iPKey ){
  87588. iCol = -1;
  87589. }
  87590. break;
  87591. }
  87592. }
  87593. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  87594. /* IMP: R-51414-32910 */
  87595. iCol = -1;
  87596. }
  87597. if( iCol<pTab->nCol ){
  87598. cnt++;
  87599. #ifndef SQLITE_OMIT_UPSERT
  87600. if( pExpr->iTable==2 ){
  87601. testcase( iCol==(-1) );
  87602. pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
  87603. eNewExprOp = TK_REGISTER;
  87604. ExprSetProperty(pExpr, EP_Alias);
  87605. }else
  87606. #endif /* SQLITE_OMIT_UPSERT */
  87607. {
  87608. #ifndef SQLITE_OMIT_TRIGGER
  87609. if( iCol<0 ){
  87610. pExpr->affinity = SQLITE_AFF_INTEGER;
  87611. }else if( pExpr->iTable==0 ){
  87612. testcase( iCol==31 );
  87613. testcase( iCol==32 );
  87614. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  87615. }else{
  87616. testcase( iCol==31 );
  87617. testcase( iCol==32 );
  87618. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  87619. }
  87620. pExpr->pTab = pTab;
  87621. pExpr->iColumn = (i16)iCol;
  87622. eNewExprOp = TK_TRIGGER;
  87623. #endif /* SQLITE_OMIT_TRIGGER */
  87624. }
  87625. }
  87626. }
  87627. }
  87628. #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
  87629. /*
  87630. ** Perhaps the name is a reference to the ROWID
  87631. */
  87632. if( cnt==0
  87633. && cntTab==1
  87634. && pMatch
  87635. && (pNC->ncFlags & NC_IdxExpr)==0
  87636. && sqlite3IsRowid(zCol)
  87637. && VisibleRowid(pMatch->pTab)
  87638. ){
  87639. cnt = 1;
  87640. pExpr->iColumn = -1;
  87641. pExpr->affinity = SQLITE_AFF_INTEGER;
  87642. }
  87643. /*
  87644. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  87645. ** might refer to an result-set alias. This happens, for example, when
  87646. ** we are resolving names in the WHERE clause of the following command:
  87647. **
  87648. ** SELECT a+b AS x FROM table WHERE x<10;
  87649. **
  87650. ** In cases like this, replace pExpr with a copy of the expression that
  87651. ** forms the result set entry ("a+b" in the example) and return immediately.
  87652. ** Note that the expression in the result set should have already been
  87653. ** resolved by the time the WHERE clause is resolved.
  87654. **
  87655. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  87656. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  87657. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  87658. ** is supported for backwards compatibility only. Hence, we issue a warning
  87659. ** on sqlite3_log() whenever the capability is used.
  87660. */
  87661. if( (pNC->ncFlags & NC_UEList)!=0
  87662. && cnt==0
  87663. && zTab==0
  87664. ){
  87665. pEList = pNC->uNC.pEList;
  87666. assert( pEList!=0 );
  87667. for(j=0; j<pEList->nExpr; j++){
  87668. char *zAs = pEList->a[j].zName;
  87669. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  87670. Expr *pOrig;
  87671. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  87672. assert( pExpr->x.pList==0 );
  87673. assert( pExpr->x.pSelect==0 );
  87674. pOrig = pEList->a[j].pExpr;
  87675. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  87676. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  87677. return WRC_Abort;
  87678. }
  87679. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  87680. sqlite3ErrorMsg(pParse, "row value misused");
  87681. return WRC_Abort;
  87682. }
  87683. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  87684. cnt = 1;
  87685. pMatch = 0;
  87686. assert( zTab==0 && zDb==0 );
  87687. goto lookupname_end;
  87688. }
  87689. }
  87690. }
  87691. /* Advance to the next name context. The loop will exit when either
  87692. ** we have a match (cnt>0) or when we run out of name contexts.
  87693. */
  87694. if( cnt ) break;
  87695. pNC = pNC->pNext;
  87696. nSubquery++;
  87697. }while( pNC );
  87698. /*
  87699. ** If X and Y are NULL (in other words if only the column name Z is
  87700. ** supplied) and the value of Z is enclosed in double-quotes, then
  87701. ** Z is a string literal if it doesn't match any column names. In that
  87702. ** case, we need to return right away and not make any changes to
  87703. ** pExpr.
  87704. **
  87705. ** Because no reference was made to outer contexts, the pNC->nRef
  87706. ** fields are not changed in any context.
  87707. */
  87708. if( cnt==0 && zTab==0 ){
  87709. assert( pExpr->op==TK_ID );
  87710. if( ExprHasProperty(pExpr,EP_DblQuoted) ){
  87711. pExpr->op = TK_STRING;
  87712. pExpr->pTab = 0;
  87713. return WRC_Prune;
  87714. }
  87715. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  87716. return WRC_Prune;
  87717. }
  87718. }
  87719. /*
  87720. ** cnt==0 means there was not match. cnt>1 means there were two or
  87721. ** more matches. Either way, we have an error.
  87722. */
  87723. if( cnt!=1 ){
  87724. const char *zErr;
  87725. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  87726. if( zDb ){
  87727. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  87728. }else if( zTab ){
  87729. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  87730. }else{
  87731. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  87732. }
  87733. pParse->checkSchema = 1;
  87734. pTopNC->nErr++;
  87735. }
  87736. /* If a column from a table in pSrcList is referenced, then record
  87737. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  87738. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  87739. ** column number is greater than the number of bits in the bitmask
  87740. ** then set the high-order bit of the bitmask.
  87741. */
  87742. if( pExpr->iColumn>=0 && pMatch!=0 ){
  87743. int n = pExpr->iColumn;
  87744. testcase( n==BMS-1 );
  87745. if( n>=BMS ){
  87746. n = BMS-1;
  87747. }
  87748. assert( pMatch->iCursor==pExpr->iTable );
  87749. pMatch->colUsed |= ((Bitmask)1)<<n;
  87750. }
  87751. /* Clean up and return
  87752. */
  87753. sqlite3ExprDelete(db, pExpr->pLeft);
  87754. pExpr->pLeft = 0;
  87755. sqlite3ExprDelete(db, pExpr->pRight);
  87756. pExpr->pRight = 0;
  87757. pExpr->op = eNewExprOp;
  87758. ExprSetProperty(pExpr, EP_Leaf);
  87759. lookupname_end:
  87760. if( cnt==1 ){
  87761. assert( pNC!=0 );
  87762. if( !ExprHasProperty(pExpr, EP_Alias) ){
  87763. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  87764. }
  87765. /* Increment the nRef value on all name contexts from TopNC up to
  87766. ** the point where the name matched. */
  87767. for(;;){
  87768. assert( pTopNC!=0 );
  87769. pTopNC->nRef++;
  87770. if( pTopNC==pNC ) break;
  87771. pTopNC = pTopNC->pNext;
  87772. }
  87773. return WRC_Prune;
  87774. } else {
  87775. return WRC_Abort;
  87776. }
  87777. }
  87778. /*
  87779. ** Allocate and return a pointer to an expression to load the column iCol
  87780. ** from datasource iSrc in SrcList pSrc.
  87781. */
  87782. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  87783. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  87784. if( p ){
  87785. struct SrcList_item *pItem = &pSrc->a[iSrc];
  87786. p->pTab = pItem->pTab;
  87787. p->iTable = pItem->iCursor;
  87788. if( p->pTab->iPKey==iCol ){
  87789. p->iColumn = -1;
  87790. }else{
  87791. p->iColumn = (ynVar)iCol;
  87792. testcase( iCol==BMS );
  87793. testcase( iCol==BMS-1 );
  87794. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  87795. }
  87796. }
  87797. return p;
  87798. }
  87799. /*
  87800. ** Report an error that an expression is not valid for some set of
  87801. ** pNC->ncFlags values determined by validMask.
  87802. */
  87803. static void notValid(
  87804. Parse *pParse, /* Leave error message here */
  87805. NameContext *pNC, /* The name context */
  87806. const char *zMsg, /* Type of error */
  87807. int validMask /* Set of contexts for which prohibited */
  87808. ){
  87809. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  87810. if( (pNC->ncFlags & validMask)!=0 ){
  87811. const char *zIn = "partial index WHERE clauses";
  87812. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  87813. #ifndef SQLITE_OMIT_CHECK
  87814. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  87815. #endif
  87816. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  87817. }
  87818. }
  87819. /*
  87820. ** Expression p should encode a floating point value between 1.0 and 0.0.
  87821. ** Return 1024 times this value. Or return -1 if p is not a floating point
  87822. ** value between 1.0 and 0.0.
  87823. */
  87824. static int exprProbability(Expr *p){
  87825. double r = -1.0;
  87826. if( p->op!=TK_FLOAT ) return -1;
  87827. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  87828. assert( r>=0.0 );
  87829. if( r>1.0 ) return -1;
  87830. return (int)(r*134217728.0);
  87831. }
  87832. /*
  87833. ** This routine is callback for sqlite3WalkExpr().
  87834. **
  87835. ** Resolve symbolic names into TK_COLUMN operators for the current
  87836. ** node in the expression tree. Return 0 to continue the search down
  87837. ** the tree or 2 to abort the tree walk.
  87838. **
  87839. ** This routine also does error checking and name resolution for
  87840. ** function names. The operator for aggregate functions is changed
  87841. ** to TK_AGG_FUNCTION.
  87842. */
  87843. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  87844. NameContext *pNC;
  87845. Parse *pParse;
  87846. pNC = pWalker->u.pNC;
  87847. assert( pNC!=0 );
  87848. pParse = pNC->pParse;
  87849. assert( pParse==pWalker->pParse );
  87850. #ifndef NDEBUG
  87851. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  87852. SrcList *pSrcList = pNC->pSrcList;
  87853. int i;
  87854. for(i=0; i<pNC->pSrcList->nSrc; i++){
  87855. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  87856. }
  87857. }
  87858. #endif
  87859. switch( pExpr->op ){
  87860. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  87861. /* The special operator TK_ROW means use the rowid for the first
  87862. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  87863. ** clause processing on UPDATE and DELETE statements.
  87864. */
  87865. case TK_ROW: {
  87866. SrcList *pSrcList = pNC->pSrcList;
  87867. struct SrcList_item *pItem;
  87868. assert( pSrcList && pSrcList->nSrc==1 );
  87869. pItem = pSrcList->a;
  87870. assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
  87871. pExpr->op = TK_COLUMN;
  87872. pExpr->pTab = pItem->pTab;
  87873. pExpr->iTable = pItem->iCursor;
  87874. pExpr->iColumn = -1;
  87875. pExpr->affinity = SQLITE_AFF_INTEGER;
  87876. break;
  87877. }
  87878. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  87879. && !defined(SQLITE_OMIT_SUBQUERY) */
  87880. /* A column name: ID
  87881. ** Or table name and column name: ID.ID
  87882. ** Or a database, table and column: ID.ID.ID
  87883. **
  87884. ** The TK_ID and TK_OUT cases are combined so that there will only
  87885. ** be one call to lookupName(). Then the compiler will in-line
  87886. ** lookupName() for a size reduction and performance increase.
  87887. */
  87888. case TK_ID:
  87889. case TK_DOT: {
  87890. const char *zColumn;
  87891. const char *zTable;
  87892. const char *zDb;
  87893. Expr *pRight;
  87894. if( pExpr->op==TK_ID ){
  87895. zDb = 0;
  87896. zTable = 0;
  87897. zColumn = pExpr->u.zToken;
  87898. }else{
  87899. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  87900. pRight = pExpr->pRight;
  87901. if( pRight->op==TK_ID ){
  87902. zDb = 0;
  87903. zTable = pExpr->pLeft->u.zToken;
  87904. zColumn = pRight->u.zToken;
  87905. }else{
  87906. assert( pRight->op==TK_DOT );
  87907. zDb = pExpr->pLeft->u.zToken;
  87908. zTable = pRight->pLeft->u.zToken;
  87909. zColumn = pRight->pRight->u.zToken;
  87910. }
  87911. }
  87912. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  87913. }
  87914. /* Resolve function names
  87915. */
  87916. case TK_FUNCTION: {
  87917. ExprList *pList = pExpr->x.pList; /* The argument list */
  87918. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  87919. int no_such_func = 0; /* True if no such function exists */
  87920. int wrong_num_args = 0; /* True if wrong number of arguments */
  87921. int is_agg = 0; /* True if is an aggregate function */
  87922. int nId; /* Number of characters in function name */
  87923. const char *zId; /* The function name. */
  87924. FuncDef *pDef; /* Information about the function */
  87925. u8 enc = ENC(pParse->db); /* The database encoding */
  87926. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  87927. zId = pExpr->u.zToken;
  87928. nId = sqlite3Strlen30(zId);
  87929. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  87930. if( pDef==0 ){
  87931. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  87932. if( pDef==0 ){
  87933. no_such_func = 1;
  87934. }else{
  87935. wrong_num_args = 1;
  87936. }
  87937. }else{
  87938. is_agg = pDef->xFinalize!=0;
  87939. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  87940. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  87941. if( n==2 ){
  87942. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  87943. if( pExpr->iTable<0 ){
  87944. sqlite3ErrorMsg(pParse,
  87945. "second argument to likelihood() must be a "
  87946. "constant between 0.0 and 1.0");
  87947. pNC->nErr++;
  87948. }
  87949. }else{
  87950. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  87951. ** equivalent to likelihood(X, 0.0625).
  87952. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  87953. ** short-hand for likelihood(X,0.0625).
  87954. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  87955. ** for likelihood(X,0.9375).
  87956. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  87957. ** to likelihood(X,0.9375). */
  87958. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  87959. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  87960. }
  87961. }
  87962. #ifndef SQLITE_OMIT_AUTHORIZATION
  87963. {
  87964. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  87965. if( auth!=SQLITE_OK ){
  87966. if( auth==SQLITE_DENY ){
  87967. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  87968. pDef->zName);
  87969. pNC->nErr++;
  87970. }
  87971. pExpr->op = TK_NULL;
  87972. return WRC_Prune;
  87973. }
  87974. }
  87975. #endif
  87976. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  87977. /* For the purposes of the EP_ConstFunc flag, date and time
  87978. ** functions and other functions that change slowly are considered
  87979. ** constant because they are constant for the duration of one query */
  87980. ExprSetProperty(pExpr,EP_ConstFunc);
  87981. }
  87982. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  87983. /* Date/time functions that use 'now', and other functions like
  87984. ** sqlite_version() that might change over time cannot be used
  87985. ** in an index. */
  87986. notValid(pParse, pNC, "non-deterministic functions",
  87987. NC_IdxExpr|NC_PartIdx);
  87988. }
  87989. }
  87990. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  87991. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  87992. pNC->nErr++;
  87993. is_agg = 0;
  87994. }else if( no_such_func && pParse->db->init.busy==0
  87995. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  87996. && pParse->explain==0
  87997. #endif
  87998. ){
  87999. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  88000. pNC->nErr++;
  88001. }else if( wrong_num_args ){
  88002. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  88003. nId, zId);
  88004. pNC->nErr++;
  88005. }
  88006. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  88007. sqlite3WalkExprList(pWalker, pList);
  88008. if( is_agg ){
  88009. NameContext *pNC2 = pNC;
  88010. pExpr->op = TK_AGG_FUNCTION;
  88011. pExpr->op2 = 0;
  88012. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  88013. pExpr->op2++;
  88014. pNC2 = pNC2->pNext;
  88015. }
  88016. assert( pDef!=0 );
  88017. if( pNC2 ){
  88018. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  88019. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  88020. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  88021. }
  88022. pNC->ncFlags |= NC_AllowAgg;
  88023. }
  88024. /* FIX ME: Compute pExpr->affinity based on the expected return
  88025. ** type of the function
  88026. */
  88027. return WRC_Prune;
  88028. }
  88029. #ifndef SQLITE_OMIT_SUBQUERY
  88030. case TK_SELECT:
  88031. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  88032. #endif
  88033. case TK_IN: {
  88034. testcase( pExpr->op==TK_IN );
  88035. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  88036. int nRef = pNC->nRef;
  88037. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  88038. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  88039. assert( pNC->nRef>=nRef );
  88040. if( nRef!=pNC->nRef ){
  88041. ExprSetProperty(pExpr, EP_VarSelect);
  88042. pNC->ncFlags |= NC_VarSelect;
  88043. }
  88044. }
  88045. break;
  88046. }
  88047. case TK_VARIABLE: {
  88048. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  88049. break;
  88050. }
  88051. case TK_IS:
  88052. case TK_ISNOT: {
  88053. Expr *pRight;
  88054. assert( !ExprHasProperty(pExpr, EP_Reduced) );
  88055. /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
  88056. ** and "x IS NOT FALSE". */
  88057. if( (pRight = pExpr->pRight)->op==TK_ID ){
  88058. int rc = resolveExprStep(pWalker, pRight);
  88059. if( rc==WRC_Abort ) return WRC_Abort;
  88060. if( pRight->op==TK_TRUEFALSE ){
  88061. pExpr->op2 = pExpr->op;
  88062. pExpr->op = TK_TRUTH;
  88063. return WRC_Continue;
  88064. }
  88065. }
  88066. /* Fall thru */
  88067. }
  88068. case TK_BETWEEN:
  88069. case TK_EQ:
  88070. case TK_NE:
  88071. case TK_LT:
  88072. case TK_LE:
  88073. case TK_GT:
  88074. case TK_GE: {
  88075. int nLeft, nRight;
  88076. if( pParse->db->mallocFailed ) break;
  88077. assert( pExpr->pLeft!=0 );
  88078. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  88079. if( pExpr->op==TK_BETWEEN ){
  88080. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  88081. if( nRight==nLeft ){
  88082. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  88083. }
  88084. }else{
  88085. assert( pExpr->pRight!=0 );
  88086. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  88087. }
  88088. if( nLeft!=nRight ){
  88089. testcase( pExpr->op==TK_EQ );
  88090. testcase( pExpr->op==TK_NE );
  88091. testcase( pExpr->op==TK_LT );
  88092. testcase( pExpr->op==TK_LE );
  88093. testcase( pExpr->op==TK_GT );
  88094. testcase( pExpr->op==TK_GE );
  88095. testcase( pExpr->op==TK_IS );
  88096. testcase( pExpr->op==TK_ISNOT );
  88097. testcase( pExpr->op==TK_BETWEEN );
  88098. sqlite3ErrorMsg(pParse, "row value misused");
  88099. }
  88100. break;
  88101. }
  88102. }
  88103. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  88104. }
  88105. /*
  88106. ** pEList is a list of expressions which are really the result set of the
  88107. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  88108. ** This routine checks to see if pE is a simple identifier which corresponds
  88109. ** to the AS-name of one of the terms of the expression list. If it is,
  88110. ** this routine return an integer between 1 and N where N is the number of
  88111. ** elements in pEList, corresponding to the matching entry. If there is
  88112. ** no match, or if pE is not a simple identifier, then this routine
  88113. ** return 0.
  88114. **
  88115. ** pEList has been resolved. pE has not.
  88116. */
  88117. static int resolveAsName(
  88118. Parse *pParse, /* Parsing context for error messages */
  88119. ExprList *pEList, /* List of expressions to scan */
  88120. Expr *pE /* Expression we are trying to match */
  88121. ){
  88122. int i; /* Loop counter */
  88123. UNUSED_PARAMETER(pParse);
  88124. if( pE->op==TK_ID ){
  88125. char *zCol = pE->u.zToken;
  88126. for(i=0; i<pEList->nExpr; i++){
  88127. char *zAs = pEList->a[i].zName;
  88128. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  88129. return i+1;
  88130. }
  88131. }
  88132. }
  88133. return 0;
  88134. }
  88135. /*
  88136. ** pE is a pointer to an expression which is a single term in the
  88137. ** ORDER BY of a compound SELECT. The expression has not been
  88138. ** name resolved.
  88139. **
  88140. ** At the point this routine is called, we already know that the
  88141. ** ORDER BY term is not an integer index into the result set. That
  88142. ** case is handled by the calling routine.
  88143. **
  88144. ** Attempt to match pE against result set columns in the left-most
  88145. ** SELECT statement. Return the index i of the matching column,
  88146. ** as an indication to the caller that it should sort by the i-th column.
  88147. ** The left-most column is 1. In other words, the value returned is the
  88148. ** same integer value that would be used in the SQL statement to indicate
  88149. ** the column.
  88150. **
  88151. ** If there is no match, return 0. Return -1 if an error occurs.
  88152. */
  88153. static int resolveOrderByTermToExprList(
  88154. Parse *pParse, /* Parsing context for error messages */
  88155. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  88156. Expr *pE /* The specific ORDER BY term */
  88157. ){
  88158. int i; /* Loop counter */
  88159. ExprList *pEList; /* The columns of the result set */
  88160. NameContext nc; /* Name context for resolving pE */
  88161. sqlite3 *db; /* Database connection */
  88162. int rc; /* Return code from subprocedures */
  88163. u8 savedSuppErr; /* Saved value of db->suppressErr */
  88164. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  88165. pEList = pSelect->pEList;
  88166. /* Resolve all names in the ORDER BY term expression
  88167. */
  88168. memset(&nc, 0, sizeof(nc));
  88169. nc.pParse = pParse;
  88170. nc.pSrcList = pSelect->pSrc;
  88171. nc.uNC.pEList = pEList;
  88172. nc.ncFlags = NC_AllowAgg|NC_UEList;
  88173. nc.nErr = 0;
  88174. db = pParse->db;
  88175. savedSuppErr = db->suppressErr;
  88176. db->suppressErr = 1;
  88177. rc = sqlite3ResolveExprNames(&nc, pE);
  88178. db->suppressErr = savedSuppErr;
  88179. if( rc ) return 0;
  88180. /* Try to match the ORDER BY expression against an expression
  88181. ** in the result set. Return an 1-based index of the matching
  88182. ** result-set entry.
  88183. */
  88184. for(i=0; i<pEList->nExpr; i++){
  88185. if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
  88186. return i+1;
  88187. }
  88188. }
  88189. /* If no match, return 0. */
  88190. return 0;
  88191. }
  88192. /*
  88193. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  88194. */
  88195. static void resolveOutOfRangeError(
  88196. Parse *pParse, /* The error context into which to write the error */
  88197. const char *zType, /* "ORDER" or "GROUP" */
  88198. int i, /* The index (1-based) of the term out of range */
  88199. int mx /* Largest permissible value of i */
  88200. ){
  88201. sqlite3ErrorMsg(pParse,
  88202. "%r %s BY term out of range - should be "
  88203. "between 1 and %d", i, zType, mx);
  88204. }
  88205. /*
  88206. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  88207. ** each term of the ORDER BY clause is a constant integer between 1
  88208. ** and N where N is the number of columns in the compound SELECT.
  88209. **
  88210. ** ORDER BY terms that are already an integer between 1 and N are
  88211. ** unmodified. ORDER BY terms that are integers outside the range of
  88212. ** 1 through N generate an error. ORDER BY terms that are expressions
  88213. ** are matched against result set expressions of compound SELECT
  88214. ** beginning with the left-most SELECT and working toward the right.
  88215. ** At the first match, the ORDER BY expression is transformed into
  88216. ** the integer column number.
  88217. **
  88218. ** Return the number of errors seen.
  88219. */
  88220. static int resolveCompoundOrderBy(
  88221. Parse *pParse, /* Parsing context. Leave error messages here */
  88222. Select *pSelect /* The SELECT statement containing the ORDER BY */
  88223. ){
  88224. int i;
  88225. ExprList *pOrderBy;
  88226. ExprList *pEList;
  88227. sqlite3 *db;
  88228. int moreToDo = 1;
  88229. pOrderBy = pSelect->pOrderBy;
  88230. if( pOrderBy==0 ) return 0;
  88231. db = pParse->db;
  88232. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  88233. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  88234. return 1;
  88235. }
  88236. for(i=0; i<pOrderBy->nExpr; i++){
  88237. pOrderBy->a[i].done = 0;
  88238. }
  88239. pSelect->pNext = 0;
  88240. while( pSelect->pPrior ){
  88241. pSelect->pPrior->pNext = pSelect;
  88242. pSelect = pSelect->pPrior;
  88243. }
  88244. while( pSelect && moreToDo ){
  88245. struct ExprList_item *pItem;
  88246. moreToDo = 0;
  88247. pEList = pSelect->pEList;
  88248. assert( pEList!=0 );
  88249. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  88250. int iCol = -1;
  88251. Expr *pE, *pDup;
  88252. if( pItem->done ) continue;
  88253. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  88254. if( sqlite3ExprIsInteger(pE, &iCol) ){
  88255. if( iCol<=0 || iCol>pEList->nExpr ){
  88256. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  88257. return 1;
  88258. }
  88259. }else{
  88260. iCol = resolveAsName(pParse, pEList, pE);
  88261. if( iCol==0 ){
  88262. pDup = sqlite3ExprDup(db, pE, 0);
  88263. if( !db->mallocFailed ){
  88264. assert(pDup);
  88265. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  88266. }
  88267. sqlite3ExprDelete(db, pDup);
  88268. }
  88269. }
  88270. if( iCol>0 ){
  88271. /* Convert the ORDER BY term into an integer column number iCol,
  88272. ** taking care to preserve the COLLATE clause if it exists */
  88273. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  88274. if( pNew==0 ) return 1;
  88275. pNew->flags |= EP_IntValue;
  88276. pNew->u.iValue = iCol;
  88277. if( pItem->pExpr==pE ){
  88278. pItem->pExpr = pNew;
  88279. }else{
  88280. Expr *pParent = pItem->pExpr;
  88281. assert( pParent->op==TK_COLLATE );
  88282. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  88283. assert( pParent->pLeft==pE );
  88284. pParent->pLeft = pNew;
  88285. }
  88286. sqlite3ExprDelete(db, pE);
  88287. pItem->u.x.iOrderByCol = (u16)iCol;
  88288. pItem->done = 1;
  88289. }else{
  88290. moreToDo = 1;
  88291. }
  88292. }
  88293. pSelect = pSelect->pNext;
  88294. }
  88295. for(i=0; i<pOrderBy->nExpr; i++){
  88296. if( pOrderBy->a[i].done==0 ){
  88297. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  88298. "column in the result set", i+1);
  88299. return 1;
  88300. }
  88301. }
  88302. return 0;
  88303. }
  88304. /*
  88305. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  88306. ** the SELECT statement pSelect. If any term is reference to a
  88307. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  88308. ** field) then convert that term into a copy of the corresponding result set
  88309. ** column.
  88310. **
  88311. ** If any errors are detected, add an error message to pParse and
  88312. ** return non-zero. Return zero if no errors are seen.
  88313. */
  88314. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  88315. Parse *pParse, /* Parsing context. Leave error messages here */
  88316. Select *pSelect, /* The SELECT statement containing the clause */
  88317. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  88318. const char *zType /* "ORDER" or "GROUP" */
  88319. ){
  88320. int i;
  88321. sqlite3 *db = pParse->db;
  88322. ExprList *pEList;
  88323. struct ExprList_item *pItem;
  88324. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  88325. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  88326. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  88327. return 1;
  88328. }
  88329. pEList = pSelect->pEList;
  88330. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  88331. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  88332. if( pItem->u.x.iOrderByCol ){
  88333. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  88334. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  88335. return 1;
  88336. }
  88337. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  88338. zType,0);
  88339. }
  88340. }
  88341. return 0;
  88342. }
  88343. /*
  88344. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  88345. ** The Name context of the SELECT statement is pNC. zType is either
  88346. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  88347. **
  88348. ** This routine resolves each term of the clause into an expression.
  88349. ** If the order-by term is an integer I between 1 and N (where N is the
  88350. ** number of columns in the result set of the SELECT) then the expression
  88351. ** in the resolution is a copy of the I-th result-set expression. If
  88352. ** the order-by term is an identifier that corresponds to the AS-name of
  88353. ** a result-set expression, then the term resolves to a copy of the
  88354. ** result-set expression. Otherwise, the expression is resolved in
  88355. ** the usual way - using sqlite3ResolveExprNames().
  88356. **
  88357. ** This routine returns the number of errors. If errors occur, then
  88358. ** an appropriate error message might be left in pParse. (OOM errors
  88359. ** excepted.)
  88360. */
  88361. static int resolveOrderGroupBy(
  88362. NameContext *pNC, /* The name context of the SELECT statement */
  88363. Select *pSelect, /* The SELECT statement holding pOrderBy */
  88364. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  88365. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  88366. ){
  88367. int i, j; /* Loop counters */
  88368. int iCol; /* Column number */
  88369. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  88370. Parse *pParse; /* Parsing context */
  88371. int nResult; /* Number of terms in the result set */
  88372. if( pOrderBy==0 ) return 0;
  88373. nResult = pSelect->pEList->nExpr;
  88374. pParse = pNC->pParse;
  88375. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  88376. Expr *pE = pItem->pExpr;
  88377. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  88378. if( zType[0]!='G' ){
  88379. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  88380. if( iCol>0 ){
  88381. /* If an AS-name match is found, mark this ORDER BY column as being
  88382. ** a copy of the iCol-th result-set column. The subsequent call to
  88383. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  88384. ** copy of the iCol-th result-set expression. */
  88385. pItem->u.x.iOrderByCol = (u16)iCol;
  88386. continue;
  88387. }
  88388. }
  88389. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  88390. /* The ORDER BY term is an integer constant. Again, set the column
  88391. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  88392. ** order-by term to a copy of the result-set expression */
  88393. if( iCol<1 || iCol>0xffff ){
  88394. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  88395. return 1;
  88396. }
  88397. pItem->u.x.iOrderByCol = (u16)iCol;
  88398. continue;
  88399. }
  88400. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  88401. pItem->u.x.iOrderByCol = 0;
  88402. if( sqlite3ResolveExprNames(pNC, pE) ){
  88403. return 1;
  88404. }
  88405. for(j=0; j<pSelect->pEList->nExpr; j++){
  88406. if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  88407. pItem->u.x.iOrderByCol = j+1;
  88408. }
  88409. }
  88410. }
  88411. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  88412. }
  88413. /*
  88414. ** Resolve names in the SELECT statement p and all of its descendants.
  88415. */
  88416. static int resolveSelectStep(Walker *pWalker, Select *p){
  88417. NameContext *pOuterNC; /* Context that contains this SELECT */
  88418. NameContext sNC; /* Name context of this SELECT */
  88419. int isCompound; /* True if p is a compound select */
  88420. int nCompound; /* Number of compound terms processed so far */
  88421. Parse *pParse; /* Parsing context */
  88422. int i; /* Loop counter */
  88423. ExprList *pGroupBy; /* The GROUP BY clause */
  88424. Select *pLeftmost; /* Left-most of SELECT of a compound */
  88425. sqlite3 *db; /* Database connection */
  88426. assert( p!=0 );
  88427. if( p->selFlags & SF_Resolved ){
  88428. return WRC_Prune;
  88429. }
  88430. pOuterNC = pWalker->u.pNC;
  88431. pParse = pWalker->pParse;
  88432. db = pParse->db;
  88433. /* Normally sqlite3SelectExpand() will be called first and will have
  88434. ** already expanded this SELECT. However, if this is a subquery within
  88435. ** an expression, sqlite3ResolveExprNames() will be called without a
  88436. ** prior call to sqlite3SelectExpand(). When that happens, let
  88437. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  88438. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  88439. ** this routine in the correct order.
  88440. */
  88441. if( (p->selFlags & SF_Expanded)==0 ){
  88442. sqlite3SelectPrep(pParse, p, pOuterNC);
  88443. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  88444. }
  88445. isCompound = p->pPrior!=0;
  88446. nCompound = 0;
  88447. pLeftmost = p;
  88448. while( p ){
  88449. assert( (p->selFlags & SF_Expanded)!=0 );
  88450. assert( (p->selFlags & SF_Resolved)==0 );
  88451. p->selFlags |= SF_Resolved;
  88452. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  88453. ** are not allowed to refer to any names, so pass an empty NameContext.
  88454. */
  88455. memset(&sNC, 0, sizeof(sNC));
  88456. sNC.pParse = pParse;
  88457. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
  88458. return WRC_Abort;
  88459. }
  88460. /* If the SF_Converted flags is set, then this Select object was
  88461. ** was created by the convertCompoundSelectToSubquery() function.
  88462. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  88463. ** as if it were part of the sub-query, not the parent. This block
  88464. ** moves the pOrderBy down to the sub-query. It will be moved back
  88465. ** after the names have been resolved. */
  88466. if( p->selFlags & SF_Converted ){
  88467. Select *pSub = p->pSrc->a[0].pSelect;
  88468. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  88469. assert( pSub->pPrior && pSub->pOrderBy==0 );
  88470. pSub->pOrderBy = p->pOrderBy;
  88471. p->pOrderBy = 0;
  88472. }
  88473. /* Recursively resolve names in all subqueries
  88474. */
  88475. for(i=0; i<p->pSrc->nSrc; i++){
  88476. struct SrcList_item *pItem = &p->pSrc->a[i];
  88477. if( pItem->pSelect ){
  88478. NameContext *pNC; /* Used to iterate name contexts */
  88479. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  88480. const char *zSavedContext = pParse->zAuthContext;
  88481. /* Count the total number of references to pOuterNC and all of its
  88482. ** parent contexts. After resolving references to expressions in
  88483. ** pItem->pSelect, check if this value has changed. If so, then
  88484. ** SELECT statement pItem->pSelect must be correlated. Set the
  88485. ** pItem->fg.isCorrelated flag if this is the case. */
  88486. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  88487. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  88488. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  88489. pParse->zAuthContext = zSavedContext;
  88490. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  88491. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  88492. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  88493. pItem->fg.isCorrelated = (nRef!=0);
  88494. }
  88495. }
  88496. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  88497. ** resolve the result-set expression list.
  88498. */
  88499. sNC.ncFlags = NC_AllowAgg;
  88500. sNC.pSrcList = p->pSrc;
  88501. sNC.pNext = pOuterNC;
  88502. /* Resolve names in the result set. */
  88503. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  88504. /* If there are no aggregate functions in the result-set, and no GROUP BY
  88505. ** expression, do not allow aggregates in any of the other expressions.
  88506. */
  88507. assert( (p->selFlags & SF_Aggregate)==0 );
  88508. pGroupBy = p->pGroupBy;
  88509. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  88510. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  88511. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  88512. }else{
  88513. sNC.ncFlags &= ~NC_AllowAgg;
  88514. }
  88515. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  88516. */
  88517. if( p->pHaving && !pGroupBy ){
  88518. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  88519. return WRC_Abort;
  88520. }
  88521. /* Add the output column list to the name-context before parsing the
  88522. ** other expressions in the SELECT statement. This is so that
  88523. ** expressions in the WHERE clause (etc.) can refer to expressions by
  88524. ** aliases in the result set.
  88525. **
  88526. ** Minor point: If this is the case, then the expression will be
  88527. ** re-evaluated for each reference to it.
  88528. */
  88529. assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
  88530. sNC.uNC.pEList = p->pEList;
  88531. sNC.ncFlags |= NC_UEList;
  88532. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  88533. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  88534. /* Resolve names in table-valued-function arguments */
  88535. for(i=0; i<p->pSrc->nSrc; i++){
  88536. struct SrcList_item *pItem = &p->pSrc->a[i];
  88537. if( pItem->fg.isTabFunc
  88538. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  88539. ){
  88540. return WRC_Abort;
  88541. }
  88542. }
  88543. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  88544. ** outer queries
  88545. */
  88546. sNC.pNext = 0;
  88547. sNC.ncFlags |= NC_AllowAgg;
  88548. /* If this is a converted compound query, move the ORDER BY clause from
  88549. ** the sub-query back to the parent query. At this point each term
  88550. ** within the ORDER BY clause has been transformed to an integer value.
  88551. ** These integers will be replaced by copies of the corresponding result
  88552. ** set expressions by the call to resolveOrderGroupBy() below. */
  88553. if( p->selFlags & SF_Converted ){
  88554. Select *pSub = p->pSrc->a[0].pSelect;
  88555. p->pOrderBy = pSub->pOrderBy;
  88556. pSub->pOrderBy = 0;
  88557. }
  88558. /* Process the ORDER BY clause for singleton SELECT statements.
  88559. ** The ORDER BY clause for compounds SELECT statements is handled
  88560. ** below, after all of the result-sets for all of the elements of
  88561. ** the compound have been resolved.
  88562. **
  88563. ** If there is an ORDER BY clause on a term of a compound-select other
  88564. ** than the right-most term, then that is a syntax error. But the error
  88565. ** is not detected until much later, and so we need to go ahead and
  88566. ** resolve those symbols on the incorrect ORDER BY for consistency.
  88567. */
  88568. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  88569. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  88570. ){
  88571. return WRC_Abort;
  88572. }
  88573. if( db->mallocFailed ){
  88574. return WRC_Abort;
  88575. }
  88576. /* Resolve the GROUP BY clause. At the same time, make sure
  88577. ** the GROUP BY clause does not contain aggregate functions.
  88578. */
  88579. if( pGroupBy ){
  88580. struct ExprList_item *pItem;
  88581. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  88582. return WRC_Abort;
  88583. }
  88584. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  88585. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  88586. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  88587. "the GROUP BY clause");
  88588. return WRC_Abort;
  88589. }
  88590. }
  88591. }
  88592. /* If this is part of a compound SELECT, check that it has the right
  88593. ** number of expressions in the select list. */
  88594. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  88595. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  88596. return WRC_Abort;
  88597. }
  88598. /* Advance to the next term of the compound
  88599. */
  88600. p = p->pPrior;
  88601. nCompound++;
  88602. }
  88603. /* Resolve the ORDER BY on a compound SELECT after all terms of
  88604. ** the compound have been resolved.
  88605. */
  88606. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  88607. return WRC_Abort;
  88608. }
  88609. return WRC_Prune;
  88610. }
  88611. /*
  88612. ** This routine walks an expression tree and resolves references to
  88613. ** table columns and result-set columns. At the same time, do error
  88614. ** checking on function usage and set a flag if any aggregate functions
  88615. ** are seen.
  88616. **
  88617. ** To resolve table columns references we look for nodes (or subtrees) of the
  88618. ** form X.Y.Z or Y.Z or just Z where
  88619. **
  88620. ** X: The name of a database. Ex: "main" or "temp" or
  88621. ** the symbolic name assigned to an ATTACH-ed database.
  88622. **
  88623. ** Y: The name of a table in a FROM clause. Or in a trigger
  88624. ** one of the special names "old" or "new".
  88625. **
  88626. ** Z: The name of a column in table Y.
  88627. **
  88628. ** The node at the root of the subtree is modified as follows:
  88629. **
  88630. ** Expr.op Changed to TK_COLUMN
  88631. ** Expr.pTab Points to the Table object for X.Y
  88632. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  88633. ** Expr.iTable The VDBE cursor number for X.Y
  88634. **
  88635. **
  88636. ** To resolve result-set references, look for expression nodes of the
  88637. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  88638. ** size of an AS clause in the result-set of a SELECT. The Z expression
  88639. ** is replaced by a copy of the left-hand side of the result-set expression.
  88640. ** Table-name and function resolution occurs on the substituted expression
  88641. ** tree. For example, in:
  88642. **
  88643. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  88644. **
  88645. ** The "x" term of the order by is replaced by "a+b" to render:
  88646. **
  88647. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  88648. **
  88649. ** Function calls are checked to make sure that the function is
  88650. ** defined and that the correct number of arguments are specified.
  88651. ** If the function is an aggregate function, then the NC_HasAgg flag is
  88652. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  88653. ** If an expression contains aggregate functions then the EP_Agg
  88654. ** property on the expression is set.
  88655. **
  88656. ** An error message is left in pParse if anything is amiss. The number
  88657. ** if errors is returned.
  88658. */
  88659. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  88660. NameContext *pNC, /* Namespace to resolve expressions in. */
  88661. Expr *pExpr /* The expression to be analyzed. */
  88662. ){
  88663. u16 savedHasAgg;
  88664. Walker w;
  88665. if( pExpr==0 ) return SQLITE_OK;
  88666. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  88667. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  88668. w.pParse = pNC->pParse;
  88669. w.xExprCallback = resolveExprStep;
  88670. w.xSelectCallback = resolveSelectStep;
  88671. w.xSelectCallback2 = 0;
  88672. w.u.pNC = pNC;
  88673. #if SQLITE_MAX_EXPR_DEPTH>0
  88674. w.pParse->nHeight += pExpr->nHeight;
  88675. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  88676. return SQLITE_ERROR;
  88677. }
  88678. #endif
  88679. sqlite3WalkExpr(&w, pExpr);
  88680. #if SQLITE_MAX_EXPR_DEPTH>0
  88681. w.pParse->nHeight -= pExpr->nHeight;
  88682. #endif
  88683. if( pNC->ncFlags & NC_HasAgg ){
  88684. ExprSetProperty(pExpr, EP_Agg);
  88685. }
  88686. pNC->ncFlags |= savedHasAgg;
  88687. return pNC->nErr>0 || w.pParse->nErr>0;
  88688. }
  88689. /*
  88690. ** Resolve all names for all expression in an expression list. This is
  88691. ** just like sqlite3ResolveExprNames() except that it works for an expression
  88692. ** list rather than a single expression.
  88693. */
  88694. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  88695. NameContext *pNC, /* Namespace to resolve expressions in. */
  88696. ExprList *pList /* The expression list to be analyzed. */
  88697. ){
  88698. int i;
  88699. if( pList ){
  88700. for(i=0; i<pList->nExpr; i++){
  88701. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  88702. }
  88703. }
  88704. return WRC_Continue;
  88705. }
  88706. /*
  88707. ** Resolve all names in all expressions of a SELECT and in all
  88708. ** decendents of the SELECT, including compounds off of p->pPrior,
  88709. ** subqueries in expressions, and subqueries used as FROM clause
  88710. ** terms.
  88711. **
  88712. ** See sqlite3ResolveExprNames() for a description of the kinds of
  88713. ** transformations that occur.
  88714. **
  88715. ** All SELECT statements should have been expanded using
  88716. ** sqlite3SelectExpand() prior to invoking this routine.
  88717. */
  88718. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  88719. Parse *pParse, /* The parser context */
  88720. Select *p, /* The SELECT statement being coded. */
  88721. NameContext *pOuterNC /* Name context for parent SELECT statement */
  88722. ){
  88723. Walker w;
  88724. assert( p!=0 );
  88725. w.xExprCallback = resolveExprStep;
  88726. w.xSelectCallback = resolveSelectStep;
  88727. w.xSelectCallback2 = 0;
  88728. w.pParse = pParse;
  88729. w.u.pNC = pOuterNC;
  88730. sqlite3WalkSelect(&w, p);
  88731. }
  88732. /*
  88733. ** Resolve names in expressions that can only reference a single table:
  88734. **
  88735. ** * CHECK constraints
  88736. ** * WHERE clauses on partial indices
  88737. **
  88738. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  88739. ** is set to -1 and the Expr.iColumn value is set to the column number.
  88740. **
  88741. ** Any errors cause an error message to be set in pParse.
  88742. */
  88743. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  88744. Parse *pParse, /* Parsing context */
  88745. Table *pTab, /* The table being referenced */
  88746. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  88747. Expr *pExpr, /* Expression to resolve. May be NULL. */
  88748. ExprList *pList /* Expression list to resolve. May be NULL. */
  88749. ){
  88750. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  88751. NameContext sNC; /* Name context for pParse->pNewTable */
  88752. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  88753. memset(&sNC, 0, sizeof(sNC));
  88754. memset(&sSrc, 0, sizeof(sSrc));
  88755. sSrc.nSrc = 1;
  88756. sSrc.a[0].zName = pTab->zName;
  88757. sSrc.a[0].pTab = pTab;
  88758. sSrc.a[0].iCursor = -1;
  88759. sNC.pParse = pParse;
  88760. sNC.pSrcList = &sSrc;
  88761. sNC.ncFlags = type;
  88762. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  88763. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  88764. }
  88765. /************** End of resolve.c *********************************************/
  88766. /************** Begin file expr.c ********************************************/
  88767. /*
  88768. ** 2001 September 15
  88769. **
  88770. ** The author disclaims copyright to this source code. In place of
  88771. ** a legal notice, here is a blessing:
  88772. **
  88773. ** May you do good and not evil.
  88774. ** May you find forgiveness for yourself and forgive others.
  88775. ** May you share freely, never taking more than you give.
  88776. **
  88777. *************************************************************************
  88778. ** This file contains routines used for analyzing expressions and
  88779. ** for generating VDBE code that evaluates expressions in SQLite.
  88780. */
  88781. /* #include "sqliteInt.h" */
  88782. /* Forward declarations */
  88783. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  88784. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  88785. /*
  88786. ** Return the affinity character for a single column of a table.
  88787. */
  88788. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  88789. assert( iCol<pTab->nCol );
  88790. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  88791. }
  88792. /*
  88793. ** Return the 'affinity' of the expression pExpr if any.
  88794. **
  88795. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  88796. ** or a sub-select with a column as the return value, then the
  88797. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  88798. ** indicating no affinity for the expression.
  88799. **
  88800. ** i.e. the WHERE clause expressions in the following statements all
  88801. ** have an affinity:
  88802. **
  88803. ** CREATE TABLE t1(a);
  88804. ** SELECT * FROM t1 WHERE a;
  88805. ** SELECT a AS b FROM t1 WHERE b;
  88806. ** SELECT * FROM t1 WHERE (select a from t1);
  88807. */
  88808. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  88809. int op;
  88810. pExpr = sqlite3ExprSkipCollate(pExpr);
  88811. if( pExpr->flags & EP_Generic ) return 0;
  88812. op = pExpr->op;
  88813. if( op==TK_SELECT ){
  88814. assert( pExpr->flags&EP_xIsSelect );
  88815. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  88816. }
  88817. if( op==TK_REGISTER ) op = pExpr->op2;
  88818. #ifndef SQLITE_OMIT_CAST
  88819. if( op==TK_CAST ){
  88820. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88821. return sqlite3AffinityType(pExpr->u.zToken, 0);
  88822. }
  88823. #endif
  88824. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
  88825. return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
  88826. }
  88827. if( op==TK_SELECT_COLUMN ){
  88828. assert( pExpr->pLeft->flags&EP_xIsSelect );
  88829. return sqlite3ExprAffinity(
  88830. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  88831. );
  88832. }
  88833. return pExpr->affinity;
  88834. }
  88835. /*
  88836. ** Set the collating sequence for expression pExpr to be the collating
  88837. ** sequence named by pToken. Return a pointer to a new Expr node that
  88838. ** implements the COLLATE operator.
  88839. **
  88840. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  88841. ** and the pExpr parameter is returned unchanged.
  88842. */
  88843. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  88844. Parse *pParse, /* Parsing context */
  88845. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  88846. const Token *pCollName, /* Name of collating sequence */
  88847. int dequote /* True to dequote pCollName */
  88848. ){
  88849. if( pCollName->n>0 ){
  88850. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  88851. if( pNew ){
  88852. pNew->pLeft = pExpr;
  88853. pNew->flags |= EP_Collate|EP_Skip;
  88854. pExpr = pNew;
  88855. }
  88856. }
  88857. return pExpr;
  88858. }
  88859. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  88860. Token s;
  88861. assert( zC!=0 );
  88862. sqlite3TokenInit(&s, (char*)zC);
  88863. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  88864. }
  88865. /*
  88866. ** Skip over any TK_COLLATE operators and any unlikely()
  88867. ** or likelihood() function at the root of an expression.
  88868. */
  88869. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  88870. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  88871. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  88872. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  88873. assert( pExpr->x.pList->nExpr>0 );
  88874. assert( pExpr->op==TK_FUNCTION );
  88875. pExpr = pExpr->x.pList->a[0].pExpr;
  88876. }else{
  88877. assert( pExpr->op==TK_COLLATE );
  88878. pExpr = pExpr->pLeft;
  88879. }
  88880. }
  88881. return pExpr;
  88882. }
  88883. /*
  88884. ** Return the collation sequence for the expression pExpr. If
  88885. ** there is no defined collating sequence, return NULL.
  88886. **
  88887. ** See also: sqlite3ExprNNCollSeq()
  88888. **
  88889. ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
  88890. ** default collation if pExpr has no defined collation.
  88891. **
  88892. ** The collating sequence might be determined by a COLLATE operator
  88893. ** or by the presence of a column with a defined collating sequence.
  88894. ** COLLATE operators take first precedence. Left operands take
  88895. ** precedence over right operands.
  88896. */
  88897. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  88898. sqlite3 *db = pParse->db;
  88899. CollSeq *pColl = 0;
  88900. Expr *p = pExpr;
  88901. while( p ){
  88902. int op = p->op;
  88903. if( p->flags & EP_Generic ) break;
  88904. if( op==TK_CAST || op==TK_UPLUS ){
  88905. p = p->pLeft;
  88906. continue;
  88907. }
  88908. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  88909. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  88910. break;
  88911. }
  88912. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  88913. || op==TK_REGISTER || op==TK_TRIGGER)
  88914. && p->pTab!=0
  88915. ){
  88916. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  88917. ** a TK_COLUMN but was previously evaluated and cached in a register */
  88918. int j = p->iColumn;
  88919. if( j>=0 ){
  88920. const char *zColl = p->pTab->aCol[j].zColl;
  88921. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  88922. }
  88923. break;
  88924. }
  88925. if( p->flags & EP_Collate ){
  88926. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  88927. p = p->pLeft;
  88928. }else{
  88929. Expr *pNext = p->pRight;
  88930. /* The Expr.x union is never used at the same time as Expr.pRight */
  88931. assert( p->x.pList==0 || p->pRight==0 );
  88932. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  88933. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  88934. ** least one EP_Collate. Thus the following two ALWAYS. */
  88935. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  88936. int i;
  88937. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  88938. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  88939. pNext = p->x.pList->a[i].pExpr;
  88940. break;
  88941. }
  88942. }
  88943. }
  88944. p = pNext;
  88945. }
  88946. }else{
  88947. break;
  88948. }
  88949. }
  88950. if( sqlite3CheckCollSeq(pParse, pColl) ){
  88951. pColl = 0;
  88952. }
  88953. return pColl;
  88954. }
  88955. /*
  88956. ** Return the collation sequence for the expression pExpr. If
  88957. ** there is no defined collating sequence, return a pointer to the
  88958. ** defautl collation sequence.
  88959. **
  88960. ** See also: sqlite3ExprCollSeq()
  88961. **
  88962. ** The sqlite3ExprCollSeq() routine works the same except that it
  88963. ** returns NULL if there is no defined collation.
  88964. */
  88965. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
  88966. CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
  88967. if( p==0 ) p = pParse->db->pDfltColl;
  88968. assert( p!=0 );
  88969. return p;
  88970. }
  88971. /*
  88972. ** Return TRUE if the two expressions have equivalent collating sequences.
  88973. */
  88974. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
  88975. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
  88976. CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
  88977. return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
  88978. }
  88979. /*
  88980. ** pExpr is an operand of a comparison operator. aff2 is the
  88981. ** type affinity of the other operand. This routine returns the
  88982. ** type affinity that should be used for the comparison operator.
  88983. */
  88984. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  88985. char aff1 = sqlite3ExprAffinity(pExpr);
  88986. if( aff1 && aff2 ){
  88987. /* Both sides of the comparison are columns. If one has numeric
  88988. ** affinity, use that. Otherwise use no affinity.
  88989. */
  88990. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  88991. return SQLITE_AFF_NUMERIC;
  88992. }else{
  88993. return SQLITE_AFF_BLOB;
  88994. }
  88995. }else if( !aff1 && !aff2 ){
  88996. /* Neither side of the comparison is a column. Compare the
  88997. ** results directly.
  88998. */
  88999. return SQLITE_AFF_BLOB;
  89000. }else{
  89001. /* One side is a column, the other is not. Use the columns affinity. */
  89002. assert( aff1==0 || aff2==0 );
  89003. return (aff1 + aff2);
  89004. }
  89005. }
  89006. /*
  89007. ** pExpr is a comparison operator. Return the type affinity that should
  89008. ** be applied to both operands prior to doing the comparison.
  89009. */
  89010. static char comparisonAffinity(Expr *pExpr){
  89011. char aff;
  89012. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  89013. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  89014. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  89015. assert( pExpr->pLeft );
  89016. aff = sqlite3ExprAffinity(pExpr->pLeft);
  89017. if( pExpr->pRight ){
  89018. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  89019. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  89020. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  89021. }else if( aff==0 ){
  89022. aff = SQLITE_AFF_BLOB;
  89023. }
  89024. return aff;
  89025. }
  89026. /*
  89027. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  89028. ** idx_affinity is the affinity of an indexed column. Return true
  89029. ** if the index with affinity idx_affinity may be used to implement
  89030. ** the comparison in pExpr.
  89031. */
  89032. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  89033. char aff = comparisonAffinity(pExpr);
  89034. switch( aff ){
  89035. case SQLITE_AFF_BLOB:
  89036. return 1;
  89037. case SQLITE_AFF_TEXT:
  89038. return idx_affinity==SQLITE_AFF_TEXT;
  89039. default:
  89040. return sqlite3IsNumericAffinity(idx_affinity);
  89041. }
  89042. }
  89043. /*
  89044. ** Return the P5 value that should be used for a binary comparison
  89045. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  89046. */
  89047. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  89048. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  89049. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  89050. return aff;
  89051. }
  89052. /*
  89053. ** Return a pointer to the collation sequence that should be used by
  89054. ** a binary comparison operator comparing pLeft and pRight.
  89055. **
  89056. ** If the left hand expression has a collating sequence type, then it is
  89057. ** used. Otherwise the collation sequence for the right hand expression
  89058. ** is used, or the default (BINARY) if neither expression has a collating
  89059. ** type.
  89060. **
  89061. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  89062. ** it is not considered.
  89063. */
  89064. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  89065. Parse *pParse,
  89066. Expr *pLeft,
  89067. Expr *pRight
  89068. ){
  89069. CollSeq *pColl;
  89070. assert( pLeft );
  89071. if( pLeft->flags & EP_Collate ){
  89072. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  89073. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  89074. pColl = sqlite3ExprCollSeq(pParse, pRight);
  89075. }else{
  89076. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  89077. if( !pColl ){
  89078. pColl = sqlite3ExprCollSeq(pParse, pRight);
  89079. }
  89080. }
  89081. return pColl;
  89082. }
  89083. /*
  89084. ** Generate code for a comparison operator.
  89085. */
  89086. static int codeCompare(
  89087. Parse *pParse, /* The parsing (and code generating) context */
  89088. Expr *pLeft, /* The left operand */
  89089. Expr *pRight, /* The right operand */
  89090. int opcode, /* The comparison opcode */
  89091. int in1, int in2, /* Register holding operands */
  89092. int dest, /* Jump here if true. */
  89093. int jumpIfNull /* If true, jump if either operand is NULL */
  89094. ){
  89095. int p5;
  89096. int addr;
  89097. CollSeq *p4;
  89098. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  89099. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  89100. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  89101. (void*)p4, P4_COLLSEQ);
  89102. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  89103. return addr;
  89104. }
  89105. /*
  89106. ** Return true if expression pExpr is a vector, or false otherwise.
  89107. **
  89108. ** A vector is defined as any expression that results in two or more
  89109. ** columns of result. Every TK_VECTOR node is an vector because the
  89110. ** parser will not generate a TK_VECTOR with fewer than two entries.
  89111. ** But a TK_SELECT might be either a vector or a scalar. It is only
  89112. ** considered a vector if it has two or more result columns.
  89113. */
  89114. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  89115. return sqlite3ExprVectorSize(pExpr)>1;
  89116. }
  89117. /*
  89118. ** If the expression passed as the only argument is of type TK_VECTOR
  89119. ** return the number of expressions in the vector. Or, if the expression
  89120. ** is a sub-select, return the number of columns in the sub-select. For
  89121. ** any other type of expression, return 1.
  89122. */
  89123. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  89124. u8 op = pExpr->op;
  89125. if( op==TK_REGISTER ) op = pExpr->op2;
  89126. if( op==TK_VECTOR ){
  89127. return pExpr->x.pList->nExpr;
  89128. }else if( op==TK_SELECT ){
  89129. return pExpr->x.pSelect->pEList->nExpr;
  89130. }else{
  89131. return 1;
  89132. }
  89133. }
  89134. /*
  89135. ** Return a pointer to a subexpression of pVector that is the i-th
  89136. ** column of the vector (numbered starting with 0). The caller must
  89137. ** ensure that i is within range.
  89138. **
  89139. ** If pVector is really a scalar (and "scalar" here includes subqueries
  89140. ** that return a single column!) then return pVector unmodified.
  89141. **
  89142. ** pVector retains ownership of the returned subexpression.
  89143. **
  89144. ** If the vector is a (SELECT ...) then the expression returned is
  89145. ** just the expression for the i-th term of the result set, and may
  89146. ** not be ready for evaluation because the table cursor has not yet
  89147. ** been positioned.
  89148. */
  89149. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  89150. assert( i<sqlite3ExprVectorSize(pVector) );
  89151. if( sqlite3ExprIsVector(pVector) ){
  89152. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  89153. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  89154. return pVector->x.pSelect->pEList->a[i].pExpr;
  89155. }else{
  89156. return pVector->x.pList->a[i].pExpr;
  89157. }
  89158. }
  89159. return pVector;
  89160. }
  89161. /*
  89162. ** Compute and return a new Expr object which when passed to
  89163. ** sqlite3ExprCode() will generate all necessary code to compute
  89164. ** the iField-th column of the vector expression pVector.
  89165. **
  89166. ** It is ok for pVector to be a scalar (as long as iField==0).
  89167. ** In that case, this routine works like sqlite3ExprDup().
  89168. **
  89169. ** The caller owns the returned Expr object and is responsible for
  89170. ** ensuring that the returned value eventually gets freed.
  89171. **
  89172. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  89173. ** then the returned object will reference pVector and so pVector must remain
  89174. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  89175. ** or a scalar expression, then it can be deleted as soon as this routine
  89176. ** returns.
  89177. **
  89178. ** A trick to cause a TK_SELECT pVector to be deleted together with
  89179. ** the returned Expr object is to attach the pVector to the pRight field
  89180. ** of the returned TK_SELECT_COLUMN Expr object.
  89181. */
  89182. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  89183. Parse *pParse, /* Parsing context */
  89184. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  89185. int iField /* Which column of the vector to return */
  89186. ){
  89187. Expr *pRet;
  89188. if( pVector->op==TK_SELECT ){
  89189. assert( pVector->flags & EP_xIsSelect );
  89190. /* The TK_SELECT_COLUMN Expr node:
  89191. **
  89192. ** pLeft: pVector containing TK_SELECT. Not deleted.
  89193. ** pRight: not used. But recursively deleted.
  89194. ** iColumn: Index of a column in pVector
  89195. ** iTable: 0 or the number of columns on the LHS of an assignment
  89196. ** pLeft->iTable: First in an array of register holding result, or 0
  89197. ** if the result is not yet computed.
  89198. **
  89199. ** sqlite3ExprDelete() specifically skips the recursive delete of
  89200. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  89201. ** can be attached to pRight to cause this node to take ownership of
  89202. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  89203. ** with the same pLeft pointer to the pVector, but only one of them
  89204. ** will own the pVector.
  89205. */
  89206. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  89207. if( pRet ){
  89208. pRet->iColumn = iField;
  89209. pRet->pLeft = pVector;
  89210. }
  89211. assert( pRet==0 || pRet->iTable==0 );
  89212. }else{
  89213. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  89214. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  89215. }
  89216. return pRet;
  89217. }
  89218. /*
  89219. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  89220. ** it. Return the register in which the result is stored (or, if the
  89221. ** sub-select returns more than one column, the first in an array
  89222. ** of registers in which the result is stored).
  89223. **
  89224. ** If pExpr is not a TK_SELECT expression, return 0.
  89225. */
  89226. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  89227. int reg = 0;
  89228. #ifndef SQLITE_OMIT_SUBQUERY
  89229. if( pExpr->op==TK_SELECT ){
  89230. reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  89231. }
  89232. #endif
  89233. return reg;
  89234. }
  89235. /*
  89236. ** Argument pVector points to a vector expression - either a TK_VECTOR
  89237. ** or TK_SELECT that returns more than one column. This function returns
  89238. ** the register number of a register that contains the value of
  89239. ** element iField of the vector.
  89240. **
  89241. ** If pVector is a TK_SELECT expression, then code for it must have
  89242. ** already been generated using the exprCodeSubselect() routine. In this
  89243. ** case parameter regSelect should be the first in an array of registers
  89244. ** containing the results of the sub-select.
  89245. **
  89246. ** If pVector is of type TK_VECTOR, then code for the requested field
  89247. ** is generated. In this case (*pRegFree) may be set to the number of
  89248. ** a temporary register to be freed by the caller before returning.
  89249. **
  89250. ** Before returning, output parameter (*ppExpr) is set to point to the
  89251. ** Expr object corresponding to element iElem of the vector.
  89252. */
  89253. static int exprVectorRegister(
  89254. Parse *pParse, /* Parse context */
  89255. Expr *pVector, /* Vector to extract element from */
  89256. int iField, /* Field to extract from pVector */
  89257. int regSelect, /* First in array of registers */
  89258. Expr **ppExpr, /* OUT: Expression element */
  89259. int *pRegFree /* OUT: Temp register to free */
  89260. ){
  89261. u8 op = pVector->op;
  89262. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  89263. if( op==TK_REGISTER ){
  89264. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  89265. return pVector->iTable+iField;
  89266. }
  89267. if( op==TK_SELECT ){
  89268. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  89269. return regSelect+iField;
  89270. }
  89271. *ppExpr = pVector->x.pList->a[iField].pExpr;
  89272. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  89273. }
  89274. /*
  89275. ** Expression pExpr is a comparison between two vector values. Compute
  89276. ** the result of the comparison (1, 0, or NULL) and write that
  89277. ** result into register dest.
  89278. **
  89279. ** The caller must satisfy the following preconditions:
  89280. **
  89281. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  89282. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  89283. ** otherwise: op==pExpr->op and p5==0
  89284. */
  89285. static void codeVectorCompare(
  89286. Parse *pParse, /* Code generator context */
  89287. Expr *pExpr, /* The comparison operation */
  89288. int dest, /* Write results into this register */
  89289. u8 op, /* Comparison operator */
  89290. u8 p5 /* SQLITE_NULLEQ or zero */
  89291. ){
  89292. Vdbe *v = pParse->pVdbe;
  89293. Expr *pLeft = pExpr->pLeft;
  89294. Expr *pRight = pExpr->pRight;
  89295. int nLeft = sqlite3ExprVectorSize(pLeft);
  89296. int i;
  89297. int regLeft = 0;
  89298. int regRight = 0;
  89299. u8 opx = op;
  89300. int addrDone = sqlite3VdbeMakeLabel(v);
  89301. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  89302. sqlite3ErrorMsg(pParse, "row value misused");
  89303. return;
  89304. }
  89305. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  89306. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  89307. || pExpr->op==TK_LT || pExpr->op==TK_GT
  89308. || pExpr->op==TK_LE || pExpr->op==TK_GE
  89309. );
  89310. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  89311. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  89312. assert( p5==0 || pExpr->op!=op );
  89313. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  89314. p5 |= SQLITE_STOREP2;
  89315. if( opx==TK_LE ) opx = TK_LT;
  89316. if( opx==TK_GE ) opx = TK_GT;
  89317. regLeft = exprCodeSubselect(pParse, pLeft);
  89318. regRight = exprCodeSubselect(pParse, pRight);
  89319. for(i=0; 1 /*Loop exits by "break"*/; i++){
  89320. int regFree1 = 0, regFree2 = 0;
  89321. Expr *pL, *pR;
  89322. int r1, r2;
  89323. assert( i>=0 && i<nLeft );
  89324. if( i>0 ) sqlite3ExprCachePush(pParse);
  89325. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  89326. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  89327. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  89328. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  89329. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  89330. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  89331. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  89332. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  89333. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  89334. sqlite3ReleaseTempReg(pParse, regFree1);
  89335. sqlite3ReleaseTempReg(pParse, regFree2);
  89336. if( i>0 ) sqlite3ExprCachePop(pParse);
  89337. if( i==nLeft-1 ){
  89338. break;
  89339. }
  89340. if( opx==TK_EQ ){
  89341. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  89342. p5 |= SQLITE_KEEPNULL;
  89343. }else if( opx==TK_NE ){
  89344. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  89345. p5 |= SQLITE_KEEPNULL;
  89346. }else{
  89347. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  89348. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  89349. VdbeCoverageIf(v, op==TK_LT);
  89350. VdbeCoverageIf(v, op==TK_GT);
  89351. VdbeCoverageIf(v, op==TK_LE);
  89352. VdbeCoverageIf(v, op==TK_GE);
  89353. if( i==nLeft-2 ) opx = op;
  89354. }
  89355. }
  89356. sqlite3VdbeResolveLabel(v, addrDone);
  89357. }
  89358. #if SQLITE_MAX_EXPR_DEPTH>0
  89359. /*
  89360. ** Check that argument nHeight is less than or equal to the maximum
  89361. ** expression depth allowed. If it is not, leave an error message in
  89362. ** pParse.
  89363. */
  89364. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  89365. int rc = SQLITE_OK;
  89366. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  89367. if( nHeight>mxHeight ){
  89368. sqlite3ErrorMsg(pParse,
  89369. "Expression tree is too large (maximum depth %d)", mxHeight
  89370. );
  89371. rc = SQLITE_ERROR;
  89372. }
  89373. return rc;
  89374. }
  89375. /* The following three functions, heightOfExpr(), heightOfExprList()
  89376. ** and heightOfSelect(), are used to determine the maximum height
  89377. ** of any expression tree referenced by the structure passed as the
  89378. ** first argument.
  89379. **
  89380. ** If this maximum height is greater than the current value pointed
  89381. ** to by pnHeight, the second parameter, then set *pnHeight to that
  89382. ** value.
  89383. */
  89384. static void heightOfExpr(Expr *p, int *pnHeight){
  89385. if( p ){
  89386. if( p->nHeight>*pnHeight ){
  89387. *pnHeight = p->nHeight;
  89388. }
  89389. }
  89390. }
  89391. static void heightOfExprList(ExprList *p, int *pnHeight){
  89392. if( p ){
  89393. int i;
  89394. for(i=0; i<p->nExpr; i++){
  89395. heightOfExpr(p->a[i].pExpr, pnHeight);
  89396. }
  89397. }
  89398. }
  89399. static void heightOfSelect(Select *pSelect, int *pnHeight){
  89400. Select *p;
  89401. for(p=pSelect; p; p=p->pPrior){
  89402. heightOfExpr(p->pWhere, pnHeight);
  89403. heightOfExpr(p->pHaving, pnHeight);
  89404. heightOfExpr(p->pLimit, pnHeight);
  89405. heightOfExprList(p->pEList, pnHeight);
  89406. heightOfExprList(p->pGroupBy, pnHeight);
  89407. heightOfExprList(p->pOrderBy, pnHeight);
  89408. }
  89409. }
  89410. /*
  89411. ** Set the Expr.nHeight variable in the structure passed as an
  89412. ** argument. An expression with no children, Expr.pList or
  89413. ** Expr.pSelect member has a height of 1. Any other expression
  89414. ** has a height equal to the maximum height of any other
  89415. ** referenced Expr plus one.
  89416. **
  89417. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  89418. ** if appropriate.
  89419. */
  89420. static void exprSetHeight(Expr *p){
  89421. int nHeight = 0;
  89422. heightOfExpr(p->pLeft, &nHeight);
  89423. heightOfExpr(p->pRight, &nHeight);
  89424. if( ExprHasProperty(p, EP_xIsSelect) ){
  89425. heightOfSelect(p->x.pSelect, &nHeight);
  89426. }else if( p->x.pList ){
  89427. heightOfExprList(p->x.pList, &nHeight);
  89428. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  89429. }
  89430. p->nHeight = nHeight + 1;
  89431. }
  89432. /*
  89433. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  89434. ** the height is greater than the maximum allowed expression depth,
  89435. ** leave an error in pParse.
  89436. **
  89437. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  89438. ** Expr.flags.
  89439. */
  89440. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  89441. if( pParse->nErr ) return;
  89442. exprSetHeight(p);
  89443. sqlite3ExprCheckHeight(pParse, p->nHeight);
  89444. }
  89445. /*
  89446. ** Return the maximum height of any expression tree referenced
  89447. ** by the select statement passed as an argument.
  89448. */
  89449. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  89450. int nHeight = 0;
  89451. heightOfSelect(p, &nHeight);
  89452. return nHeight;
  89453. }
  89454. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  89455. /*
  89456. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  89457. ** Expr.flags.
  89458. */
  89459. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  89460. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  89461. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  89462. }
  89463. }
  89464. #define exprSetHeight(y)
  89465. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  89466. /*
  89467. ** This routine is the core allocator for Expr nodes.
  89468. **
  89469. ** Construct a new expression node and return a pointer to it. Memory
  89470. ** for this node and for the pToken argument is a single allocation
  89471. ** obtained from sqlite3DbMalloc(). The calling function
  89472. ** is responsible for making sure the node eventually gets freed.
  89473. **
  89474. ** If dequote is true, then the token (if it exists) is dequoted.
  89475. ** If dequote is false, no dequoting is performed. The deQuote
  89476. ** parameter is ignored if pToken is NULL or if the token does not
  89477. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  89478. ** then the EP_DblQuoted flag is set on the expression node.
  89479. **
  89480. ** Special case: If op==TK_INTEGER and pToken points to a string that
  89481. ** can be translated into a 32-bit integer, then the token is not
  89482. ** stored in u.zToken. Instead, the integer values is written
  89483. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  89484. ** is allocated to hold the integer text and the dequote flag is ignored.
  89485. */
  89486. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  89487. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  89488. int op, /* Expression opcode */
  89489. const Token *pToken, /* Token argument. Might be NULL */
  89490. int dequote /* True to dequote */
  89491. ){
  89492. Expr *pNew;
  89493. int nExtra = 0;
  89494. int iValue = 0;
  89495. assert( db!=0 );
  89496. if( pToken ){
  89497. if( op!=TK_INTEGER || pToken->z==0
  89498. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  89499. nExtra = pToken->n+1;
  89500. assert( iValue>=0 );
  89501. }
  89502. }
  89503. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  89504. if( pNew ){
  89505. memset(pNew, 0, sizeof(Expr));
  89506. pNew->op = (u8)op;
  89507. pNew->iAgg = -1;
  89508. if( pToken ){
  89509. if( nExtra==0 ){
  89510. pNew->flags |= EP_IntValue|EP_Leaf;
  89511. pNew->u.iValue = iValue;
  89512. }else{
  89513. pNew->u.zToken = (char*)&pNew[1];
  89514. assert( pToken->z!=0 || pToken->n==0 );
  89515. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  89516. pNew->u.zToken[pToken->n] = 0;
  89517. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  89518. if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
  89519. sqlite3Dequote(pNew->u.zToken);
  89520. }
  89521. }
  89522. }
  89523. #if SQLITE_MAX_EXPR_DEPTH>0
  89524. pNew->nHeight = 1;
  89525. #endif
  89526. }
  89527. return pNew;
  89528. }
  89529. /*
  89530. ** Allocate a new expression node from a zero-terminated token that has
  89531. ** already been dequoted.
  89532. */
  89533. SQLITE_PRIVATE Expr *sqlite3Expr(
  89534. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  89535. int op, /* Expression opcode */
  89536. const char *zToken /* Token argument. Might be NULL */
  89537. ){
  89538. Token x;
  89539. x.z = zToken;
  89540. x.n = sqlite3Strlen30(zToken);
  89541. return sqlite3ExprAlloc(db, op, &x, 0);
  89542. }
  89543. /*
  89544. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  89545. **
  89546. ** If pRoot==NULL that means that a memory allocation error has occurred.
  89547. ** In that case, delete the subtrees pLeft and pRight.
  89548. */
  89549. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  89550. sqlite3 *db,
  89551. Expr *pRoot,
  89552. Expr *pLeft,
  89553. Expr *pRight
  89554. ){
  89555. if( pRoot==0 ){
  89556. assert( db->mallocFailed );
  89557. sqlite3ExprDelete(db, pLeft);
  89558. sqlite3ExprDelete(db, pRight);
  89559. }else{
  89560. if( pRight ){
  89561. pRoot->pRight = pRight;
  89562. pRoot->flags |= EP_Propagate & pRight->flags;
  89563. }
  89564. if( pLeft ){
  89565. pRoot->pLeft = pLeft;
  89566. pRoot->flags |= EP_Propagate & pLeft->flags;
  89567. }
  89568. exprSetHeight(pRoot);
  89569. }
  89570. }
  89571. /*
  89572. ** Allocate an Expr node which joins as many as two subtrees.
  89573. **
  89574. ** One or both of the subtrees can be NULL. Return a pointer to the new
  89575. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  89576. ** free the subtrees and return NULL.
  89577. */
  89578. SQLITE_PRIVATE Expr *sqlite3PExpr(
  89579. Parse *pParse, /* Parsing context */
  89580. int op, /* Expression opcode */
  89581. Expr *pLeft, /* Left operand */
  89582. Expr *pRight /* Right operand */
  89583. ){
  89584. Expr *p;
  89585. if( op==TK_AND && pParse->nErr==0 ){
  89586. /* Take advantage of short-circuit false optimization for AND */
  89587. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  89588. }else{
  89589. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  89590. if( p ){
  89591. memset(p, 0, sizeof(Expr));
  89592. p->op = op & TKFLG_MASK;
  89593. p->iAgg = -1;
  89594. }
  89595. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  89596. }
  89597. if( p ) {
  89598. sqlite3ExprCheckHeight(pParse, p->nHeight);
  89599. }
  89600. return p;
  89601. }
  89602. /*
  89603. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  89604. ** do a memory allocation failure) then delete the pSelect object.
  89605. */
  89606. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  89607. if( pExpr ){
  89608. pExpr->x.pSelect = pSelect;
  89609. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  89610. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  89611. }else{
  89612. assert( pParse->db->mallocFailed );
  89613. sqlite3SelectDelete(pParse->db, pSelect);
  89614. }
  89615. }
  89616. /*
  89617. ** If the expression is always either TRUE or FALSE (respectively),
  89618. ** then return 1. If one cannot determine the truth value of the
  89619. ** expression at compile-time return 0.
  89620. **
  89621. ** This is an optimization. If is OK to return 0 here even if
  89622. ** the expression really is always false or false (a false negative).
  89623. ** But it is a bug to return 1 if the expression might have different
  89624. ** boolean values in different circumstances (a false positive.)
  89625. **
  89626. ** Note that if the expression is part of conditional for a
  89627. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  89628. ** is it true or false, so always return 0.
  89629. */
  89630. static int exprAlwaysTrue(Expr *p){
  89631. int v = 0;
  89632. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  89633. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  89634. return v!=0;
  89635. }
  89636. static int exprAlwaysFalse(Expr *p){
  89637. int v = 0;
  89638. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  89639. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  89640. return v==0;
  89641. }
  89642. /*
  89643. ** Join two expressions using an AND operator. If either expression is
  89644. ** NULL, then just return the other expression.
  89645. **
  89646. ** If one side or the other of the AND is known to be false, then instead
  89647. ** of returning an AND expression, just return a constant expression with
  89648. ** a value of false.
  89649. */
  89650. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  89651. if( pLeft==0 ){
  89652. return pRight;
  89653. }else if( pRight==0 ){
  89654. return pLeft;
  89655. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  89656. sqlite3ExprDelete(db, pLeft);
  89657. sqlite3ExprDelete(db, pRight);
  89658. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  89659. }else{
  89660. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  89661. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  89662. return pNew;
  89663. }
  89664. }
  89665. /*
  89666. ** Construct a new expression node for a function with multiple
  89667. ** arguments.
  89668. */
  89669. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  89670. Expr *pNew;
  89671. sqlite3 *db = pParse->db;
  89672. assert( pToken );
  89673. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  89674. if( pNew==0 ){
  89675. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  89676. return 0;
  89677. }
  89678. pNew->x.pList = pList;
  89679. ExprSetProperty(pNew, EP_HasFunc);
  89680. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  89681. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  89682. return pNew;
  89683. }
  89684. /*
  89685. ** Assign a variable number to an expression that encodes a wildcard
  89686. ** in the original SQL statement.
  89687. **
  89688. ** Wildcards consisting of a single "?" are assigned the next sequential
  89689. ** variable number.
  89690. **
  89691. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  89692. ** sure "nnn" is not too big to avoid a denial of service attack when
  89693. ** the SQL statement comes from an external source.
  89694. **
  89695. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  89696. ** as the previous instance of the same wildcard. Or if this is the first
  89697. ** instance of the wildcard, the next sequential variable number is
  89698. ** assigned.
  89699. */
  89700. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  89701. sqlite3 *db = pParse->db;
  89702. const char *z;
  89703. ynVar x;
  89704. if( pExpr==0 ) return;
  89705. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  89706. z = pExpr->u.zToken;
  89707. assert( z!=0 );
  89708. assert( z[0]!=0 );
  89709. assert( n==(u32)sqlite3Strlen30(z) );
  89710. if( z[1]==0 ){
  89711. /* Wildcard of the form "?". Assign the next variable number */
  89712. assert( z[0]=='?' );
  89713. x = (ynVar)(++pParse->nVar);
  89714. }else{
  89715. int doAdd = 0;
  89716. if( z[0]=='?' ){
  89717. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  89718. ** use it as the variable number */
  89719. i64 i;
  89720. int bOk;
  89721. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  89722. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  89723. bOk = 1;
  89724. }else{
  89725. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  89726. }
  89727. testcase( i==0 );
  89728. testcase( i==1 );
  89729. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  89730. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  89731. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  89732. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  89733. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  89734. return;
  89735. }
  89736. x = (ynVar)i;
  89737. if( x>pParse->nVar ){
  89738. pParse->nVar = (int)x;
  89739. doAdd = 1;
  89740. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  89741. doAdd = 1;
  89742. }
  89743. }else{
  89744. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  89745. ** number as the prior appearance of the same name, or if the name
  89746. ** has never appeared before, reuse the same variable number
  89747. */
  89748. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  89749. if( x==0 ){
  89750. x = (ynVar)(++pParse->nVar);
  89751. doAdd = 1;
  89752. }
  89753. }
  89754. if( doAdd ){
  89755. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  89756. }
  89757. }
  89758. pExpr->iColumn = x;
  89759. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  89760. sqlite3ErrorMsg(pParse, "too many SQL variables");
  89761. }
  89762. }
  89763. /*
  89764. ** Recursively delete an expression tree.
  89765. */
  89766. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  89767. assert( p!=0 );
  89768. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  89769. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  89770. #ifdef SQLITE_DEBUG
  89771. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  89772. assert( p->pLeft==0 );
  89773. assert( p->pRight==0 );
  89774. assert( p->x.pSelect==0 );
  89775. }
  89776. #endif
  89777. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  89778. /* The Expr.x union is never used at the same time as Expr.pRight */
  89779. assert( p->x.pList==0 || p->pRight==0 );
  89780. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  89781. if( p->pRight ){
  89782. sqlite3ExprDeleteNN(db, p->pRight);
  89783. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  89784. sqlite3SelectDelete(db, p->x.pSelect);
  89785. }else{
  89786. sqlite3ExprListDelete(db, p->x.pList);
  89787. }
  89788. }
  89789. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  89790. if( !ExprHasProperty(p, EP_Static) ){
  89791. sqlite3DbFreeNN(db, p);
  89792. }
  89793. }
  89794. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  89795. if( p ) sqlite3ExprDeleteNN(db, p);
  89796. }
  89797. /*
  89798. ** Return the number of bytes allocated for the expression structure
  89799. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  89800. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  89801. */
  89802. static int exprStructSize(Expr *p){
  89803. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  89804. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  89805. return EXPR_FULLSIZE;
  89806. }
  89807. /*
  89808. ** The dupedExpr*Size() routines each return the number of bytes required
  89809. ** to store a copy of an expression or expression tree. They differ in
  89810. ** how much of the tree is measured.
  89811. **
  89812. ** dupedExprStructSize() Size of only the Expr structure
  89813. ** dupedExprNodeSize() Size of Expr + space for token
  89814. ** dupedExprSize() Expr + token + subtree components
  89815. **
  89816. ***************************************************************************
  89817. **
  89818. ** The dupedExprStructSize() function returns two values OR-ed together:
  89819. ** (1) the space required for a copy of the Expr structure only and
  89820. ** (2) the EP_xxx flags that indicate what the structure size should be.
  89821. ** The return values is always one of:
  89822. **
  89823. ** EXPR_FULLSIZE
  89824. ** EXPR_REDUCEDSIZE | EP_Reduced
  89825. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  89826. **
  89827. ** The size of the structure can be found by masking the return value
  89828. ** of this routine with 0xfff. The flags can be found by masking the
  89829. ** return value with EP_Reduced|EP_TokenOnly.
  89830. **
  89831. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  89832. ** (unreduced) Expr objects as they or originally constructed by the parser.
  89833. ** During expression analysis, extra information is computed and moved into
  89834. ** later parts of teh Expr object and that extra information might get chopped
  89835. ** off if the expression is reduced. Note also that it does not work to
  89836. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  89837. ** to reduce a pristine expression tree from the parser. The implementation
  89838. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  89839. ** to enforce this constraint.
  89840. */
  89841. static int dupedExprStructSize(Expr *p, int flags){
  89842. int nSize;
  89843. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  89844. assert( EXPR_FULLSIZE<=0xfff );
  89845. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  89846. if( 0==flags || p->op==TK_SELECT_COLUMN ){
  89847. nSize = EXPR_FULLSIZE;
  89848. }else{
  89849. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  89850. assert( !ExprHasProperty(p, EP_FromJoin) );
  89851. assert( !ExprHasProperty(p, EP_MemToken) );
  89852. assert( !ExprHasProperty(p, EP_NoReduce) );
  89853. if( p->pLeft || p->x.pList ){
  89854. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  89855. }else{
  89856. assert( p->pRight==0 );
  89857. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  89858. }
  89859. }
  89860. return nSize;
  89861. }
  89862. /*
  89863. ** This function returns the space in bytes required to store the copy
  89864. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  89865. ** string is defined.)
  89866. */
  89867. static int dupedExprNodeSize(Expr *p, int flags){
  89868. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  89869. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  89870. nByte += sqlite3Strlen30(p->u.zToken)+1;
  89871. }
  89872. return ROUND8(nByte);
  89873. }
  89874. /*
  89875. ** Return the number of bytes required to create a duplicate of the
  89876. ** expression passed as the first argument. The second argument is a
  89877. ** mask containing EXPRDUP_XXX flags.
  89878. **
  89879. ** The value returned includes space to create a copy of the Expr struct
  89880. ** itself and the buffer referred to by Expr.u.zToken, if any.
  89881. **
  89882. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  89883. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  89884. ** and Expr.pRight variables (but not for any structures pointed to or
  89885. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  89886. */
  89887. static int dupedExprSize(Expr *p, int flags){
  89888. int nByte = 0;
  89889. if( p ){
  89890. nByte = dupedExprNodeSize(p, flags);
  89891. if( flags&EXPRDUP_REDUCE ){
  89892. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  89893. }
  89894. }
  89895. return nByte;
  89896. }
  89897. /*
  89898. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  89899. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  89900. ** to store the copy of expression p, the copies of p->u.zToken
  89901. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  89902. ** if any. Before returning, *pzBuffer is set to the first byte past the
  89903. ** portion of the buffer copied into by this function.
  89904. */
  89905. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  89906. Expr *pNew; /* Value to return */
  89907. u8 *zAlloc; /* Memory space from which to build Expr object */
  89908. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  89909. assert( db!=0 );
  89910. assert( p );
  89911. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  89912. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  89913. /* Figure out where to write the new Expr structure. */
  89914. if( pzBuffer ){
  89915. zAlloc = *pzBuffer;
  89916. staticFlag = EP_Static;
  89917. }else{
  89918. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  89919. staticFlag = 0;
  89920. }
  89921. pNew = (Expr *)zAlloc;
  89922. if( pNew ){
  89923. /* Set nNewSize to the size allocated for the structure pointed to
  89924. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  89925. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  89926. ** by the copy of the p->u.zToken string (if any).
  89927. */
  89928. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  89929. const int nNewSize = nStructSize & 0xfff;
  89930. int nToken;
  89931. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  89932. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  89933. }else{
  89934. nToken = 0;
  89935. }
  89936. if( dupFlags ){
  89937. assert( ExprHasProperty(p, EP_Reduced)==0 );
  89938. memcpy(zAlloc, p, nNewSize);
  89939. }else{
  89940. u32 nSize = (u32)exprStructSize(p);
  89941. memcpy(zAlloc, p, nSize);
  89942. if( nSize<EXPR_FULLSIZE ){
  89943. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  89944. }
  89945. }
  89946. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  89947. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  89948. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  89949. pNew->flags |= staticFlag;
  89950. /* Copy the p->u.zToken string, if any. */
  89951. if( nToken ){
  89952. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  89953. memcpy(zToken, p->u.zToken, nToken);
  89954. }
  89955. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  89956. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  89957. if( ExprHasProperty(p, EP_xIsSelect) ){
  89958. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  89959. }else{
  89960. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  89961. }
  89962. }
  89963. /* Fill in pNew->pLeft and pNew->pRight. */
  89964. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  89965. zAlloc += dupedExprNodeSize(p, dupFlags);
  89966. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  89967. pNew->pLeft = p->pLeft ?
  89968. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  89969. pNew->pRight = p->pRight ?
  89970. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  89971. }
  89972. if( pzBuffer ){
  89973. *pzBuffer = zAlloc;
  89974. }
  89975. }else{
  89976. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  89977. if( pNew->op==TK_SELECT_COLUMN ){
  89978. pNew->pLeft = p->pLeft;
  89979. assert( p->iColumn==0 || p->pRight==0 );
  89980. assert( p->pRight==0 || p->pRight==p->pLeft );
  89981. }else{
  89982. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  89983. }
  89984. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  89985. }
  89986. }
  89987. }
  89988. return pNew;
  89989. }
  89990. /*
  89991. ** Create and return a deep copy of the object passed as the second
  89992. ** argument. If an OOM condition is encountered, NULL is returned
  89993. ** and the db->mallocFailed flag set.
  89994. */
  89995. #ifndef SQLITE_OMIT_CTE
  89996. static With *withDup(sqlite3 *db, With *p){
  89997. With *pRet = 0;
  89998. if( p ){
  89999. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  90000. pRet = sqlite3DbMallocZero(db, nByte);
  90001. if( pRet ){
  90002. int i;
  90003. pRet->nCte = p->nCte;
  90004. for(i=0; i<p->nCte; i++){
  90005. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  90006. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  90007. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  90008. }
  90009. }
  90010. }
  90011. return pRet;
  90012. }
  90013. #else
  90014. # define withDup(x,y) 0
  90015. #endif
  90016. /*
  90017. ** The following group of routines make deep copies of expressions,
  90018. ** expression lists, ID lists, and select statements. The copies can
  90019. ** be deleted (by being passed to their respective ...Delete() routines)
  90020. ** without effecting the originals.
  90021. **
  90022. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  90023. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  90024. ** by subsequent calls to sqlite*ListAppend() routines.
  90025. **
  90026. ** Any tables that the SrcList might point to are not duplicated.
  90027. **
  90028. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  90029. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  90030. ** truncated version of the usual Expr structure that will be stored as
  90031. ** part of the in-memory representation of the database schema.
  90032. */
  90033. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  90034. assert( flags==0 || flags==EXPRDUP_REDUCE );
  90035. return p ? exprDup(db, p, flags, 0) : 0;
  90036. }
  90037. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  90038. ExprList *pNew;
  90039. struct ExprList_item *pItem, *pOldItem;
  90040. int i;
  90041. Expr *pPriorSelectCol = 0;
  90042. assert( db!=0 );
  90043. if( p==0 ) return 0;
  90044. pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
  90045. if( pNew==0 ) return 0;
  90046. pNew->nExpr = p->nExpr;
  90047. pItem = pNew->a;
  90048. pOldItem = p->a;
  90049. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  90050. Expr *pOldExpr = pOldItem->pExpr;
  90051. Expr *pNewExpr;
  90052. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  90053. if( pOldExpr
  90054. && pOldExpr->op==TK_SELECT_COLUMN
  90055. && (pNewExpr = pItem->pExpr)!=0
  90056. ){
  90057. assert( pNewExpr->iColumn==0 || i>0 );
  90058. if( pNewExpr->iColumn==0 ){
  90059. assert( pOldExpr->pLeft==pOldExpr->pRight );
  90060. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  90061. }else{
  90062. assert( i>0 );
  90063. assert( pItem[-1].pExpr!=0 );
  90064. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  90065. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  90066. pNewExpr->pLeft = pPriorSelectCol;
  90067. }
  90068. }
  90069. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  90070. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  90071. pItem->sortOrder = pOldItem->sortOrder;
  90072. pItem->done = 0;
  90073. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  90074. pItem->bSorterRef = pOldItem->bSorterRef;
  90075. pItem->u = pOldItem->u;
  90076. }
  90077. return pNew;
  90078. }
  90079. /*
  90080. ** If cursors, triggers, views and subqueries are all omitted from
  90081. ** the build, then none of the following routines, except for
  90082. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  90083. ** called with a NULL argument.
  90084. */
  90085. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  90086. || !defined(SQLITE_OMIT_SUBQUERY)
  90087. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  90088. SrcList *pNew;
  90089. int i;
  90090. int nByte;
  90091. assert( db!=0 );
  90092. if( p==0 ) return 0;
  90093. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  90094. pNew = sqlite3DbMallocRawNN(db, nByte );
  90095. if( pNew==0 ) return 0;
  90096. pNew->nSrc = pNew->nAlloc = p->nSrc;
  90097. for(i=0; i<p->nSrc; i++){
  90098. struct SrcList_item *pNewItem = &pNew->a[i];
  90099. struct SrcList_item *pOldItem = &p->a[i];
  90100. Table *pTab;
  90101. pNewItem->pSchema = pOldItem->pSchema;
  90102. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  90103. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  90104. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  90105. pNewItem->fg = pOldItem->fg;
  90106. pNewItem->iCursor = pOldItem->iCursor;
  90107. pNewItem->addrFillSub = pOldItem->addrFillSub;
  90108. pNewItem->regReturn = pOldItem->regReturn;
  90109. if( pNewItem->fg.isIndexedBy ){
  90110. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  90111. }
  90112. pNewItem->pIBIndex = pOldItem->pIBIndex;
  90113. if( pNewItem->fg.isTabFunc ){
  90114. pNewItem->u1.pFuncArg =
  90115. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  90116. }
  90117. pTab = pNewItem->pTab = pOldItem->pTab;
  90118. if( pTab ){
  90119. pTab->nTabRef++;
  90120. }
  90121. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  90122. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  90123. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  90124. pNewItem->colUsed = pOldItem->colUsed;
  90125. }
  90126. return pNew;
  90127. }
  90128. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  90129. IdList *pNew;
  90130. int i;
  90131. assert( db!=0 );
  90132. if( p==0 ) return 0;
  90133. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  90134. if( pNew==0 ) return 0;
  90135. pNew->nId = p->nId;
  90136. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  90137. if( pNew->a==0 ){
  90138. sqlite3DbFreeNN(db, pNew);
  90139. return 0;
  90140. }
  90141. /* Note that because the size of the allocation for p->a[] is not
  90142. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  90143. ** on the duplicate created by this function. */
  90144. for(i=0; i<p->nId; i++){
  90145. struct IdList_item *pNewItem = &pNew->a[i];
  90146. struct IdList_item *pOldItem = &p->a[i];
  90147. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  90148. pNewItem->idx = pOldItem->idx;
  90149. }
  90150. return pNew;
  90151. }
  90152. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  90153. Select *pRet = 0;
  90154. Select *pNext = 0;
  90155. Select **pp = &pRet;
  90156. Select *p;
  90157. assert( db!=0 );
  90158. for(p=pDup; p; p=p->pPrior){
  90159. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  90160. if( pNew==0 ) break;
  90161. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  90162. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  90163. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  90164. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  90165. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  90166. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  90167. pNew->op = p->op;
  90168. pNew->pNext = pNext;
  90169. pNew->pPrior = 0;
  90170. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  90171. pNew->iLimit = 0;
  90172. pNew->iOffset = 0;
  90173. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  90174. pNew->addrOpenEphm[0] = -1;
  90175. pNew->addrOpenEphm[1] = -1;
  90176. pNew->nSelectRow = p->nSelectRow;
  90177. pNew->pWith = withDup(db, p->pWith);
  90178. sqlite3SelectSetName(pNew, p->zSelName);
  90179. *pp = pNew;
  90180. pp = &pNew->pPrior;
  90181. pNext = pNew;
  90182. }
  90183. return pRet;
  90184. }
  90185. #else
  90186. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  90187. assert( p==0 );
  90188. return 0;
  90189. }
  90190. #endif
  90191. /*
  90192. ** Add a new element to the end of an expression list. If pList is
  90193. ** initially NULL, then create a new expression list.
  90194. **
  90195. ** The pList argument must be either NULL or a pointer to an ExprList
  90196. ** obtained from a prior call to sqlite3ExprListAppend(). This routine
  90197. ** may not be used with an ExprList obtained from sqlite3ExprListDup().
  90198. ** Reason: This routine assumes that the number of slots in pList->a[]
  90199. ** is a power of two. That is true for sqlite3ExprListAppend() returns
  90200. ** but is not necessarily true from the return value of sqlite3ExprListDup().
  90201. **
  90202. ** If a memory allocation error occurs, the entire list is freed and
  90203. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  90204. ** that the new entry was successfully appended.
  90205. */
  90206. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  90207. Parse *pParse, /* Parsing context */
  90208. ExprList *pList, /* List to which to append. Might be NULL */
  90209. Expr *pExpr /* Expression to be appended. Might be NULL */
  90210. ){
  90211. struct ExprList_item *pItem;
  90212. sqlite3 *db = pParse->db;
  90213. assert( db!=0 );
  90214. if( pList==0 ){
  90215. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  90216. if( pList==0 ){
  90217. goto no_mem;
  90218. }
  90219. pList->nExpr = 0;
  90220. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  90221. ExprList *pNew;
  90222. pNew = sqlite3DbRealloc(db, pList,
  90223. sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
  90224. if( pNew==0 ){
  90225. goto no_mem;
  90226. }
  90227. pList = pNew;
  90228. }
  90229. pItem = &pList->a[pList->nExpr++];
  90230. assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
  90231. assert( offsetof(struct ExprList_item,pExpr)==0 );
  90232. memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
  90233. pItem->pExpr = pExpr;
  90234. return pList;
  90235. no_mem:
  90236. /* Avoid leaking memory if malloc has failed. */
  90237. sqlite3ExprDelete(db, pExpr);
  90238. sqlite3ExprListDelete(db, pList);
  90239. return 0;
  90240. }
  90241. /*
  90242. ** pColumns and pExpr form a vector assignment which is part of the SET
  90243. ** clause of an UPDATE statement. Like this:
  90244. **
  90245. ** (a,b,c) = (expr1,expr2,expr3)
  90246. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  90247. **
  90248. ** For each term of the vector assignment, append new entries to the
  90249. ** expression list pList. In the case of a subquery on the RHS, append
  90250. ** TK_SELECT_COLUMN expressions.
  90251. */
  90252. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  90253. Parse *pParse, /* Parsing context */
  90254. ExprList *pList, /* List to which to append. Might be NULL */
  90255. IdList *pColumns, /* List of names of LHS of the assignment */
  90256. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  90257. ){
  90258. sqlite3 *db = pParse->db;
  90259. int n;
  90260. int i;
  90261. int iFirst = pList ? pList->nExpr : 0;
  90262. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  90263. ** exit prior to this routine being invoked */
  90264. if( NEVER(pColumns==0) ) goto vector_append_error;
  90265. if( pExpr==0 ) goto vector_append_error;
  90266. /* If the RHS is a vector, then we can immediately check to see that
  90267. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  90268. ** wildcards ("*") in the result set of the SELECT must be expanded before
  90269. ** we can do the size check, so defer the size check until code generation.
  90270. */
  90271. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  90272. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  90273. pColumns->nId, n);
  90274. goto vector_append_error;
  90275. }
  90276. for(i=0; i<pColumns->nId; i++){
  90277. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  90278. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  90279. if( pList ){
  90280. assert( pList->nExpr==iFirst+i+1 );
  90281. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  90282. pColumns->a[i].zName = 0;
  90283. }
  90284. }
  90285. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  90286. Expr *pFirst = pList->a[iFirst].pExpr;
  90287. assert( pFirst!=0 );
  90288. assert( pFirst->op==TK_SELECT_COLUMN );
  90289. /* Store the SELECT statement in pRight so it will be deleted when
  90290. ** sqlite3ExprListDelete() is called */
  90291. pFirst->pRight = pExpr;
  90292. pExpr = 0;
  90293. /* Remember the size of the LHS in iTable so that we can check that
  90294. ** the RHS and LHS sizes match during code generation. */
  90295. pFirst->iTable = pColumns->nId;
  90296. }
  90297. vector_append_error:
  90298. sqlite3ExprDelete(db, pExpr);
  90299. sqlite3IdListDelete(db, pColumns);
  90300. return pList;
  90301. }
  90302. /*
  90303. ** Set the sort order for the last element on the given ExprList.
  90304. */
  90305. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  90306. if( p==0 ) return;
  90307. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  90308. assert( p->nExpr>0 );
  90309. if( iSortOrder<0 ){
  90310. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  90311. return;
  90312. }
  90313. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  90314. }
  90315. /*
  90316. ** Set the ExprList.a[].zName element of the most recently added item
  90317. ** on the expression list.
  90318. **
  90319. ** pList might be NULL following an OOM error. But pName should never be
  90320. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  90321. ** is set.
  90322. */
  90323. SQLITE_PRIVATE void sqlite3ExprListSetName(
  90324. Parse *pParse, /* Parsing context */
  90325. ExprList *pList, /* List to which to add the span. */
  90326. Token *pName, /* Name to be added */
  90327. int dequote /* True to cause the name to be dequoted */
  90328. ){
  90329. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  90330. if( pList ){
  90331. struct ExprList_item *pItem;
  90332. assert( pList->nExpr>0 );
  90333. pItem = &pList->a[pList->nExpr-1];
  90334. assert( pItem->zName==0 );
  90335. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  90336. if( dequote ) sqlite3Dequote(pItem->zName);
  90337. }
  90338. }
  90339. /*
  90340. ** Set the ExprList.a[].zSpan element of the most recently added item
  90341. ** on the expression list.
  90342. **
  90343. ** pList might be NULL following an OOM error. But pSpan should never be
  90344. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  90345. ** is set.
  90346. */
  90347. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  90348. Parse *pParse, /* Parsing context */
  90349. ExprList *pList, /* List to which to add the span. */
  90350. const char *zStart, /* Start of the span */
  90351. const char *zEnd /* End of the span */
  90352. ){
  90353. sqlite3 *db = pParse->db;
  90354. assert( pList!=0 || db->mallocFailed!=0 );
  90355. if( pList ){
  90356. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  90357. assert( pList->nExpr>0 );
  90358. sqlite3DbFree(db, pItem->zSpan);
  90359. pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
  90360. }
  90361. }
  90362. /*
  90363. ** If the expression list pEList contains more than iLimit elements,
  90364. ** leave an error message in pParse.
  90365. */
  90366. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  90367. Parse *pParse,
  90368. ExprList *pEList,
  90369. const char *zObject
  90370. ){
  90371. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  90372. testcase( pEList && pEList->nExpr==mx );
  90373. testcase( pEList && pEList->nExpr==mx+1 );
  90374. if( pEList && pEList->nExpr>mx ){
  90375. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  90376. }
  90377. }
  90378. /*
  90379. ** Delete an entire expression list.
  90380. */
  90381. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  90382. int i = pList->nExpr;
  90383. struct ExprList_item *pItem = pList->a;
  90384. assert( pList->nExpr>0 );
  90385. do{
  90386. sqlite3ExprDelete(db, pItem->pExpr);
  90387. sqlite3DbFree(db, pItem->zName);
  90388. sqlite3DbFree(db, pItem->zSpan);
  90389. pItem++;
  90390. }while( --i>0 );
  90391. sqlite3DbFreeNN(db, pList);
  90392. }
  90393. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  90394. if( pList ) exprListDeleteNN(db, pList);
  90395. }
  90396. /*
  90397. ** Return the bitwise-OR of all Expr.flags fields in the given
  90398. ** ExprList.
  90399. */
  90400. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  90401. int i;
  90402. u32 m = 0;
  90403. assert( pList!=0 );
  90404. for(i=0; i<pList->nExpr; i++){
  90405. Expr *pExpr = pList->a[i].pExpr;
  90406. assert( pExpr!=0 );
  90407. m |= pExpr->flags;
  90408. }
  90409. return m;
  90410. }
  90411. /*
  90412. ** This is a SELECT-node callback for the expression walker that
  90413. ** always "fails". By "fail" in this case, we mean set
  90414. ** pWalker->eCode to zero and abort.
  90415. **
  90416. ** This callback is used by multiple expression walkers.
  90417. */
  90418. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
  90419. UNUSED_PARAMETER(NotUsed);
  90420. pWalker->eCode = 0;
  90421. return WRC_Abort;
  90422. }
  90423. /*
  90424. ** If the input expression is an ID with the name "true" or "false"
  90425. ** then convert it into an TK_TRUEFALSE term. Return non-zero if
  90426. ** the conversion happened, and zero if the expression is unaltered.
  90427. */
  90428. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
  90429. assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
  90430. if( sqlite3StrICmp(pExpr->u.zToken, "true")==0
  90431. || sqlite3StrICmp(pExpr->u.zToken, "false")==0
  90432. ){
  90433. pExpr->op = TK_TRUEFALSE;
  90434. return 1;
  90435. }
  90436. return 0;
  90437. }
  90438. /*
  90439. ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
  90440. ** and 0 if it is FALSE.
  90441. */
  90442. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
  90443. assert( pExpr->op==TK_TRUEFALSE );
  90444. assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
  90445. || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
  90446. return pExpr->u.zToken[4]==0;
  90447. }
  90448. /*
  90449. ** These routines are Walker callbacks used to check expressions to
  90450. ** see if they are "constant" for some definition of constant. The
  90451. ** Walker.eCode value determines the type of "constant" we are looking
  90452. ** for.
  90453. **
  90454. ** These callback routines are used to implement the following:
  90455. **
  90456. ** sqlite3ExprIsConstant() pWalker->eCode==1
  90457. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  90458. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  90459. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  90460. **
  90461. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  90462. ** is found to not be a constant.
  90463. **
  90464. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  90465. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  90466. ** an existing schema and 4 when processing a new statement. A bound
  90467. ** parameter raises an error for new statements, but is silently converted
  90468. ** to NULL for existing schemas. This allows sqlite_master tables that
  90469. ** contain a bound parameter because they were generated by older versions
  90470. ** of SQLite to be parsed by newer versions of SQLite without raising a
  90471. ** malformed schema error.
  90472. */
  90473. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  90474. /* If pWalker->eCode is 2 then any term of the expression that comes from
  90475. ** the ON or USING clauses of a left join disqualifies the expression
  90476. ** from being considered constant. */
  90477. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  90478. pWalker->eCode = 0;
  90479. return WRC_Abort;
  90480. }
  90481. switch( pExpr->op ){
  90482. /* Consider functions to be constant if all their arguments are constant
  90483. ** and either pWalker->eCode==4 or 5 or the function has the
  90484. ** SQLITE_FUNC_CONST flag. */
  90485. case TK_FUNCTION:
  90486. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  90487. return WRC_Continue;
  90488. }else{
  90489. pWalker->eCode = 0;
  90490. return WRC_Abort;
  90491. }
  90492. case TK_ID:
  90493. /* Convert "true" or "false" in a DEFAULT clause into the
  90494. ** appropriate TK_TRUEFALSE operator */
  90495. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  90496. return WRC_Prune;
  90497. }
  90498. /* Fall thru */
  90499. case TK_COLUMN:
  90500. case TK_AGG_FUNCTION:
  90501. case TK_AGG_COLUMN:
  90502. testcase( pExpr->op==TK_ID );
  90503. testcase( pExpr->op==TK_COLUMN );
  90504. testcase( pExpr->op==TK_AGG_FUNCTION );
  90505. testcase( pExpr->op==TK_AGG_COLUMN );
  90506. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  90507. return WRC_Continue;
  90508. }
  90509. /* Fall through */
  90510. case TK_IF_NULL_ROW:
  90511. case TK_REGISTER:
  90512. testcase( pExpr->op==TK_REGISTER );
  90513. testcase( pExpr->op==TK_IF_NULL_ROW );
  90514. pWalker->eCode = 0;
  90515. return WRC_Abort;
  90516. case TK_VARIABLE:
  90517. if( pWalker->eCode==5 ){
  90518. /* Silently convert bound parameters that appear inside of CREATE
  90519. ** statements into a NULL when parsing the CREATE statement text out
  90520. ** of the sqlite_master table */
  90521. pExpr->op = TK_NULL;
  90522. }else if( pWalker->eCode==4 ){
  90523. /* A bound parameter in a CREATE statement that originates from
  90524. ** sqlite3_prepare() causes an error */
  90525. pWalker->eCode = 0;
  90526. return WRC_Abort;
  90527. }
  90528. /* Fall through */
  90529. default:
  90530. testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
  90531. testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
  90532. return WRC_Continue;
  90533. }
  90534. }
  90535. static int exprIsConst(Expr *p, int initFlag, int iCur){
  90536. Walker w;
  90537. w.eCode = initFlag;
  90538. w.xExprCallback = exprNodeIsConstant;
  90539. w.xSelectCallback = sqlite3SelectWalkFail;
  90540. #ifdef SQLITE_DEBUG
  90541. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  90542. #endif
  90543. w.u.iCur = iCur;
  90544. sqlite3WalkExpr(&w, p);
  90545. return w.eCode;
  90546. }
  90547. /*
  90548. ** Walk an expression tree. Return non-zero if the expression is constant
  90549. ** and 0 if it involves variables or function calls.
  90550. **
  90551. ** For the purposes of this function, a double-quoted string (ex: "abc")
  90552. ** is considered a variable but a single-quoted string (ex: 'abc') is
  90553. ** a constant.
  90554. */
  90555. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  90556. return exprIsConst(p, 1, 0);
  90557. }
  90558. /*
  90559. ** Walk an expression tree. Return non-zero if the expression is constant
  90560. ** that does no originate from the ON or USING clauses of a join.
  90561. ** Return 0 if it involves variables or function calls or terms from
  90562. ** an ON or USING clause.
  90563. */
  90564. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  90565. return exprIsConst(p, 2, 0);
  90566. }
  90567. /*
  90568. ** Walk an expression tree. Return non-zero if the expression is constant
  90569. ** for any single row of the table with cursor iCur. In other words, the
  90570. ** expression must not refer to any non-deterministic function nor any
  90571. ** table other than iCur.
  90572. */
  90573. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  90574. return exprIsConst(p, 3, iCur);
  90575. }
  90576. /*
  90577. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  90578. */
  90579. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  90580. ExprList *pGroupBy = pWalker->u.pGroupBy;
  90581. int i;
  90582. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  90583. ** it constant. */
  90584. for(i=0; i<pGroupBy->nExpr; i++){
  90585. Expr *p = pGroupBy->a[i].pExpr;
  90586. if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
  90587. CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
  90588. if( sqlite3_stricmp("BINARY", pColl->zName)==0 ){
  90589. return WRC_Prune;
  90590. }
  90591. }
  90592. }
  90593. /* Check if pExpr is a sub-select. If so, consider it variable. */
  90594. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  90595. pWalker->eCode = 0;
  90596. return WRC_Abort;
  90597. }
  90598. return exprNodeIsConstant(pWalker, pExpr);
  90599. }
  90600. /*
  90601. ** Walk the expression tree passed as the first argument. Return non-zero
  90602. ** if the expression consists entirely of constants or copies of terms
  90603. ** in pGroupBy that sort with the BINARY collation sequence.
  90604. **
  90605. ** This routine is used to determine if a term of the HAVING clause can
  90606. ** be promoted into the WHERE clause. In order for such a promotion to work,
  90607. ** the value of the HAVING clause term must be the same for all members of
  90608. ** a "group". The requirement that the GROUP BY term must be BINARY
  90609. ** assumes that no other collating sequence will have a finer-grained
  90610. ** grouping than binary. In other words (A=B COLLATE binary) implies
  90611. ** A=B in every other collating sequence. The requirement that the
  90612. ** GROUP BY be BINARY is stricter than necessary. It would also work
  90613. ** to promote HAVING clauses that use the same alternative collating
  90614. ** sequence as the GROUP BY term, but that is much harder to check,
  90615. ** alternative collating sequences are uncommon, and this is only an
  90616. ** optimization, so we take the easy way out and simply require the
  90617. ** GROUP BY to use the BINARY collating sequence.
  90618. */
  90619. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  90620. Walker w;
  90621. w.eCode = 1;
  90622. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  90623. w.xSelectCallback = 0;
  90624. w.u.pGroupBy = pGroupBy;
  90625. w.pParse = pParse;
  90626. sqlite3WalkExpr(&w, p);
  90627. return w.eCode;
  90628. }
  90629. /*
  90630. ** Walk an expression tree. Return non-zero if the expression is constant
  90631. ** or a function call with constant arguments. Return and 0 if there
  90632. ** are any variables.
  90633. **
  90634. ** For the purposes of this function, a double-quoted string (ex: "abc")
  90635. ** is considered a variable but a single-quoted string (ex: 'abc') is
  90636. ** a constant.
  90637. */
  90638. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  90639. assert( isInit==0 || isInit==1 );
  90640. return exprIsConst(p, 4+isInit, 0);
  90641. }
  90642. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  90643. /*
  90644. ** Walk an expression tree. Return 1 if the expression contains a
  90645. ** subquery of some kind. Return 0 if there are no subqueries.
  90646. */
  90647. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  90648. Walker w;
  90649. w.eCode = 1;
  90650. w.xExprCallback = sqlite3ExprWalkNoop;
  90651. w.xSelectCallback = sqlite3SelectWalkFail;
  90652. #ifdef SQLITE_DEBUG
  90653. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  90654. #endif
  90655. sqlite3WalkExpr(&w, p);
  90656. return w.eCode==0;
  90657. }
  90658. #endif
  90659. /*
  90660. ** If the expression p codes a constant integer that is small enough
  90661. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  90662. ** in *pValue. If the expression is not an integer or if it is too big
  90663. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  90664. */
  90665. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  90666. int rc = 0;
  90667. if( p==0 ) return 0; /* Can only happen following on OOM */
  90668. /* If an expression is an integer literal that fits in a signed 32-bit
  90669. ** integer, then the EP_IntValue flag will have already been set */
  90670. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  90671. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  90672. if( p->flags & EP_IntValue ){
  90673. *pValue = p->u.iValue;
  90674. return 1;
  90675. }
  90676. switch( p->op ){
  90677. case TK_UPLUS: {
  90678. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  90679. break;
  90680. }
  90681. case TK_UMINUS: {
  90682. int v;
  90683. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  90684. assert( v!=(-2147483647-1) );
  90685. *pValue = -v;
  90686. rc = 1;
  90687. }
  90688. break;
  90689. }
  90690. default: break;
  90691. }
  90692. return rc;
  90693. }
  90694. /*
  90695. ** Return FALSE if there is no chance that the expression can be NULL.
  90696. **
  90697. ** If the expression might be NULL or if the expression is too complex
  90698. ** to tell return TRUE.
  90699. **
  90700. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  90701. ** when we know that a value cannot be NULL. Hence, a false positive
  90702. ** (returning TRUE when in fact the expression can never be NULL) might
  90703. ** be a small performance hit but is otherwise harmless. On the other
  90704. ** hand, a false negative (returning FALSE when the result could be NULL)
  90705. ** will likely result in an incorrect answer. So when in doubt, return
  90706. ** TRUE.
  90707. */
  90708. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  90709. u8 op;
  90710. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  90711. op = p->op;
  90712. if( op==TK_REGISTER ) op = p->op2;
  90713. switch( op ){
  90714. case TK_INTEGER:
  90715. case TK_STRING:
  90716. case TK_FLOAT:
  90717. case TK_BLOB:
  90718. return 0;
  90719. case TK_COLUMN:
  90720. return ExprHasProperty(p, EP_CanBeNull) ||
  90721. p->pTab==0 || /* Reference to column of index on expression */
  90722. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  90723. default:
  90724. return 1;
  90725. }
  90726. }
  90727. /*
  90728. ** Return TRUE if the given expression is a constant which would be
  90729. ** unchanged by OP_Affinity with the affinity given in the second
  90730. ** argument.
  90731. **
  90732. ** This routine is used to determine if the OP_Affinity operation
  90733. ** can be omitted. When in doubt return FALSE. A false negative
  90734. ** is harmless. A false positive, however, can result in the wrong
  90735. ** answer.
  90736. */
  90737. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  90738. u8 op;
  90739. if( aff==SQLITE_AFF_BLOB ) return 1;
  90740. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  90741. op = p->op;
  90742. if( op==TK_REGISTER ) op = p->op2;
  90743. switch( op ){
  90744. case TK_INTEGER: {
  90745. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  90746. }
  90747. case TK_FLOAT: {
  90748. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  90749. }
  90750. case TK_STRING: {
  90751. return aff==SQLITE_AFF_TEXT;
  90752. }
  90753. case TK_BLOB: {
  90754. return 1;
  90755. }
  90756. case TK_COLUMN: {
  90757. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  90758. return p->iColumn<0
  90759. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  90760. }
  90761. default: {
  90762. return 0;
  90763. }
  90764. }
  90765. }
  90766. /*
  90767. ** Return TRUE if the given string is a row-id column name.
  90768. */
  90769. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  90770. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  90771. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  90772. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  90773. return 0;
  90774. }
  90775. /*
  90776. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  90777. ** that can be simplified to a direct table access, then return
  90778. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  90779. ** or if the SELECT statement needs to be manifested into a transient
  90780. ** table, then return NULL.
  90781. */
  90782. #ifndef SQLITE_OMIT_SUBQUERY
  90783. static Select *isCandidateForInOpt(Expr *pX){
  90784. Select *p;
  90785. SrcList *pSrc;
  90786. ExprList *pEList;
  90787. Table *pTab;
  90788. int i;
  90789. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  90790. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  90791. p = pX->x.pSelect;
  90792. if( p->pPrior ) return 0; /* Not a compound SELECT */
  90793. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  90794. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  90795. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  90796. return 0; /* No DISTINCT keyword and no aggregate functions */
  90797. }
  90798. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  90799. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  90800. if( p->pWhere ) return 0; /* Has no WHERE clause */
  90801. pSrc = p->pSrc;
  90802. assert( pSrc!=0 );
  90803. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  90804. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  90805. pTab = pSrc->a[0].pTab;
  90806. assert( pTab!=0 );
  90807. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  90808. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  90809. pEList = p->pEList;
  90810. assert( pEList!=0 );
  90811. /* All SELECT results must be columns. */
  90812. for(i=0; i<pEList->nExpr; i++){
  90813. Expr *pRes = pEList->a[i].pExpr;
  90814. if( pRes->op!=TK_COLUMN ) return 0;
  90815. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  90816. }
  90817. return p;
  90818. }
  90819. #endif /* SQLITE_OMIT_SUBQUERY */
  90820. #ifndef SQLITE_OMIT_SUBQUERY
  90821. /*
  90822. ** Generate code that checks the left-most column of index table iCur to see if
  90823. ** it contains any NULL entries. Cause the register at regHasNull to be set
  90824. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  90825. ** to be set to NULL if iCur contains one or more NULL values.
  90826. */
  90827. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  90828. int addr1;
  90829. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  90830. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  90831. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  90832. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  90833. VdbeComment((v, "first_entry_in(%d)", iCur));
  90834. sqlite3VdbeJumpHere(v, addr1);
  90835. }
  90836. #endif
  90837. #ifndef SQLITE_OMIT_SUBQUERY
  90838. /*
  90839. ** The argument is an IN operator with a list (not a subquery) on the
  90840. ** right-hand side. Return TRUE if that list is constant.
  90841. */
  90842. static int sqlite3InRhsIsConstant(Expr *pIn){
  90843. Expr *pLHS;
  90844. int res;
  90845. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  90846. pLHS = pIn->pLeft;
  90847. pIn->pLeft = 0;
  90848. res = sqlite3ExprIsConstant(pIn);
  90849. pIn->pLeft = pLHS;
  90850. return res;
  90851. }
  90852. #endif
  90853. /*
  90854. ** This function is used by the implementation of the IN (...) operator.
  90855. ** The pX parameter is the expression on the RHS of the IN operator, which
  90856. ** might be either a list of expressions or a subquery.
  90857. **
  90858. ** The job of this routine is to find or create a b-tree object that can
  90859. ** be used either to test for membership in the RHS set or to iterate through
  90860. ** all members of the RHS set, skipping duplicates.
  90861. **
  90862. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  90863. ** and pX->iTable is set to the index of that cursor.
  90864. **
  90865. ** The returned value of this function indicates the b-tree type, as follows:
  90866. **
  90867. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  90868. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  90869. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  90870. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  90871. ** populated epheremal table.
  90872. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  90873. ** implemented as a sequence of comparisons.
  90874. **
  90875. ** An existing b-tree might be used if the RHS expression pX is a simple
  90876. ** subquery such as:
  90877. **
  90878. ** SELECT <column1>, <column2>... FROM <table>
  90879. **
  90880. ** If the RHS of the IN operator is a list or a more complex subquery, then
  90881. ** an ephemeral table might need to be generated from the RHS and then
  90882. ** pX->iTable made to point to the ephemeral table instead of an
  90883. ** existing table.
  90884. **
  90885. ** The inFlags parameter must contain, at a minimum, one of the bits
  90886. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
  90887. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
  90888. ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
  90889. ** be used to loop over all values of the RHS of the IN operator.
  90890. **
  90891. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  90892. ** through the set members) then the b-tree must not contain duplicates.
  90893. ** An epheremal table will be created unless the selected columns are guaranteed
  90894. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  90895. ** a UNIQUE constraint or index.
  90896. **
  90897. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  90898. ** for fast set membership tests) then an epheremal table must
  90899. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  90900. ** index can be found with the specified <columns> as its left-most.
  90901. **
  90902. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  90903. ** if the RHS of the IN operator is a list (not a subquery) then this
  90904. ** routine might decide that creating an ephemeral b-tree for membership
  90905. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  90906. ** calling routine should implement the IN operator using a sequence
  90907. ** of Eq or Ne comparison operations.
  90908. **
  90909. ** When the b-tree is being used for membership tests, the calling function
  90910. ** might need to know whether or not the RHS side of the IN operator
  90911. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  90912. ** if there is any chance that the (...) might contain a NULL value at
  90913. ** runtime, then a register is allocated and the register number written
  90914. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  90915. ** NULL value, then *prRhsHasNull is left unchanged.
  90916. **
  90917. ** If a register is allocated and its location stored in *prRhsHasNull, then
  90918. ** the value in that register will be NULL if the b-tree contains one or more
  90919. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  90920. ** NULL values.
  90921. **
  90922. ** If the aiMap parameter is not NULL, it must point to an array containing
  90923. ** one element for each column returned by the SELECT statement on the RHS
  90924. ** of the IN(...) operator. The i'th entry of the array is populated with the
  90925. ** offset of the index column that matches the i'th column returned by the
  90926. ** SELECT. For example, if the expression and selected index are:
  90927. **
  90928. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  90929. ** CREATE INDEX i1 ON t1(b, c, a);
  90930. **
  90931. ** then aiMap[] is populated with {2, 0, 1}.
  90932. */
  90933. #ifndef SQLITE_OMIT_SUBQUERY
  90934. SQLITE_PRIVATE int sqlite3FindInIndex(
  90935. Parse *pParse, /* Parsing context */
  90936. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  90937. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  90938. int *prRhsHasNull, /* Register holding NULL status. See notes */
  90939. int *aiMap /* Mapping from Index fields to RHS fields */
  90940. ){
  90941. Select *p; /* SELECT to the right of IN operator */
  90942. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  90943. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  90944. int mustBeUnique; /* True if RHS must be unique */
  90945. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  90946. assert( pX->op==TK_IN );
  90947. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  90948. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  90949. ** whether or not the SELECT result contains NULL values, check whether
  90950. ** or not NULL is actually possible (it may not be, for example, due
  90951. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  90952. ** set prRhsHasNull to 0 before continuing. */
  90953. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  90954. int i;
  90955. ExprList *pEList = pX->x.pSelect->pEList;
  90956. for(i=0; i<pEList->nExpr; i++){
  90957. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  90958. }
  90959. if( i==pEList->nExpr ){
  90960. prRhsHasNull = 0;
  90961. }
  90962. }
  90963. /* Check to see if an existing table or index can be used to
  90964. ** satisfy the query. This is preferable to generating a new
  90965. ** ephemeral table. */
  90966. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  90967. sqlite3 *db = pParse->db; /* Database connection */
  90968. Table *pTab; /* Table <table>. */
  90969. i16 iDb; /* Database idx for pTab */
  90970. ExprList *pEList = p->pEList;
  90971. int nExpr = pEList->nExpr;
  90972. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  90973. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  90974. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  90975. pTab = p->pSrc->a[0].pTab;
  90976. /* Code an OP_Transaction and OP_TableLock for <table>. */
  90977. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90978. sqlite3CodeVerifySchema(pParse, iDb);
  90979. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  90980. assert(v); /* sqlite3GetVdbe() has always been previously called */
  90981. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  90982. /* The "x IN (SELECT rowid FROM table)" case */
  90983. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  90984. VdbeCoverage(v);
  90985. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  90986. eType = IN_INDEX_ROWID;
  90987. sqlite3VdbeJumpHere(v, iAddr);
  90988. }else{
  90989. Index *pIdx; /* Iterator variable */
  90990. int affinity_ok = 1;
  90991. int i;
  90992. /* Check that the affinity that will be used to perform each
  90993. ** comparison is the same as the affinity of each column in table
  90994. ** on the RHS of the IN operator. If it not, it is not possible to
  90995. ** use any index of the RHS table. */
  90996. for(i=0; i<nExpr && affinity_ok; i++){
  90997. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  90998. int iCol = pEList->a[i].pExpr->iColumn;
  90999. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  91000. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  91001. testcase( cmpaff==SQLITE_AFF_BLOB );
  91002. testcase( cmpaff==SQLITE_AFF_TEXT );
  91003. switch( cmpaff ){
  91004. case SQLITE_AFF_BLOB:
  91005. break;
  91006. case SQLITE_AFF_TEXT:
  91007. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  91008. ** other has no affinity and the other side is TEXT. Hence,
  91009. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  91010. ** and for the term on the LHS of the IN to have no affinity. */
  91011. assert( idxaff==SQLITE_AFF_TEXT );
  91012. break;
  91013. default:
  91014. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  91015. }
  91016. }
  91017. if( affinity_ok ){
  91018. /* Search for an existing index that will work for this IN operator */
  91019. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  91020. Bitmask colUsed; /* Columns of the index used */
  91021. Bitmask mCol; /* Mask for the current column */
  91022. if( pIdx->nColumn<nExpr ) continue;
  91023. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  91024. ** BITMASK(nExpr) without overflowing */
  91025. testcase( pIdx->nColumn==BMS-2 );
  91026. testcase( pIdx->nColumn==BMS-1 );
  91027. if( pIdx->nColumn>=BMS-1 ) continue;
  91028. if( mustBeUnique ){
  91029. if( pIdx->nKeyCol>nExpr
  91030. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  91031. ){
  91032. continue; /* This index is not unique over the IN RHS columns */
  91033. }
  91034. }
  91035. colUsed = 0; /* Columns of index used so far */
  91036. for(i=0; i<nExpr; i++){
  91037. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  91038. Expr *pRhs = pEList->a[i].pExpr;
  91039. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  91040. int j;
  91041. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  91042. for(j=0; j<nExpr; j++){
  91043. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  91044. assert( pIdx->azColl[j] );
  91045. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  91046. continue;
  91047. }
  91048. break;
  91049. }
  91050. if( j==nExpr ) break;
  91051. mCol = MASKBIT(j);
  91052. if( mCol & colUsed ) break; /* Each column used only once */
  91053. colUsed |= mCol;
  91054. if( aiMap ) aiMap[i] = j;
  91055. }
  91056. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  91057. if( colUsed==(MASKBIT(nExpr)-1) ){
  91058. /* If we reach this point, that means the index pIdx is usable */
  91059. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  91060. ExplainQueryPlan((pParse, 0,
  91061. "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
  91062. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  91063. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  91064. VdbeComment((v, "%s", pIdx->zName));
  91065. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  91066. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  91067. if( prRhsHasNull ){
  91068. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  91069. i64 mask = (1<<nExpr)-1;
  91070. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  91071. iTab, 0, 0, (u8*)&mask, P4_INT64);
  91072. #endif
  91073. *prRhsHasNull = ++pParse->nMem;
  91074. if( nExpr==1 ){
  91075. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  91076. }
  91077. }
  91078. sqlite3VdbeJumpHere(v, iAddr);
  91079. }
  91080. } /* End loop over indexes */
  91081. } /* End if( affinity_ok ) */
  91082. } /* End if not an rowid index */
  91083. } /* End attempt to optimize using an index */
  91084. /* If no preexisting index is available for the IN clause
  91085. ** and IN_INDEX_NOOP is an allowed reply
  91086. ** and the RHS of the IN operator is a list, not a subquery
  91087. ** and the RHS is not constant or has two or fewer terms,
  91088. ** then it is not worth creating an ephemeral table to evaluate
  91089. ** the IN operator so return IN_INDEX_NOOP.
  91090. */
  91091. if( eType==0
  91092. && (inFlags & IN_INDEX_NOOP_OK)
  91093. && !ExprHasProperty(pX, EP_xIsSelect)
  91094. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  91095. ){
  91096. eType = IN_INDEX_NOOP;
  91097. }
  91098. if( eType==0 ){
  91099. /* Could not find an existing table or index to use as the RHS b-tree.
  91100. ** We will have to generate an ephemeral table to do the job.
  91101. */
  91102. u32 savedNQueryLoop = pParse->nQueryLoop;
  91103. int rMayHaveNull = 0;
  91104. eType = IN_INDEX_EPH;
  91105. if( inFlags & IN_INDEX_LOOP ){
  91106. pParse->nQueryLoop = 0;
  91107. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  91108. eType = IN_INDEX_ROWID;
  91109. }
  91110. }else if( prRhsHasNull ){
  91111. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  91112. }
  91113. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  91114. pParse->nQueryLoop = savedNQueryLoop;
  91115. }else{
  91116. pX->iTable = iTab;
  91117. }
  91118. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  91119. int i, n;
  91120. n = sqlite3ExprVectorSize(pX->pLeft);
  91121. for(i=0; i<n; i++) aiMap[i] = i;
  91122. }
  91123. return eType;
  91124. }
  91125. #endif
  91126. #ifndef SQLITE_OMIT_SUBQUERY
  91127. /*
  91128. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  91129. ** function allocates and returns a nul-terminated string containing
  91130. ** the affinities to be used for each column of the comparison.
  91131. **
  91132. ** It is the responsibility of the caller to ensure that the returned
  91133. ** string is eventually freed using sqlite3DbFree().
  91134. */
  91135. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  91136. Expr *pLeft = pExpr->pLeft;
  91137. int nVal = sqlite3ExprVectorSize(pLeft);
  91138. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  91139. char *zRet;
  91140. assert( pExpr->op==TK_IN );
  91141. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  91142. if( zRet ){
  91143. int i;
  91144. for(i=0; i<nVal; i++){
  91145. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  91146. char a = sqlite3ExprAffinity(pA);
  91147. if( pSelect ){
  91148. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  91149. }else{
  91150. zRet[i] = a;
  91151. }
  91152. }
  91153. zRet[nVal] = '\0';
  91154. }
  91155. return zRet;
  91156. }
  91157. #endif
  91158. #ifndef SQLITE_OMIT_SUBQUERY
  91159. /*
  91160. ** Load the Parse object passed as the first argument with an error
  91161. ** message of the form:
  91162. **
  91163. ** "sub-select returns N columns - expected M"
  91164. */
  91165. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  91166. const char *zFmt = "sub-select returns %d columns - expected %d";
  91167. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  91168. }
  91169. #endif
  91170. /*
  91171. ** Expression pExpr is a vector that has been used in a context where
  91172. ** it is not permitted. If pExpr is a sub-select vector, this routine
  91173. ** loads the Parse object with a message of the form:
  91174. **
  91175. ** "sub-select returns N columns - expected 1"
  91176. **
  91177. ** Or, if it is a regular scalar vector:
  91178. **
  91179. ** "row value misused"
  91180. */
  91181. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  91182. #ifndef SQLITE_OMIT_SUBQUERY
  91183. if( pExpr->flags & EP_xIsSelect ){
  91184. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  91185. }else
  91186. #endif
  91187. {
  91188. sqlite3ErrorMsg(pParse, "row value misused");
  91189. }
  91190. }
  91191. /*
  91192. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  91193. ** or IN operators. Examples:
  91194. **
  91195. ** (SELECT a FROM b) -- subquery
  91196. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  91197. ** x IN (4,5,11) -- IN operator with list on right-hand side
  91198. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  91199. **
  91200. ** The pExpr parameter describes the expression that contains the IN
  91201. ** operator or subquery.
  91202. **
  91203. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  91204. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  91205. ** to some integer key column of a table B-Tree. In this case, use an
  91206. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  91207. ** (slower) variable length keys B-Tree.
  91208. **
  91209. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  91210. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  91211. ** All this routine does is initialize the register given by rMayHaveNull
  91212. ** to NULL. Calling routines will take care of changing this register
  91213. ** value to non-NULL if the RHS is NULL-free.
  91214. **
  91215. ** For a SELECT or EXISTS operator, return the register that holds the
  91216. ** result. For a multi-column SELECT, the result is stored in a contiguous
  91217. ** array of registers and the return value is the register of the left-most
  91218. ** result column. Return 0 for IN operators or if an error occurs.
  91219. */
  91220. #ifndef SQLITE_OMIT_SUBQUERY
  91221. SQLITE_PRIVATE int sqlite3CodeSubselect(
  91222. Parse *pParse, /* Parsing context */
  91223. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  91224. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  91225. int isRowid /* If true, LHS of IN operator is a rowid */
  91226. ){
  91227. int jmpIfDynamic = -1; /* One-time test address */
  91228. int rReg = 0; /* Register storing resulting */
  91229. Vdbe *v = sqlite3GetVdbe(pParse);
  91230. if( NEVER(v==0) ) return 0;
  91231. sqlite3ExprCachePush(pParse);
  91232. /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
  91233. ** is encountered if any of the following is true:
  91234. **
  91235. ** * The right-hand side is a correlated subquery
  91236. ** * The right-hand side is an expression list containing variables
  91237. ** * We are inside a trigger
  91238. **
  91239. ** If all of the above are false, then we can run this code just once
  91240. ** save the results, and reuse the same result on subsequent invocations.
  91241. */
  91242. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  91243. jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  91244. }
  91245. switch( pExpr->op ){
  91246. case TK_IN: {
  91247. int addr; /* Address of OP_OpenEphemeral instruction */
  91248. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  91249. KeyInfo *pKeyInfo = 0; /* Key information */
  91250. int nVal; /* Size of vector pLeft */
  91251. nVal = sqlite3ExprVectorSize(pLeft);
  91252. assert( !isRowid || nVal==1 );
  91253. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  91254. ** expression it is handled the same way. An ephemeral table is
  91255. ** filled with index keys representing the results from the
  91256. ** SELECT or the <exprlist>.
  91257. **
  91258. ** If the 'x' expression is a column value, or the SELECT...
  91259. ** statement returns a column value, then the affinity of that
  91260. ** column is used to build the index keys. If both 'x' and the
  91261. ** SELECT... statement are columns, then numeric affinity is used
  91262. ** if either column has NUMERIC or INTEGER affinity. If neither
  91263. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  91264. ** is used.
  91265. */
  91266. pExpr->iTable = pParse->nTab++;
  91267. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
  91268. pExpr->iTable, (isRowid?0:nVal));
  91269. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  91270. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  91271. /* Case 1: expr IN (SELECT ...)
  91272. **
  91273. ** Generate code to write the results of the select into the temporary
  91274. ** table allocated and opened above.
  91275. */
  91276. Select *pSelect = pExpr->x.pSelect;
  91277. ExprList *pEList = pSelect->pEList;
  91278. ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY",
  91279. jmpIfDynamic>=0?"":"CORRELATED "
  91280. ));
  91281. assert( !isRowid );
  91282. /* If the LHS and RHS of the IN operator do not match, that
  91283. ** error will have been caught long before we reach this point. */
  91284. if( ALWAYS(pEList->nExpr==nVal) ){
  91285. SelectDest dest;
  91286. int i;
  91287. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  91288. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  91289. pSelect->iLimit = 0;
  91290. testcase( pSelect->selFlags & SF_Distinct );
  91291. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  91292. if( sqlite3Select(pParse, pSelect, &dest) ){
  91293. sqlite3DbFree(pParse->db, dest.zAffSdst);
  91294. sqlite3KeyInfoUnref(pKeyInfo);
  91295. return 0;
  91296. }
  91297. sqlite3DbFree(pParse->db, dest.zAffSdst);
  91298. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  91299. assert( pEList!=0 );
  91300. assert( pEList->nExpr>0 );
  91301. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  91302. for(i=0; i<nVal; i++){
  91303. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  91304. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  91305. pParse, p, pEList->a[i].pExpr
  91306. );
  91307. }
  91308. }
  91309. }else if( ALWAYS(pExpr->x.pList!=0) ){
  91310. /* Case 2: expr IN (exprlist)
  91311. **
  91312. ** For each expression, build an index key from the evaluation and
  91313. ** store it in the temporary table. If <expr> is a column, then use
  91314. ** that columns affinity when building index keys. If <expr> is not
  91315. ** a column, use numeric affinity.
  91316. */
  91317. char affinity; /* Affinity of the LHS of the IN */
  91318. int i;
  91319. ExprList *pList = pExpr->x.pList;
  91320. struct ExprList_item *pItem;
  91321. int r1, r2, r3;
  91322. affinity = sqlite3ExprAffinity(pLeft);
  91323. if( !affinity ){
  91324. affinity = SQLITE_AFF_BLOB;
  91325. }
  91326. if( pKeyInfo ){
  91327. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  91328. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  91329. }
  91330. /* Loop through each expression in <exprlist>. */
  91331. r1 = sqlite3GetTempReg(pParse);
  91332. r2 = sqlite3GetTempReg(pParse);
  91333. if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
  91334. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  91335. Expr *pE2 = pItem->pExpr;
  91336. int iValToIns;
  91337. /* If the expression is not constant then we will need to
  91338. ** disable the test that was generated above that makes sure
  91339. ** this code only executes once. Because for a non-constant
  91340. ** expression we need to rerun this code each time.
  91341. */
  91342. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  91343. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  91344. jmpIfDynamic = -1;
  91345. }
  91346. /* Evaluate the expression and insert it into the temp table */
  91347. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  91348. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  91349. }else{
  91350. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  91351. if( isRowid ){
  91352. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  91353. sqlite3VdbeCurrentAddr(v)+2);
  91354. VdbeCoverage(v);
  91355. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  91356. }else{
  91357. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  91358. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  91359. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
  91360. }
  91361. }
  91362. }
  91363. sqlite3ReleaseTempReg(pParse, r1);
  91364. sqlite3ReleaseTempReg(pParse, r2);
  91365. }
  91366. if( pKeyInfo ){
  91367. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  91368. }
  91369. break;
  91370. }
  91371. case TK_EXISTS:
  91372. case TK_SELECT:
  91373. default: {
  91374. /* Case 3: (SELECT ... FROM ...)
  91375. ** or: EXISTS(SELECT ... FROM ...)
  91376. **
  91377. ** For a SELECT, generate code to put the values for all columns of
  91378. ** the first row into an array of registers and return the index of
  91379. ** the first register.
  91380. **
  91381. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  91382. ** into a register and return that register number.
  91383. **
  91384. ** In both cases, the query is augmented with "LIMIT 1". Any
  91385. ** preexisting limit is discarded in place of the new LIMIT 1.
  91386. */
  91387. Select *pSel; /* SELECT statement to encode */
  91388. SelectDest dest; /* How to deal with SELECT result */
  91389. int nReg; /* Registers to allocate */
  91390. Expr *pLimit; /* New limit expression */
  91391. testcase( pExpr->op==TK_EXISTS );
  91392. testcase( pExpr->op==TK_SELECT );
  91393. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  91394. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  91395. pSel = pExpr->x.pSelect;
  91396. ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY",
  91397. jmpIfDynamic>=0?"":"CORRELATED "));
  91398. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  91399. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  91400. pParse->nMem += nReg;
  91401. if( pExpr->op==TK_SELECT ){
  91402. dest.eDest = SRT_Mem;
  91403. dest.iSdst = dest.iSDParm;
  91404. dest.nSdst = nReg;
  91405. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  91406. VdbeComment((v, "Init subquery result"));
  91407. }else{
  91408. dest.eDest = SRT_Exists;
  91409. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  91410. VdbeComment((v, "Init EXISTS result"));
  91411. }
  91412. pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
  91413. if( pSel->pLimit ){
  91414. sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
  91415. pSel->pLimit->pLeft = pLimit;
  91416. }else{
  91417. pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
  91418. }
  91419. pSel->iLimit = 0;
  91420. if( sqlite3Select(pParse, pSel, &dest) ){
  91421. return 0;
  91422. }
  91423. rReg = dest.iSDParm;
  91424. ExprSetVVAProperty(pExpr, EP_NoReduce);
  91425. break;
  91426. }
  91427. }
  91428. if( rHasNullFlag ){
  91429. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  91430. }
  91431. if( jmpIfDynamic>=0 ){
  91432. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  91433. }
  91434. sqlite3ExprCachePop(pParse);
  91435. return rReg;
  91436. }
  91437. #endif /* SQLITE_OMIT_SUBQUERY */
  91438. #ifndef SQLITE_OMIT_SUBQUERY
  91439. /*
  91440. ** Expr pIn is an IN(...) expression. This function checks that the
  91441. ** sub-select on the RHS of the IN() operator has the same number of
  91442. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  91443. ** a sub-query, that the LHS is a vector of size 1.
  91444. */
  91445. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  91446. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  91447. if( (pIn->flags & EP_xIsSelect) ){
  91448. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  91449. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  91450. return 1;
  91451. }
  91452. }else if( nVector!=1 ){
  91453. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  91454. return 1;
  91455. }
  91456. return 0;
  91457. }
  91458. #endif
  91459. #ifndef SQLITE_OMIT_SUBQUERY
  91460. /*
  91461. ** Generate code for an IN expression.
  91462. **
  91463. ** x IN (SELECT ...)
  91464. ** x IN (value, value, ...)
  91465. **
  91466. ** The left-hand side (LHS) is a scalar or vector expression. The
  91467. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  91468. ** subquery. If the RHS is a subquery, the number of result columns must
  91469. ** match the number of columns in the vector on the LHS. If the RHS is
  91470. ** a list of values, the LHS must be a scalar.
  91471. **
  91472. ** The IN operator is true if the LHS value is contained within the RHS.
  91473. ** The result is false if the LHS is definitely not in the RHS. The
  91474. ** result is NULL if the presence of the LHS in the RHS cannot be
  91475. ** determined due to NULLs.
  91476. **
  91477. ** This routine generates code that jumps to destIfFalse if the LHS is not
  91478. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  91479. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  91480. ** within the RHS then fall through.
  91481. **
  91482. ** See the separate in-operator.md documentation file in the canonical
  91483. ** SQLite source tree for additional information.
  91484. */
  91485. static void sqlite3ExprCodeIN(
  91486. Parse *pParse, /* Parsing and code generating context */
  91487. Expr *pExpr, /* The IN expression */
  91488. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  91489. int destIfNull /* Jump here if the results are unknown due to NULLs */
  91490. ){
  91491. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  91492. int eType; /* Type of the RHS */
  91493. int rLhs; /* Register(s) holding the LHS values */
  91494. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  91495. Vdbe *v; /* Statement under construction */
  91496. int *aiMap = 0; /* Map from vector field to index column */
  91497. char *zAff = 0; /* Affinity string for comparisons */
  91498. int nVector; /* Size of vectors for this IN operator */
  91499. int iDummy; /* Dummy parameter to exprCodeVector() */
  91500. Expr *pLeft; /* The LHS of the IN operator */
  91501. int i; /* loop counter */
  91502. int destStep2; /* Where to jump when NULLs seen in step 2 */
  91503. int destStep6 = 0; /* Start of code for Step 6 */
  91504. int addrTruthOp; /* Address of opcode that determines the IN is true */
  91505. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  91506. int addrTop; /* Top of the step-6 loop */
  91507. pLeft = pExpr->pLeft;
  91508. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  91509. zAff = exprINAffinity(pParse, pExpr);
  91510. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  91511. aiMap = (int*)sqlite3DbMallocZero(
  91512. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  91513. );
  91514. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  91515. /* Attempt to compute the RHS. After this step, if anything other than
  91516. ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
  91517. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  91518. ** the RHS has not yet been coded. */
  91519. v = pParse->pVdbe;
  91520. assert( v!=0 ); /* OOM detected prior to this routine */
  91521. VdbeNoopComment((v, "begin IN expr"));
  91522. eType = sqlite3FindInIndex(pParse, pExpr,
  91523. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  91524. destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
  91525. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  91526. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  91527. );
  91528. #ifdef SQLITE_DEBUG
  91529. /* Confirm that aiMap[] contains nVector integer values between 0 and
  91530. ** nVector-1. */
  91531. for(i=0; i<nVector; i++){
  91532. int j, cnt;
  91533. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  91534. assert( cnt==1 );
  91535. }
  91536. #endif
  91537. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  91538. ** vector, then it is stored in an array of nVector registers starting
  91539. ** at r1.
  91540. **
  91541. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  91542. ** so that the fields are in the same order as an existing index. The
  91543. ** aiMap[] array contains a mapping from the original LHS field order to
  91544. ** the field order that matches the RHS index.
  91545. */
  91546. sqlite3ExprCachePush(pParse);
  91547. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  91548. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  91549. if( i==nVector ){
  91550. /* LHS fields are not reordered */
  91551. rLhs = rLhsOrig;
  91552. }else{
  91553. /* Need to reorder the LHS fields according to aiMap */
  91554. rLhs = sqlite3GetTempRange(pParse, nVector);
  91555. for(i=0; i<nVector; i++){
  91556. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  91557. }
  91558. }
  91559. /* If sqlite3FindInIndex() did not find or create an index that is
  91560. ** suitable for evaluating the IN operator, then evaluate using a
  91561. ** sequence of comparisons.
  91562. **
  91563. ** This is step (1) in the in-operator.md optimized algorithm.
  91564. */
  91565. if( eType==IN_INDEX_NOOP ){
  91566. ExprList *pList = pExpr->x.pList;
  91567. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  91568. int labelOk = sqlite3VdbeMakeLabel(v);
  91569. int r2, regToFree;
  91570. int regCkNull = 0;
  91571. int ii;
  91572. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  91573. if( destIfNull!=destIfFalse ){
  91574. regCkNull = sqlite3GetTempReg(pParse);
  91575. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  91576. }
  91577. for(ii=0; ii<pList->nExpr; ii++){
  91578. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  91579. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  91580. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  91581. }
  91582. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  91583. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  91584. (void*)pColl, P4_COLLSEQ);
  91585. VdbeCoverageIf(v, ii<pList->nExpr-1);
  91586. VdbeCoverageIf(v, ii==pList->nExpr-1);
  91587. sqlite3VdbeChangeP5(v, zAff[0]);
  91588. }else{
  91589. assert( destIfNull==destIfFalse );
  91590. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  91591. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  91592. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  91593. }
  91594. sqlite3ReleaseTempReg(pParse, regToFree);
  91595. }
  91596. if( regCkNull ){
  91597. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  91598. sqlite3VdbeGoto(v, destIfFalse);
  91599. }
  91600. sqlite3VdbeResolveLabel(v, labelOk);
  91601. sqlite3ReleaseTempReg(pParse, regCkNull);
  91602. goto sqlite3ExprCodeIN_finished;
  91603. }
  91604. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  91605. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  91606. ** We will then skip the binary search of the RHS.
  91607. */
  91608. if( destIfNull==destIfFalse ){
  91609. destStep2 = destIfFalse;
  91610. }else{
  91611. destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
  91612. }
  91613. for(i=0; i<nVector; i++){
  91614. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  91615. if( sqlite3ExprCanBeNull(p) ){
  91616. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  91617. VdbeCoverage(v);
  91618. }
  91619. }
  91620. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  91621. ** of the RHS using the LHS as a probe. If found, the result is
  91622. ** true.
  91623. */
  91624. if( eType==IN_INDEX_ROWID ){
  91625. /* In this case, the RHS is the ROWID of table b-tree and so we also
  91626. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  91627. ** into a single opcode. */
  91628. sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
  91629. VdbeCoverage(v);
  91630. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  91631. }else{
  91632. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  91633. if( destIfFalse==destIfNull ){
  91634. /* Combine Step 3 and Step 5 into a single opcode */
  91635. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
  91636. rLhs, nVector); VdbeCoverage(v);
  91637. goto sqlite3ExprCodeIN_finished;
  91638. }
  91639. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  91640. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
  91641. rLhs, nVector); VdbeCoverage(v);
  91642. }
  91643. /* Step 4. If the RHS is known to be non-NULL and we did not find
  91644. ** an match on the search above, then the result must be FALSE.
  91645. */
  91646. if( rRhsHasNull && nVector==1 ){
  91647. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  91648. VdbeCoverage(v);
  91649. }
  91650. /* Step 5. If we do not care about the difference between NULL and
  91651. ** FALSE, then just return false.
  91652. */
  91653. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  91654. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  91655. ** If any comparison is NULL, then the result is NULL. If all
  91656. ** comparisons are FALSE then the final result is FALSE.
  91657. **
  91658. ** For a scalar LHS, it is sufficient to check just the first row
  91659. ** of the RHS.
  91660. */
  91661. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  91662. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  91663. VdbeCoverage(v);
  91664. if( nVector>1 ){
  91665. destNotNull = sqlite3VdbeMakeLabel(v);
  91666. }else{
  91667. /* For nVector==1, combine steps 6 and 7 by immediately returning
  91668. ** FALSE if the first comparison is not NULL */
  91669. destNotNull = destIfFalse;
  91670. }
  91671. for(i=0; i<nVector; i++){
  91672. Expr *p;
  91673. CollSeq *pColl;
  91674. int r3 = sqlite3GetTempReg(pParse);
  91675. p = sqlite3VectorFieldSubexpr(pLeft, i);
  91676. pColl = sqlite3ExprCollSeq(pParse, p);
  91677. sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
  91678. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  91679. (void*)pColl, P4_COLLSEQ);
  91680. VdbeCoverage(v);
  91681. sqlite3ReleaseTempReg(pParse, r3);
  91682. }
  91683. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  91684. if( nVector>1 ){
  91685. sqlite3VdbeResolveLabel(v, destNotNull);
  91686. sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
  91687. VdbeCoverage(v);
  91688. /* Step 7: If we reach this point, we know that the result must
  91689. ** be false. */
  91690. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  91691. }
  91692. /* Jumps here in order to return true. */
  91693. sqlite3VdbeJumpHere(v, addrTruthOp);
  91694. sqlite3ExprCodeIN_finished:
  91695. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  91696. sqlite3ExprCachePop(pParse);
  91697. VdbeComment((v, "end IN expr"));
  91698. sqlite3ExprCodeIN_oom_error:
  91699. sqlite3DbFree(pParse->db, aiMap);
  91700. sqlite3DbFree(pParse->db, zAff);
  91701. }
  91702. #endif /* SQLITE_OMIT_SUBQUERY */
  91703. #ifndef SQLITE_OMIT_FLOATING_POINT
  91704. /*
  91705. ** Generate an instruction that will put the floating point
  91706. ** value described by z[0..n-1] into register iMem.
  91707. **
  91708. ** The z[] string will probably not be zero-terminated. But the
  91709. ** z[n] character is guaranteed to be something that does not look
  91710. ** like the continuation of the number.
  91711. */
  91712. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  91713. if( ALWAYS(z!=0) ){
  91714. double value;
  91715. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  91716. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  91717. if( negateFlag ) value = -value;
  91718. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  91719. }
  91720. }
  91721. #endif
  91722. /*
  91723. ** Generate an instruction that will put the integer describe by
  91724. ** text z[0..n-1] into register iMem.
  91725. **
  91726. ** Expr.u.zToken is always UTF8 and zero-terminated.
  91727. */
  91728. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  91729. Vdbe *v = pParse->pVdbe;
  91730. if( pExpr->flags & EP_IntValue ){
  91731. int i = pExpr->u.iValue;
  91732. assert( i>=0 );
  91733. if( negFlag ) i = -i;
  91734. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  91735. }else{
  91736. int c;
  91737. i64 value;
  91738. const char *z = pExpr->u.zToken;
  91739. assert( z!=0 );
  91740. c = sqlite3DecOrHexToI64(z, &value);
  91741. if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
  91742. #ifdef SQLITE_OMIT_FLOATING_POINT
  91743. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  91744. #else
  91745. #ifndef SQLITE_OMIT_HEX_INTEGER
  91746. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  91747. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  91748. }else
  91749. #endif
  91750. {
  91751. codeReal(v, z, negFlag, iMem);
  91752. }
  91753. #endif
  91754. }else{
  91755. if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
  91756. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  91757. }
  91758. }
  91759. }
  91760. /*
  91761. ** Erase column-cache entry number i
  91762. */
  91763. static void cacheEntryClear(Parse *pParse, int i){
  91764. if( pParse->aColCache[i].tempReg ){
  91765. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  91766. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  91767. }
  91768. }
  91769. pParse->nColCache--;
  91770. if( i<pParse->nColCache ){
  91771. pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
  91772. }
  91773. }
  91774. /*
  91775. ** Record in the column cache that a particular column from a
  91776. ** particular table is stored in a particular register.
  91777. */
  91778. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  91779. int i;
  91780. int minLru;
  91781. int idxLru;
  91782. struct yColCache *p;
  91783. /* Unless an error has occurred, register numbers are always positive. */
  91784. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  91785. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  91786. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  91787. ** for testing only - to verify that SQLite always gets the same answer
  91788. ** with and without the column cache.
  91789. */
  91790. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  91791. /* First replace any existing entry.
  91792. **
  91793. ** Actually, the way the column cache is currently used, we are guaranteed
  91794. ** that the object will never already be in cache. Verify this guarantee.
  91795. */
  91796. #ifndef NDEBUG
  91797. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  91798. assert( p->iTable!=iTab || p->iColumn!=iCol );
  91799. }
  91800. #endif
  91801. /* If the cache is already full, delete the least recently used entry */
  91802. if( pParse->nColCache>=SQLITE_N_COLCACHE ){
  91803. minLru = 0x7fffffff;
  91804. idxLru = -1;
  91805. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  91806. if( p->lru<minLru ){
  91807. idxLru = i;
  91808. minLru = p->lru;
  91809. }
  91810. }
  91811. p = &pParse->aColCache[idxLru];
  91812. }else{
  91813. p = &pParse->aColCache[pParse->nColCache++];
  91814. }
  91815. /* Add the new entry to the end of the cache */
  91816. p->iLevel = pParse->iCacheLevel;
  91817. p->iTable = iTab;
  91818. p->iColumn = iCol;
  91819. p->iReg = iReg;
  91820. p->tempReg = 0;
  91821. p->lru = pParse->iCacheCnt++;
  91822. }
  91823. /*
  91824. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  91825. ** Purge the range of registers from the column cache.
  91826. */
  91827. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  91828. int i = 0;
  91829. while( i<pParse->nColCache ){
  91830. struct yColCache *p = &pParse->aColCache[i];
  91831. if( p->iReg >= iReg && p->iReg < iReg+nReg ){
  91832. cacheEntryClear(pParse, i);
  91833. }else{
  91834. i++;
  91835. }
  91836. }
  91837. }
  91838. /*
  91839. ** Remember the current column cache context. Any new entries added
  91840. ** added to the column cache after this call are removed when the
  91841. ** corresponding pop occurs.
  91842. */
  91843. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  91844. pParse->iCacheLevel++;
  91845. #ifdef SQLITE_DEBUG
  91846. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  91847. printf("PUSH to %d\n", pParse->iCacheLevel);
  91848. }
  91849. #endif
  91850. }
  91851. /*
  91852. ** Remove from the column cache any entries that were added since the
  91853. ** the previous sqlite3ExprCachePush operation. In other words, restore
  91854. ** the cache to the state it was in prior the most recent Push.
  91855. */
  91856. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  91857. int i = 0;
  91858. assert( pParse->iCacheLevel>=1 );
  91859. pParse->iCacheLevel--;
  91860. #ifdef SQLITE_DEBUG
  91861. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  91862. printf("POP to %d\n", pParse->iCacheLevel);
  91863. }
  91864. #endif
  91865. while( i<pParse->nColCache ){
  91866. if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
  91867. cacheEntryClear(pParse, i);
  91868. }else{
  91869. i++;
  91870. }
  91871. }
  91872. }
  91873. /*
  91874. ** When a cached column is reused, make sure that its register is
  91875. ** no longer available as a temp register. ticket #3879: that same
  91876. ** register might be in the cache in multiple places, so be sure to
  91877. ** get them all.
  91878. */
  91879. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  91880. int i;
  91881. struct yColCache *p;
  91882. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  91883. if( p->iReg==iReg ){
  91884. p->tempReg = 0;
  91885. }
  91886. }
  91887. }
  91888. /* Generate code that will load into register regOut a value that is
  91889. ** appropriate for the iIdxCol-th column of index pIdx.
  91890. */
  91891. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  91892. Parse *pParse, /* The parsing context */
  91893. Index *pIdx, /* The index whose column is to be loaded */
  91894. int iTabCur, /* Cursor pointing to a table row */
  91895. int iIdxCol, /* The column of the index to be loaded */
  91896. int regOut /* Store the index column value in this register */
  91897. ){
  91898. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  91899. if( iTabCol==XN_EXPR ){
  91900. assert( pIdx->aColExpr );
  91901. assert( pIdx->aColExpr->nExpr>iIdxCol );
  91902. pParse->iSelfTab = iTabCur + 1;
  91903. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  91904. pParse->iSelfTab = 0;
  91905. }else{
  91906. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  91907. iTabCol, regOut);
  91908. }
  91909. }
  91910. /*
  91911. ** Generate code to extract the value of the iCol-th column of a table.
  91912. */
  91913. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  91914. Vdbe *v, /* The VDBE under construction */
  91915. Table *pTab, /* The table containing the value */
  91916. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  91917. int iCol, /* Index of the column to extract */
  91918. int regOut /* Extract the value into this register */
  91919. ){
  91920. if( pTab==0 ){
  91921. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  91922. return;
  91923. }
  91924. if( iCol<0 || iCol==pTab->iPKey ){
  91925. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  91926. }else{
  91927. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  91928. int x = iCol;
  91929. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  91930. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  91931. }
  91932. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  91933. }
  91934. if( iCol>=0 ){
  91935. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  91936. }
  91937. }
  91938. /*
  91939. ** Generate code that will extract the iColumn-th column from
  91940. ** table pTab and store the column value in a register.
  91941. **
  91942. ** An effort is made to store the column value in register iReg. This
  91943. ** is not garanteeed for GetColumn() - the result can be stored in
  91944. ** any register. But the result is guaranteed to land in register iReg
  91945. ** for GetColumnToReg().
  91946. **
  91947. ** There must be an open cursor to pTab in iTable when this routine
  91948. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  91949. */
  91950. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  91951. Parse *pParse, /* Parsing and code generating context */
  91952. Table *pTab, /* Description of the table we are reading from */
  91953. int iColumn, /* Index of the table column */
  91954. int iTable, /* The cursor pointing to the table */
  91955. int iReg, /* Store results here */
  91956. u8 p5 /* P5 value for OP_Column + FLAGS */
  91957. ){
  91958. Vdbe *v = pParse->pVdbe;
  91959. int i;
  91960. struct yColCache *p;
  91961. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  91962. if( p->iTable==iTable && p->iColumn==iColumn ){
  91963. p->lru = pParse->iCacheCnt++;
  91964. sqlite3ExprCachePinRegister(pParse, p->iReg);
  91965. return p->iReg;
  91966. }
  91967. }
  91968. assert( v!=0 );
  91969. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  91970. if( p5 ){
  91971. sqlite3VdbeChangeP5(v, p5);
  91972. }else{
  91973. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  91974. }
  91975. return iReg;
  91976. }
  91977. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
  91978. Parse *pParse, /* Parsing and code generating context */
  91979. Table *pTab, /* Description of the table we are reading from */
  91980. int iColumn, /* Index of the table column */
  91981. int iTable, /* The cursor pointing to the table */
  91982. int iReg /* Store results here */
  91983. ){
  91984. int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
  91985. if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
  91986. }
  91987. /*
  91988. ** Clear all column cache entries.
  91989. */
  91990. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  91991. int i;
  91992. #ifdef SQLITE_DEBUG
  91993. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  91994. printf("CLEAR\n");
  91995. }
  91996. #endif
  91997. for(i=0; i<pParse->nColCache; i++){
  91998. if( pParse->aColCache[i].tempReg
  91999. && pParse->nTempReg<ArraySize(pParse->aTempReg)
  92000. ){
  92001. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  92002. }
  92003. }
  92004. pParse->nColCache = 0;
  92005. }
  92006. /*
  92007. ** Record the fact that an affinity change has occurred on iCount
  92008. ** registers starting with iStart.
  92009. */
  92010. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  92011. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  92012. }
  92013. /*
  92014. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  92015. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  92016. */
  92017. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  92018. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  92019. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  92020. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  92021. }
  92022. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  92023. /*
  92024. ** Return true if any register in the range iFrom..iTo (inclusive)
  92025. ** is used as part of the column cache.
  92026. **
  92027. ** This routine is used within assert() and testcase() macros only
  92028. ** and does not appear in a normal build.
  92029. */
  92030. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  92031. int i;
  92032. struct yColCache *p;
  92033. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  92034. int r = p->iReg;
  92035. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  92036. }
  92037. return 0;
  92038. }
  92039. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  92040. /*
  92041. ** Convert a scalar expression node to a TK_REGISTER referencing
  92042. ** register iReg. The caller must ensure that iReg already contains
  92043. ** the correct value for the expression.
  92044. */
  92045. static void exprToRegister(Expr *p, int iReg){
  92046. p->op2 = p->op;
  92047. p->op = TK_REGISTER;
  92048. p->iTable = iReg;
  92049. ExprClearProperty(p, EP_Skip);
  92050. }
  92051. /*
  92052. ** Evaluate an expression (either a vector or a scalar expression) and store
  92053. ** the result in continguous temporary registers. Return the index of
  92054. ** the first register used to store the result.
  92055. **
  92056. ** If the returned result register is a temporary scalar, then also write
  92057. ** that register number into *piFreeable. If the returned result register
  92058. ** is not a temporary or if the expression is a vector set *piFreeable
  92059. ** to 0.
  92060. */
  92061. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  92062. int iResult;
  92063. int nResult = sqlite3ExprVectorSize(p);
  92064. if( nResult==1 ){
  92065. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  92066. }else{
  92067. *piFreeable = 0;
  92068. if( p->op==TK_SELECT ){
  92069. #if SQLITE_OMIT_SUBQUERY
  92070. iResult = 0;
  92071. #else
  92072. iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
  92073. #endif
  92074. }else{
  92075. int i;
  92076. iResult = pParse->nMem+1;
  92077. pParse->nMem += nResult;
  92078. for(i=0; i<nResult; i++){
  92079. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  92080. }
  92081. }
  92082. }
  92083. return iResult;
  92084. }
  92085. /*
  92086. ** Generate code into the current Vdbe to evaluate the given
  92087. ** expression. Attempt to store the results in register "target".
  92088. ** Return the register where results are stored.
  92089. **
  92090. ** With this routine, there is no guarantee that results will
  92091. ** be stored in target. The result might be stored in some other
  92092. ** register if it is convenient to do so. The calling function
  92093. ** must check the return code and move the results to the desired
  92094. ** register.
  92095. */
  92096. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  92097. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  92098. int op; /* The opcode being coded */
  92099. int inReg = target; /* Results stored in register inReg */
  92100. int regFree1 = 0; /* If non-zero free this temporary register */
  92101. int regFree2 = 0; /* If non-zero free this temporary register */
  92102. int r1, r2; /* Various register numbers */
  92103. Expr tempX; /* Temporary expression node */
  92104. int p5 = 0;
  92105. assert( target>0 && target<=pParse->nMem );
  92106. if( v==0 ){
  92107. assert( pParse->db->mallocFailed );
  92108. return 0;
  92109. }
  92110. expr_code_doover:
  92111. if( pExpr==0 ){
  92112. op = TK_NULL;
  92113. }else{
  92114. op = pExpr->op;
  92115. }
  92116. switch( op ){
  92117. case TK_AGG_COLUMN: {
  92118. AggInfo *pAggInfo = pExpr->pAggInfo;
  92119. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  92120. if( !pAggInfo->directMode ){
  92121. assert( pCol->iMem>0 );
  92122. return pCol->iMem;
  92123. }else if( pAggInfo->useSortingIdx ){
  92124. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  92125. pCol->iSorterColumn, target);
  92126. return target;
  92127. }
  92128. /* Otherwise, fall thru into the TK_COLUMN case */
  92129. }
  92130. case TK_COLUMN: {
  92131. int iTab = pExpr->iTable;
  92132. if( iTab<0 ){
  92133. if( pParse->iSelfTab<0 ){
  92134. /* Generating CHECK constraints or inserting into partial index */
  92135. return pExpr->iColumn - pParse->iSelfTab;
  92136. }else{
  92137. /* Coding an expression that is part of an index where column names
  92138. ** in the index refer to the table to which the index belongs */
  92139. iTab = pParse->iSelfTab - 1;
  92140. }
  92141. }
  92142. return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  92143. pExpr->iColumn, iTab, target,
  92144. pExpr->op2);
  92145. }
  92146. case TK_INTEGER: {
  92147. codeInteger(pParse, pExpr, 0, target);
  92148. return target;
  92149. }
  92150. case TK_TRUEFALSE: {
  92151. sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
  92152. return target;
  92153. }
  92154. #ifndef SQLITE_OMIT_FLOATING_POINT
  92155. case TK_FLOAT: {
  92156. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92157. codeReal(v, pExpr->u.zToken, 0, target);
  92158. return target;
  92159. }
  92160. #endif
  92161. case TK_STRING: {
  92162. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92163. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  92164. return target;
  92165. }
  92166. case TK_NULL: {
  92167. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  92168. return target;
  92169. }
  92170. #ifndef SQLITE_OMIT_BLOB_LITERAL
  92171. case TK_BLOB: {
  92172. int n;
  92173. const char *z;
  92174. char *zBlob;
  92175. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92176. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  92177. assert( pExpr->u.zToken[1]=='\'' );
  92178. z = &pExpr->u.zToken[2];
  92179. n = sqlite3Strlen30(z) - 1;
  92180. assert( z[n]=='\'' );
  92181. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  92182. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  92183. return target;
  92184. }
  92185. #endif
  92186. case TK_VARIABLE: {
  92187. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92188. assert( pExpr->u.zToken!=0 );
  92189. assert( pExpr->u.zToken[0]!=0 );
  92190. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  92191. if( pExpr->u.zToken[1]!=0 ){
  92192. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  92193. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  92194. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  92195. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  92196. }
  92197. return target;
  92198. }
  92199. case TK_REGISTER: {
  92200. return pExpr->iTable;
  92201. }
  92202. #ifndef SQLITE_OMIT_CAST
  92203. case TK_CAST: {
  92204. /* Expressions of the form: CAST(pLeft AS token) */
  92205. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  92206. if( inReg!=target ){
  92207. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  92208. inReg = target;
  92209. }
  92210. sqlite3VdbeAddOp2(v, OP_Cast, target,
  92211. sqlite3AffinityType(pExpr->u.zToken, 0));
  92212. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  92213. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  92214. return inReg;
  92215. }
  92216. #endif /* SQLITE_OMIT_CAST */
  92217. case TK_IS:
  92218. case TK_ISNOT:
  92219. op = (op==TK_IS) ? TK_EQ : TK_NE;
  92220. p5 = SQLITE_NULLEQ;
  92221. /* fall-through */
  92222. case TK_LT:
  92223. case TK_LE:
  92224. case TK_GT:
  92225. case TK_GE:
  92226. case TK_NE:
  92227. case TK_EQ: {
  92228. Expr *pLeft = pExpr->pLeft;
  92229. if( sqlite3ExprIsVector(pLeft) ){
  92230. codeVectorCompare(pParse, pExpr, target, op, p5);
  92231. }else{
  92232. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  92233. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  92234. codeCompare(pParse, pLeft, pExpr->pRight, op,
  92235. r1, r2, inReg, SQLITE_STOREP2 | p5);
  92236. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  92237. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  92238. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  92239. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  92240. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  92241. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  92242. testcase( regFree1==0 );
  92243. testcase( regFree2==0 );
  92244. }
  92245. break;
  92246. }
  92247. case TK_AND:
  92248. case TK_OR:
  92249. case TK_PLUS:
  92250. case TK_STAR:
  92251. case TK_MINUS:
  92252. case TK_REM:
  92253. case TK_BITAND:
  92254. case TK_BITOR:
  92255. case TK_SLASH:
  92256. case TK_LSHIFT:
  92257. case TK_RSHIFT:
  92258. case TK_CONCAT: {
  92259. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  92260. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  92261. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  92262. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  92263. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  92264. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  92265. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  92266. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  92267. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  92268. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  92269. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  92270. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92271. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  92272. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  92273. testcase( regFree1==0 );
  92274. testcase( regFree2==0 );
  92275. break;
  92276. }
  92277. case TK_UMINUS: {
  92278. Expr *pLeft = pExpr->pLeft;
  92279. assert( pLeft );
  92280. if( pLeft->op==TK_INTEGER ){
  92281. codeInteger(pParse, pLeft, 1, target);
  92282. return target;
  92283. #ifndef SQLITE_OMIT_FLOATING_POINT
  92284. }else if( pLeft->op==TK_FLOAT ){
  92285. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92286. codeReal(v, pLeft->u.zToken, 1, target);
  92287. return target;
  92288. #endif
  92289. }else{
  92290. tempX.op = TK_INTEGER;
  92291. tempX.flags = EP_IntValue|EP_TokenOnly;
  92292. tempX.u.iValue = 0;
  92293. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  92294. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  92295. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  92296. testcase( regFree2==0 );
  92297. }
  92298. break;
  92299. }
  92300. case TK_BITNOT:
  92301. case TK_NOT: {
  92302. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  92303. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  92304. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92305. testcase( regFree1==0 );
  92306. sqlite3VdbeAddOp2(v, op, r1, inReg);
  92307. break;
  92308. }
  92309. case TK_TRUTH: {
  92310. int isTrue; /* IS TRUE or IS NOT TRUE */
  92311. int bNormal; /* IS TRUE or IS FALSE */
  92312. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92313. testcase( regFree1==0 );
  92314. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  92315. bNormal = pExpr->op2==TK_IS;
  92316. testcase( isTrue && bNormal);
  92317. testcase( !isTrue && bNormal);
  92318. sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
  92319. break;
  92320. }
  92321. case TK_ISNULL:
  92322. case TK_NOTNULL: {
  92323. int addr;
  92324. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  92325. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  92326. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  92327. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92328. testcase( regFree1==0 );
  92329. addr = sqlite3VdbeAddOp1(v, op, r1);
  92330. VdbeCoverageIf(v, op==TK_ISNULL);
  92331. VdbeCoverageIf(v, op==TK_NOTNULL);
  92332. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  92333. sqlite3VdbeJumpHere(v, addr);
  92334. break;
  92335. }
  92336. case TK_AGG_FUNCTION: {
  92337. AggInfo *pInfo = pExpr->pAggInfo;
  92338. if( pInfo==0 ){
  92339. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92340. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  92341. }else{
  92342. return pInfo->aFunc[pExpr->iAgg].iMem;
  92343. }
  92344. break;
  92345. }
  92346. case TK_FUNCTION: {
  92347. ExprList *pFarg; /* List of function arguments */
  92348. int nFarg; /* Number of function arguments */
  92349. FuncDef *pDef; /* The function definition object */
  92350. const char *zId; /* The function name */
  92351. u32 constMask = 0; /* Mask of function arguments that are constant */
  92352. int i; /* Loop counter */
  92353. sqlite3 *db = pParse->db; /* The database connection */
  92354. u8 enc = ENC(db); /* The text encoding used by this database */
  92355. CollSeq *pColl = 0; /* A collating sequence */
  92356. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  92357. /* SQL functions can be expensive. So try to move constant functions
  92358. ** out of the inner loop, even if that means an extra OP_Copy. */
  92359. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  92360. }
  92361. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  92362. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  92363. pFarg = 0;
  92364. }else{
  92365. pFarg = pExpr->x.pList;
  92366. }
  92367. nFarg = pFarg ? pFarg->nExpr : 0;
  92368. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92369. zId = pExpr->u.zToken;
  92370. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  92371. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  92372. if( pDef==0 && pParse->explain ){
  92373. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  92374. }
  92375. #endif
  92376. if( pDef==0 || pDef->xFinalize!=0 ){
  92377. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  92378. break;
  92379. }
  92380. /* Attempt a direct implementation of the built-in COALESCE() and
  92381. ** IFNULL() functions. This avoids unnecessary evaluation of
  92382. ** arguments past the first non-NULL argument.
  92383. */
  92384. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  92385. int endCoalesce = sqlite3VdbeMakeLabel(v);
  92386. assert( nFarg>=2 );
  92387. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  92388. for(i=1; i<nFarg; i++){
  92389. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  92390. VdbeCoverage(v);
  92391. sqlite3ExprCacheRemove(pParse, target, 1);
  92392. sqlite3ExprCachePush(pParse);
  92393. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  92394. sqlite3ExprCachePop(pParse);
  92395. }
  92396. sqlite3VdbeResolveLabel(v, endCoalesce);
  92397. break;
  92398. }
  92399. /* The UNLIKELY() function is a no-op. The result is the value
  92400. ** of the first argument.
  92401. */
  92402. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  92403. assert( nFarg>=1 );
  92404. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  92405. }
  92406. #ifdef SQLITE_DEBUG
  92407. /* The AFFINITY() function evaluates to a string that describes
  92408. ** the type affinity of the argument. This is used for testing of
  92409. ** the SQLite type logic.
  92410. */
  92411. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  92412. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  92413. char aff;
  92414. assert( nFarg==1 );
  92415. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  92416. sqlite3VdbeLoadString(v, target,
  92417. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  92418. return target;
  92419. }
  92420. #endif
  92421. for(i=0; i<nFarg; i++){
  92422. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  92423. testcase( i==31 );
  92424. constMask |= MASKBIT32(i);
  92425. }
  92426. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  92427. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  92428. }
  92429. }
  92430. if( pFarg ){
  92431. if( constMask ){
  92432. r1 = pParse->nMem+1;
  92433. pParse->nMem += nFarg;
  92434. }else{
  92435. r1 = sqlite3GetTempRange(pParse, nFarg);
  92436. }
  92437. /* For length() and typeof() functions with a column argument,
  92438. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  92439. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  92440. ** loading.
  92441. */
  92442. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  92443. u8 exprOp;
  92444. assert( nFarg==1 );
  92445. assert( pFarg->a[0].pExpr!=0 );
  92446. exprOp = pFarg->a[0].pExpr->op;
  92447. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  92448. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  92449. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  92450. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  92451. pFarg->a[0].pExpr->op2 =
  92452. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  92453. }
  92454. }
  92455. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  92456. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  92457. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  92458. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  92459. }else{
  92460. r1 = 0;
  92461. }
  92462. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92463. /* Possibly overload the function if the first argument is
  92464. ** a virtual table column.
  92465. **
  92466. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  92467. ** second argument, not the first, as the argument to test to
  92468. ** see if it is a column in a virtual table. This is done because
  92469. ** the left operand of infix functions (the operand we want to
  92470. ** control overloading) ends up as the second argument to the
  92471. ** function. The expression "A glob B" is equivalent to
  92472. ** "glob(B,A). We want to use the A in "A glob B" to test
  92473. ** for function overloading. But we use the B term in "glob(B,A)".
  92474. */
  92475. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  92476. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  92477. }else if( nFarg>0 ){
  92478. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  92479. }
  92480. #endif
  92481. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  92482. if( !pColl ) pColl = db->pDfltColl;
  92483. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  92484. }
  92485. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  92486. if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
  92487. Expr *pArg = pFarg->a[0].pExpr;
  92488. if( pArg->op==TK_COLUMN ){
  92489. sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
  92490. }else{
  92491. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  92492. }
  92493. }else
  92494. #endif
  92495. {
  92496. sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
  92497. constMask, r1, target, (char*)pDef, P4_FUNCDEF);
  92498. sqlite3VdbeChangeP5(v, (u8)nFarg);
  92499. }
  92500. if( nFarg && constMask==0 ){
  92501. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  92502. }
  92503. return target;
  92504. }
  92505. #ifndef SQLITE_OMIT_SUBQUERY
  92506. case TK_EXISTS:
  92507. case TK_SELECT: {
  92508. int nCol;
  92509. testcase( op==TK_EXISTS );
  92510. testcase( op==TK_SELECT );
  92511. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  92512. sqlite3SubselectError(pParse, nCol, 1);
  92513. }else{
  92514. return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  92515. }
  92516. break;
  92517. }
  92518. case TK_SELECT_COLUMN: {
  92519. int n;
  92520. if( pExpr->pLeft->iTable==0 ){
  92521. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
  92522. }
  92523. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  92524. if( pExpr->iTable
  92525. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  92526. ){
  92527. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  92528. pExpr->iTable, n);
  92529. }
  92530. return pExpr->pLeft->iTable + pExpr->iColumn;
  92531. }
  92532. case TK_IN: {
  92533. int destIfFalse = sqlite3VdbeMakeLabel(v);
  92534. int destIfNull = sqlite3VdbeMakeLabel(v);
  92535. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  92536. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  92537. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  92538. sqlite3VdbeResolveLabel(v, destIfFalse);
  92539. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  92540. sqlite3VdbeResolveLabel(v, destIfNull);
  92541. return target;
  92542. }
  92543. #endif /* SQLITE_OMIT_SUBQUERY */
  92544. /*
  92545. ** x BETWEEN y AND z
  92546. **
  92547. ** This is equivalent to
  92548. **
  92549. ** x>=y AND x<=z
  92550. **
  92551. ** X is stored in pExpr->pLeft.
  92552. ** Y is stored in pExpr->pList->a[0].pExpr.
  92553. ** Z is stored in pExpr->pList->a[1].pExpr.
  92554. */
  92555. case TK_BETWEEN: {
  92556. exprCodeBetween(pParse, pExpr, target, 0, 0);
  92557. return target;
  92558. }
  92559. case TK_SPAN:
  92560. case TK_COLLATE:
  92561. case TK_UPLUS: {
  92562. pExpr = pExpr->pLeft;
  92563. goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
  92564. }
  92565. case TK_TRIGGER: {
  92566. /* If the opcode is TK_TRIGGER, then the expression is a reference
  92567. ** to a column in the new.* or old.* pseudo-tables available to
  92568. ** trigger programs. In this case Expr.iTable is set to 1 for the
  92569. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  92570. ** is set to the column of the pseudo-table to read, or to -1 to
  92571. ** read the rowid field.
  92572. **
  92573. ** The expression is implemented using an OP_Param opcode. The p1
  92574. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  92575. ** to reference another column of the old.* pseudo-table, where
  92576. ** i is the index of the column. For a new.rowid reference, p1 is
  92577. ** set to (n+1), where n is the number of columns in each pseudo-table.
  92578. ** For a reference to any other column in the new.* pseudo-table, p1
  92579. ** is set to (n+2+i), where n and i are as defined previously. For
  92580. ** example, if the table on which triggers are being fired is
  92581. ** declared as:
  92582. **
  92583. ** CREATE TABLE t1(a, b);
  92584. **
  92585. ** Then p1 is interpreted as follows:
  92586. **
  92587. ** p1==0 -> old.rowid p1==3 -> new.rowid
  92588. ** p1==1 -> old.a p1==4 -> new.a
  92589. ** p1==2 -> old.b p1==5 -> new.b
  92590. */
  92591. Table *pTab = pExpr->pTab;
  92592. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  92593. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  92594. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  92595. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  92596. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  92597. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  92598. VdbeComment((v, "r[%d]=%s.%s", target,
  92599. (pExpr->iTable ? "new" : "old"),
  92600. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName)
  92601. ));
  92602. #ifndef SQLITE_OMIT_FLOATING_POINT
  92603. /* If the column has REAL affinity, it may currently be stored as an
  92604. ** integer. Use OP_RealAffinity to make sure it is really real.
  92605. **
  92606. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  92607. ** floating point when extracting it from the record. */
  92608. if( pExpr->iColumn>=0
  92609. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  92610. ){
  92611. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  92612. }
  92613. #endif
  92614. break;
  92615. }
  92616. case TK_VECTOR: {
  92617. sqlite3ErrorMsg(pParse, "row value misused");
  92618. break;
  92619. }
  92620. case TK_IF_NULL_ROW: {
  92621. int addrINR;
  92622. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  92623. sqlite3ExprCachePush(pParse);
  92624. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  92625. sqlite3ExprCachePop(pParse);
  92626. sqlite3VdbeJumpHere(v, addrINR);
  92627. sqlite3VdbeChangeP3(v, addrINR, inReg);
  92628. break;
  92629. }
  92630. /*
  92631. ** Form A:
  92632. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  92633. **
  92634. ** Form B:
  92635. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  92636. **
  92637. ** Form A is can be transformed into the equivalent form B as follows:
  92638. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  92639. ** WHEN x=eN THEN rN ELSE y END
  92640. **
  92641. ** X (if it exists) is in pExpr->pLeft.
  92642. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  92643. ** odd. The Y is also optional. If the number of elements in x.pList
  92644. ** is even, then Y is omitted and the "otherwise" result is NULL.
  92645. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  92646. **
  92647. ** The result of the expression is the Ri for the first matching Ei,
  92648. ** or if there is no matching Ei, the ELSE term Y, or if there is
  92649. ** no ELSE term, NULL.
  92650. */
  92651. default: assert( op==TK_CASE ); {
  92652. int endLabel; /* GOTO label for end of CASE stmt */
  92653. int nextCase; /* GOTO label for next WHEN clause */
  92654. int nExpr; /* 2x number of WHEN terms */
  92655. int i; /* Loop counter */
  92656. ExprList *pEList; /* List of WHEN terms */
  92657. struct ExprList_item *aListelem; /* Array of WHEN terms */
  92658. Expr opCompare; /* The X==Ei expression */
  92659. Expr *pX; /* The X expression */
  92660. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  92661. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  92662. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  92663. assert(pExpr->x.pList->nExpr > 0);
  92664. pEList = pExpr->x.pList;
  92665. aListelem = pEList->a;
  92666. nExpr = pEList->nExpr;
  92667. endLabel = sqlite3VdbeMakeLabel(v);
  92668. if( (pX = pExpr->pLeft)!=0 ){
  92669. tempX = *pX;
  92670. testcase( pX->op==TK_COLUMN );
  92671. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  92672. testcase( regFree1==0 );
  92673. memset(&opCompare, 0, sizeof(opCompare));
  92674. opCompare.op = TK_EQ;
  92675. opCompare.pLeft = &tempX;
  92676. pTest = &opCompare;
  92677. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  92678. ** The value in regFree1 might get SCopy-ed into the file result.
  92679. ** So make sure that the regFree1 register is not reused for other
  92680. ** purposes and possibly overwritten. */
  92681. regFree1 = 0;
  92682. }
  92683. for(i=0; i<nExpr-1; i=i+2){
  92684. sqlite3ExprCachePush(pParse);
  92685. if( pX ){
  92686. assert( pTest!=0 );
  92687. opCompare.pRight = aListelem[i].pExpr;
  92688. }else{
  92689. pTest = aListelem[i].pExpr;
  92690. }
  92691. nextCase = sqlite3VdbeMakeLabel(v);
  92692. testcase( pTest->op==TK_COLUMN );
  92693. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  92694. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  92695. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  92696. sqlite3VdbeGoto(v, endLabel);
  92697. sqlite3ExprCachePop(pParse);
  92698. sqlite3VdbeResolveLabel(v, nextCase);
  92699. }
  92700. if( (nExpr&1)!=0 ){
  92701. sqlite3ExprCachePush(pParse);
  92702. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  92703. sqlite3ExprCachePop(pParse);
  92704. }else{
  92705. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  92706. }
  92707. assert( pParse->db->mallocFailed || pParse->nErr>0
  92708. || pParse->iCacheLevel==iCacheLevel );
  92709. sqlite3VdbeResolveLabel(v, endLabel);
  92710. break;
  92711. }
  92712. #ifndef SQLITE_OMIT_TRIGGER
  92713. case TK_RAISE: {
  92714. assert( pExpr->affinity==OE_Rollback
  92715. || pExpr->affinity==OE_Abort
  92716. || pExpr->affinity==OE_Fail
  92717. || pExpr->affinity==OE_Ignore
  92718. );
  92719. if( !pParse->pTriggerTab ){
  92720. sqlite3ErrorMsg(pParse,
  92721. "RAISE() may only be used within a trigger-program");
  92722. return 0;
  92723. }
  92724. if( pExpr->affinity==OE_Abort ){
  92725. sqlite3MayAbort(pParse);
  92726. }
  92727. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92728. if( pExpr->affinity==OE_Ignore ){
  92729. sqlite3VdbeAddOp4(
  92730. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  92731. VdbeCoverage(v);
  92732. }else{
  92733. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  92734. pExpr->affinity, pExpr->u.zToken, 0, 0);
  92735. }
  92736. break;
  92737. }
  92738. #endif
  92739. }
  92740. sqlite3ReleaseTempReg(pParse, regFree1);
  92741. sqlite3ReleaseTempReg(pParse, regFree2);
  92742. return inReg;
  92743. }
  92744. /*
  92745. ** Factor out the code of the given expression to initialization time.
  92746. **
  92747. ** If regDest>=0 then the result is always stored in that register and the
  92748. ** result is not reusable. If regDest<0 then this routine is free to
  92749. ** store the value whereever it wants. The register where the expression
  92750. ** is stored is returned. When regDest<0, two identical expressions will
  92751. ** code to the same register.
  92752. */
  92753. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  92754. Parse *pParse, /* Parsing context */
  92755. Expr *pExpr, /* The expression to code when the VDBE initializes */
  92756. int regDest /* Store the value in this register */
  92757. ){
  92758. ExprList *p;
  92759. assert( ConstFactorOk(pParse) );
  92760. p = pParse->pConstExpr;
  92761. if( regDest<0 && p ){
  92762. struct ExprList_item *pItem;
  92763. int i;
  92764. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  92765. if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
  92766. return pItem->u.iConstExprReg;
  92767. }
  92768. }
  92769. }
  92770. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  92771. p = sqlite3ExprListAppend(pParse, p, pExpr);
  92772. if( p ){
  92773. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  92774. pItem->reusable = regDest<0;
  92775. if( regDest<0 ) regDest = ++pParse->nMem;
  92776. pItem->u.iConstExprReg = regDest;
  92777. }
  92778. pParse->pConstExpr = p;
  92779. return regDest;
  92780. }
  92781. /*
  92782. ** Generate code to evaluate an expression and store the results
  92783. ** into a register. Return the register number where the results
  92784. ** are stored.
  92785. **
  92786. ** If the register is a temporary register that can be deallocated,
  92787. ** then write its number into *pReg. If the result register is not
  92788. ** a temporary, then set *pReg to zero.
  92789. **
  92790. ** If pExpr is a constant, then this routine might generate this
  92791. ** code to fill the register in the initialization section of the
  92792. ** VDBE program, in order to factor it out of the evaluation loop.
  92793. */
  92794. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  92795. int r2;
  92796. pExpr = sqlite3ExprSkipCollate(pExpr);
  92797. if( ConstFactorOk(pParse)
  92798. && pExpr->op!=TK_REGISTER
  92799. && sqlite3ExprIsConstantNotJoin(pExpr)
  92800. ){
  92801. *pReg = 0;
  92802. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  92803. }else{
  92804. int r1 = sqlite3GetTempReg(pParse);
  92805. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  92806. if( r2==r1 ){
  92807. *pReg = r1;
  92808. }else{
  92809. sqlite3ReleaseTempReg(pParse, r1);
  92810. *pReg = 0;
  92811. }
  92812. }
  92813. return r2;
  92814. }
  92815. /*
  92816. ** Generate code that will evaluate expression pExpr and store the
  92817. ** results in register target. The results are guaranteed to appear
  92818. ** in register target.
  92819. */
  92820. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  92821. int inReg;
  92822. assert( target>0 && target<=pParse->nMem );
  92823. if( pExpr && pExpr->op==TK_REGISTER ){
  92824. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  92825. }else{
  92826. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  92827. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  92828. if( inReg!=target && pParse->pVdbe ){
  92829. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  92830. }
  92831. }
  92832. }
  92833. /*
  92834. ** Make a transient copy of expression pExpr and then code it using
  92835. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  92836. ** except that the input expression is guaranteed to be unchanged.
  92837. */
  92838. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  92839. sqlite3 *db = pParse->db;
  92840. pExpr = sqlite3ExprDup(db, pExpr, 0);
  92841. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  92842. sqlite3ExprDelete(db, pExpr);
  92843. }
  92844. /*
  92845. ** Generate code that will evaluate expression pExpr and store the
  92846. ** results in register target. The results are guaranteed to appear
  92847. ** in register target. If the expression is constant, then this routine
  92848. ** might choose to code the expression at initialization time.
  92849. */
  92850. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  92851. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  92852. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  92853. }else{
  92854. sqlite3ExprCode(pParse, pExpr, target);
  92855. }
  92856. }
  92857. /*
  92858. ** Generate code that evaluates the given expression and puts the result
  92859. ** in register target.
  92860. **
  92861. ** Also make a copy of the expression results into another "cache" register
  92862. ** and modify the expression so that the next time it is evaluated,
  92863. ** the result is a copy of the cache register.
  92864. **
  92865. ** This routine is used for expressions that are used multiple
  92866. ** times. They are evaluated once and the results of the expression
  92867. ** are reused.
  92868. */
  92869. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  92870. Vdbe *v = pParse->pVdbe;
  92871. int iMem;
  92872. assert( target>0 );
  92873. assert( pExpr->op!=TK_REGISTER );
  92874. sqlite3ExprCode(pParse, pExpr, target);
  92875. iMem = ++pParse->nMem;
  92876. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  92877. exprToRegister(pExpr, iMem);
  92878. }
  92879. /*
  92880. ** Generate code that pushes the value of every element of the given
  92881. ** expression list into a sequence of registers beginning at target.
  92882. **
  92883. ** Return the number of elements evaluated. The number returned will
  92884. ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
  92885. ** is defined.
  92886. **
  92887. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  92888. ** filled using OP_SCopy. OP_Copy must be used instead.
  92889. **
  92890. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  92891. ** factored out into initialization code.
  92892. **
  92893. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  92894. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  92895. ** in registers at srcReg, and so the value can be copied from there.
  92896. ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
  92897. ** are simply omitted rather than being copied from srcReg.
  92898. */
  92899. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  92900. Parse *pParse, /* Parsing context */
  92901. ExprList *pList, /* The expression list to be coded */
  92902. int target, /* Where to write results */
  92903. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  92904. u8 flags /* SQLITE_ECEL_* flags */
  92905. ){
  92906. struct ExprList_item *pItem;
  92907. int i, j, n;
  92908. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  92909. Vdbe *v = pParse->pVdbe;
  92910. assert( pList!=0 );
  92911. assert( target>0 );
  92912. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  92913. n = pList->nExpr;
  92914. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  92915. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  92916. Expr *pExpr = pItem->pExpr;
  92917. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  92918. if( pItem->bSorterRef ){
  92919. i--;
  92920. n--;
  92921. }else
  92922. #endif
  92923. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  92924. if( flags & SQLITE_ECEL_OMITREF ){
  92925. i--;
  92926. n--;
  92927. }else{
  92928. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  92929. }
  92930. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  92931. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  92932. }else{
  92933. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  92934. if( inReg!=target+i ){
  92935. VdbeOp *pOp;
  92936. if( copyOp==OP_Copy
  92937. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  92938. && pOp->p1+pOp->p3+1==inReg
  92939. && pOp->p2+pOp->p3+1==target+i
  92940. ){
  92941. pOp->p3++;
  92942. }else{
  92943. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  92944. }
  92945. }
  92946. }
  92947. }
  92948. return n;
  92949. }
  92950. /*
  92951. ** Generate code for a BETWEEN operator.
  92952. **
  92953. ** x BETWEEN y AND z
  92954. **
  92955. ** The above is equivalent to
  92956. **
  92957. ** x>=y AND x<=z
  92958. **
  92959. ** Code it as such, taking care to do the common subexpression
  92960. ** elimination of x.
  92961. **
  92962. ** The xJumpIf parameter determines details:
  92963. **
  92964. ** NULL: Store the boolean result in reg[dest]
  92965. ** sqlite3ExprIfTrue: Jump to dest if true
  92966. ** sqlite3ExprIfFalse: Jump to dest if false
  92967. **
  92968. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  92969. */
  92970. static void exprCodeBetween(
  92971. Parse *pParse, /* Parsing and code generating context */
  92972. Expr *pExpr, /* The BETWEEN expression */
  92973. int dest, /* Jump destination or storage location */
  92974. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  92975. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  92976. ){
  92977. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  92978. Expr compLeft; /* The x>=y term */
  92979. Expr compRight; /* The x<=z term */
  92980. Expr exprX; /* The x subexpression */
  92981. int regFree1 = 0; /* Temporary use register */
  92982. memset(&compLeft, 0, sizeof(Expr));
  92983. memset(&compRight, 0, sizeof(Expr));
  92984. memset(&exprAnd, 0, sizeof(Expr));
  92985. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  92986. exprX = *pExpr->pLeft;
  92987. exprAnd.op = TK_AND;
  92988. exprAnd.pLeft = &compLeft;
  92989. exprAnd.pRight = &compRight;
  92990. compLeft.op = TK_GE;
  92991. compLeft.pLeft = &exprX;
  92992. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  92993. compRight.op = TK_LE;
  92994. compRight.pLeft = &exprX;
  92995. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  92996. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  92997. if( xJump ){
  92998. xJump(pParse, &exprAnd, dest, jumpIfNull);
  92999. }else{
  93000. /* Mark the expression is being from the ON or USING clause of a join
  93001. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  93002. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  93003. ** for clarity, but we are out of bits in the Expr.flags field so we
  93004. ** have to reuse the EP_FromJoin bit. Bummer. */
  93005. exprX.flags |= EP_FromJoin;
  93006. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  93007. }
  93008. sqlite3ReleaseTempReg(pParse, regFree1);
  93009. /* Ensure adequate test coverage */
  93010. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  93011. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  93012. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  93013. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  93014. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  93015. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  93016. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  93017. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  93018. testcase( xJump==0 );
  93019. }
  93020. /*
  93021. ** Generate code for a boolean expression such that a jump is made
  93022. ** to the label "dest" if the expression is true but execution
  93023. ** continues straight thru if the expression is false.
  93024. **
  93025. ** If the expression evaluates to NULL (neither true nor false), then
  93026. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  93027. **
  93028. ** This code depends on the fact that certain token values (ex: TK_EQ)
  93029. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  93030. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  93031. ** the make process cause these values to align. Assert()s in the code
  93032. ** below verify that the numbers are aligned correctly.
  93033. */
  93034. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  93035. Vdbe *v = pParse->pVdbe;
  93036. int op = 0;
  93037. int regFree1 = 0;
  93038. int regFree2 = 0;
  93039. int r1, r2;
  93040. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  93041. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  93042. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  93043. op = pExpr->op;
  93044. switch( op ){
  93045. case TK_AND: {
  93046. int d2 = sqlite3VdbeMakeLabel(v);
  93047. testcase( jumpIfNull==0 );
  93048. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  93049. sqlite3ExprCachePush(pParse);
  93050. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  93051. sqlite3VdbeResolveLabel(v, d2);
  93052. sqlite3ExprCachePop(pParse);
  93053. break;
  93054. }
  93055. case TK_OR: {
  93056. testcase( jumpIfNull==0 );
  93057. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  93058. sqlite3ExprCachePush(pParse);
  93059. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  93060. sqlite3ExprCachePop(pParse);
  93061. break;
  93062. }
  93063. case TK_NOT: {
  93064. testcase( jumpIfNull==0 );
  93065. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  93066. break;
  93067. }
  93068. case TK_TRUTH: {
  93069. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  93070. int isTrue; /* IS TRUE or IS NOT TRUE */
  93071. testcase( jumpIfNull==0 );
  93072. isNot = pExpr->op2==TK_ISNOT;
  93073. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  93074. testcase( isTrue && isNot );
  93075. testcase( !isTrue && isNot );
  93076. if( isTrue ^ isNot ){
  93077. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  93078. isNot ? SQLITE_JUMPIFNULL : 0);
  93079. }else{
  93080. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  93081. isNot ? SQLITE_JUMPIFNULL : 0);
  93082. }
  93083. break;
  93084. }
  93085. case TK_IS:
  93086. case TK_ISNOT:
  93087. testcase( op==TK_IS );
  93088. testcase( op==TK_ISNOT );
  93089. op = (op==TK_IS) ? TK_EQ : TK_NE;
  93090. jumpIfNull = SQLITE_NULLEQ;
  93091. /* Fall thru */
  93092. case TK_LT:
  93093. case TK_LE:
  93094. case TK_GT:
  93095. case TK_GE:
  93096. case TK_NE:
  93097. case TK_EQ: {
  93098. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  93099. testcase( jumpIfNull==0 );
  93100. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93101. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  93102. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  93103. r1, r2, dest, jumpIfNull);
  93104. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  93105. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  93106. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  93107. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  93108. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  93109. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  93110. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  93111. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  93112. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  93113. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  93114. testcase( regFree1==0 );
  93115. testcase( regFree2==0 );
  93116. break;
  93117. }
  93118. case TK_ISNULL:
  93119. case TK_NOTNULL: {
  93120. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  93121. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  93122. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93123. sqlite3VdbeAddOp2(v, op, r1, dest);
  93124. VdbeCoverageIf(v, op==TK_ISNULL);
  93125. VdbeCoverageIf(v, op==TK_NOTNULL);
  93126. testcase( regFree1==0 );
  93127. break;
  93128. }
  93129. case TK_BETWEEN: {
  93130. testcase( jumpIfNull==0 );
  93131. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  93132. break;
  93133. }
  93134. #ifndef SQLITE_OMIT_SUBQUERY
  93135. case TK_IN: {
  93136. int destIfFalse = sqlite3VdbeMakeLabel(v);
  93137. int destIfNull = jumpIfNull ? dest : destIfFalse;
  93138. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  93139. sqlite3VdbeGoto(v, dest);
  93140. sqlite3VdbeResolveLabel(v, destIfFalse);
  93141. break;
  93142. }
  93143. #endif
  93144. default: {
  93145. default_expr:
  93146. if( exprAlwaysTrue(pExpr) ){
  93147. sqlite3VdbeGoto(v, dest);
  93148. }else if( exprAlwaysFalse(pExpr) ){
  93149. /* No-op */
  93150. }else{
  93151. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  93152. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  93153. VdbeCoverage(v);
  93154. testcase( regFree1==0 );
  93155. testcase( jumpIfNull==0 );
  93156. }
  93157. break;
  93158. }
  93159. }
  93160. sqlite3ReleaseTempReg(pParse, regFree1);
  93161. sqlite3ReleaseTempReg(pParse, regFree2);
  93162. }
  93163. /*
  93164. ** Generate code for a boolean expression such that a jump is made
  93165. ** to the label "dest" if the expression is false but execution
  93166. ** continues straight thru if the expression is true.
  93167. **
  93168. ** If the expression evaluates to NULL (neither true nor false) then
  93169. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  93170. ** is 0.
  93171. */
  93172. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  93173. Vdbe *v = pParse->pVdbe;
  93174. int op = 0;
  93175. int regFree1 = 0;
  93176. int regFree2 = 0;
  93177. int r1, r2;
  93178. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  93179. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  93180. if( pExpr==0 ) return;
  93181. /* The value of pExpr->op and op are related as follows:
  93182. **
  93183. ** pExpr->op op
  93184. ** --------- ----------
  93185. ** TK_ISNULL OP_NotNull
  93186. ** TK_NOTNULL OP_IsNull
  93187. ** TK_NE OP_Eq
  93188. ** TK_EQ OP_Ne
  93189. ** TK_GT OP_Le
  93190. ** TK_LE OP_Gt
  93191. ** TK_GE OP_Lt
  93192. ** TK_LT OP_Ge
  93193. **
  93194. ** For other values of pExpr->op, op is undefined and unused.
  93195. ** The value of TK_ and OP_ constants are arranged such that we
  93196. ** can compute the mapping above using the following expression.
  93197. ** Assert()s verify that the computation is correct.
  93198. */
  93199. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  93200. /* Verify correct alignment of TK_ and OP_ constants
  93201. */
  93202. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  93203. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  93204. assert( pExpr->op!=TK_NE || op==OP_Eq );
  93205. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  93206. assert( pExpr->op!=TK_LT || op==OP_Ge );
  93207. assert( pExpr->op!=TK_LE || op==OP_Gt );
  93208. assert( pExpr->op!=TK_GT || op==OP_Le );
  93209. assert( pExpr->op!=TK_GE || op==OP_Lt );
  93210. switch( pExpr->op ){
  93211. case TK_AND: {
  93212. testcase( jumpIfNull==0 );
  93213. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  93214. sqlite3ExprCachePush(pParse);
  93215. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  93216. sqlite3ExprCachePop(pParse);
  93217. break;
  93218. }
  93219. case TK_OR: {
  93220. int d2 = sqlite3VdbeMakeLabel(v);
  93221. testcase( jumpIfNull==0 );
  93222. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  93223. sqlite3ExprCachePush(pParse);
  93224. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  93225. sqlite3VdbeResolveLabel(v, d2);
  93226. sqlite3ExprCachePop(pParse);
  93227. break;
  93228. }
  93229. case TK_NOT: {
  93230. testcase( jumpIfNull==0 );
  93231. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  93232. break;
  93233. }
  93234. case TK_TRUTH: {
  93235. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  93236. int isTrue; /* IS TRUE or IS NOT TRUE */
  93237. testcase( jumpIfNull==0 );
  93238. isNot = pExpr->op2==TK_ISNOT;
  93239. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  93240. testcase( isTrue && isNot );
  93241. testcase( !isTrue && isNot );
  93242. if( isTrue ^ isNot ){
  93243. /* IS TRUE and IS NOT FALSE */
  93244. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  93245. isNot ? 0 : SQLITE_JUMPIFNULL);
  93246. }else{
  93247. /* IS FALSE and IS NOT TRUE */
  93248. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  93249. isNot ? 0 : SQLITE_JUMPIFNULL);
  93250. }
  93251. break;
  93252. }
  93253. case TK_IS:
  93254. case TK_ISNOT:
  93255. testcase( pExpr->op==TK_IS );
  93256. testcase( pExpr->op==TK_ISNOT );
  93257. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  93258. jumpIfNull = SQLITE_NULLEQ;
  93259. /* Fall thru */
  93260. case TK_LT:
  93261. case TK_LE:
  93262. case TK_GT:
  93263. case TK_GE:
  93264. case TK_NE:
  93265. case TK_EQ: {
  93266. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  93267. testcase( jumpIfNull==0 );
  93268. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93269. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  93270. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  93271. r1, r2, dest, jumpIfNull);
  93272. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  93273. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  93274. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  93275. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  93276. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  93277. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  93278. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  93279. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  93280. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  93281. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  93282. testcase( regFree1==0 );
  93283. testcase( regFree2==0 );
  93284. break;
  93285. }
  93286. case TK_ISNULL:
  93287. case TK_NOTNULL: {
  93288. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  93289. sqlite3VdbeAddOp2(v, op, r1, dest);
  93290. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  93291. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  93292. testcase( regFree1==0 );
  93293. break;
  93294. }
  93295. case TK_BETWEEN: {
  93296. testcase( jumpIfNull==0 );
  93297. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  93298. break;
  93299. }
  93300. #ifndef SQLITE_OMIT_SUBQUERY
  93301. case TK_IN: {
  93302. if( jumpIfNull ){
  93303. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  93304. }else{
  93305. int destIfNull = sqlite3VdbeMakeLabel(v);
  93306. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  93307. sqlite3VdbeResolveLabel(v, destIfNull);
  93308. }
  93309. break;
  93310. }
  93311. #endif
  93312. default: {
  93313. default_expr:
  93314. if( exprAlwaysFalse(pExpr) ){
  93315. sqlite3VdbeGoto(v, dest);
  93316. }else if( exprAlwaysTrue(pExpr) ){
  93317. /* no-op */
  93318. }else{
  93319. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  93320. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  93321. VdbeCoverage(v);
  93322. testcase( regFree1==0 );
  93323. testcase( jumpIfNull==0 );
  93324. }
  93325. break;
  93326. }
  93327. }
  93328. sqlite3ReleaseTempReg(pParse, regFree1);
  93329. sqlite3ReleaseTempReg(pParse, regFree2);
  93330. }
  93331. /*
  93332. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  93333. ** code generation, and that copy is deleted after code generation. This
  93334. ** ensures that the original pExpr is unchanged.
  93335. */
  93336. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  93337. sqlite3 *db = pParse->db;
  93338. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  93339. if( db->mallocFailed==0 ){
  93340. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  93341. }
  93342. sqlite3ExprDelete(db, pCopy);
  93343. }
  93344. /*
  93345. ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
  93346. ** type of expression.
  93347. **
  93348. ** If pExpr is a simple SQL value - an integer, real, string, blob
  93349. ** or NULL value - then the VDBE currently being prepared is configured
  93350. ** to re-prepare each time a new value is bound to variable pVar.
  93351. **
  93352. ** Additionally, if pExpr is a simple SQL value and the value is the
  93353. ** same as that currently bound to variable pVar, non-zero is returned.
  93354. ** Otherwise, if the values are not the same or if pExpr is not a simple
  93355. ** SQL value, zero is returned.
  93356. */
  93357. static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
  93358. int res = 0;
  93359. int iVar;
  93360. sqlite3_value *pL, *pR = 0;
  93361. sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
  93362. if( pR ){
  93363. iVar = pVar->iColumn;
  93364. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  93365. pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
  93366. if( pL ){
  93367. if( sqlite3_value_type(pL)==SQLITE_TEXT ){
  93368. sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
  93369. }
  93370. res = 0==sqlite3MemCompare(pL, pR, 0);
  93371. }
  93372. sqlite3ValueFree(pR);
  93373. sqlite3ValueFree(pL);
  93374. }
  93375. return res;
  93376. }
  93377. /*
  93378. ** Do a deep comparison of two expression trees. Return 0 if the two
  93379. ** expressions are completely identical. Return 1 if they differ only
  93380. ** by a COLLATE operator at the top level. Return 2 if there are differences
  93381. ** other than the top-level COLLATE operator.
  93382. **
  93383. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  93384. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  93385. **
  93386. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  93387. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  93388. **
  93389. ** Sometimes this routine will return 2 even if the two expressions
  93390. ** really are equivalent. If we cannot prove that the expressions are
  93391. ** identical, we return 2 just to be safe. So if this routine
  93392. ** returns 2, then you do not really know for certain if the two
  93393. ** expressions are the same. But if you get a 0 or 1 return, then you
  93394. ** can be sure the expressions are the same. In the places where
  93395. ** this routine is used, it does not hurt to get an extra 2 - that
  93396. ** just might result in some slightly slower code. But returning
  93397. ** an incorrect 0 or 1 could lead to a malfunction.
  93398. **
  93399. ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
  93400. ** pParse->pReprepare can be matched against literals in pB. The
  93401. ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
  93402. ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
  93403. ** Argument pParse should normally be NULL. If it is not NULL and pA or
  93404. ** pB causes a return value of 2.
  93405. */
  93406. SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
  93407. u32 combinedFlags;
  93408. if( pA==0 || pB==0 ){
  93409. return pB==pA ? 0 : 2;
  93410. }
  93411. if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
  93412. return 0;
  93413. }
  93414. combinedFlags = pA->flags | pB->flags;
  93415. if( combinedFlags & EP_IntValue ){
  93416. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  93417. return 0;
  93418. }
  93419. return 2;
  93420. }
  93421. if( pA->op!=pB->op ){
  93422. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
  93423. return 1;
  93424. }
  93425. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
  93426. return 1;
  93427. }
  93428. return 2;
  93429. }
  93430. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  93431. if( pA->op==TK_FUNCTION ){
  93432. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  93433. }else if( pA->op==TK_COLLATE ){
  93434. if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  93435. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  93436. return 2;
  93437. }
  93438. }
  93439. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  93440. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  93441. if( combinedFlags & EP_xIsSelect ) return 2;
  93442. if( sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
  93443. if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
  93444. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  93445. assert( (combinedFlags & EP_Reduced)==0 );
  93446. if( pA->op!=TK_STRING && pA->op!=TK_TRUEFALSE ){
  93447. if( pA->iColumn!=pB->iColumn ) return 2;
  93448. if( pA->iTable!=pB->iTable
  93449. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  93450. }
  93451. }
  93452. return 0;
  93453. }
  93454. /*
  93455. ** Compare two ExprList objects. Return 0 if they are identical and
  93456. ** non-zero if they differ in any way.
  93457. **
  93458. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  93459. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  93460. **
  93461. ** This routine might return non-zero for equivalent ExprLists. The
  93462. ** only consequence will be disabled optimizations. But this routine
  93463. ** must never return 0 if the two ExprList objects are different, or
  93464. ** a malfunction will result.
  93465. **
  93466. ** Two NULL pointers are considered to be the same. But a NULL pointer
  93467. ** always differs from a non-NULL pointer.
  93468. */
  93469. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  93470. int i;
  93471. if( pA==0 && pB==0 ) return 0;
  93472. if( pA==0 || pB==0 ) return 1;
  93473. if( pA->nExpr!=pB->nExpr ) return 1;
  93474. for(i=0; i<pA->nExpr; i++){
  93475. Expr *pExprA = pA->a[i].pExpr;
  93476. Expr *pExprB = pB->a[i].pExpr;
  93477. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  93478. if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
  93479. }
  93480. return 0;
  93481. }
  93482. /*
  93483. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  93484. ** are ignored.
  93485. */
  93486. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  93487. return sqlite3ExprCompare(0,
  93488. sqlite3ExprSkipCollate(pA),
  93489. sqlite3ExprSkipCollate(pB),
  93490. iTab);
  93491. }
  93492. /*
  93493. ** Return true if we can prove the pE2 will always be true if pE1 is
  93494. ** true. Return false if we cannot complete the proof or if pE2 might
  93495. ** be false. Examples:
  93496. **
  93497. ** pE1: x==5 pE2: x==5 Result: true
  93498. ** pE1: x>0 pE2: x==5 Result: false
  93499. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  93500. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  93501. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  93502. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  93503. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  93504. **
  93505. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  93506. ** Expr.iTable<0 then assume a table number given by iTab.
  93507. **
  93508. ** If pParse is not NULL, then the values of bound variables in pE1 are
  93509. ** compared against literal values in pE2 and pParse->pVdbe->expmask is
  93510. ** modified to record which bound variables are referenced. If pParse
  93511. ** is NULL, then false will be returned if pE1 contains any bound variables.
  93512. **
  93513. ** When in doubt, return false. Returning true might give a performance
  93514. ** improvement. Returning false might cause a performance reduction, but
  93515. ** it will always give the correct answer and is hence always safe.
  93516. */
  93517. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
  93518. if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
  93519. return 1;
  93520. }
  93521. if( pE2->op==TK_OR
  93522. && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
  93523. || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
  93524. ){
  93525. return 1;
  93526. }
  93527. if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
  93528. Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
  93529. testcase( pX!=pE1->pLeft );
  93530. if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
  93531. }
  93532. return 0;
  93533. }
  93534. /*
  93535. ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
  93536. ** If the expression node requires that the table at pWalker->iCur
  93537. ** have a non-NULL column, then set pWalker->eCode to 1 and abort.
  93538. */
  93539. static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
  93540. /* This routine is only called for WHERE clause expressions and so it
  93541. ** cannot have any TK_AGG_COLUMN entries because those are only found
  93542. ** in HAVING clauses. We can get a TK_AGG_FUNCTION in a WHERE clause,
  93543. ** but that is an illegal construct and the query will be rejected at
  93544. ** a later stage of processing, so the TK_AGG_FUNCTION case does not
  93545. ** need to be considered here. */
  93546. assert( pExpr->op!=TK_AGG_COLUMN );
  93547. testcase( pExpr->op==TK_AGG_FUNCTION );
  93548. if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
  93549. switch( pExpr->op ){
  93550. case TK_ISNOT:
  93551. case TK_NOT:
  93552. case TK_ISNULL:
  93553. case TK_IS:
  93554. case TK_OR:
  93555. case TK_CASE:
  93556. case TK_IN:
  93557. case TK_FUNCTION:
  93558. testcase( pExpr->op==TK_ISNOT );
  93559. testcase( pExpr->op==TK_NOT );
  93560. testcase( pExpr->op==TK_ISNULL );
  93561. testcase( pExpr->op==TK_IS );
  93562. testcase( pExpr->op==TK_OR );
  93563. testcase( pExpr->op==TK_CASE );
  93564. testcase( pExpr->op==TK_IN );
  93565. testcase( pExpr->op==TK_FUNCTION );
  93566. return WRC_Prune;
  93567. case TK_COLUMN:
  93568. if( pWalker->u.iCur==pExpr->iTable ){
  93569. pWalker->eCode = 1;
  93570. return WRC_Abort;
  93571. }
  93572. return WRC_Prune;
  93573. /* Virtual tables are allowed to use constraints like x=NULL. So
  93574. ** a term of the form x=y does not prove that y is not null if x
  93575. ** is the column of a virtual table */
  93576. case TK_EQ:
  93577. case TK_NE:
  93578. case TK_LT:
  93579. case TK_LE:
  93580. case TK_GT:
  93581. case TK_GE:
  93582. testcase( pExpr->op==TK_EQ );
  93583. testcase( pExpr->op==TK_NE );
  93584. testcase( pExpr->op==TK_LT );
  93585. testcase( pExpr->op==TK_LE );
  93586. testcase( pExpr->op==TK_GT );
  93587. testcase( pExpr->op==TK_GE );
  93588. if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->pTab))
  93589. || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->pTab))
  93590. ){
  93591. return WRC_Prune;
  93592. }
  93593. default:
  93594. return WRC_Continue;
  93595. }
  93596. }
  93597. /*
  93598. ** Return true (non-zero) if expression p can only be true if at least
  93599. ** one column of table iTab is non-null. In other words, return true
  93600. ** if expression p will always be NULL or false if every column of iTab
  93601. ** is NULL.
  93602. **
  93603. ** False negatives are acceptable. In other words, it is ok to return
  93604. ** zero even if expression p will never be true of every column of iTab
  93605. ** is NULL. A false negative is merely a missed optimization opportunity.
  93606. **
  93607. ** False positives are not allowed, however. A false positive may result
  93608. ** in an incorrect answer.
  93609. **
  93610. ** Terms of p that are marked with EP_FromJoin (and hence that come from
  93611. ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
  93612. **
  93613. ** This routine is used to check if a LEFT JOIN can be converted into
  93614. ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
  93615. ** clause requires that some column of the right table of the LEFT JOIN
  93616. ** be non-NULL, then the LEFT JOIN can be safely converted into an
  93617. ** ordinary join.
  93618. */
  93619. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
  93620. Walker w;
  93621. w.xExprCallback = impliesNotNullRow;
  93622. w.xSelectCallback = 0;
  93623. w.xSelectCallback2 = 0;
  93624. w.eCode = 0;
  93625. w.u.iCur = iTab;
  93626. sqlite3WalkExpr(&w, p);
  93627. return w.eCode;
  93628. }
  93629. /*
  93630. ** An instance of the following structure is used by the tree walker
  93631. ** to determine if an expression can be evaluated by reference to the
  93632. ** index only, without having to do a search for the corresponding
  93633. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  93634. ** is the cursor for the table.
  93635. */
  93636. struct IdxCover {
  93637. Index *pIdx; /* The index to be tested for coverage */
  93638. int iCur; /* Cursor number for the table corresponding to the index */
  93639. };
  93640. /*
  93641. ** Check to see if there are references to columns in table
  93642. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  93643. ** pWalker->u.pIdxCover->pIdx.
  93644. */
  93645. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  93646. if( pExpr->op==TK_COLUMN
  93647. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  93648. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  93649. ){
  93650. pWalker->eCode = 1;
  93651. return WRC_Abort;
  93652. }
  93653. return WRC_Continue;
  93654. }
  93655. /*
  93656. ** Determine if an index pIdx on table with cursor iCur contains will
  93657. ** the expression pExpr. Return true if the index does cover the
  93658. ** expression and false if the pExpr expression references table columns
  93659. ** that are not found in the index pIdx.
  93660. **
  93661. ** An index covering an expression means that the expression can be
  93662. ** evaluated using only the index and without having to lookup the
  93663. ** corresponding table entry.
  93664. */
  93665. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  93666. Expr *pExpr, /* The index to be tested */
  93667. int iCur, /* The cursor number for the corresponding table */
  93668. Index *pIdx /* The index that might be used for coverage */
  93669. ){
  93670. Walker w;
  93671. struct IdxCover xcov;
  93672. memset(&w, 0, sizeof(w));
  93673. xcov.iCur = iCur;
  93674. xcov.pIdx = pIdx;
  93675. w.xExprCallback = exprIdxCover;
  93676. w.u.pIdxCover = &xcov;
  93677. sqlite3WalkExpr(&w, pExpr);
  93678. return !w.eCode;
  93679. }
  93680. /*
  93681. ** An instance of the following structure is used by the tree walker
  93682. ** to count references to table columns in the arguments of an
  93683. ** aggregate function, in order to implement the
  93684. ** sqlite3FunctionThisSrc() routine.
  93685. */
  93686. struct SrcCount {
  93687. SrcList *pSrc; /* One particular FROM clause in a nested query */
  93688. int nThis; /* Number of references to columns in pSrcList */
  93689. int nOther; /* Number of references to columns in other FROM clauses */
  93690. };
  93691. /*
  93692. ** Count the number of references to columns.
  93693. */
  93694. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  93695. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  93696. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  93697. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  93698. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  93699. ** NEVER() will need to be removed. */
  93700. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  93701. int i;
  93702. struct SrcCount *p = pWalker->u.pSrcCount;
  93703. SrcList *pSrc = p->pSrc;
  93704. int nSrc = pSrc ? pSrc->nSrc : 0;
  93705. for(i=0; i<nSrc; i++){
  93706. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  93707. }
  93708. if( i<nSrc ){
  93709. p->nThis++;
  93710. }else{
  93711. p->nOther++;
  93712. }
  93713. }
  93714. return WRC_Continue;
  93715. }
  93716. /*
  93717. ** Determine if any of the arguments to the pExpr Function reference
  93718. ** pSrcList. Return true if they do. Also return true if the function
  93719. ** has no arguments or has only constant arguments. Return false if pExpr
  93720. ** references columns but not columns of tables found in pSrcList.
  93721. */
  93722. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  93723. Walker w;
  93724. struct SrcCount cnt;
  93725. assert( pExpr->op==TK_AGG_FUNCTION );
  93726. w.xExprCallback = exprSrcCount;
  93727. w.xSelectCallback = 0;
  93728. w.u.pSrcCount = &cnt;
  93729. cnt.pSrc = pSrcList;
  93730. cnt.nThis = 0;
  93731. cnt.nOther = 0;
  93732. sqlite3WalkExprList(&w, pExpr->x.pList);
  93733. return cnt.nThis>0 || cnt.nOther==0;
  93734. }
  93735. /*
  93736. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  93737. ** the new element. Return a negative number if malloc fails.
  93738. */
  93739. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  93740. int i;
  93741. pInfo->aCol = sqlite3ArrayAllocate(
  93742. db,
  93743. pInfo->aCol,
  93744. sizeof(pInfo->aCol[0]),
  93745. &pInfo->nColumn,
  93746. &i
  93747. );
  93748. return i;
  93749. }
  93750. /*
  93751. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  93752. ** the new element. Return a negative number if malloc fails.
  93753. */
  93754. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  93755. int i;
  93756. pInfo->aFunc = sqlite3ArrayAllocate(
  93757. db,
  93758. pInfo->aFunc,
  93759. sizeof(pInfo->aFunc[0]),
  93760. &pInfo->nFunc,
  93761. &i
  93762. );
  93763. return i;
  93764. }
  93765. /*
  93766. ** This is the xExprCallback for a tree walker. It is used to
  93767. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  93768. ** for additional information.
  93769. */
  93770. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  93771. int i;
  93772. NameContext *pNC = pWalker->u.pNC;
  93773. Parse *pParse = pNC->pParse;
  93774. SrcList *pSrcList = pNC->pSrcList;
  93775. AggInfo *pAggInfo = pNC->uNC.pAggInfo;
  93776. assert( pNC->ncFlags & NC_UAggInfo );
  93777. switch( pExpr->op ){
  93778. case TK_AGG_COLUMN:
  93779. case TK_COLUMN: {
  93780. testcase( pExpr->op==TK_AGG_COLUMN );
  93781. testcase( pExpr->op==TK_COLUMN );
  93782. /* Check to see if the column is in one of the tables in the FROM
  93783. ** clause of the aggregate query */
  93784. if( ALWAYS(pSrcList!=0) ){
  93785. struct SrcList_item *pItem = pSrcList->a;
  93786. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  93787. struct AggInfo_col *pCol;
  93788. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  93789. if( pExpr->iTable==pItem->iCursor ){
  93790. /* If we reach this point, it means that pExpr refers to a table
  93791. ** that is in the FROM clause of the aggregate query.
  93792. **
  93793. ** Make an entry for the column in pAggInfo->aCol[] if there
  93794. ** is not an entry there already.
  93795. */
  93796. int k;
  93797. pCol = pAggInfo->aCol;
  93798. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  93799. if( pCol->iTable==pExpr->iTable &&
  93800. pCol->iColumn==pExpr->iColumn ){
  93801. break;
  93802. }
  93803. }
  93804. if( (k>=pAggInfo->nColumn)
  93805. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  93806. ){
  93807. pCol = &pAggInfo->aCol[k];
  93808. pCol->pTab = pExpr->pTab;
  93809. pCol->iTable = pExpr->iTable;
  93810. pCol->iColumn = pExpr->iColumn;
  93811. pCol->iMem = ++pParse->nMem;
  93812. pCol->iSorterColumn = -1;
  93813. pCol->pExpr = pExpr;
  93814. if( pAggInfo->pGroupBy ){
  93815. int j, n;
  93816. ExprList *pGB = pAggInfo->pGroupBy;
  93817. struct ExprList_item *pTerm = pGB->a;
  93818. n = pGB->nExpr;
  93819. for(j=0; j<n; j++, pTerm++){
  93820. Expr *pE = pTerm->pExpr;
  93821. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  93822. pE->iColumn==pExpr->iColumn ){
  93823. pCol->iSorterColumn = j;
  93824. break;
  93825. }
  93826. }
  93827. }
  93828. if( pCol->iSorterColumn<0 ){
  93829. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  93830. }
  93831. }
  93832. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  93833. ** because it was there before or because we just created it).
  93834. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  93835. ** pAggInfo->aCol[] entry.
  93836. */
  93837. ExprSetVVAProperty(pExpr, EP_NoReduce);
  93838. pExpr->pAggInfo = pAggInfo;
  93839. pExpr->op = TK_AGG_COLUMN;
  93840. pExpr->iAgg = (i16)k;
  93841. break;
  93842. } /* endif pExpr->iTable==pItem->iCursor */
  93843. } /* end loop over pSrcList */
  93844. }
  93845. return WRC_Prune;
  93846. }
  93847. case TK_AGG_FUNCTION: {
  93848. if( (pNC->ncFlags & NC_InAggFunc)==0
  93849. && pWalker->walkerDepth==pExpr->op2
  93850. ){
  93851. /* Check to see if pExpr is a duplicate of another aggregate
  93852. ** function that is already in the pAggInfo structure
  93853. */
  93854. struct AggInfo_func *pItem = pAggInfo->aFunc;
  93855. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  93856. if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
  93857. break;
  93858. }
  93859. }
  93860. if( i>=pAggInfo->nFunc ){
  93861. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  93862. */
  93863. u8 enc = ENC(pParse->db);
  93864. i = addAggInfoFunc(pParse->db, pAggInfo);
  93865. if( i>=0 ){
  93866. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  93867. pItem = &pAggInfo->aFunc[i];
  93868. pItem->pExpr = pExpr;
  93869. pItem->iMem = ++pParse->nMem;
  93870. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93871. pItem->pFunc = sqlite3FindFunction(pParse->db,
  93872. pExpr->u.zToken,
  93873. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  93874. if( pExpr->flags & EP_Distinct ){
  93875. pItem->iDistinct = pParse->nTab++;
  93876. }else{
  93877. pItem->iDistinct = -1;
  93878. }
  93879. }
  93880. }
  93881. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  93882. */
  93883. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  93884. ExprSetVVAProperty(pExpr, EP_NoReduce);
  93885. pExpr->iAgg = (i16)i;
  93886. pExpr->pAggInfo = pAggInfo;
  93887. return WRC_Prune;
  93888. }else{
  93889. return WRC_Continue;
  93890. }
  93891. }
  93892. }
  93893. return WRC_Continue;
  93894. }
  93895. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  93896. UNUSED_PARAMETER(pSelect);
  93897. pWalker->walkerDepth++;
  93898. return WRC_Continue;
  93899. }
  93900. static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
  93901. UNUSED_PARAMETER(pSelect);
  93902. pWalker->walkerDepth--;
  93903. }
  93904. /*
  93905. ** Analyze the pExpr expression looking for aggregate functions and
  93906. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  93907. ** points to. Additional entries are made on the AggInfo object as
  93908. ** necessary.
  93909. **
  93910. ** This routine should only be called after the expression has been
  93911. ** analyzed by sqlite3ResolveExprNames().
  93912. */
  93913. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  93914. Walker w;
  93915. w.xExprCallback = analyzeAggregate;
  93916. w.xSelectCallback = analyzeAggregatesInSelect;
  93917. w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
  93918. w.walkerDepth = 0;
  93919. w.u.pNC = pNC;
  93920. assert( pNC->pSrcList!=0 );
  93921. sqlite3WalkExpr(&w, pExpr);
  93922. }
  93923. /*
  93924. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  93925. ** expression list. Return the number of errors.
  93926. **
  93927. ** If an error is found, the analysis is cut short.
  93928. */
  93929. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  93930. struct ExprList_item *pItem;
  93931. int i;
  93932. if( pList ){
  93933. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  93934. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  93935. }
  93936. }
  93937. }
  93938. /*
  93939. ** Allocate a single new register for use to hold some intermediate result.
  93940. */
  93941. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  93942. if( pParse->nTempReg==0 ){
  93943. return ++pParse->nMem;
  93944. }
  93945. return pParse->aTempReg[--pParse->nTempReg];
  93946. }
  93947. /*
  93948. ** Deallocate a register, making available for reuse for some other
  93949. ** purpose.
  93950. **
  93951. ** If a register is currently being used by the column cache, then
  93952. ** the deallocation is deferred until the column cache line that uses
  93953. ** the register becomes stale.
  93954. */
  93955. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  93956. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  93957. int i;
  93958. struct yColCache *p;
  93959. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  93960. if( p->iReg==iReg ){
  93961. p->tempReg = 1;
  93962. return;
  93963. }
  93964. }
  93965. pParse->aTempReg[pParse->nTempReg++] = iReg;
  93966. }
  93967. }
  93968. /*
  93969. ** Allocate or deallocate a block of nReg consecutive registers.
  93970. */
  93971. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  93972. int i, n;
  93973. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  93974. i = pParse->iRangeReg;
  93975. n = pParse->nRangeReg;
  93976. if( nReg<=n ){
  93977. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  93978. pParse->iRangeReg += nReg;
  93979. pParse->nRangeReg -= nReg;
  93980. }else{
  93981. i = pParse->nMem+1;
  93982. pParse->nMem += nReg;
  93983. }
  93984. return i;
  93985. }
  93986. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  93987. if( nReg==1 ){
  93988. sqlite3ReleaseTempReg(pParse, iReg);
  93989. return;
  93990. }
  93991. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  93992. if( nReg>pParse->nRangeReg ){
  93993. pParse->nRangeReg = nReg;
  93994. pParse->iRangeReg = iReg;
  93995. }
  93996. }
  93997. /*
  93998. ** Mark all temporary registers as being unavailable for reuse.
  93999. */
  94000. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  94001. pParse->nTempReg = 0;
  94002. pParse->nRangeReg = 0;
  94003. }
  94004. /*
  94005. ** Validate that no temporary register falls within the range of
  94006. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  94007. ** statements.
  94008. */
  94009. #ifdef SQLITE_DEBUG
  94010. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  94011. int i;
  94012. if( pParse->nRangeReg>0
  94013. && pParse->iRangeReg+pParse->nRangeReg > iFirst
  94014. && pParse->iRangeReg <= iLast
  94015. ){
  94016. return 0;
  94017. }
  94018. for(i=0; i<pParse->nTempReg; i++){
  94019. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  94020. return 0;
  94021. }
  94022. }
  94023. return 1;
  94024. }
  94025. #endif /* SQLITE_DEBUG */
  94026. /************** End of expr.c ************************************************/
  94027. /************** Begin file alter.c *******************************************/
  94028. /*
  94029. ** 2005 February 15
  94030. **
  94031. ** The author disclaims copyright to this source code. In place of
  94032. ** a legal notice, here is a blessing:
  94033. **
  94034. ** May you do good and not evil.
  94035. ** May you find forgiveness for yourself and forgive others.
  94036. ** May you share freely, never taking more than you give.
  94037. **
  94038. *************************************************************************
  94039. ** This file contains C code routines that used to generate VDBE code
  94040. ** that implements the ALTER TABLE command.
  94041. */
  94042. /* #include "sqliteInt.h" */
  94043. /*
  94044. ** The code in this file only exists if we are not omitting the
  94045. ** ALTER TABLE logic from the build.
  94046. */
  94047. #ifndef SQLITE_OMIT_ALTERTABLE
  94048. /*
  94049. ** This function is used by SQL generated to implement the
  94050. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  94051. ** CREATE INDEX command. The second is a table name. The table name in
  94052. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  94053. ** argument and the result returned. Examples:
  94054. **
  94055. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  94056. ** -> 'CREATE TABLE def(a, b, c)'
  94057. **
  94058. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  94059. ** -> 'CREATE INDEX i ON def(a, b, c)'
  94060. */
  94061. static void renameTableFunc(
  94062. sqlite3_context *context,
  94063. int NotUsed,
  94064. sqlite3_value **argv
  94065. ){
  94066. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  94067. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  94068. int token;
  94069. Token tname;
  94070. unsigned char const *zCsr = zSql;
  94071. int len = 0;
  94072. char *zRet;
  94073. sqlite3 *db = sqlite3_context_db_handle(context);
  94074. UNUSED_PARAMETER(NotUsed);
  94075. /* The principle used to locate the table name in the CREATE TABLE
  94076. ** statement is that the table name is the first non-space token that
  94077. ** is immediately followed by a TK_LP or TK_USING token.
  94078. */
  94079. if( zSql ){
  94080. do {
  94081. if( !*zCsr ){
  94082. /* Ran out of input before finding an opening bracket. Return NULL. */
  94083. return;
  94084. }
  94085. /* Store the token that zCsr points to in tname. */
  94086. tname.z = (char*)zCsr;
  94087. tname.n = len;
  94088. /* Advance zCsr to the next token. Store that token type in 'token',
  94089. ** and its length in 'len' (to be used next iteration of this loop).
  94090. */
  94091. do {
  94092. zCsr += len;
  94093. len = sqlite3GetToken(zCsr, &token);
  94094. } while( token==TK_SPACE );
  94095. assert( len>0 );
  94096. } while( token!=TK_LP && token!=TK_USING );
  94097. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  94098. zSql, zTableName, tname.z+tname.n);
  94099. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  94100. }
  94101. }
  94102. /*
  94103. ** This C function implements an SQL user function that is used by SQL code
  94104. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  94105. ** of any foreign key constraints that use the table being renamed as the
  94106. ** parent table. It is passed three arguments:
  94107. **
  94108. ** 1) The complete text of the CREATE TABLE statement being modified,
  94109. ** 2) The old name of the table being renamed, and
  94110. ** 3) The new name of the table being renamed.
  94111. **
  94112. ** It returns the new CREATE TABLE statement. For example:
  94113. **
  94114. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  94115. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  94116. */
  94117. #ifndef SQLITE_OMIT_FOREIGN_KEY
  94118. static void renameParentFunc(
  94119. sqlite3_context *context,
  94120. int NotUsed,
  94121. sqlite3_value **argv
  94122. ){
  94123. sqlite3 *db = sqlite3_context_db_handle(context);
  94124. char *zOutput = 0;
  94125. char *zResult;
  94126. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  94127. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  94128. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  94129. unsigned const char *z; /* Pointer to token */
  94130. int n; /* Length of token z */
  94131. int token; /* Type of token */
  94132. UNUSED_PARAMETER(NotUsed);
  94133. if( zInput==0 || zOld==0 ) return;
  94134. for(z=zInput; *z; z=z+n){
  94135. n = sqlite3GetToken(z, &token);
  94136. if( token==TK_REFERENCES ){
  94137. char *zParent;
  94138. do {
  94139. z += n;
  94140. n = sqlite3GetToken(z, &token);
  94141. }while( token==TK_SPACE );
  94142. if( token==TK_ILLEGAL ) break;
  94143. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  94144. if( zParent==0 ) break;
  94145. sqlite3Dequote(zParent);
  94146. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  94147. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  94148. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  94149. );
  94150. sqlite3DbFree(db, zOutput);
  94151. zOutput = zOut;
  94152. zInput = &z[n];
  94153. }
  94154. sqlite3DbFree(db, zParent);
  94155. }
  94156. }
  94157. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  94158. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  94159. sqlite3DbFree(db, zOutput);
  94160. }
  94161. #endif
  94162. #ifndef SQLITE_OMIT_TRIGGER
  94163. /* This function is used by SQL generated to implement the
  94164. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  94165. ** statement. The second is a table name. The table name in the CREATE
  94166. ** TRIGGER statement is replaced with the third argument and the result
  94167. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  94168. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  94169. */
  94170. static void renameTriggerFunc(
  94171. sqlite3_context *context,
  94172. int NotUsed,
  94173. sqlite3_value **argv
  94174. ){
  94175. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  94176. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  94177. int token;
  94178. Token tname;
  94179. int dist = 3;
  94180. unsigned char const *zCsr = zSql;
  94181. int len = 0;
  94182. char *zRet;
  94183. sqlite3 *db = sqlite3_context_db_handle(context);
  94184. UNUSED_PARAMETER(NotUsed);
  94185. /* The principle used to locate the table name in the CREATE TRIGGER
  94186. ** statement is that the table name is the first token that is immediately
  94187. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  94188. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  94189. */
  94190. if( zSql ){
  94191. do {
  94192. if( !*zCsr ){
  94193. /* Ran out of input before finding the table name. Return NULL. */
  94194. return;
  94195. }
  94196. /* Store the token that zCsr points to in tname. */
  94197. tname.z = (char*)zCsr;
  94198. tname.n = len;
  94199. /* Advance zCsr to the next token. Store that token type in 'token',
  94200. ** and its length in 'len' (to be used next iteration of this loop).
  94201. */
  94202. do {
  94203. zCsr += len;
  94204. len = sqlite3GetToken(zCsr, &token);
  94205. }while( token==TK_SPACE );
  94206. assert( len>0 );
  94207. /* Variable 'dist' stores the number of tokens read since the most
  94208. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  94209. ** token is read and 'dist' equals 2, the condition stated above
  94210. ** to be met.
  94211. **
  94212. ** Note that ON cannot be a database, table or column name, so
  94213. ** there is no need to worry about syntax like
  94214. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  94215. */
  94216. dist++;
  94217. if( token==TK_DOT || token==TK_ON ){
  94218. dist = 0;
  94219. }
  94220. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  94221. /* Variable tname now contains the token that is the old table-name
  94222. ** in the CREATE TRIGGER statement.
  94223. */
  94224. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  94225. zSql, zTableName, tname.z+tname.n);
  94226. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  94227. }
  94228. }
  94229. #endif /* !SQLITE_OMIT_TRIGGER */
  94230. /*
  94231. ** Register built-in functions used to help implement ALTER TABLE
  94232. */
  94233. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  94234. static FuncDef aAlterTableFuncs[] = {
  94235. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  94236. #ifndef SQLITE_OMIT_TRIGGER
  94237. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  94238. #endif
  94239. #ifndef SQLITE_OMIT_FOREIGN_KEY
  94240. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  94241. #endif
  94242. };
  94243. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  94244. }
  94245. /*
  94246. ** This function is used to create the text of expressions of the form:
  94247. **
  94248. ** name=<constant1> OR name=<constant2> OR ...
  94249. **
  94250. ** If argument zWhere is NULL, then a pointer string containing the text
  94251. ** "name=<constant>" is returned, where <constant> is the quoted version
  94252. ** of the string passed as argument zConstant. The returned buffer is
  94253. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  94254. ** caller to ensure that it is eventually freed.
  94255. **
  94256. ** If argument zWhere is not NULL, then the string returned is
  94257. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  94258. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  94259. **
  94260. */
  94261. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  94262. char *zNew;
  94263. if( !zWhere ){
  94264. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  94265. }else{
  94266. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  94267. sqlite3DbFree(db, zWhere);
  94268. }
  94269. return zNew;
  94270. }
  94271. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94272. /*
  94273. ** Generate the text of a WHERE expression which can be used to select all
  94274. ** tables that have foreign key constraints that refer to table pTab (i.e.
  94275. ** constraints for which pTab is the parent table) from the sqlite_master
  94276. ** table.
  94277. */
  94278. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  94279. FKey *p;
  94280. char *zWhere = 0;
  94281. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  94282. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  94283. }
  94284. return zWhere;
  94285. }
  94286. #endif
  94287. /*
  94288. ** Generate the text of a WHERE expression which can be used to select all
  94289. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  94290. ** table pTab has no temporary triggers, or is itself stored in the
  94291. ** temporary database, NULL is returned.
  94292. */
  94293. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  94294. Trigger *pTrig;
  94295. char *zWhere = 0;
  94296. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  94297. /* If the table is not located in the temp-db (in which case NULL is
  94298. ** returned, loop through the tables list of triggers. For each trigger
  94299. ** that is not part of the temp-db schema, add a clause to the WHERE
  94300. ** expression being built up in zWhere.
  94301. */
  94302. if( pTab->pSchema!=pTempSchema ){
  94303. sqlite3 *db = pParse->db;
  94304. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  94305. if( pTrig->pSchema==pTempSchema ){
  94306. zWhere = whereOrName(db, zWhere, pTrig->zName);
  94307. }
  94308. }
  94309. }
  94310. if( zWhere ){
  94311. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  94312. sqlite3DbFree(pParse->db, zWhere);
  94313. zWhere = zNew;
  94314. }
  94315. return zWhere;
  94316. }
  94317. /*
  94318. ** Generate code to drop and reload the internal representation of table
  94319. ** pTab from the database, including triggers and temporary triggers.
  94320. ** Argument zName is the name of the table in the database schema at
  94321. ** the time the generated code is executed. This can be different from
  94322. ** pTab->zName if this function is being called to code part of an
  94323. ** "ALTER TABLE RENAME TO" statement.
  94324. */
  94325. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  94326. Vdbe *v;
  94327. char *zWhere;
  94328. int iDb; /* Index of database containing pTab */
  94329. #ifndef SQLITE_OMIT_TRIGGER
  94330. Trigger *pTrig;
  94331. #endif
  94332. v = sqlite3GetVdbe(pParse);
  94333. if( NEVER(v==0) ) return;
  94334. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  94335. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  94336. assert( iDb>=0 );
  94337. #ifndef SQLITE_OMIT_TRIGGER
  94338. /* Drop any table triggers from the internal schema. */
  94339. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  94340. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  94341. assert( iTrigDb==iDb || iTrigDb==1 );
  94342. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  94343. }
  94344. #endif
  94345. /* Drop the table and index from the internal schema. */
  94346. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  94347. /* Reload the table, index and permanent trigger schemas. */
  94348. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  94349. if( !zWhere ) return;
  94350. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  94351. #ifndef SQLITE_OMIT_TRIGGER
  94352. /* Now, if the table is not stored in the temp database, reload any temp
  94353. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  94354. */
  94355. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  94356. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  94357. }
  94358. #endif
  94359. }
  94360. /*
  94361. ** Parameter zName is the name of a table that is about to be altered
  94362. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  94363. ** If the table is a system table, this function leaves an error message
  94364. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  94365. **
  94366. ** Or, if zName is not a system table, zero is returned.
  94367. */
  94368. static int isSystemTable(Parse *pParse, const char *zName){
  94369. if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  94370. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  94371. return 1;
  94372. }
  94373. return 0;
  94374. }
  94375. /*
  94376. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  94377. ** command.
  94378. */
  94379. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  94380. Parse *pParse, /* Parser context. */
  94381. SrcList *pSrc, /* The table to rename. */
  94382. Token *pName /* The new table name. */
  94383. ){
  94384. int iDb; /* Database that contains the table */
  94385. char *zDb; /* Name of database iDb */
  94386. Table *pTab; /* Table being renamed */
  94387. char *zName = 0; /* NULL-terminated version of pName */
  94388. sqlite3 *db = pParse->db; /* Database connection */
  94389. int nTabName; /* Number of UTF-8 characters in zTabName */
  94390. const char *zTabName; /* Original name of the table */
  94391. Vdbe *v;
  94392. #ifndef SQLITE_OMIT_TRIGGER
  94393. char *zWhere = 0; /* Where clause to locate temp triggers */
  94394. #endif
  94395. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  94396. u32 savedDbFlags; /* Saved value of db->mDbFlags */
  94397. savedDbFlags = db->mDbFlags;
  94398. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  94399. assert( pSrc->nSrc==1 );
  94400. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  94401. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  94402. if( !pTab ) goto exit_rename_table;
  94403. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  94404. zDb = db->aDb[iDb].zDbSName;
  94405. db->mDbFlags |= DBFLAG_PreferBuiltin;
  94406. /* Get a NULL terminated version of the new table name. */
  94407. zName = sqlite3NameFromToken(db, pName);
  94408. if( !zName ) goto exit_rename_table;
  94409. /* Check that a table or index named 'zName' does not already exist
  94410. ** in database iDb. If so, this is an error.
  94411. */
  94412. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  94413. sqlite3ErrorMsg(pParse,
  94414. "there is already another table or index with this name: %s", zName);
  94415. goto exit_rename_table;
  94416. }
  94417. /* Make sure it is not a system table being altered, or a reserved name
  94418. ** that the table is being renamed to.
  94419. */
  94420. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  94421. goto exit_rename_table;
  94422. }
  94423. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  94424. exit_rename_table;
  94425. }
  94426. #ifndef SQLITE_OMIT_VIEW
  94427. if( pTab->pSelect ){
  94428. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  94429. goto exit_rename_table;
  94430. }
  94431. #endif
  94432. #ifndef SQLITE_OMIT_AUTHORIZATION
  94433. /* Invoke the authorization callback. */
  94434. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  94435. goto exit_rename_table;
  94436. }
  94437. #endif
  94438. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94439. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  94440. goto exit_rename_table;
  94441. }
  94442. if( IsVirtual(pTab) ){
  94443. pVTab = sqlite3GetVTable(db, pTab);
  94444. if( pVTab->pVtab->pModule->xRename==0 ){
  94445. pVTab = 0;
  94446. }
  94447. }
  94448. #endif
  94449. /* Begin a transaction for database iDb.
  94450. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  94451. ** schema). Open a statement transaction if the table is a virtual
  94452. ** table.
  94453. */
  94454. v = sqlite3GetVdbe(pParse);
  94455. if( v==0 ){
  94456. goto exit_rename_table;
  94457. }
  94458. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  94459. sqlite3ChangeCookie(pParse, iDb);
  94460. /* If this is a virtual table, invoke the xRename() function if
  94461. ** one is defined. The xRename() callback will modify the names
  94462. ** of any resources used by the v-table implementation (including other
  94463. ** SQLite tables) that are identified by the name of the virtual table.
  94464. */
  94465. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94466. if( pVTab ){
  94467. int i = ++pParse->nMem;
  94468. sqlite3VdbeLoadString(v, i, zName);
  94469. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  94470. sqlite3MayAbort(pParse);
  94471. }
  94472. #endif
  94473. /* figure out how many UTF-8 characters are in zName */
  94474. zTabName = pTab->zName;
  94475. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  94476. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94477. if( db->flags&SQLITE_ForeignKeys ){
  94478. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  94479. ** statements corresponding to all child tables of foreign key constraints
  94480. ** for which the renamed table is the parent table. */
  94481. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  94482. sqlite3NestedParse(pParse,
  94483. "UPDATE \"%w\".%s SET "
  94484. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  94485. "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
  94486. sqlite3DbFree(db, zWhere);
  94487. }
  94488. }
  94489. #endif
  94490. /* Modify the sqlite_master table to use the new table name. */
  94491. sqlite3NestedParse(pParse,
  94492. "UPDATE %Q.%s SET "
  94493. #ifdef SQLITE_OMIT_TRIGGER
  94494. "sql = sqlite_rename_table(sql, %Q), "
  94495. #else
  94496. "sql = CASE "
  94497. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  94498. "ELSE sqlite_rename_table(sql, %Q) END, "
  94499. #endif
  94500. "tbl_name = %Q, "
  94501. "name = CASE "
  94502. "WHEN type='table' THEN %Q "
  94503. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  94504. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  94505. "ELSE name END "
  94506. "WHERE tbl_name=%Q COLLATE nocase AND "
  94507. "(type='table' OR type='index' OR type='trigger');",
  94508. zDb, MASTER_NAME, zName, zName, zName,
  94509. #ifndef SQLITE_OMIT_TRIGGER
  94510. zName,
  94511. #endif
  94512. zName, nTabName, zTabName
  94513. );
  94514. #ifndef SQLITE_OMIT_AUTOINCREMENT
  94515. /* If the sqlite_sequence table exists in this database, then update
  94516. ** it with the new table name.
  94517. */
  94518. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  94519. sqlite3NestedParse(pParse,
  94520. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  94521. zDb, zName, pTab->zName);
  94522. }
  94523. #endif
  94524. #ifndef SQLITE_OMIT_TRIGGER
  94525. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  94526. ** table. Don't do this if the table being ALTERed is itself located in
  94527. ** the temp database.
  94528. */
  94529. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  94530. sqlite3NestedParse(pParse,
  94531. "UPDATE sqlite_temp_master SET "
  94532. "sql = sqlite_rename_trigger(sql, %Q), "
  94533. "tbl_name = %Q "
  94534. "WHERE %s;", zName, zName, zWhere);
  94535. sqlite3DbFree(db, zWhere);
  94536. }
  94537. #endif
  94538. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94539. if( db->flags&SQLITE_ForeignKeys ){
  94540. FKey *p;
  94541. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  94542. Table *pFrom = p->pFrom;
  94543. if( pFrom!=pTab ){
  94544. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  94545. }
  94546. }
  94547. }
  94548. #endif
  94549. /* Drop and reload the internal table schema. */
  94550. reloadTableSchema(pParse, pTab, zName);
  94551. exit_rename_table:
  94552. sqlite3SrcListDelete(db, pSrc);
  94553. sqlite3DbFree(db, zName);
  94554. db->mDbFlags = savedDbFlags;
  94555. }
  94556. /*
  94557. ** This function is called after an "ALTER TABLE ... ADD" statement
  94558. ** has been parsed. Argument pColDef contains the text of the new
  94559. ** column definition.
  94560. **
  94561. ** The Table structure pParse->pNewTable was extended to include
  94562. ** the new column during parsing.
  94563. */
  94564. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  94565. Table *pNew; /* Copy of pParse->pNewTable */
  94566. Table *pTab; /* Table being altered */
  94567. int iDb; /* Database number */
  94568. const char *zDb; /* Database name */
  94569. const char *zTab; /* Table name */
  94570. char *zCol; /* Null-terminated column definition */
  94571. Column *pCol; /* The new column */
  94572. Expr *pDflt; /* Default value for the new column */
  94573. sqlite3 *db; /* The database connection; */
  94574. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  94575. int r1; /* Temporary registers */
  94576. db = pParse->db;
  94577. if( pParse->nErr || db->mallocFailed ) return;
  94578. assert( v!=0 );
  94579. pNew = pParse->pNewTable;
  94580. assert( pNew );
  94581. assert( sqlite3BtreeHoldsAllMutexes(db) );
  94582. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  94583. zDb = db->aDb[iDb].zDbSName;
  94584. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  94585. pCol = &pNew->aCol[pNew->nCol-1];
  94586. pDflt = pCol->pDflt;
  94587. pTab = sqlite3FindTable(db, zTab, zDb);
  94588. assert( pTab );
  94589. #ifndef SQLITE_OMIT_AUTHORIZATION
  94590. /* Invoke the authorization callback. */
  94591. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  94592. return;
  94593. }
  94594. #endif
  94595. /* If the default value for the new column was specified with a
  94596. ** literal NULL, then set pDflt to 0. This simplifies checking
  94597. ** for an SQL NULL default below.
  94598. */
  94599. assert( pDflt==0 || pDflt->op==TK_SPAN );
  94600. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  94601. pDflt = 0;
  94602. }
  94603. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  94604. ** If there is a NOT NULL constraint, then the default value for the
  94605. ** column must not be NULL.
  94606. */
  94607. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  94608. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  94609. return;
  94610. }
  94611. if( pNew->pIndex ){
  94612. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  94613. return;
  94614. }
  94615. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  94616. sqlite3ErrorMsg(pParse,
  94617. "Cannot add a REFERENCES column with non-NULL default value");
  94618. return;
  94619. }
  94620. if( pCol->notNull && !pDflt ){
  94621. sqlite3ErrorMsg(pParse,
  94622. "Cannot add a NOT NULL column with default value NULL");
  94623. return;
  94624. }
  94625. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  94626. ** can handle (i.e. not CURRENT_TIME etc.)
  94627. */
  94628. if( pDflt ){
  94629. sqlite3_value *pVal = 0;
  94630. int rc;
  94631. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  94632. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  94633. if( rc!=SQLITE_OK ){
  94634. assert( db->mallocFailed == 1 );
  94635. return;
  94636. }
  94637. if( !pVal ){
  94638. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  94639. return;
  94640. }
  94641. sqlite3ValueFree(pVal);
  94642. }
  94643. /* Modify the CREATE TABLE statement. */
  94644. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  94645. if( zCol ){
  94646. char *zEnd = &zCol[pColDef->n-1];
  94647. u32 savedDbFlags = db->mDbFlags;
  94648. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  94649. *zEnd-- = '\0';
  94650. }
  94651. db->mDbFlags |= DBFLAG_PreferBuiltin;
  94652. sqlite3NestedParse(pParse,
  94653. "UPDATE \"%w\".%s SET "
  94654. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  94655. "WHERE type = 'table' AND name = %Q",
  94656. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  94657. zTab
  94658. );
  94659. sqlite3DbFree(db, zCol);
  94660. db->mDbFlags = savedDbFlags;
  94661. }
  94662. /* Make sure the schema version is at least 3. But do not upgrade
  94663. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  94664. ** index.
  94665. */
  94666. r1 = sqlite3GetTempReg(pParse);
  94667. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  94668. sqlite3VdbeUsesBtree(v, iDb);
  94669. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  94670. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  94671. VdbeCoverage(v);
  94672. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  94673. sqlite3ReleaseTempReg(pParse, r1);
  94674. /* Reload the schema of the modified table. */
  94675. reloadTableSchema(pParse, pTab, pTab->zName);
  94676. }
  94677. /*
  94678. ** This function is called by the parser after the table-name in
  94679. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  94680. ** pSrc is the full-name of the table being altered.
  94681. **
  94682. ** This routine makes a (partial) copy of the Table structure
  94683. ** for the table being altered and sets Parse.pNewTable to point
  94684. ** to it. Routines called by the parser as the column definition
  94685. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  94686. ** the copy. The copy of the Table structure is deleted by tokenize.c
  94687. ** after parsing is finished.
  94688. **
  94689. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  94690. ** coding the "ALTER TABLE ... ADD" statement.
  94691. */
  94692. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  94693. Table *pNew;
  94694. Table *pTab;
  94695. Vdbe *v;
  94696. int iDb;
  94697. int i;
  94698. int nAlloc;
  94699. sqlite3 *db = pParse->db;
  94700. /* Look up the table being altered. */
  94701. assert( pParse->pNewTable==0 );
  94702. assert( sqlite3BtreeHoldsAllMutexes(db) );
  94703. if( db->mallocFailed ) goto exit_begin_add_column;
  94704. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  94705. if( !pTab ) goto exit_begin_add_column;
  94706. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94707. if( IsVirtual(pTab) ){
  94708. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  94709. goto exit_begin_add_column;
  94710. }
  94711. #endif
  94712. /* Make sure this is not an attempt to ALTER a view. */
  94713. if( pTab->pSelect ){
  94714. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  94715. goto exit_begin_add_column;
  94716. }
  94717. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  94718. goto exit_begin_add_column;
  94719. }
  94720. assert( pTab->addColOffset>0 );
  94721. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  94722. /* Put a copy of the Table struct in Parse.pNewTable for the
  94723. ** sqlite3AddColumn() function and friends to modify. But modify
  94724. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  94725. ** prefix, we insure that the name will not collide with an existing
  94726. ** table because user table are not allowed to have the "sqlite_"
  94727. ** prefix on their name.
  94728. */
  94729. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  94730. if( !pNew ) goto exit_begin_add_column;
  94731. pParse->pNewTable = pNew;
  94732. pNew->nTabRef = 1;
  94733. pNew->nCol = pTab->nCol;
  94734. assert( pNew->nCol>0 );
  94735. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  94736. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  94737. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  94738. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  94739. if( !pNew->aCol || !pNew->zName ){
  94740. assert( db->mallocFailed );
  94741. goto exit_begin_add_column;
  94742. }
  94743. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  94744. for(i=0; i<pNew->nCol; i++){
  94745. Column *pCol = &pNew->aCol[i];
  94746. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  94747. pCol->zColl = 0;
  94748. pCol->pDflt = 0;
  94749. }
  94750. pNew->pSchema = db->aDb[iDb].pSchema;
  94751. pNew->addColOffset = pTab->addColOffset;
  94752. pNew->nTabRef = 1;
  94753. /* Begin a transaction and increment the schema cookie. */
  94754. sqlite3BeginWriteOperation(pParse, 0, iDb);
  94755. v = sqlite3GetVdbe(pParse);
  94756. if( !v ) goto exit_begin_add_column;
  94757. sqlite3ChangeCookie(pParse, iDb);
  94758. exit_begin_add_column:
  94759. sqlite3SrcListDelete(db, pSrc);
  94760. return;
  94761. }
  94762. #endif /* SQLITE_ALTER_TABLE */
  94763. /************** End of alter.c ***********************************************/
  94764. /************** Begin file analyze.c *****************************************/
  94765. /*
  94766. ** 2005-07-08
  94767. **
  94768. ** The author disclaims copyright to this source code. In place of
  94769. ** a legal notice, here is a blessing:
  94770. **
  94771. ** May you do good and not evil.
  94772. ** May you find forgiveness for yourself and forgive others.
  94773. ** May you share freely, never taking more than you give.
  94774. **
  94775. *************************************************************************
  94776. ** This file contains code associated with the ANALYZE command.
  94777. **
  94778. ** The ANALYZE command gather statistics about the content of tables
  94779. ** and indices. These statistics are made available to the query planner
  94780. ** to help it make better decisions about how to perform queries.
  94781. **
  94782. ** The following system tables are or have been supported:
  94783. **
  94784. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  94785. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  94786. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  94787. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  94788. **
  94789. ** Additional tables might be added in future releases of SQLite.
  94790. ** The sqlite_stat2 table is not created or used unless the SQLite version
  94791. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  94792. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  94793. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  94794. ** created and used by SQLite versions 3.7.9 and later and with
  94795. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  94796. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  94797. ** version of sqlite_stat3 and is only available when compiled with
  94798. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  94799. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  94800. ** are both enabled, then STAT4 takes precedence.
  94801. **
  94802. ** For most applications, sqlite_stat1 provides all the statistics required
  94803. ** for the query planner to make good choices.
  94804. **
  94805. ** Format of sqlite_stat1:
  94806. **
  94807. ** There is normally one row per index, with the index identified by the
  94808. ** name in the idx column. The tbl column is the name of the table to
  94809. ** which the index belongs. In each such row, the stat column will be
  94810. ** a string consisting of a list of integers. The first integer in this
  94811. ** list is the number of rows in the index. (This is the same as the
  94812. ** number of rows in the table, except for partial indices.) The second
  94813. ** integer is the average number of rows in the index that have the same
  94814. ** value in the first column of the index. The third integer is the average
  94815. ** number of rows in the index that have the same value for the first two
  94816. ** columns. The N-th integer (for N>1) is the average number of rows in
  94817. ** the index which have the same value for the first N-1 columns. For
  94818. ** a K-column index, there will be K+1 integers in the stat column. If
  94819. ** the index is unique, then the last integer will be 1.
  94820. **
  94821. ** The list of integers in the stat column can optionally be followed
  94822. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  94823. ** must be separated from the last integer by a single space. If the
  94824. ** "unordered" keyword is present, then the query planner assumes that
  94825. ** the index is unordered and will not use the index for a range query.
  94826. **
  94827. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  94828. ** column contains a single integer which is the (estimated) number of
  94829. ** rows in the table identified by sqlite_stat1.tbl.
  94830. **
  94831. ** Format of sqlite_stat2:
  94832. **
  94833. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  94834. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  94835. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  94836. ** about the distribution of keys within an index. The index is identified by
  94837. ** the "idx" column and the "tbl" column is the name of the table to which
  94838. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  94839. ** table for each index.
  94840. **
  94841. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  94842. ** inclusive are samples of the left-most key value in the index taken at
  94843. ** evenly spaced points along the index. Let the number of samples be S
  94844. ** (10 in the standard build) and let C be the number of rows in the index.
  94845. ** Then the sampled rows are given by:
  94846. **
  94847. ** rownumber = (i*C*2 + C)/(S*2)
  94848. **
  94849. ** For i between 0 and S-1. Conceptually, the index space is divided into
  94850. ** S uniform buckets and the samples are the middle row from each bucket.
  94851. **
  94852. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  94853. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  94854. ** writes the sqlite_stat2 table. This version of SQLite only supports
  94855. ** sqlite_stat3.
  94856. **
  94857. ** Format for sqlite_stat3:
  94858. **
  94859. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  94860. ** sqlite_stat4 format will be described first. Further information
  94861. ** about sqlite_stat3 follows the sqlite_stat4 description.
  94862. **
  94863. ** Format for sqlite_stat4:
  94864. **
  94865. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  94866. ** to aid the query planner in choosing good indices based on the values
  94867. ** that indexed columns are compared against in the WHERE clauses of
  94868. ** queries.
  94869. **
  94870. ** The sqlite_stat4 table contains multiple entries for each index.
  94871. ** The idx column names the index and the tbl column is the table of the
  94872. ** index. If the idx and tbl columns are the same, then the sample is
  94873. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  94874. ** binary encoding of a key from the index. The nEq column is a
  94875. ** list of integers. The first integer is the approximate number
  94876. ** of entries in the index whose left-most column exactly matches
  94877. ** the left-most column of the sample. The second integer in nEq
  94878. ** is the approximate number of entries in the index where the
  94879. ** first two columns match the first two columns of the sample.
  94880. ** And so forth. nLt is another list of integers that show the approximate
  94881. ** number of entries that are strictly less than the sample. The first
  94882. ** integer in nLt contains the number of entries in the index where the
  94883. ** left-most column is less than the left-most column of the sample.
  94884. ** The K-th integer in the nLt entry is the number of index entries
  94885. ** where the first K columns are less than the first K columns of the
  94886. ** sample. The nDLt column is like nLt except that it contains the
  94887. ** number of distinct entries in the index that are less than the
  94888. ** sample.
  94889. **
  94890. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  94891. ** The ANALYZE command will typically generate sqlite_stat4 tables
  94892. ** that contain between 10 and 40 samples which are distributed across
  94893. ** the key space, though not uniformly, and which include samples with
  94894. ** large nEq values.
  94895. **
  94896. ** Format for sqlite_stat3 redux:
  94897. **
  94898. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  94899. ** looks at the left-most column of the index. The sqlite_stat3.sample
  94900. ** column contains the actual value of the left-most column instead
  94901. ** of a blob encoding of the complete index key as is found in
  94902. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  94903. ** all contain just a single integer which is the same as the first
  94904. ** integer in the equivalent columns in sqlite_stat4.
  94905. */
  94906. #ifndef SQLITE_OMIT_ANALYZE
  94907. /* #include "sqliteInt.h" */
  94908. #if defined(SQLITE_ENABLE_STAT4)
  94909. # define IsStat4 1
  94910. # define IsStat3 0
  94911. #elif defined(SQLITE_ENABLE_STAT3)
  94912. # define IsStat4 0
  94913. # define IsStat3 1
  94914. #else
  94915. # define IsStat4 0
  94916. # define IsStat3 0
  94917. # undef SQLITE_STAT4_SAMPLES
  94918. # define SQLITE_STAT4_SAMPLES 1
  94919. #endif
  94920. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  94921. /*
  94922. ** This routine generates code that opens the sqlite_statN tables.
  94923. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  94924. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  94925. ** appropriate compile-time options are provided.
  94926. **
  94927. ** If the sqlite_statN tables do not previously exist, it is created.
  94928. **
  94929. ** Argument zWhere may be a pointer to a buffer containing a table name,
  94930. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  94931. ** the sqlite_statN tables associated with the named table are deleted.
  94932. ** If zWhere==0, then code is generated to delete all stat table entries.
  94933. */
  94934. static void openStatTable(
  94935. Parse *pParse, /* Parsing context */
  94936. int iDb, /* The database we are looking in */
  94937. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  94938. const char *zWhere, /* Delete entries for this table or index */
  94939. const char *zWhereType /* Either "tbl" or "idx" */
  94940. ){
  94941. static const struct {
  94942. const char *zName;
  94943. const char *zCols;
  94944. } aTable[] = {
  94945. { "sqlite_stat1", "tbl,idx,stat" },
  94946. #if defined(SQLITE_ENABLE_STAT4)
  94947. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  94948. { "sqlite_stat3", 0 },
  94949. #elif defined(SQLITE_ENABLE_STAT3)
  94950. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  94951. { "sqlite_stat4", 0 },
  94952. #else
  94953. { "sqlite_stat3", 0 },
  94954. { "sqlite_stat4", 0 },
  94955. #endif
  94956. };
  94957. int i;
  94958. sqlite3 *db = pParse->db;
  94959. Db *pDb;
  94960. Vdbe *v = sqlite3GetVdbe(pParse);
  94961. int aRoot[ArraySize(aTable)];
  94962. u8 aCreateTbl[ArraySize(aTable)];
  94963. if( v==0 ) return;
  94964. assert( sqlite3BtreeHoldsAllMutexes(db) );
  94965. assert( sqlite3VdbeDb(v)==db );
  94966. pDb = &db->aDb[iDb];
  94967. /* Create new statistic tables if they do not exist, or clear them
  94968. ** if they do already exist.
  94969. */
  94970. for(i=0; i<ArraySize(aTable); i++){
  94971. const char *zTab = aTable[i].zName;
  94972. Table *pStat;
  94973. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  94974. if( aTable[i].zCols ){
  94975. /* The sqlite_statN table does not exist. Create it. Note that a
  94976. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  94977. ** of the new table in register pParse->regRoot. This is important
  94978. ** because the OpenWrite opcode below will be needing it. */
  94979. sqlite3NestedParse(pParse,
  94980. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  94981. );
  94982. aRoot[i] = pParse->regRoot;
  94983. aCreateTbl[i] = OPFLAG_P2ISREG;
  94984. }
  94985. }else{
  94986. /* The table already exists. If zWhere is not NULL, delete all entries
  94987. ** associated with the table zWhere. If zWhere is NULL, delete the
  94988. ** entire contents of the table. */
  94989. aRoot[i] = pStat->tnum;
  94990. aCreateTbl[i] = 0;
  94991. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  94992. if( zWhere ){
  94993. sqlite3NestedParse(pParse,
  94994. "DELETE FROM %Q.%s WHERE %s=%Q",
  94995. pDb->zDbSName, zTab, zWhereType, zWhere
  94996. );
  94997. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  94998. }else if( db->xPreUpdateCallback ){
  94999. sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
  95000. #endif
  95001. }else{
  95002. /* The sqlite_stat[134] table already exists. Delete all rows. */
  95003. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  95004. }
  95005. }
  95006. }
  95007. /* Open the sqlite_stat[134] tables for writing. */
  95008. for(i=0; aTable[i].zCols; i++){
  95009. assert( i<ArraySize(aTable) );
  95010. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  95011. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  95012. VdbeComment((v, aTable[i].zName));
  95013. }
  95014. }
  95015. /*
  95016. ** Recommended number of samples for sqlite_stat4
  95017. */
  95018. #ifndef SQLITE_STAT4_SAMPLES
  95019. # define SQLITE_STAT4_SAMPLES 24
  95020. #endif
  95021. /*
  95022. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  95023. ** share an instance of the following structure to hold their state
  95024. ** information.
  95025. */
  95026. typedef struct Stat4Accum Stat4Accum;
  95027. typedef struct Stat4Sample Stat4Sample;
  95028. struct Stat4Sample {
  95029. tRowcnt *anEq; /* sqlite_stat4.nEq */
  95030. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  95031. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95032. tRowcnt *anLt; /* sqlite_stat4.nLt */
  95033. union {
  95034. i64 iRowid; /* Rowid in main table of the key */
  95035. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  95036. } u;
  95037. u32 nRowid; /* Sizeof aRowid[] */
  95038. u8 isPSample; /* True if a periodic sample */
  95039. int iCol; /* If !isPSample, the reason for inclusion */
  95040. u32 iHash; /* Tiebreaker hash */
  95041. #endif
  95042. };
  95043. struct Stat4Accum {
  95044. tRowcnt nRow; /* Number of rows in the entire table */
  95045. tRowcnt nPSample; /* How often to do a periodic sample */
  95046. int nCol; /* Number of columns in index + pk/rowid */
  95047. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  95048. int mxSample; /* Maximum number of samples to accumulate */
  95049. Stat4Sample current; /* Current row as a Stat4Sample */
  95050. u32 iPrn; /* Pseudo-random number used for sampling */
  95051. Stat4Sample *aBest; /* Array of nCol best samples */
  95052. int iMin; /* Index in a[] of entry with minimum score */
  95053. int nSample; /* Current number of samples */
  95054. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  95055. int iGet; /* Index of current sample accessed by stat_get() */
  95056. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  95057. sqlite3 *db; /* Database connection, for malloc() */
  95058. };
  95059. /* Reclaim memory used by a Stat4Sample
  95060. */
  95061. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95062. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  95063. assert( db!=0 );
  95064. if( p->nRowid ){
  95065. sqlite3DbFree(db, p->u.aRowid);
  95066. p->nRowid = 0;
  95067. }
  95068. }
  95069. #endif
  95070. /* Initialize the BLOB value of a ROWID
  95071. */
  95072. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95073. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  95074. assert( db!=0 );
  95075. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  95076. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  95077. if( p->u.aRowid ){
  95078. p->nRowid = n;
  95079. memcpy(p->u.aRowid, pData, n);
  95080. }else{
  95081. p->nRowid = 0;
  95082. }
  95083. }
  95084. #endif
  95085. /* Initialize the INTEGER value of a ROWID.
  95086. */
  95087. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95088. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  95089. assert( db!=0 );
  95090. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  95091. p->nRowid = 0;
  95092. p->u.iRowid = iRowid;
  95093. }
  95094. #endif
  95095. /*
  95096. ** Copy the contents of object (*pFrom) into (*pTo).
  95097. */
  95098. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95099. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  95100. pTo->isPSample = pFrom->isPSample;
  95101. pTo->iCol = pFrom->iCol;
  95102. pTo->iHash = pFrom->iHash;
  95103. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  95104. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  95105. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  95106. if( pFrom->nRowid ){
  95107. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  95108. }else{
  95109. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  95110. }
  95111. }
  95112. #endif
  95113. /*
  95114. ** Reclaim all memory of a Stat4Accum structure.
  95115. */
  95116. static void stat4Destructor(void *pOld){
  95117. Stat4Accum *p = (Stat4Accum*)pOld;
  95118. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95119. int i;
  95120. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  95121. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  95122. sampleClear(p->db, &p->current);
  95123. #endif
  95124. sqlite3DbFree(p->db, p);
  95125. }
  95126. /*
  95127. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  95128. ** are:
  95129. ** N: The number of columns in the index including the rowid/pk (note 1)
  95130. ** K: The number of columns in the index excluding the rowid/pk.
  95131. ** C: The number of rows in the index (note 2)
  95132. **
  95133. ** Note 1: In the special case of the covering index that implements a
  95134. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  95135. ** total number of columns in the table.
  95136. **
  95137. ** Note 2: C is only used for STAT3 and STAT4.
  95138. **
  95139. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  95140. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  95141. ** PRIMARY KEY of the table. The covering index that implements the
  95142. ** original WITHOUT ROWID table as N==K as a special case.
  95143. **
  95144. ** This routine allocates the Stat4Accum object in heap memory. The return
  95145. ** value is a pointer to the Stat4Accum object. The datatype of the
  95146. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  95147. ** object.
  95148. */
  95149. static void statInit(
  95150. sqlite3_context *context,
  95151. int argc,
  95152. sqlite3_value **argv
  95153. ){
  95154. Stat4Accum *p;
  95155. int nCol; /* Number of columns in index being sampled */
  95156. int nKeyCol; /* Number of key columns */
  95157. int nColUp; /* nCol rounded up for alignment */
  95158. int n; /* Bytes of space to allocate */
  95159. sqlite3 *db; /* Database connection */
  95160. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95161. int mxSample = SQLITE_STAT4_SAMPLES;
  95162. #endif
  95163. /* Decode the three function arguments */
  95164. UNUSED_PARAMETER(argc);
  95165. nCol = sqlite3_value_int(argv[0]);
  95166. assert( nCol>0 );
  95167. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  95168. nKeyCol = sqlite3_value_int(argv[1]);
  95169. assert( nKeyCol<=nCol );
  95170. assert( nKeyCol>0 );
  95171. /* Allocate the space required for the Stat4Accum object */
  95172. n = sizeof(*p)
  95173. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  95174. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  95175. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95176. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  95177. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  95178. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  95179. #endif
  95180. ;
  95181. db = sqlite3_context_db_handle(context);
  95182. p = sqlite3DbMallocZero(db, n);
  95183. if( p==0 ){
  95184. sqlite3_result_error_nomem(context);
  95185. return;
  95186. }
  95187. p->db = db;
  95188. p->nRow = 0;
  95189. p->nCol = nCol;
  95190. p->nKeyCol = nKeyCol;
  95191. p->current.anDLt = (tRowcnt*)&p[1];
  95192. p->current.anEq = &p->current.anDLt[nColUp];
  95193. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95194. {
  95195. u8 *pSpace; /* Allocated space not yet assigned */
  95196. int i; /* Used to iterate through p->aSample[] */
  95197. p->iGet = -1;
  95198. p->mxSample = mxSample;
  95199. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  95200. p->current.anLt = &p->current.anEq[nColUp];
  95201. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  95202. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  95203. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  95204. p->aBest = &p->a[mxSample];
  95205. pSpace = (u8*)(&p->a[mxSample+nCol]);
  95206. for(i=0; i<(mxSample+nCol); i++){
  95207. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  95208. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  95209. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  95210. }
  95211. assert( (pSpace - (u8*)p)==n );
  95212. for(i=0; i<nCol; i++){
  95213. p->aBest[i].iCol = i;
  95214. }
  95215. }
  95216. #endif
  95217. /* Return a pointer to the allocated object to the caller. Note that
  95218. ** only the pointer (the 2nd parameter) matters. The size of the object
  95219. ** (given by the 3rd parameter) is never used and can be any positive
  95220. ** value. */
  95221. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  95222. }
  95223. static const FuncDef statInitFuncdef = {
  95224. 2+IsStat34, /* nArg */
  95225. SQLITE_UTF8, /* funcFlags */
  95226. 0, /* pUserData */
  95227. 0, /* pNext */
  95228. statInit, /* xSFunc */
  95229. 0, /* xFinalize */
  95230. "stat_init", /* zName */
  95231. {0}
  95232. };
  95233. #ifdef SQLITE_ENABLE_STAT4
  95234. /*
  95235. ** pNew and pOld are both candidate non-periodic samples selected for
  95236. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  95237. ** considering only any trailing columns and the sample hash value, this
  95238. ** function returns true if sample pNew is to be preferred over pOld.
  95239. ** In other words, if we assume that the cardinalities of the selected
  95240. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  95241. **
  95242. ** This function assumes that for each argument sample, the contents of
  95243. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  95244. */
  95245. static int sampleIsBetterPost(
  95246. Stat4Accum *pAccum,
  95247. Stat4Sample *pNew,
  95248. Stat4Sample *pOld
  95249. ){
  95250. int nCol = pAccum->nCol;
  95251. int i;
  95252. assert( pNew->iCol==pOld->iCol );
  95253. for(i=pNew->iCol+1; i<nCol; i++){
  95254. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  95255. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  95256. }
  95257. if( pNew->iHash>pOld->iHash ) return 1;
  95258. return 0;
  95259. }
  95260. #endif
  95261. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95262. /*
  95263. ** Return true if pNew is to be preferred over pOld.
  95264. **
  95265. ** This function assumes that for each argument sample, the contents of
  95266. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  95267. */
  95268. static int sampleIsBetter(
  95269. Stat4Accum *pAccum,
  95270. Stat4Sample *pNew,
  95271. Stat4Sample *pOld
  95272. ){
  95273. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  95274. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  95275. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  95276. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  95277. if( (nEqNew>nEqOld) ) return 1;
  95278. #ifdef SQLITE_ENABLE_STAT4
  95279. if( nEqNew==nEqOld ){
  95280. if( pNew->iCol<pOld->iCol ) return 1;
  95281. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  95282. }
  95283. return 0;
  95284. #else
  95285. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  95286. #endif
  95287. }
  95288. /*
  95289. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  95290. ** remove the least desirable sample from p->a[] to make room.
  95291. */
  95292. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  95293. Stat4Sample *pSample = 0;
  95294. int i;
  95295. assert( IsStat4 || nEqZero==0 );
  95296. #ifdef SQLITE_ENABLE_STAT4
  95297. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  95298. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  95299. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  95300. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  95301. if( nEqZero>p->nMaxEqZero ){
  95302. p->nMaxEqZero = nEqZero;
  95303. }
  95304. if( pNew->isPSample==0 ){
  95305. Stat4Sample *pUpgrade = 0;
  95306. assert( pNew->anEq[pNew->iCol]>0 );
  95307. /* This sample is being added because the prefix that ends in column
  95308. ** iCol occurs many times in the table. However, if we have already
  95309. ** added a sample that shares this prefix, there is no need to add
  95310. ** this one. Instead, upgrade the priority of the highest priority
  95311. ** existing sample that shares this prefix. */
  95312. for(i=p->nSample-1; i>=0; i--){
  95313. Stat4Sample *pOld = &p->a[i];
  95314. if( pOld->anEq[pNew->iCol]==0 ){
  95315. if( pOld->isPSample ) return;
  95316. assert( pOld->iCol>pNew->iCol );
  95317. assert( sampleIsBetter(p, pNew, pOld) );
  95318. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  95319. pUpgrade = pOld;
  95320. }
  95321. }
  95322. }
  95323. if( pUpgrade ){
  95324. pUpgrade->iCol = pNew->iCol;
  95325. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  95326. goto find_new_min;
  95327. }
  95328. }
  95329. #endif
  95330. /* If necessary, remove sample iMin to make room for the new sample. */
  95331. if( p->nSample>=p->mxSample ){
  95332. Stat4Sample *pMin = &p->a[p->iMin];
  95333. tRowcnt *anEq = pMin->anEq;
  95334. tRowcnt *anLt = pMin->anLt;
  95335. tRowcnt *anDLt = pMin->anDLt;
  95336. sampleClear(p->db, pMin);
  95337. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  95338. pSample = &p->a[p->nSample-1];
  95339. pSample->nRowid = 0;
  95340. pSample->anEq = anEq;
  95341. pSample->anDLt = anDLt;
  95342. pSample->anLt = anLt;
  95343. p->nSample = p->mxSample-1;
  95344. }
  95345. /* The "rows less-than" for the rowid column must be greater than that
  95346. ** for the last sample in the p->a[] array. Otherwise, the samples would
  95347. ** be out of order. */
  95348. #ifdef SQLITE_ENABLE_STAT4
  95349. assert( p->nSample==0
  95350. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  95351. #endif
  95352. /* Insert the new sample */
  95353. pSample = &p->a[p->nSample];
  95354. sampleCopy(p, pSample, pNew);
  95355. p->nSample++;
  95356. /* Zero the first nEqZero entries in the anEq[] array. */
  95357. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  95358. #ifdef SQLITE_ENABLE_STAT4
  95359. find_new_min:
  95360. #endif
  95361. if( p->nSample>=p->mxSample ){
  95362. int iMin = -1;
  95363. for(i=0; i<p->mxSample; i++){
  95364. if( p->a[i].isPSample ) continue;
  95365. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  95366. iMin = i;
  95367. }
  95368. }
  95369. assert( iMin>=0 );
  95370. p->iMin = iMin;
  95371. }
  95372. }
  95373. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  95374. /*
  95375. ** Field iChng of the index being scanned has changed. So at this point
  95376. ** p->current contains a sample that reflects the previous row of the
  95377. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  95378. ** correct at this point.
  95379. */
  95380. static void samplePushPrevious(Stat4Accum *p, int iChng){
  95381. #ifdef SQLITE_ENABLE_STAT4
  95382. int i;
  95383. /* Check if any samples from the aBest[] array should be pushed
  95384. ** into IndexSample.a[] at this point. */
  95385. for(i=(p->nCol-2); i>=iChng; i--){
  95386. Stat4Sample *pBest = &p->aBest[i];
  95387. pBest->anEq[i] = p->current.anEq[i];
  95388. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  95389. sampleInsert(p, pBest, i);
  95390. }
  95391. }
  95392. /* Check that no sample contains an anEq[] entry with an index of
  95393. ** p->nMaxEqZero or greater set to zero. */
  95394. for(i=p->nSample-1; i>=0; i--){
  95395. int j;
  95396. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  95397. }
  95398. /* Update the anEq[] fields of any samples already collected. */
  95399. if( iChng<p->nMaxEqZero ){
  95400. for(i=p->nSample-1; i>=0; i--){
  95401. int j;
  95402. for(j=iChng; j<p->nCol; j++){
  95403. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  95404. }
  95405. }
  95406. p->nMaxEqZero = iChng;
  95407. }
  95408. #endif
  95409. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  95410. if( iChng==0 ){
  95411. tRowcnt nLt = p->current.anLt[0];
  95412. tRowcnt nEq = p->current.anEq[0];
  95413. /* Check if this is to be a periodic sample. If so, add it. */
  95414. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  95415. p->current.isPSample = 1;
  95416. sampleInsert(p, &p->current, 0);
  95417. p->current.isPSample = 0;
  95418. }else
  95419. /* Or if it is a non-periodic sample. Add it in this case too. */
  95420. if( p->nSample<p->mxSample
  95421. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  95422. ){
  95423. sampleInsert(p, &p->current, 0);
  95424. }
  95425. }
  95426. #endif
  95427. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  95428. UNUSED_PARAMETER( p );
  95429. UNUSED_PARAMETER( iChng );
  95430. #endif
  95431. }
  95432. /*
  95433. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  95434. ** Arguments:
  95435. **
  95436. ** P Pointer to the Stat4Accum object created by stat_init()
  95437. ** C Index of left-most column to differ from previous row
  95438. ** R Rowid for the current row. Might be a key record for
  95439. ** WITHOUT ROWID tables.
  95440. **
  95441. ** This SQL function always returns NULL. It's purpose it to accumulate
  95442. ** statistical data and/or samples in the Stat4Accum object about the
  95443. ** index being analyzed. The stat_get() SQL function will later be used to
  95444. ** extract relevant information for constructing the sqlite_statN tables.
  95445. **
  95446. ** The R parameter is only used for STAT3 and STAT4
  95447. */
  95448. static void statPush(
  95449. sqlite3_context *context,
  95450. int argc,
  95451. sqlite3_value **argv
  95452. ){
  95453. int i;
  95454. /* The three function arguments */
  95455. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  95456. int iChng = sqlite3_value_int(argv[1]);
  95457. UNUSED_PARAMETER( argc );
  95458. UNUSED_PARAMETER( context );
  95459. assert( p->nCol>0 );
  95460. assert( iChng<p->nCol );
  95461. if( p->nRow==0 ){
  95462. /* This is the first call to this function. Do initialization. */
  95463. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  95464. }else{
  95465. /* Second and subsequent calls get processed here */
  95466. samplePushPrevious(p, iChng);
  95467. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  95468. ** to the current row of the index. */
  95469. for(i=0; i<iChng; i++){
  95470. p->current.anEq[i]++;
  95471. }
  95472. for(i=iChng; i<p->nCol; i++){
  95473. p->current.anDLt[i]++;
  95474. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95475. p->current.anLt[i] += p->current.anEq[i];
  95476. #endif
  95477. p->current.anEq[i] = 1;
  95478. }
  95479. }
  95480. p->nRow++;
  95481. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95482. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  95483. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  95484. }else{
  95485. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  95486. sqlite3_value_blob(argv[2]));
  95487. }
  95488. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  95489. #endif
  95490. #ifdef SQLITE_ENABLE_STAT4
  95491. {
  95492. tRowcnt nLt = p->current.anLt[p->nCol-1];
  95493. /* Check if this is to be a periodic sample. If so, add it. */
  95494. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  95495. p->current.isPSample = 1;
  95496. p->current.iCol = 0;
  95497. sampleInsert(p, &p->current, p->nCol-1);
  95498. p->current.isPSample = 0;
  95499. }
  95500. /* Update the aBest[] array. */
  95501. for(i=0; i<(p->nCol-1); i++){
  95502. p->current.iCol = i;
  95503. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  95504. sampleCopy(p, &p->aBest[i], &p->current);
  95505. }
  95506. }
  95507. }
  95508. #endif
  95509. }
  95510. static const FuncDef statPushFuncdef = {
  95511. 2+IsStat34, /* nArg */
  95512. SQLITE_UTF8, /* funcFlags */
  95513. 0, /* pUserData */
  95514. 0, /* pNext */
  95515. statPush, /* xSFunc */
  95516. 0, /* xFinalize */
  95517. "stat_push", /* zName */
  95518. {0}
  95519. };
  95520. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  95521. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  95522. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  95523. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  95524. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  95525. /*
  95526. ** Implementation of the stat_get(P,J) SQL function. This routine is
  95527. ** used to query statistical information that has been gathered into
  95528. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  95529. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  95530. ** The content to returned is determined by the parameter J
  95531. ** which is one of the STAT_GET_xxxx values defined above.
  95532. **
  95533. ** The stat_get(P,J) function is not available to generic SQL. It is
  95534. ** inserted as part of a manually constructed bytecode program. (See
  95535. ** the callStatGet() routine below.) It is guaranteed that the P
  95536. ** parameter will always be a poiner to a Stat4Accum object, never a
  95537. ** NULL.
  95538. **
  95539. ** If neither STAT3 nor STAT4 are enabled, then J is always
  95540. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  95541. ** a one-parameter function, stat_get(P), that always returns the
  95542. ** stat1 table entry information.
  95543. */
  95544. static void statGet(
  95545. sqlite3_context *context,
  95546. int argc,
  95547. sqlite3_value **argv
  95548. ){
  95549. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  95550. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95551. /* STAT3 and STAT4 have a parameter on this routine. */
  95552. int eCall = sqlite3_value_int(argv[1]);
  95553. assert( argc==2 );
  95554. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  95555. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  95556. || eCall==STAT_GET_NDLT
  95557. );
  95558. if( eCall==STAT_GET_STAT1 )
  95559. #else
  95560. assert( argc==1 );
  95561. #endif
  95562. {
  95563. /* Return the value to store in the "stat" column of the sqlite_stat1
  95564. ** table for this index.
  95565. **
  95566. ** The value is a string composed of a list of integers describing
  95567. ** the index. The first integer in the list is the total number of
  95568. ** entries in the index. There is one additional integer in the list
  95569. ** for each indexed column. This additional integer is an estimate of
  95570. ** the number of rows matched by a stabbing query on the index using
  95571. ** a key with the corresponding number of fields. In other words,
  95572. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  95573. ** "100 10 2", then SQLite estimates that:
  95574. **
  95575. ** * the index contains 100 rows,
  95576. ** * "WHERE a=?" matches 10 rows, and
  95577. ** * "WHERE a=? AND b=?" matches 2 rows.
  95578. **
  95579. ** If D is the count of distinct values and K is the total number of
  95580. ** rows, then each estimate is computed as:
  95581. **
  95582. ** I = (K+D-1)/D
  95583. */
  95584. char *z;
  95585. int i;
  95586. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  95587. if( zRet==0 ){
  95588. sqlite3_result_error_nomem(context);
  95589. return;
  95590. }
  95591. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  95592. z = zRet + sqlite3Strlen30(zRet);
  95593. for(i=0; i<p->nKeyCol; i++){
  95594. u64 nDistinct = p->current.anDLt[i] + 1;
  95595. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  95596. sqlite3_snprintf(24, z, " %llu", iVal);
  95597. z += sqlite3Strlen30(z);
  95598. assert( p->current.anEq[i] );
  95599. }
  95600. assert( z[0]=='\0' && z>zRet );
  95601. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  95602. }
  95603. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95604. else if( eCall==STAT_GET_ROWID ){
  95605. if( p->iGet<0 ){
  95606. samplePushPrevious(p, 0);
  95607. p->iGet = 0;
  95608. }
  95609. if( p->iGet<p->nSample ){
  95610. Stat4Sample *pS = p->a + p->iGet;
  95611. if( pS->nRowid==0 ){
  95612. sqlite3_result_int64(context, pS->u.iRowid);
  95613. }else{
  95614. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  95615. SQLITE_TRANSIENT);
  95616. }
  95617. }
  95618. }else{
  95619. tRowcnt *aCnt = 0;
  95620. assert( p->iGet<p->nSample );
  95621. switch( eCall ){
  95622. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  95623. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  95624. default: {
  95625. aCnt = p->a[p->iGet].anDLt;
  95626. p->iGet++;
  95627. break;
  95628. }
  95629. }
  95630. if( IsStat3 ){
  95631. sqlite3_result_int64(context, (i64)aCnt[0]);
  95632. }else{
  95633. char *zRet = sqlite3MallocZero(p->nCol * 25);
  95634. if( zRet==0 ){
  95635. sqlite3_result_error_nomem(context);
  95636. }else{
  95637. int i;
  95638. char *z = zRet;
  95639. for(i=0; i<p->nCol; i++){
  95640. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  95641. z += sqlite3Strlen30(z);
  95642. }
  95643. assert( z[0]=='\0' && z>zRet );
  95644. z[-1] = '\0';
  95645. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  95646. }
  95647. }
  95648. }
  95649. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  95650. #ifndef SQLITE_DEBUG
  95651. UNUSED_PARAMETER( argc );
  95652. #endif
  95653. }
  95654. static const FuncDef statGetFuncdef = {
  95655. 1+IsStat34, /* nArg */
  95656. SQLITE_UTF8, /* funcFlags */
  95657. 0, /* pUserData */
  95658. 0, /* pNext */
  95659. statGet, /* xSFunc */
  95660. 0, /* xFinalize */
  95661. "stat_get", /* zName */
  95662. {0}
  95663. };
  95664. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  95665. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  95666. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95667. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  95668. #elif SQLITE_DEBUG
  95669. assert( iParam==STAT_GET_STAT1 );
  95670. #else
  95671. UNUSED_PARAMETER( iParam );
  95672. #endif
  95673. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  95674. (char*)&statGetFuncdef, P4_FUNCDEF);
  95675. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  95676. }
  95677. /*
  95678. ** Generate code to do an analysis of all indices associated with
  95679. ** a single table.
  95680. */
  95681. static void analyzeOneTable(
  95682. Parse *pParse, /* Parser context */
  95683. Table *pTab, /* Table whose indices are to be analyzed */
  95684. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  95685. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  95686. int iMem, /* Available memory locations begin here */
  95687. int iTab /* Next available cursor */
  95688. ){
  95689. sqlite3 *db = pParse->db; /* Database handle */
  95690. Index *pIdx; /* An index to being analyzed */
  95691. int iIdxCur; /* Cursor open on index being analyzed */
  95692. int iTabCur; /* Table cursor */
  95693. Vdbe *v; /* The virtual machine being built up */
  95694. int i; /* Loop counter */
  95695. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  95696. int iDb; /* Index of database containing pTab */
  95697. u8 needTableCnt = 1; /* True to count the table */
  95698. int regNewRowid = iMem++; /* Rowid for the inserted record */
  95699. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  95700. int regChng = iMem++; /* Index of changed index field */
  95701. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95702. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  95703. #endif
  95704. int regTemp = iMem++; /* Temporary use register */
  95705. int regTabname = iMem++; /* Register containing table name */
  95706. int regIdxname = iMem++; /* Register containing index name */
  95707. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  95708. int regPrev = iMem; /* MUST BE LAST (see below) */
  95709. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  95710. Table *pStat1 = 0;
  95711. #endif
  95712. pParse->nMem = MAX(pParse->nMem, iMem);
  95713. v = sqlite3GetVdbe(pParse);
  95714. if( v==0 || NEVER(pTab==0) ){
  95715. return;
  95716. }
  95717. if( pTab->tnum==0 ){
  95718. /* Do not gather statistics on views or virtual tables */
  95719. return;
  95720. }
  95721. if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
  95722. /* Do not gather statistics on system tables */
  95723. return;
  95724. }
  95725. assert( sqlite3BtreeHoldsAllMutexes(db) );
  95726. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95727. assert( iDb>=0 );
  95728. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95729. #ifndef SQLITE_OMIT_AUTHORIZATION
  95730. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  95731. db->aDb[iDb].zDbSName ) ){
  95732. return;
  95733. }
  95734. #endif
  95735. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  95736. if( db->xPreUpdateCallback ){
  95737. pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
  95738. if( pStat1==0 ) return;
  95739. pStat1->zName = (char*)&pStat1[1];
  95740. memcpy(pStat1->zName, "sqlite_stat1", 13);
  95741. pStat1->nCol = 3;
  95742. pStat1->iPKey = -1;
  95743. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
  95744. }
  95745. #endif
  95746. /* Establish a read-lock on the table at the shared-cache level.
  95747. ** Open a read-only cursor on the table. Also allocate a cursor number
  95748. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  95749. ** this time though. */
  95750. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  95751. iTabCur = iTab++;
  95752. iIdxCur = iTab++;
  95753. pParse->nTab = MAX(pParse->nTab, iTab);
  95754. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  95755. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  95756. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95757. int nCol; /* Number of columns in pIdx. "N" */
  95758. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  95759. int addrNextRow; /* Address of "next_row:" */
  95760. const char *zIdxName; /* Name of the index */
  95761. int nColTest; /* Number of columns to test for changes */
  95762. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  95763. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  95764. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  95765. nCol = pIdx->nKeyCol;
  95766. zIdxName = pTab->zName;
  95767. nColTest = nCol - 1;
  95768. }else{
  95769. nCol = pIdx->nColumn;
  95770. zIdxName = pIdx->zName;
  95771. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  95772. }
  95773. /* Populate the register containing the index name. */
  95774. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  95775. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  95776. /*
  95777. ** Pseudo-code for loop that calls stat_push():
  95778. **
  95779. ** Rewind csr
  95780. ** if eof(csr) goto end_of_scan;
  95781. ** regChng = 0
  95782. ** goto chng_addr_0;
  95783. **
  95784. ** next_row:
  95785. ** regChng = 0
  95786. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  95787. ** regChng = 1
  95788. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  95789. ** ...
  95790. ** regChng = N
  95791. ** goto chng_addr_N
  95792. **
  95793. ** chng_addr_0:
  95794. ** regPrev(0) = idx(0)
  95795. ** chng_addr_1:
  95796. ** regPrev(1) = idx(1)
  95797. ** ...
  95798. **
  95799. ** endDistinctTest:
  95800. ** regRowid = idx(rowid)
  95801. ** stat_push(P, regChng, regRowid)
  95802. ** Next csr
  95803. ** if !eof(csr) goto next_row;
  95804. **
  95805. ** end_of_scan:
  95806. */
  95807. /* Make sure there are enough memory cells allocated to accommodate
  95808. ** the regPrev array and a trailing rowid (the rowid slot is required
  95809. ** when building a record to insert into the sample column of
  95810. ** the sqlite_stat4 table. */
  95811. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  95812. /* Open a read-only cursor on the index being analyzed. */
  95813. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  95814. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  95815. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  95816. VdbeComment((v, "%s", pIdx->zName));
  95817. /* Invoke the stat_init() function. The arguments are:
  95818. **
  95819. ** (1) the number of columns in the index including the rowid
  95820. ** (or for a WITHOUT ROWID table, the number of PK columns),
  95821. ** (2) the number of columns in the key without the rowid/pk
  95822. ** (3) the number of rows in the index,
  95823. **
  95824. **
  95825. ** The third argument is only used for STAT3 and STAT4
  95826. */
  95827. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95828. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  95829. #endif
  95830. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  95831. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  95832. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  95833. (char*)&statInitFuncdef, P4_FUNCDEF);
  95834. sqlite3VdbeChangeP5(v, 2+IsStat34);
  95835. /* Implementation of the following:
  95836. **
  95837. ** Rewind csr
  95838. ** if eof(csr) goto end_of_scan;
  95839. ** regChng = 0
  95840. ** goto next_push_0;
  95841. **
  95842. */
  95843. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  95844. VdbeCoverage(v);
  95845. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  95846. addrNextRow = sqlite3VdbeCurrentAddr(v);
  95847. if( nColTest>0 ){
  95848. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  95849. int *aGotoChng; /* Array of jump instruction addresses */
  95850. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  95851. if( aGotoChng==0 ) continue;
  95852. /*
  95853. ** next_row:
  95854. ** regChng = 0
  95855. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  95856. ** regChng = 1
  95857. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  95858. ** ...
  95859. ** regChng = N
  95860. ** goto endDistinctTest
  95861. */
  95862. sqlite3VdbeAddOp0(v, OP_Goto);
  95863. addrNextRow = sqlite3VdbeCurrentAddr(v);
  95864. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  95865. /* For a single-column UNIQUE index, once we have found a non-NULL
  95866. ** row, we know that all the rest will be distinct, so skip
  95867. ** subsequent distinctness tests. */
  95868. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  95869. VdbeCoverage(v);
  95870. }
  95871. for(i=0; i<nColTest; i++){
  95872. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  95873. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  95874. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  95875. aGotoChng[i] =
  95876. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  95877. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  95878. VdbeCoverage(v);
  95879. }
  95880. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  95881. sqlite3VdbeGoto(v, endDistinctTest);
  95882. /*
  95883. ** chng_addr_0:
  95884. ** regPrev(0) = idx(0)
  95885. ** chng_addr_1:
  95886. ** regPrev(1) = idx(1)
  95887. ** ...
  95888. */
  95889. sqlite3VdbeJumpHere(v, addrNextRow-1);
  95890. for(i=0; i<nColTest; i++){
  95891. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  95892. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  95893. }
  95894. sqlite3VdbeResolveLabel(v, endDistinctTest);
  95895. sqlite3DbFree(db, aGotoChng);
  95896. }
  95897. /*
  95898. ** chng_addr_N:
  95899. ** regRowid = idx(rowid) // STAT34 only
  95900. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  95901. ** Next csr
  95902. ** if !eof(csr) goto next_row;
  95903. */
  95904. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95905. assert( regRowid==(regStat4+2) );
  95906. if( HasRowid(pTab) ){
  95907. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  95908. }else{
  95909. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  95910. int j, k, regKey;
  95911. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  95912. for(j=0; j<pPk->nKeyCol; j++){
  95913. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  95914. assert( k>=0 && k<pIdx->nColumn );
  95915. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  95916. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  95917. }
  95918. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  95919. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  95920. }
  95921. #endif
  95922. assert( regChng==(regStat4+1) );
  95923. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  95924. (char*)&statPushFuncdef, P4_FUNCDEF);
  95925. sqlite3VdbeChangeP5(v, 2+IsStat34);
  95926. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  95927. /* Add the entry to the stat1 table. */
  95928. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  95929. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  95930. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  95931. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  95932. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  95933. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  95934. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  95935. #endif
  95936. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95937. /* Add the entries to the stat3 or stat4 table. */
  95938. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95939. {
  95940. int regEq = regStat1;
  95941. int regLt = regStat1+1;
  95942. int regDLt = regStat1+2;
  95943. int regSample = regStat1+3;
  95944. int regCol = regStat1+4;
  95945. int regSampleRowid = regCol + nCol;
  95946. int addrNext;
  95947. int addrIsNull;
  95948. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  95949. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  95950. addrNext = sqlite3VdbeCurrentAddr(v);
  95951. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  95952. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  95953. VdbeCoverage(v);
  95954. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  95955. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  95956. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  95957. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  95958. /* We know that the regSampleRowid row exists because it was read by
  95959. ** the previous loop. Thus the not-found jump of seekOp will never
  95960. ** be taken */
  95961. VdbeCoverageNeverTaken(v);
  95962. #ifdef SQLITE_ENABLE_STAT3
  95963. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  95964. #else
  95965. for(i=0; i<nCol; i++){
  95966. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  95967. }
  95968. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  95969. #endif
  95970. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  95971. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  95972. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  95973. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  95974. sqlite3VdbeJumpHere(v, addrIsNull);
  95975. }
  95976. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  95977. /* End of analysis */
  95978. sqlite3VdbeJumpHere(v, addrRewind);
  95979. }
  95980. /* Create a single sqlite_stat1 entry containing NULL as the index
  95981. ** name and the row count as the content.
  95982. */
  95983. if( pOnlyIdx==0 && needTableCnt ){
  95984. VdbeComment((v, "%s", pTab->zName));
  95985. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  95986. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  95987. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  95988. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  95989. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  95990. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  95991. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  95992. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95993. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  95994. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  95995. #endif
  95996. sqlite3VdbeJumpHere(v, jZeroRows);
  95997. }
  95998. }
  95999. /*
  96000. ** Generate code that will cause the most recent index analysis to
  96001. ** be loaded into internal hash tables where is can be used.
  96002. */
  96003. static void loadAnalysis(Parse *pParse, int iDb){
  96004. Vdbe *v = sqlite3GetVdbe(pParse);
  96005. if( v ){
  96006. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  96007. }
  96008. }
  96009. /*
  96010. ** Generate code that will do an analysis of an entire database
  96011. */
  96012. static void analyzeDatabase(Parse *pParse, int iDb){
  96013. sqlite3 *db = pParse->db;
  96014. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  96015. HashElem *k;
  96016. int iStatCur;
  96017. int iMem;
  96018. int iTab;
  96019. sqlite3BeginWriteOperation(pParse, 0, iDb);
  96020. iStatCur = pParse->nTab;
  96021. pParse->nTab += 3;
  96022. openStatTable(pParse, iDb, iStatCur, 0, 0);
  96023. iMem = pParse->nMem+1;
  96024. iTab = pParse->nTab;
  96025. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96026. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  96027. Table *pTab = (Table*)sqliteHashData(k);
  96028. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  96029. }
  96030. loadAnalysis(pParse, iDb);
  96031. }
  96032. /*
  96033. ** Generate code that will do an analysis of a single table in
  96034. ** a database. If pOnlyIdx is not NULL then it is a single index
  96035. ** in pTab that should be analyzed.
  96036. */
  96037. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  96038. int iDb;
  96039. int iStatCur;
  96040. assert( pTab!=0 );
  96041. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  96042. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  96043. sqlite3BeginWriteOperation(pParse, 0, iDb);
  96044. iStatCur = pParse->nTab;
  96045. pParse->nTab += 3;
  96046. if( pOnlyIdx ){
  96047. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  96048. }else{
  96049. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  96050. }
  96051. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  96052. loadAnalysis(pParse, iDb);
  96053. }
  96054. /*
  96055. ** Generate code for the ANALYZE command. The parser calls this routine
  96056. ** when it recognizes an ANALYZE command.
  96057. **
  96058. ** ANALYZE -- 1
  96059. ** ANALYZE <database> -- 2
  96060. ** ANALYZE ?<database>.?<tablename> -- 3
  96061. **
  96062. ** Form 1 causes all indices in all attached databases to be analyzed.
  96063. ** Form 2 analyzes all indices the single database named.
  96064. ** Form 3 analyzes all indices associated with the named table.
  96065. */
  96066. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  96067. sqlite3 *db = pParse->db;
  96068. int iDb;
  96069. int i;
  96070. char *z, *zDb;
  96071. Table *pTab;
  96072. Index *pIdx;
  96073. Token *pTableName;
  96074. Vdbe *v;
  96075. /* Read the database schema. If an error occurs, leave an error message
  96076. ** and code in pParse and return NULL. */
  96077. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  96078. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  96079. return;
  96080. }
  96081. assert( pName2!=0 || pName1==0 );
  96082. if( pName1==0 ){
  96083. /* Form 1: Analyze everything */
  96084. for(i=0; i<db->nDb; i++){
  96085. if( i==1 ) continue; /* Do not analyze the TEMP database */
  96086. analyzeDatabase(pParse, i);
  96087. }
  96088. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  96089. /* Analyze the schema named as the argument */
  96090. analyzeDatabase(pParse, iDb);
  96091. }else{
  96092. /* Form 3: Analyze the table or index named as an argument */
  96093. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  96094. if( iDb>=0 ){
  96095. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  96096. z = sqlite3NameFromToken(db, pTableName);
  96097. if( z ){
  96098. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  96099. analyzeTable(pParse, pIdx->pTable, pIdx);
  96100. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  96101. analyzeTable(pParse, pTab, 0);
  96102. }
  96103. sqlite3DbFree(db, z);
  96104. }
  96105. }
  96106. }
  96107. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  96108. sqlite3VdbeAddOp0(v, OP_Expire);
  96109. }
  96110. }
  96111. /*
  96112. ** Used to pass information from the analyzer reader through to the
  96113. ** callback routine.
  96114. */
  96115. typedef struct analysisInfo analysisInfo;
  96116. struct analysisInfo {
  96117. sqlite3 *db;
  96118. const char *zDatabase;
  96119. };
  96120. /*
  96121. ** The first argument points to a nul-terminated string containing a
  96122. ** list of space separated integers. Read the first nOut of these into
  96123. ** the array aOut[].
  96124. */
  96125. static void decodeIntArray(
  96126. char *zIntArray, /* String containing int array to decode */
  96127. int nOut, /* Number of slots in aOut[] */
  96128. tRowcnt *aOut, /* Store integers here */
  96129. LogEst *aLog, /* Or, if aOut==0, here */
  96130. Index *pIndex /* Handle extra flags for this index, if not NULL */
  96131. ){
  96132. char *z = zIntArray;
  96133. int c;
  96134. int i;
  96135. tRowcnt v;
  96136. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96137. if( z==0 ) z = "";
  96138. #else
  96139. assert( z!=0 );
  96140. #endif
  96141. for(i=0; *z && i<nOut; i++){
  96142. v = 0;
  96143. while( (c=z[0])>='0' && c<='9' ){
  96144. v = v*10 + c - '0';
  96145. z++;
  96146. }
  96147. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96148. if( aOut ) aOut[i] = v;
  96149. if( aLog ) aLog[i] = sqlite3LogEst(v);
  96150. #else
  96151. assert( aOut==0 );
  96152. UNUSED_PARAMETER(aOut);
  96153. assert( aLog!=0 );
  96154. aLog[i] = sqlite3LogEst(v);
  96155. #endif
  96156. if( *z==' ' ) z++;
  96157. }
  96158. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  96159. assert( pIndex!=0 ); {
  96160. #else
  96161. if( pIndex ){
  96162. #endif
  96163. pIndex->bUnordered = 0;
  96164. pIndex->noSkipScan = 0;
  96165. while( z[0] ){
  96166. if( sqlite3_strglob("unordered*", z)==0 ){
  96167. pIndex->bUnordered = 1;
  96168. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  96169. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  96170. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  96171. pIndex->noSkipScan = 1;
  96172. }
  96173. #ifdef SQLITE_ENABLE_COSTMULT
  96174. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  96175. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  96176. }
  96177. #endif
  96178. while( z[0]!=0 && z[0]!=' ' ) z++;
  96179. while( z[0]==' ' ) z++;
  96180. }
  96181. }
  96182. }
  96183. /*
  96184. ** This callback is invoked once for each index when reading the
  96185. ** sqlite_stat1 table.
  96186. **
  96187. ** argv[0] = name of the table
  96188. ** argv[1] = name of the index (might be NULL)
  96189. ** argv[2] = results of analysis - on integer for each column
  96190. **
  96191. ** Entries for which argv[1]==NULL simply record the number of rows in
  96192. ** the table.
  96193. */
  96194. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  96195. analysisInfo *pInfo = (analysisInfo*)pData;
  96196. Index *pIndex;
  96197. Table *pTable;
  96198. const char *z;
  96199. assert( argc==3 );
  96200. UNUSED_PARAMETER2(NotUsed, argc);
  96201. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  96202. return 0;
  96203. }
  96204. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  96205. if( pTable==0 ){
  96206. return 0;
  96207. }
  96208. if( argv[1]==0 ){
  96209. pIndex = 0;
  96210. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  96211. pIndex = sqlite3PrimaryKeyIndex(pTable);
  96212. }else{
  96213. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  96214. }
  96215. z = argv[2];
  96216. if( pIndex ){
  96217. tRowcnt *aiRowEst = 0;
  96218. int nCol = pIndex->nKeyCol+1;
  96219. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96220. /* Index.aiRowEst may already be set here if there are duplicate
  96221. ** sqlite_stat1 entries for this index. In that case just clobber
  96222. ** the old data with the new instead of allocating a new array. */
  96223. if( pIndex->aiRowEst==0 ){
  96224. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  96225. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  96226. }
  96227. aiRowEst = pIndex->aiRowEst;
  96228. #endif
  96229. pIndex->bUnordered = 0;
  96230. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  96231. pIndex->hasStat1 = 1;
  96232. if( pIndex->pPartIdxWhere==0 ){
  96233. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  96234. pTable->tabFlags |= TF_HasStat1;
  96235. }
  96236. }else{
  96237. Index fakeIdx;
  96238. fakeIdx.szIdxRow = pTable->szTabRow;
  96239. #ifdef SQLITE_ENABLE_COSTMULT
  96240. fakeIdx.pTable = pTable;
  96241. #endif
  96242. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  96243. pTable->szTabRow = fakeIdx.szIdxRow;
  96244. pTable->tabFlags |= TF_HasStat1;
  96245. }
  96246. return 0;
  96247. }
  96248. /*
  96249. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  96250. ** and its contents.
  96251. */
  96252. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  96253. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96254. if( pIdx->aSample ){
  96255. int j;
  96256. for(j=0; j<pIdx->nSample; j++){
  96257. IndexSample *p = &pIdx->aSample[j];
  96258. sqlite3DbFree(db, p->p);
  96259. }
  96260. sqlite3DbFree(db, pIdx->aSample);
  96261. }
  96262. if( db && db->pnBytesFreed==0 ){
  96263. pIdx->nSample = 0;
  96264. pIdx->aSample = 0;
  96265. }
  96266. #else
  96267. UNUSED_PARAMETER(db);
  96268. UNUSED_PARAMETER(pIdx);
  96269. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  96270. }
  96271. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96272. /*
  96273. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  96274. ** stored in pIdx->aSample[].
  96275. */
  96276. static void initAvgEq(Index *pIdx){
  96277. if( pIdx ){
  96278. IndexSample *aSample = pIdx->aSample;
  96279. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  96280. int iCol;
  96281. int nCol = 1;
  96282. if( pIdx->nSampleCol>1 ){
  96283. /* If this is stat4 data, then calculate aAvgEq[] values for all
  96284. ** sample columns except the last. The last is always set to 1, as
  96285. ** once the trailing PK fields are considered all index keys are
  96286. ** unique. */
  96287. nCol = pIdx->nSampleCol-1;
  96288. pIdx->aAvgEq[nCol] = 1;
  96289. }
  96290. for(iCol=0; iCol<nCol; iCol++){
  96291. int nSample = pIdx->nSample;
  96292. int i; /* Used to iterate through samples */
  96293. tRowcnt sumEq = 0; /* Sum of the nEq values */
  96294. tRowcnt avgEq = 0;
  96295. tRowcnt nRow; /* Number of rows in index */
  96296. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  96297. i64 nDist100; /* Number of distinct values in index */
  96298. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  96299. nRow = pFinal->anLt[iCol];
  96300. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  96301. nSample--;
  96302. }else{
  96303. nRow = pIdx->aiRowEst[0];
  96304. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  96305. }
  96306. pIdx->nRowEst0 = nRow;
  96307. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  96308. ** occur in the stat4 table for this index. Set sumEq to the sum of
  96309. ** the nEq values for column iCol for the same set (adding the value
  96310. ** only once where there exist duplicate prefixes). */
  96311. for(i=0; i<nSample; i++){
  96312. if( i==(pIdx->nSample-1)
  96313. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  96314. ){
  96315. sumEq += aSample[i].anEq[iCol];
  96316. nSum100 += 100;
  96317. }
  96318. }
  96319. if( nDist100>nSum100 && sumEq<nRow ){
  96320. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  96321. }
  96322. if( avgEq==0 ) avgEq = 1;
  96323. pIdx->aAvgEq[iCol] = avgEq;
  96324. }
  96325. }
  96326. }
  96327. /*
  96328. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  96329. ** is supplied instead, find the PRIMARY KEY index for that table.
  96330. */
  96331. static Index *findIndexOrPrimaryKey(
  96332. sqlite3 *db,
  96333. const char *zName,
  96334. const char *zDb
  96335. ){
  96336. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  96337. if( pIdx==0 ){
  96338. Table *pTab = sqlite3FindTable(db, zName, zDb);
  96339. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  96340. }
  96341. return pIdx;
  96342. }
  96343. /*
  96344. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  96345. ** into the relevant Index.aSample[] arrays.
  96346. **
  96347. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  96348. ** data equivalent to the following (statements are different for stat3,
  96349. ** see the caller of this function for details):
  96350. **
  96351. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  96352. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  96353. **
  96354. ** where %Q is replaced with the database name before the SQL is executed.
  96355. */
  96356. static int loadStatTbl(
  96357. sqlite3 *db, /* Database handle */
  96358. int bStat3, /* Assume single column records only */
  96359. const char *zSql1, /* SQL statement 1 (see above) */
  96360. const char *zSql2, /* SQL statement 2 (see above) */
  96361. const char *zDb /* Database name (e.g. "main") */
  96362. ){
  96363. int rc; /* Result codes from subroutines */
  96364. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  96365. char *zSql; /* Text of the SQL statement */
  96366. Index *pPrevIdx = 0; /* Previous index in the loop */
  96367. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  96368. assert( db->lookaside.bDisable );
  96369. zSql = sqlite3MPrintf(db, zSql1, zDb);
  96370. if( !zSql ){
  96371. return SQLITE_NOMEM_BKPT;
  96372. }
  96373. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  96374. sqlite3DbFree(db, zSql);
  96375. if( rc ) return rc;
  96376. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  96377. int nIdxCol = 1; /* Number of columns in stat4 records */
  96378. char *zIndex; /* Index name */
  96379. Index *pIdx; /* Pointer to the index object */
  96380. int nSample; /* Number of samples */
  96381. int nByte; /* Bytes of space required */
  96382. int i; /* Bytes of space required */
  96383. tRowcnt *pSpace;
  96384. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  96385. if( zIndex==0 ) continue;
  96386. nSample = sqlite3_column_int(pStmt, 1);
  96387. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  96388. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  96389. /* Index.nSample is non-zero at this point if data has already been
  96390. ** loaded from the stat4 table. In this case ignore stat3 data. */
  96391. if( pIdx==0 || pIdx->nSample ) continue;
  96392. if( bStat3==0 ){
  96393. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  96394. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  96395. nIdxCol = pIdx->nKeyCol;
  96396. }else{
  96397. nIdxCol = pIdx->nColumn;
  96398. }
  96399. }
  96400. pIdx->nSampleCol = nIdxCol;
  96401. nByte = sizeof(IndexSample) * nSample;
  96402. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  96403. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  96404. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  96405. if( pIdx->aSample==0 ){
  96406. sqlite3_finalize(pStmt);
  96407. return SQLITE_NOMEM_BKPT;
  96408. }
  96409. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  96410. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  96411. for(i=0; i<nSample; i++){
  96412. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  96413. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  96414. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  96415. }
  96416. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  96417. }
  96418. rc = sqlite3_finalize(pStmt);
  96419. if( rc ) return rc;
  96420. zSql = sqlite3MPrintf(db, zSql2, zDb);
  96421. if( !zSql ){
  96422. return SQLITE_NOMEM_BKPT;
  96423. }
  96424. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  96425. sqlite3DbFree(db, zSql);
  96426. if( rc ) return rc;
  96427. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  96428. char *zIndex; /* Index name */
  96429. Index *pIdx; /* Pointer to the index object */
  96430. int nCol = 1; /* Number of columns in index */
  96431. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  96432. if( zIndex==0 ) continue;
  96433. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  96434. if( pIdx==0 ) continue;
  96435. /* This next condition is true if data has already been loaded from
  96436. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  96437. nCol = pIdx->nSampleCol;
  96438. if( bStat3 && nCol>1 ) continue;
  96439. if( pIdx!=pPrevIdx ){
  96440. initAvgEq(pPrevIdx);
  96441. pPrevIdx = pIdx;
  96442. }
  96443. pSample = &pIdx->aSample[pIdx->nSample];
  96444. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  96445. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  96446. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  96447. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  96448. ** This is in case the sample record is corrupted. In that case, the
  96449. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  96450. ** end of the allocated buffer before it realizes it is dealing with
  96451. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  96452. ** a buffer overread. */
  96453. pSample->n = sqlite3_column_bytes(pStmt, 4);
  96454. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  96455. if( pSample->p==0 ){
  96456. sqlite3_finalize(pStmt);
  96457. return SQLITE_NOMEM_BKPT;
  96458. }
  96459. if( pSample->n ){
  96460. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  96461. }
  96462. pIdx->nSample++;
  96463. }
  96464. rc = sqlite3_finalize(pStmt);
  96465. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  96466. return rc;
  96467. }
  96468. /*
  96469. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  96470. ** the Index.aSample[] arrays of all indices.
  96471. */
  96472. static int loadStat4(sqlite3 *db, const char *zDb){
  96473. int rc = SQLITE_OK; /* Result codes from subroutines */
  96474. assert( db->lookaside.bDisable );
  96475. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  96476. rc = loadStatTbl(db, 0,
  96477. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  96478. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  96479. zDb
  96480. );
  96481. }
  96482. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  96483. rc = loadStatTbl(db, 1,
  96484. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  96485. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  96486. zDb
  96487. );
  96488. }
  96489. return rc;
  96490. }
  96491. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  96492. /*
  96493. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  96494. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  96495. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  96496. ** Index.aSample[] arrays.
  96497. **
  96498. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  96499. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  96500. ** during compilation and the sqlite_stat3/4 table is present, no data is
  96501. ** read from it.
  96502. **
  96503. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  96504. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  96505. ** returned. However, in this case, data is read from the sqlite_stat1
  96506. ** table (if it is present) before returning.
  96507. **
  96508. ** If an OOM error occurs, this function always sets db->mallocFailed.
  96509. ** This means if the caller does not care about other errors, the return
  96510. ** code may be ignored.
  96511. */
  96512. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  96513. analysisInfo sInfo;
  96514. HashElem *i;
  96515. char *zSql;
  96516. int rc = SQLITE_OK;
  96517. Schema *pSchema = db->aDb[iDb].pSchema;
  96518. assert( iDb>=0 && iDb<db->nDb );
  96519. assert( db->aDb[iDb].pBt!=0 );
  96520. /* Clear any prior statistics */
  96521. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96522. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  96523. Table *pTab = sqliteHashData(i);
  96524. pTab->tabFlags &= ~TF_HasStat1;
  96525. }
  96526. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  96527. Index *pIdx = sqliteHashData(i);
  96528. pIdx->hasStat1 = 0;
  96529. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96530. sqlite3DeleteIndexSamples(db, pIdx);
  96531. pIdx->aSample = 0;
  96532. #endif
  96533. }
  96534. /* Load new statistics out of the sqlite_stat1 table */
  96535. sInfo.db = db;
  96536. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  96537. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  96538. zSql = sqlite3MPrintf(db,
  96539. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  96540. if( zSql==0 ){
  96541. rc = SQLITE_NOMEM_BKPT;
  96542. }else{
  96543. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  96544. sqlite3DbFree(db, zSql);
  96545. }
  96546. }
  96547. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  96548. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96549. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  96550. Index *pIdx = sqliteHashData(i);
  96551. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  96552. }
  96553. /* Load the statistics from the sqlite_stat4 table. */
  96554. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  96555. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  96556. db->lookaside.bDisable++;
  96557. rc = loadStat4(db, sInfo.zDatabase);
  96558. db->lookaside.bDisable--;
  96559. }
  96560. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  96561. Index *pIdx = sqliteHashData(i);
  96562. sqlite3_free(pIdx->aiRowEst);
  96563. pIdx->aiRowEst = 0;
  96564. }
  96565. #endif
  96566. if( rc==SQLITE_NOMEM ){
  96567. sqlite3OomFault(db);
  96568. }
  96569. return rc;
  96570. }
  96571. #endif /* SQLITE_OMIT_ANALYZE */
  96572. /************** End of analyze.c *********************************************/
  96573. /************** Begin file attach.c ******************************************/
  96574. /*
  96575. ** 2003 April 6
  96576. **
  96577. ** The author disclaims copyright to this source code. In place of
  96578. ** a legal notice, here is a blessing:
  96579. **
  96580. ** May you do good and not evil.
  96581. ** May you find forgiveness for yourself and forgive others.
  96582. ** May you share freely, never taking more than you give.
  96583. **
  96584. *************************************************************************
  96585. ** This file contains code used to implement the ATTACH and DETACH commands.
  96586. */
  96587. /* #include "sqliteInt.h" */
  96588. #ifndef SQLITE_OMIT_ATTACH
  96589. /*
  96590. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  96591. ** is slightly different from resolving a normal SQL expression, because simple
  96592. ** identifiers are treated as strings, not possible column names or aliases.
  96593. **
  96594. ** i.e. if the parser sees:
  96595. **
  96596. ** ATTACH DATABASE abc AS def
  96597. **
  96598. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  96599. ** looking for columns of the same name.
  96600. **
  96601. ** This only applies to the root node of pExpr, so the statement:
  96602. **
  96603. ** ATTACH DATABASE abc||def AS 'db2'
  96604. **
  96605. ** will fail because neither abc or def can be resolved.
  96606. */
  96607. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  96608. {
  96609. int rc = SQLITE_OK;
  96610. if( pExpr ){
  96611. if( pExpr->op!=TK_ID ){
  96612. rc = sqlite3ResolveExprNames(pName, pExpr);
  96613. }else{
  96614. pExpr->op = TK_STRING;
  96615. }
  96616. }
  96617. return rc;
  96618. }
  96619. /*
  96620. ** An SQL user-function registered to do the work of an ATTACH statement. The
  96621. ** three arguments to the function come directly from an attach statement:
  96622. **
  96623. ** ATTACH DATABASE x AS y KEY z
  96624. **
  96625. ** SELECT sqlite_attach(x, y, z)
  96626. **
  96627. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  96628. ** third argument.
  96629. **
  96630. ** If the db->init.reopenMemdb flags is set, then instead of attaching a
  96631. ** new database, close the database on db->init.iDb and reopen it as an
  96632. ** empty MemDB.
  96633. */
  96634. static void attachFunc(
  96635. sqlite3_context *context,
  96636. int NotUsed,
  96637. sqlite3_value **argv
  96638. ){
  96639. int i;
  96640. int rc = 0;
  96641. sqlite3 *db = sqlite3_context_db_handle(context);
  96642. const char *zName;
  96643. const char *zFile;
  96644. char *zPath = 0;
  96645. char *zErr = 0;
  96646. unsigned int flags;
  96647. Db *aNew; /* New array of Db pointers */
  96648. Db *pNew; /* Db object for the newly attached database */
  96649. char *zErrDyn = 0;
  96650. sqlite3_vfs *pVfs;
  96651. UNUSED_PARAMETER(NotUsed);
  96652. zFile = (const char *)sqlite3_value_text(argv[0]);
  96653. zName = (const char *)sqlite3_value_text(argv[1]);
  96654. if( zFile==0 ) zFile = "";
  96655. if( zName==0 ) zName = "";
  96656. #ifdef SQLITE_ENABLE_DESERIALIZE
  96657. # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
  96658. #else
  96659. # define REOPEN_AS_MEMDB(db) (0)
  96660. #endif
  96661. if( REOPEN_AS_MEMDB(db) ){
  96662. /* This is not a real ATTACH. Instead, this routine is being called
  96663. ** from sqlite3_deserialize() to close database db->init.iDb and
  96664. ** reopen it as a MemDB */
  96665. pVfs = sqlite3_vfs_find("memdb");
  96666. if( pVfs==0 ) return;
  96667. pNew = &db->aDb[db->init.iDb];
  96668. if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
  96669. pNew->pBt = 0;
  96670. pNew->pSchema = 0;
  96671. rc = sqlite3BtreeOpen(pVfs, "x", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
  96672. }else{
  96673. /* This is a real ATTACH
  96674. **
  96675. ** Check for the following errors:
  96676. **
  96677. ** * Too many attached databases,
  96678. ** * Transaction currently open
  96679. ** * Specified database name already being used.
  96680. */
  96681. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  96682. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  96683. db->aLimit[SQLITE_LIMIT_ATTACHED]
  96684. );
  96685. goto attach_error;
  96686. }
  96687. for(i=0; i<db->nDb; i++){
  96688. char *z = db->aDb[i].zDbSName;
  96689. assert( z && zName );
  96690. if( sqlite3StrICmp(z, zName)==0 ){
  96691. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  96692. goto attach_error;
  96693. }
  96694. }
  96695. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  96696. ** hash tables.
  96697. */
  96698. if( db->aDb==db->aDbStatic ){
  96699. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  96700. if( aNew==0 ) return;
  96701. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  96702. }else{
  96703. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  96704. if( aNew==0 ) return;
  96705. }
  96706. db->aDb = aNew;
  96707. pNew = &db->aDb[db->nDb];
  96708. memset(pNew, 0, sizeof(*pNew));
  96709. /* Open the database file. If the btree is successfully opened, use
  96710. ** it to obtain the database schema. At this point the schema may
  96711. ** or may not be initialized.
  96712. */
  96713. flags = db->openFlags;
  96714. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  96715. if( rc!=SQLITE_OK ){
  96716. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  96717. sqlite3_result_error(context, zErr, -1);
  96718. sqlite3_free(zErr);
  96719. return;
  96720. }
  96721. assert( pVfs );
  96722. flags |= SQLITE_OPEN_MAIN_DB;
  96723. rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
  96724. sqlite3_free( zPath );
  96725. db->nDb++;
  96726. }
  96727. db->noSharedCache = 0;
  96728. if( rc==SQLITE_CONSTRAINT ){
  96729. rc = SQLITE_ERROR;
  96730. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  96731. }else if( rc==SQLITE_OK ){
  96732. Pager *pPager;
  96733. pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
  96734. if( !pNew->pSchema ){
  96735. rc = SQLITE_NOMEM_BKPT;
  96736. }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
  96737. zErrDyn = sqlite3MPrintf(db,
  96738. "attached databases must use the same text encoding as main database");
  96739. rc = SQLITE_ERROR;
  96740. }
  96741. sqlite3BtreeEnter(pNew->pBt);
  96742. pPager = sqlite3BtreePager(pNew->pBt);
  96743. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  96744. sqlite3BtreeSecureDelete(pNew->pBt,
  96745. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  96746. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  96747. sqlite3BtreeSetPagerFlags(pNew->pBt,
  96748. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  96749. #endif
  96750. sqlite3BtreeLeave(pNew->pBt);
  96751. }
  96752. pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  96753. if( !REOPEN_AS_MEMDB(db) ) pNew->zDbSName = sqlite3DbStrDup(db, zName);
  96754. if( rc==SQLITE_OK && pNew->zDbSName==0 ){
  96755. rc = SQLITE_NOMEM_BKPT;
  96756. }
  96757. #ifdef SQLITE_HAS_CODEC
  96758. if( rc==SQLITE_OK ){
  96759. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  96760. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  96761. int nKey;
  96762. char *zKey;
  96763. int t = sqlite3_value_type(argv[2]);
  96764. switch( t ){
  96765. case SQLITE_INTEGER:
  96766. case SQLITE_FLOAT:
  96767. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  96768. rc = SQLITE_ERROR;
  96769. break;
  96770. case SQLITE_TEXT:
  96771. case SQLITE_BLOB:
  96772. nKey = sqlite3_value_bytes(argv[2]);
  96773. zKey = (char *)sqlite3_value_blob(argv[2]);
  96774. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  96775. break;
  96776. case SQLITE_NULL:
  96777. /* No key specified. Use the key from the main database */
  96778. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  96779. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  96780. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  96781. }
  96782. break;
  96783. }
  96784. }
  96785. #endif
  96786. /* If the file was opened successfully, read the schema for the new database.
  96787. ** If this fails, or if opening the file failed, then close the file and
  96788. ** remove the entry from the db->aDb[] array. i.e. put everything back the
  96789. ** way we found it.
  96790. */
  96791. if( rc==SQLITE_OK ){
  96792. sqlite3BtreeEnterAll(db);
  96793. db->init.iDb = 0;
  96794. db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
  96795. rc = sqlite3Init(db, &zErrDyn);
  96796. sqlite3BtreeLeaveAll(db);
  96797. assert( zErrDyn==0 || rc!=SQLITE_OK );
  96798. }
  96799. #ifdef SQLITE_USER_AUTHENTICATION
  96800. if( rc==SQLITE_OK ){
  96801. u8 newAuth = 0;
  96802. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  96803. if( newAuth<db->auth.authLevel ){
  96804. rc = SQLITE_AUTH_USER;
  96805. }
  96806. }
  96807. #endif
  96808. if( rc ){
  96809. if( !REOPEN_AS_MEMDB(db) ){
  96810. int iDb = db->nDb - 1;
  96811. assert( iDb>=2 );
  96812. if( db->aDb[iDb].pBt ){
  96813. sqlite3BtreeClose(db->aDb[iDb].pBt);
  96814. db->aDb[iDb].pBt = 0;
  96815. db->aDb[iDb].pSchema = 0;
  96816. }
  96817. sqlite3ResetAllSchemasOfConnection(db);
  96818. db->nDb = iDb;
  96819. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  96820. sqlite3OomFault(db);
  96821. sqlite3DbFree(db, zErrDyn);
  96822. zErrDyn = sqlite3MPrintf(db, "out of memory");
  96823. }else if( zErrDyn==0 ){
  96824. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  96825. }
  96826. }
  96827. goto attach_error;
  96828. }
  96829. return;
  96830. attach_error:
  96831. /* Return an error if we get here */
  96832. if( zErrDyn ){
  96833. sqlite3_result_error(context, zErrDyn, -1);
  96834. sqlite3DbFree(db, zErrDyn);
  96835. }
  96836. if( rc ) sqlite3_result_error_code(context, rc);
  96837. }
  96838. /*
  96839. ** An SQL user-function registered to do the work of an DETACH statement. The
  96840. ** three arguments to the function come directly from a detach statement:
  96841. **
  96842. ** DETACH DATABASE x
  96843. **
  96844. ** SELECT sqlite_detach(x)
  96845. */
  96846. static void detachFunc(
  96847. sqlite3_context *context,
  96848. int NotUsed,
  96849. sqlite3_value **argv
  96850. ){
  96851. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  96852. sqlite3 *db = sqlite3_context_db_handle(context);
  96853. int i;
  96854. Db *pDb = 0;
  96855. char zErr[128];
  96856. UNUSED_PARAMETER(NotUsed);
  96857. if( zName==0 ) zName = "";
  96858. for(i=0; i<db->nDb; i++){
  96859. pDb = &db->aDb[i];
  96860. if( pDb->pBt==0 ) continue;
  96861. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  96862. }
  96863. if( i>=db->nDb ){
  96864. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  96865. goto detach_error;
  96866. }
  96867. if( i<2 ){
  96868. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  96869. goto detach_error;
  96870. }
  96871. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  96872. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  96873. goto detach_error;
  96874. }
  96875. sqlite3BtreeClose(pDb->pBt);
  96876. pDb->pBt = 0;
  96877. pDb->pSchema = 0;
  96878. sqlite3CollapseDatabaseArray(db);
  96879. return;
  96880. detach_error:
  96881. sqlite3_result_error(context, zErr, -1);
  96882. }
  96883. /*
  96884. ** This procedure generates VDBE code for a single invocation of either the
  96885. ** sqlite_detach() or sqlite_attach() SQL user functions.
  96886. */
  96887. static void codeAttach(
  96888. Parse *pParse, /* The parser context */
  96889. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  96890. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  96891. Expr *pAuthArg, /* Expression to pass to authorization callback */
  96892. Expr *pFilename, /* Name of database file */
  96893. Expr *pDbname, /* Name of the database to use internally */
  96894. Expr *pKey /* Database key for encryption extension */
  96895. ){
  96896. int rc;
  96897. NameContext sName;
  96898. Vdbe *v;
  96899. sqlite3* db = pParse->db;
  96900. int regArgs;
  96901. if( pParse->nErr ) goto attach_end;
  96902. memset(&sName, 0, sizeof(NameContext));
  96903. sName.pParse = pParse;
  96904. if(
  96905. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  96906. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  96907. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  96908. ){
  96909. goto attach_end;
  96910. }
  96911. #ifndef SQLITE_OMIT_AUTHORIZATION
  96912. if( pAuthArg ){
  96913. char *zAuthArg;
  96914. if( pAuthArg->op==TK_STRING ){
  96915. zAuthArg = pAuthArg->u.zToken;
  96916. }else{
  96917. zAuthArg = 0;
  96918. }
  96919. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  96920. if(rc!=SQLITE_OK ){
  96921. goto attach_end;
  96922. }
  96923. }
  96924. #endif /* SQLITE_OMIT_AUTHORIZATION */
  96925. v = sqlite3GetVdbe(pParse);
  96926. regArgs = sqlite3GetTempRange(pParse, 4);
  96927. sqlite3ExprCode(pParse, pFilename, regArgs);
  96928. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  96929. sqlite3ExprCode(pParse, pKey, regArgs+2);
  96930. assert( v || db->mallocFailed );
  96931. if( v ){
  96932. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  96933. (char *)pFunc, P4_FUNCDEF);
  96934. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  96935. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  96936. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  96937. ** statement only). For DETACH, set it to false (expire all existing
  96938. ** statements).
  96939. */
  96940. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  96941. }
  96942. attach_end:
  96943. sqlite3ExprDelete(db, pFilename);
  96944. sqlite3ExprDelete(db, pDbname);
  96945. sqlite3ExprDelete(db, pKey);
  96946. }
  96947. /*
  96948. ** Called by the parser to compile a DETACH statement.
  96949. **
  96950. ** DETACH pDbname
  96951. */
  96952. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  96953. static const FuncDef detach_func = {
  96954. 1, /* nArg */
  96955. SQLITE_UTF8, /* funcFlags */
  96956. 0, /* pUserData */
  96957. 0, /* pNext */
  96958. detachFunc, /* xSFunc */
  96959. 0, /* xFinalize */
  96960. "sqlite_detach", /* zName */
  96961. {0}
  96962. };
  96963. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  96964. }
  96965. /*
  96966. ** Called by the parser to compile an ATTACH statement.
  96967. **
  96968. ** ATTACH p AS pDbname KEY pKey
  96969. */
  96970. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  96971. static const FuncDef attach_func = {
  96972. 3, /* nArg */
  96973. SQLITE_UTF8, /* funcFlags */
  96974. 0, /* pUserData */
  96975. 0, /* pNext */
  96976. attachFunc, /* xSFunc */
  96977. 0, /* xFinalize */
  96978. "sqlite_attach", /* zName */
  96979. {0}
  96980. };
  96981. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  96982. }
  96983. #endif /* SQLITE_OMIT_ATTACH */
  96984. /*
  96985. ** Initialize a DbFixer structure. This routine must be called prior
  96986. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  96987. */
  96988. SQLITE_PRIVATE void sqlite3FixInit(
  96989. DbFixer *pFix, /* The fixer to be initialized */
  96990. Parse *pParse, /* Error messages will be written here */
  96991. int iDb, /* This is the database that must be used */
  96992. const char *zType, /* "view", "trigger", or "index" */
  96993. const Token *pName /* Name of the view, trigger, or index */
  96994. ){
  96995. sqlite3 *db;
  96996. db = pParse->db;
  96997. assert( db->nDb>iDb );
  96998. pFix->pParse = pParse;
  96999. pFix->zDb = db->aDb[iDb].zDbSName;
  97000. pFix->pSchema = db->aDb[iDb].pSchema;
  97001. pFix->zType = zType;
  97002. pFix->pName = pName;
  97003. pFix->bVarOnly = (iDb==1);
  97004. }
  97005. /*
  97006. ** The following set of routines walk through the parse tree and assign
  97007. ** a specific database to all table references where the database name
  97008. ** was left unspecified in the original SQL statement. The pFix structure
  97009. ** must have been initialized by a prior call to sqlite3FixInit().
  97010. **
  97011. ** These routines are used to make sure that an index, trigger, or
  97012. ** view in one database does not refer to objects in a different database.
  97013. ** (Exception: indices, triggers, and views in the TEMP database are
  97014. ** allowed to refer to anything.) If a reference is explicitly made
  97015. ** to an object in a different database, an error message is added to
  97016. ** pParse->zErrMsg and these routines return non-zero. If everything
  97017. ** checks out, these routines return 0.
  97018. */
  97019. SQLITE_PRIVATE int sqlite3FixSrcList(
  97020. DbFixer *pFix, /* Context of the fixation */
  97021. SrcList *pList /* The Source list to check and modify */
  97022. ){
  97023. int i;
  97024. const char *zDb;
  97025. struct SrcList_item *pItem;
  97026. if( NEVER(pList==0) ) return 0;
  97027. zDb = pFix->zDb;
  97028. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  97029. if( pFix->bVarOnly==0 ){
  97030. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  97031. sqlite3ErrorMsg(pFix->pParse,
  97032. "%s %T cannot reference objects in database %s",
  97033. pFix->zType, pFix->pName, pItem->zDatabase);
  97034. return 1;
  97035. }
  97036. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  97037. pItem->zDatabase = 0;
  97038. pItem->pSchema = pFix->pSchema;
  97039. }
  97040. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  97041. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  97042. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  97043. #endif
  97044. if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
  97045. return 1;
  97046. }
  97047. }
  97048. return 0;
  97049. }
  97050. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  97051. SQLITE_PRIVATE int sqlite3FixSelect(
  97052. DbFixer *pFix, /* Context of the fixation */
  97053. Select *pSelect /* The SELECT statement to be fixed to one database */
  97054. ){
  97055. while( pSelect ){
  97056. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  97057. return 1;
  97058. }
  97059. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  97060. return 1;
  97061. }
  97062. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  97063. return 1;
  97064. }
  97065. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  97066. return 1;
  97067. }
  97068. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  97069. return 1;
  97070. }
  97071. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  97072. return 1;
  97073. }
  97074. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  97075. return 1;
  97076. }
  97077. if( pSelect->pWith ){
  97078. int i;
  97079. for(i=0; i<pSelect->pWith->nCte; i++){
  97080. if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
  97081. return 1;
  97082. }
  97083. }
  97084. }
  97085. pSelect = pSelect->pPrior;
  97086. }
  97087. return 0;
  97088. }
  97089. SQLITE_PRIVATE int sqlite3FixExpr(
  97090. DbFixer *pFix, /* Context of the fixation */
  97091. Expr *pExpr /* The expression to be fixed to one database */
  97092. ){
  97093. while( pExpr ){
  97094. if( pExpr->op==TK_VARIABLE ){
  97095. if( pFix->pParse->db->init.busy ){
  97096. pExpr->op = TK_NULL;
  97097. }else{
  97098. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  97099. return 1;
  97100. }
  97101. }
  97102. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  97103. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  97104. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  97105. }else{
  97106. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  97107. }
  97108. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  97109. return 1;
  97110. }
  97111. pExpr = pExpr->pLeft;
  97112. }
  97113. return 0;
  97114. }
  97115. SQLITE_PRIVATE int sqlite3FixExprList(
  97116. DbFixer *pFix, /* Context of the fixation */
  97117. ExprList *pList /* The expression to be fixed to one database */
  97118. ){
  97119. int i;
  97120. struct ExprList_item *pItem;
  97121. if( pList==0 ) return 0;
  97122. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  97123. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  97124. return 1;
  97125. }
  97126. }
  97127. return 0;
  97128. }
  97129. #endif
  97130. #ifndef SQLITE_OMIT_TRIGGER
  97131. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  97132. DbFixer *pFix, /* Context of the fixation */
  97133. TriggerStep *pStep /* The trigger step be fixed to one database */
  97134. ){
  97135. while( pStep ){
  97136. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  97137. return 1;
  97138. }
  97139. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  97140. return 1;
  97141. }
  97142. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  97143. return 1;
  97144. }
  97145. #ifndef SQLITE_OMIT_UPSERT
  97146. if( pStep->pUpsert ){
  97147. Upsert *pUp = pStep->pUpsert;
  97148. if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
  97149. || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
  97150. || sqlite3FixExprList(pFix, pUp->pUpsertSet)
  97151. || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
  97152. ){
  97153. return 1;
  97154. }
  97155. }
  97156. #endif
  97157. pStep = pStep->pNext;
  97158. }
  97159. return 0;
  97160. }
  97161. #endif
  97162. /************** End of attach.c **********************************************/
  97163. /************** Begin file auth.c ********************************************/
  97164. /*
  97165. ** 2003 January 11
  97166. **
  97167. ** The author disclaims copyright to this source code. In place of
  97168. ** a legal notice, here is a blessing:
  97169. **
  97170. ** May you do good and not evil.
  97171. ** May you find forgiveness for yourself and forgive others.
  97172. ** May you share freely, never taking more than you give.
  97173. **
  97174. *************************************************************************
  97175. ** This file contains code used to implement the sqlite3_set_authorizer()
  97176. ** API. This facility is an optional feature of the library. Embedded
  97177. ** systems that do not need this facility may omit it by recompiling
  97178. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  97179. */
  97180. /* #include "sqliteInt.h" */
  97181. /*
  97182. ** All of the code in this file may be omitted by defining a single
  97183. ** macro.
  97184. */
  97185. #ifndef SQLITE_OMIT_AUTHORIZATION
  97186. /*
  97187. ** Set or clear the access authorization function.
  97188. **
  97189. ** The access authorization function is be called during the compilation
  97190. ** phase to verify that the user has read and/or write access permission on
  97191. ** various fields of the database. The first argument to the auth function
  97192. ** is a copy of the 3rd argument to this routine. The second argument
  97193. ** to the auth function is one of these constants:
  97194. **
  97195. ** SQLITE_CREATE_INDEX
  97196. ** SQLITE_CREATE_TABLE
  97197. ** SQLITE_CREATE_TEMP_INDEX
  97198. ** SQLITE_CREATE_TEMP_TABLE
  97199. ** SQLITE_CREATE_TEMP_TRIGGER
  97200. ** SQLITE_CREATE_TEMP_VIEW
  97201. ** SQLITE_CREATE_TRIGGER
  97202. ** SQLITE_CREATE_VIEW
  97203. ** SQLITE_DELETE
  97204. ** SQLITE_DROP_INDEX
  97205. ** SQLITE_DROP_TABLE
  97206. ** SQLITE_DROP_TEMP_INDEX
  97207. ** SQLITE_DROP_TEMP_TABLE
  97208. ** SQLITE_DROP_TEMP_TRIGGER
  97209. ** SQLITE_DROP_TEMP_VIEW
  97210. ** SQLITE_DROP_TRIGGER
  97211. ** SQLITE_DROP_VIEW
  97212. ** SQLITE_INSERT
  97213. ** SQLITE_PRAGMA
  97214. ** SQLITE_READ
  97215. ** SQLITE_SELECT
  97216. ** SQLITE_TRANSACTION
  97217. ** SQLITE_UPDATE
  97218. **
  97219. ** The third and fourth arguments to the auth function are the name of
  97220. ** the table and the column that are being accessed. The auth function
  97221. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  97222. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  97223. ** means that the SQL statement will never-run - the sqlite3_exec() call
  97224. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  97225. ** should run but attempts to read the specified column will return NULL
  97226. ** and attempts to write the column will be ignored.
  97227. **
  97228. ** Setting the auth function to NULL disables this hook. The default
  97229. ** setting of the auth function is NULL.
  97230. */
  97231. SQLITE_API int sqlite3_set_authorizer(
  97232. sqlite3 *db,
  97233. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  97234. void *pArg
  97235. ){
  97236. #ifdef SQLITE_ENABLE_API_ARMOR
  97237. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  97238. #endif
  97239. sqlite3_mutex_enter(db->mutex);
  97240. db->xAuth = (sqlite3_xauth)xAuth;
  97241. db->pAuthArg = pArg;
  97242. sqlite3ExpirePreparedStatements(db);
  97243. sqlite3_mutex_leave(db->mutex);
  97244. return SQLITE_OK;
  97245. }
  97246. /*
  97247. ** Write an error message into pParse->zErrMsg that explains that the
  97248. ** user-supplied authorization function returned an illegal value.
  97249. */
  97250. static void sqliteAuthBadReturnCode(Parse *pParse){
  97251. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  97252. pParse->rc = SQLITE_ERROR;
  97253. }
  97254. /*
  97255. ** Invoke the authorization callback for permission to read column zCol from
  97256. ** table zTab in database zDb. This function assumes that an authorization
  97257. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  97258. **
  97259. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  97260. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  97261. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  97262. */
  97263. SQLITE_PRIVATE int sqlite3AuthReadCol(
  97264. Parse *pParse, /* The parser context */
  97265. const char *zTab, /* Table name */
  97266. const char *zCol, /* Column name */
  97267. int iDb /* Index of containing database. */
  97268. ){
  97269. sqlite3 *db = pParse->db; /* Database handle */
  97270. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  97271. int rc; /* Auth callback return code */
  97272. if( db->init.busy ) return SQLITE_OK;
  97273. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  97274. #ifdef SQLITE_USER_AUTHENTICATION
  97275. ,db->auth.zAuthUser
  97276. #endif
  97277. );
  97278. if( rc==SQLITE_DENY ){
  97279. char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
  97280. if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
  97281. sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
  97282. pParse->rc = SQLITE_AUTH;
  97283. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  97284. sqliteAuthBadReturnCode(pParse);
  97285. }
  97286. return rc;
  97287. }
  97288. /*
  97289. ** The pExpr should be a TK_COLUMN expression. The table referred to
  97290. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  97291. ** Check to see if it is OK to read this particular column.
  97292. **
  97293. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  97294. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  97295. ** then generate an error.
  97296. */
  97297. SQLITE_PRIVATE void sqlite3AuthRead(
  97298. Parse *pParse, /* The parser context */
  97299. Expr *pExpr, /* The expression to check authorization on */
  97300. Schema *pSchema, /* The schema of the expression */
  97301. SrcList *pTabList /* All table that pExpr might refer to */
  97302. ){
  97303. sqlite3 *db = pParse->db;
  97304. Table *pTab = 0; /* The table being read */
  97305. const char *zCol; /* Name of the column of the table */
  97306. int iSrc; /* Index in pTabList->a[] of table being read */
  97307. int iDb; /* The index of the database the expression refers to */
  97308. int iCol; /* Index of column in table */
  97309. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  97310. if( db->xAuth==0 ) return;
  97311. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  97312. if( iDb<0 ){
  97313. /* An attempt to read a column out of a subquery or other
  97314. ** temporary table. */
  97315. return;
  97316. }
  97317. if( pExpr->op==TK_TRIGGER ){
  97318. pTab = pParse->pTriggerTab;
  97319. }else{
  97320. assert( pTabList );
  97321. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  97322. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  97323. pTab = pTabList->a[iSrc].pTab;
  97324. break;
  97325. }
  97326. }
  97327. }
  97328. iCol = pExpr->iColumn;
  97329. if( NEVER(pTab==0) ) return;
  97330. if( iCol>=0 ){
  97331. assert( iCol<pTab->nCol );
  97332. zCol = pTab->aCol[iCol].zName;
  97333. }else if( pTab->iPKey>=0 ){
  97334. assert( pTab->iPKey<pTab->nCol );
  97335. zCol = pTab->aCol[pTab->iPKey].zName;
  97336. }else{
  97337. zCol = "ROWID";
  97338. }
  97339. assert( iDb>=0 && iDb<db->nDb );
  97340. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  97341. pExpr->op = TK_NULL;
  97342. }
  97343. }
  97344. /*
  97345. ** Do an authorization check using the code and arguments given. Return
  97346. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  97347. ** is returned, then the error count and error message in pParse are
  97348. ** modified appropriately.
  97349. */
  97350. SQLITE_PRIVATE int sqlite3AuthCheck(
  97351. Parse *pParse,
  97352. int code,
  97353. const char *zArg1,
  97354. const char *zArg2,
  97355. const char *zArg3
  97356. ){
  97357. sqlite3 *db = pParse->db;
  97358. int rc;
  97359. /* Don't do any authorization checks if the database is initialising
  97360. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  97361. */
  97362. if( db->init.busy || IN_DECLARE_VTAB ){
  97363. return SQLITE_OK;
  97364. }
  97365. if( db->xAuth==0 ){
  97366. return SQLITE_OK;
  97367. }
  97368. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  97369. ** callback are either NULL pointers or zero-terminated strings that
  97370. ** contain additional details about the action to be authorized.
  97371. **
  97372. ** The following testcase() macros show that any of the 3rd through 6th
  97373. ** parameters can be either NULL or a string. */
  97374. testcase( zArg1==0 );
  97375. testcase( zArg2==0 );
  97376. testcase( zArg3==0 );
  97377. testcase( pParse->zAuthContext==0 );
  97378. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  97379. #ifdef SQLITE_USER_AUTHENTICATION
  97380. ,db->auth.zAuthUser
  97381. #endif
  97382. );
  97383. if( rc==SQLITE_DENY ){
  97384. sqlite3ErrorMsg(pParse, "not authorized");
  97385. pParse->rc = SQLITE_AUTH;
  97386. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  97387. rc = SQLITE_DENY;
  97388. sqliteAuthBadReturnCode(pParse);
  97389. }
  97390. return rc;
  97391. }
  97392. /*
  97393. ** Push an authorization context. After this routine is called, the
  97394. ** zArg3 argument to authorization callbacks will be zContext until
  97395. ** popped. Or if pParse==0, this routine is a no-op.
  97396. */
  97397. SQLITE_PRIVATE void sqlite3AuthContextPush(
  97398. Parse *pParse,
  97399. AuthContext *pContext,
  97400. const char *zContext
  97401. ){
  97402. assert( pParse );
  97403. pContext->pParse = pParse;
  97404. pContext->zAuthContext = pParse->zAuthContext;
  97405. pParse->zAuthContext = zContext;
  97406. }
  97407. /*
  97408. ** Pop an authorization context that was previously pushed
  97409. ** by sqlite3AuthContextPush
  97410. */
  97411. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  97412. if( pContext->pParse ){
  97413. pContext->pParse->zAuthContext = pContext->zAuthContext;
  97414. pContext->pParse = 0;
  97415. }
  97416. }
  97417. #endif /* SQLITE_OMIT_AUTHORIZATION */
  97418. /************** End of auth.c ************************************************/
  97419. /************** Begin file build.c *******************************************/
  97420. /*
  97421. ** 2001 September 15
  97422. **
  97423. ** The author disclaims copyright to this source code. In place of
  97424. ** a legal notice, here is a blessing:
  97425. **
  97426. ** May you do good and not evil.
  97427. ** May you find forgiveness for yourself and forgive others.
  97428. ** May you share freely, never taking more than you give.
  97429. **
  97430. *************************************************************************
  97431. ** This file contains C code routines that are called by the SQLite parser
  97432. ** when syntax rules are reduced. The routines in this file handle the
  97433. ** following kinds of SQL syntax:
  97434. **
  97435. ** CREATE TABLE
  97436. ** DROP TABLE
  97437. ** CREATE INDEX
  97438. ** DROP INDEX
  97439. ** creating ID lists
  97440. ** BEGIN TRANSACTION
  97441. ** COMMIT
  97442. ** ROLLBACK
  97443. */
  97444. /* #include "sqliteInt.h" */
  97445. #ifndef SQLITE_OMIT_SHARED_CACHE
  97446. /*
  97447. ** The TableLock structure is only used by the sqlite3TableLock() and
  97448. ** codeTableLocks() functions.
  97449. */
  97450. struct TableLock {
  97451. int iDb; /* The database containing the table to be locked */
  97452. int iTab; /* The root page of the table to be locked */
  97453. u8 isWriteLock; /* True for write lock. False for a read lock */
  97454. const char *zLockName; /* Name of the table */
  97455. };
  97456. /*
  97457. ** Record the fact that we want to lock a table at run-time.
  97458. **
  97459. ** The table to be locked has root page iTab and is found in database iDb.
  97460. ** A read or a write lock can be taken depending on isWritelock.
  97461. **
  97462. ** This routine just records the fact that the lock is desired. The
  97463. ** code to make the lock occur is generated by a later call to
  97464. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  97465. */
  97466. SQLITE_PRIVATE void sqlite3TableLock(
  97467. Parse *pParse, /* Parsing context */
  97468. int iDb, /* Index of the database containing the table to lock */
  97469. int iTab, /* Root page number of the table to be locked */
  97470. u8 isWriteLock, /* True for a write lock */
  97471. const char *zName /* Name of the table to be locked */
  97472. ){
  97473. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97474. int i;
  97475. int nBytes;
  97476. TableLock *p;
  97477. assert( iDb>=0 );
  97478. if( iDb==1 ) return;
  97479. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  97480. for(i=0; i<pToplevel->nTableLock; i++){
  97481. p = &pToplevel->aTableLock[i];
  97482. if( p->iDb==iDb && p->iTab==iTab ){
  97483. p->isWriteLock = (p->isWriteLock || isWriteLock);
  97484. return;
  97485. }
  97486. }
  97487. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  97488. pToplevel->aTableLock =
  97489. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  97490. if( pToplevel->aTableLock ){
  97491. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  97492. p->iDb = iDb;
  97493. p->iTab = iTab;
  97494. p->isWriteLock = isWriteLock;
  97495. p->zLockName = zName;
  97496. }else{
  97497. pToplevel->nTableLock = 0;
  97498. sqlite3OomFault(pToplevel->db);
  97499. }
  97500. }
  97501. /*
  97502. ** Code an OP_TableLock instruction for each table locked by the
  97503. ** statement (configured by calls to sqlite3TableLock()).
  97504. */
  97505. static void codeTableLocks(Parse *pParse){
  97506. int i;
  97507. Vdbe *pVdbe;
  97508. pVdbe = sqlite3GetVdbe(pParse);
  97509. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  97510. for(i=0; i<pParse->nTableLock; i++){
  97511. TableLock *p = &pParse->aTableLock[i];
  97512. int p1 = p->iDb;
  97513. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  97514. p->zLockName, P4_STATIC);
  97515. }
  97516. }
  97517. #else
  97518. #define codeTableLocks(x)
  97519. #endif
  97520. /*
  97521. ** Return TRUE if the given yDbMask object is empty - if it contains no
  97522. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  97523. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  97524. */
  97525. #if SQLITE_MAX_ATTACHED>30
  97526. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  97527. int i;
  97528. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  97529. return 1;
  97530. }
  97531. #endif
  97532. /*
  97533. ** This routine is called after a single SQL statement has been
  97534. ** parsed and a VDBE program to execute that statement has been
  97535. ** prepared. This routine puts the finishing touches on the
  97536. ** VDBE program and resets the pParse structure for the next
  97537. ** parse.
  97538. **
  97539. ** Note that if an error occurred, it might be the case that
  97540. ** no VDBE code was generated.
  97541. */
  97542. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  97543. sqlite3 *db;
  97544. Vdbe *v;
  97545. assert( pParse->pToplevel==0 );
  97546. db = pParse->db;
  97547. if( pParse->nested ) return;
  97548. if( db->mallocFailed || pParse->nErr ){
  97549. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  97550. return;
  97551. }
  97552. /* Begin by generating some termination code at the end of the
  97553. ** vdbe program
  97554. */
  97555. v = sqlite3GetVdbe(pParse);
  97556. assert( !pParse->isMultiWrite
  97557. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  97558. if( v ){
  97559. sqlite3VdbeAddOp0(v, OP_Halt);
  97560. #if SQLITE_USER_AUTHENTICATION
  97561. if( pParse->nTableLock>0 && db->init.busy==0 ){
  97562. sqlite3UserAuthInit(db);
  97563. if( db->auth.authLevel<UAUTH_User ){
  97564. sqlite3ErrorMsg(pParse, "user not authenticated");
  97565. pParse->rc = SQLITE_AUTH_USER;
  97566. return;
  97567. }
  97568. }
  97569. #endif
  97570. /* The cookie mask contains one bit for each database file open.
  97571. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  97572. ** set for each database that is used. Generate code to start a
  97573. ** transaction on each used database and to verify the schema cookie
  97574. ** on each used database.
  97575. */
  97576. if( db->mallocFailed==0
  97577. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  97578. ){
  97579. int iDb, i;
  97580. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  97581. sqlite3VdbeJumpHere(v, 0);
  97582. for(iDb=0; iDb<db->nDb; iDb++){
  97583. Schema *pSchema;
  97584. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  97585. sqlite3VdbeUsesBtree(v, iDb);
  97586. pSchema = db->aDb[iDb].pSchema;
  97587. sqlite3VdbeAddOp4Int(v,
  97588. OP_Transaction, /* Opcode */
  97589. iDb, /* P1 */
  97590. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  97591. pSchema->schema_cookie, /* P3 */
  97592. pSchema->iGeneration /* P4 */
  97593. );
  97594. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  97595. VdbeComment((v,
  97596. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  97597. }
  97598. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97599. for(i=0; i<pParse->nVtabLock; i++){
  97600. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  97601. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  97602. }
  97603. pParse->nVtabLock = 0;
  97604. #endif
  97605. /* Once all the cookies have been verified and transactions opened,
  97606. ** obtain the required table-locks. This is a no-op unless the
  97607. ** shared-cache feature is enabled.
  97608. */
  97609. codeTableLocks(pParse);
  97610. /* Initialize any AUTOINCREMENT data structures required.
  97611. */
  97612. sqlite3AutoincrementBegin(pParse);
  97613. /* Code constant expressions that where factored out of inner loops */
  97614. if( pParse->pConstExpr ){
  97615. ExprList *pEL = pParse->pConstExpr;
  97616. pParse->okConstFactor = 0;
  97617. for(i=0; i<pEL->nExpr; i++){
  97618. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  97619. }
  97620. }
  97621. /* Finally, jump back to the beginning of the executable code. */
  97622. sqlite3VdbeGoto(v, 1);
  97623. }
  97624. }
  97625. /* Get the VDBE program ready for execution
  97626. */
  97627. if( v && pParse->nErr==0 && !db->mallocFailed ){
  97628. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  97629. /* A minimum of one cursor is required if autoincrement is used
  97630. * See ticket [a696379c1f08866] */
  97631. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  97632. sqlite3VdbeMakeReady(v, pParse);
  97633. pParse->rc = SQLITE_DONE;
  97634. }else{
  97635. pParse->rc = SQLITE_ERROR;
  97636. }
  97637. }
  97638. /*
  97639. ** Run the parser and code generator recursively in order to generate
  97640. ** code for the SQL statement given onto the end of the pParse context
  97641. ** currently under construction. When the parser is run recursively
  97642. ** this way, the final OP_Halt is not appended and other initialization
  97643. ** and finalization steps are omitted because those are handling by the
  97644. ** outermost parser.
  97645. **
  97646. ** Not everything is nestable. This facility is designed to permit
  97647. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  97648. ** care if you decide to try to use this routine for some other purposes.
  97649. */
  97650. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  97651. va_list ap;
  97652. char *zSql;
  97653. char *zErrMsg = 0;
  97654. sqlite3 *db = pParse->db;
  97655. char saveBuf[PARSE_TAIL_SZ];
  97656. if( pParse->nErr ) return;
  97657. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  97658. va_start(ap, zFormat);
  97659. zSql = sqlite3VMPrintf(db, zFormat, ap);
  97660. va_end(ap);
  97661. if( zSql==0 ){
  97662. return; /* A malloc must have failed */
  97663. }
  97664. pParse->nested++;
  97665. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  97666. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  97667. sqlite3RunParser(pParse, zSql, &zErrMsg);
  97668. sqlite3DbFree(db, zErrMsg);
  97669. sqlite3DbFree(db, zSql);
  97670. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  97671. pParse->nested--;
  97672. }
  97673. #if SQLITE_USER_AUTHENTICATION
  97674. /*
  97675. ** Return TRUE if zTable is the name of the system table that stores the
  97676. ** list of users and their access credentials.
  97677. */
  97678. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  97679. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  97680. }
  97681. #endif
  97682. /*
  97683. ** Locate the in-memory structure that describes a particular database
  97684. ** table given the name of that table and (optionally) the name of the
  97685. ** database containing the table. Return NULL if not found.
  97686. **
  97687. ** If zDatabase is 0, all databases are searched for the table and the
  97688. ** first matching table is returned. (No checking for duplicate table
  97689. ** names is done.) The search order is TEMP first, then MAIN, then any
  97690. ** auxiliary databases added using the ATTACH command.
  97691. **
  97692. ** See also sqlite3LocateTable().
  97693. */
  97694. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  97695. Table *p = 0;
  97696. int i;
  97697. /* All mutexes are required for schema access. Make sure we hold them. */
  97698. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  97699. #if SQLITE_USER_AUTHENTICATION
  97700. /* Only the admin user is allowed to know that the sqlite_user table
  97701. ** exists */
  97702. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  97703. return 0;
  97704. }
  97705. #endif
  97706. while(1){
  97707. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  97708. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  97709. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  97710. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  97711. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  97712. if( p ) return p;
  97713. }
  97714. }
  97715. /* Not found. If the name we were looking for was temp.sqlite_master
  97716. ** then change the name to sqlite_temp_master and try again. */
  97717. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  97718. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  97719. zName = TEMP_MASTER_NAME;
  97720. }
  97721. return 0;
  97722. }
  97723. /*
  97724. ** Locate the in-memory structure that describes a particular database
  97725. ** table given the name of that table and (optionally) the name of the
  97726. ** database containing the table. Return NULL if not found. Also leave an
  97727. ** error message in pParse->zErrMsg.
  97728. **
  97729. ** The difference between this routine and sqlite3FindTable() is that this
  97730. ** routine leaves an error message in pParse->zErrMsg where
  97731. ** sqlite3FindTable() does not.
  97732. */
  97733. SQLITE_PRIVATE Table *sqlite3LocateTable(
  97734. Parse *pParse, /* context in which to report errors */
  97735. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  97736. const char *zName, /* Name of the table we are looking for */
  97737. const char *zDbase /* Name of the database. Might be NULL */
  97738. ){
  97739. Table *p;
  97740. sqlite3 *db = pParse->db;
  97741. /* Read the database schema. If an error occurs, leave an error message
  97742. ** and code in pParse and return NULL. */
  97743. if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
  97744. && SQLITE_OK!=sqlite3ReadSchema(pParse)
  97745. ){
  97746. return 0;
  97747. }
  97748. p = sqlite3FindTable(db, zName, zDbase);
  97749. if( p==0 ){
  97750. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  97751. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97752. if( sqlite3FindDbName(db, zDbase)<1 ){
  97753. /* If zName is the not the name of a table in the schema created using
  97754. ** CREATE, then check to see if it is the name of an virtual table that
  97755. ** can be an eponymous virtual table. */
  97756. Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
  97757. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  97758. pMod = sqlite3PragmaVtabRegister(db, zName);
  97759. }
  97760. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  97761. return pMod->pEpoTab;
  97762. }
  97763. }
  97764. #endif
  97765. if( (flags & LOCATE_NOERR)==0 ){
  97766. if( zDbase ){
  97767. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  97768. }else{
  97769. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  97770. }
  97771. pParse->checkSchema = 1;
  97772. }
  97773. }
  97774. return p;
  97775. }
  97776. /*
  97777. ** Locate the table identified by *p.
  97778. **
  97779. ** This is a wrapper around sqlite3LocateTable(). The difference between
  97780. ** sqlite3LocateTable() and this function is that this function restricts
  97781. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  97782. ** non-NULL if it is part of a view or trigger program definition. See
  97783. ** sqlite3FixSrcList() for details.
  97784. */
  97785. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  97786. Parse *pParse,
  97787. u32 flags,
  97788. struct SrcList_item *p
  97789. ){
  97790. const char *zDb;
  97791. assert( p->pSchema==0 || p->zDatabase==0 );
  97792. if( p->pSchema ){
  97793. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  97794. zDb = pParse->db->aDb[iDb].zDbSName;
  97795. }else{
  97796. zDb = p->zDatabase;
  97797. }
  97798. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  97799. }
  97800. /*
  97801. ** Locate the in-memory structure that describes
  97802. ** a particular index given the name of that index
  97803. ** and the name of the database that contains the index.
  97804. ** Return NULL if not found.
  97805. **
  97806. ** If zDatabase is 0, all databases are searched for the
  97807. ** table and the first matching index is returned. (No checking
  97808. ** for duplicate index names is done.) The search order is
  97809. ** TEMP first, then MAIN, then any auxiliary databases added
  97810. ** using the ATTACH command.
  97811. */
  97812. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  97813. Index *p = 0;
  97814. int i;
  97815. /* All mutexes are required for schema access. Make sure we hold them. */
  97816. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  97817. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  97818. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  97819. Schema *pSchema = db->aDb[j].pSchema;
  97820. assert( pSchema );
  97821. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  97822. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  97823. p = sqlite3HashFind(&pSchema->idxHash, zName);
  97824. if( p ) break;
  97825. }
  97826. return p;
  97827. }
  97828. /*
  97829. ** Reclaim the memory used by an index
  97830. */
  97831. static void freeIndex(sqlite3 *db, Index *p){
  97832. #ifndef SQLITE_OMIT_ANALYZE
  97833. sqlite3DeleteIndexSamples(db, p);
  97834. #endif
  97835. sqlite3ExprDelete(db, p->pPartIdxWhere);
  97836. sqlite3ExprListDelete(db, p->aColExpr);
  97837. sqlite3DbFree(db, p->zColAff);
  97838. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  97839. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97840. sqlite3_free(p->aiRowEst);
  97841. #endif
  97842. sqlite3DbFree(db, p);
  97843. }
  97844. /*
  97845. ** For the index called zIdxName which is found in the database iDb,
  97846. ** unlike that index from its Table then remove the index from
  97847. ** the index hash table and free all memory structures associated
  97848. ** with the index.
  97849. */
  97850. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  97851. Index *pIndex;
  97852. Hash *pHash;
  97853. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97854. pHash = &db->aDb[iDb].pSchema->idxHash;
  97855. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  97856. if( ALWAYS(pIndex) ){
  97857. if( pIndex->pTable->pIndex==pIndex ){
  97858. pIndex->pTable->pIndex = pIndex->pNext;
  97859. }else{
  97860. Index *p;
  97861. /* Justification of ALWAYS(); The index must be on the list of
  97862. ** indices. */
  97863. p = pIndex->pTable->pIndex;
  97864. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  97865. if( ALWAYS(p && p->pNext==pIndex) ){
  97866. p->pNext = pIndex->pNext;
  97867. }
  97868. }
  97869. freeIndex(db, pIndex);
  97870. }
  97871. db->mDbFlags |= DBFLAG_SchemaChange;
  97872. }
  97873. /*
  97874. ** Look through the list of open database files in db->aDb[] and if
  97875. ** any have been closed, remove them from the list. Reallocate the
  97876. ** db->aDb[] structure to a smaller size, if possible.
  97877. **
  97878. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  97879. ** are never candidates for being collapsed.
  97880. */
  97881. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  97882. int i, j;
  97883. for(i=j=2; i<db->nDb; i++){
  97884. struct Db *pDb = &db->aDb[i];
  97885. if( pDb->pBt==0 ){
  97886. sqlite3DbFree(db, pDb->zDbSName);
  97887. pDb->zDbSName = 0;
  97888. continue;
  97889. }
  97890. if( j<i ){
  97891. db->aDb[j] = db->aDb[i];
  97892. }
  97893. j++;
  97894. }
  97895. db->nDb = j;
  97896. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  97897. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  97898. sqlite3DbFree(db, db->aDb);
  97899. db->aDb = db->aDbStatic;
  97900. }
  97901. }
  97902. /*
  97903. ** Reset the schema for the database at index iDb. Also reset the
  97904. ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
  97905. ** Deferred resets may be run by calling with iDb<0.
  97906. */
  97907. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  97908. int i;
  97909. assert( iDb<db->nDb );
  97910. if( iDb>=0 ){
  97911. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97912. DbSetProperty(db, iDb, DB_ResetWanted);
  97913. DbSetProperty(db, 1, DB_ResetWanted);
  97914. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  97915. }
  97916. if( db->nSchemaLock==0 ){
  97917. for(i=0; i<db->nDb; i++){
  97918. if( DbHasProperty(db, i, DB_ResetWanted) ){
  97919. sqlite3SchemaClear(db->aDb[i].pSchema);
  97920. }
  97921. }
  97922. }
  97923. }
  97924. /*
  97925. ** Erase all schema information from all attached databases (including
  97926. ** "main" and "temp") for a single database connection.
  97927. */
  97928. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  97929. int i;
  97930. sqlite3BtreeEnterAll(db);
  97931. assert( db->nSchemaLock==0 );
  97932. for(i=0; i<db->nDb; i++){
  97933. Db *pDb = &db->aDb[i];
  97934. if( pDb->pSchema ){
  97935. sqlite3SchemaClear(pDb->pSchema);
  97936. }
  97937. }
  97938. db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
  97939. sqlite3VtabUnlockList(db);
  97940. sqlite3BtreeLeaveAll(db);
  97941. sqlite3CollapseDatabaseArray(db);
  97942. }
  97943. /*
  97944. ** This routine is called when a commit occurs.
  97945. */
  97946. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  97947. db->mDbFlags &= ~DBFLAG_SchemaChange;
  97948. }
  97949. /*
  97950. ** Delete memory allocated for the column names of a table or view (the
  97951. ** Table.aCol[] array).
  97952. */
  97953. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  97954. int i;
  97955. Column *pCol;
  97956. assert( pTable!=0 );
  97957. if( (pCol = pTable->aCol)!=0 ){
  97958. for(i=0; i<pTable->nCol; i++, pCol++){
  97959. sqlite3DbFree(db, pCol->zName);
  97960. sqlite3ExprDelete(db, pCol->pDflt);
  97961. sqlite3DbFree(db, pCol->zColl);
  97962. }
  97963. sqlite3DbFree(db, pTable->aCol);
  97964. }
  97965. }
  97966. /*
  97967. ** Remove the memory data structures associated with the given
  97968. ** Table. No changes are made to disk by this routine.
  97969. **
  97970. ** This routine just deletes the data structure. It does not unlink
  97971. ** the table data structure from the hash table. But it does destroy
  97972. ** memory structures of the indices and foreign keys associated with
  97973. ** the table.
  97974. **
  97975. ** The db parameter is optional. It is needed if the Table object
  97976. ** contains lookaside memory. (Table objects in the schema do not use
  97977. ** lookaside memory, but some ephemeral Table objects do.) Or the
  97978. ** db parameter can be used with db->pnBytesFreed to measure the memory
  97979. ** used by the Table object.
  97980. */
  97981. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  97982. Index *pIndex, *pNext;
  97983. #ifdef SQLITE_DEBUG
  97984. /* Record the number of outstanding lookaside allocations in schema Tables
  97985. ** prior to doing any free() operations. Since schema Tables do not use
  97986. ** lookaside, this number should not change. */
  97987. int nLookaside = 0;
  97988. if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
  97989. nLookaside = sqlite3LookasideUsed(db, 0);
  97990. }
  97991. #endif
  97992. /* Delete all indices associated with this table. */
  97993. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  97994. pNext = pIndex->pNext;
  97995. assert( pIndex->pSchema==pTable->pSchema
  97996. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  97997. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  97998. char *zName = pIndex->zName;
  97999. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  98000. &pIndex->pSchema->idxHash, zName, 0
  98001. );
  98002. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  98003. assert( pOld==pIndex || pOld==0 );
  98004. }
  98005. freeIndex(db, pIndex);
  98006. }
  98007. /* Delete any foreign keys attached to this table. */
  98008. sqlite3FkDelete(db, pTable);
  98009. /* Delete the Table structure itself.
  98010. */
  98011. sqlite3DeleteColumnNames(db, pTable);
  98012. sqlite3DbFree(db, pTable->zName);
  98013. sqlite3DbFree(db, pTable->zColAff);
  98014. sqlite3SelectDelete(db, pTable->pSelect);
  98015. sqlite3ExprListDelete(db, pTable->pCheck);
  98016. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98017. sqlite3VtabClear(db, pTable);
  98018. #endif
  98019. sqlite3DbFree(db, pTable);
  98020. /* Verify that no lookaside memory was used by schema tables */
  98021. assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
  98022. }
  98023. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  98024. /* Do not delete the table until the reference count reaches zero. */
  98025. if( !pTable ) return;
  98026. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  98027. deleteTable(db, pTable);
  98028. }
  98029. /*
  98030. ** Unlink the given table from the hash tables and the delete the
  98031. ** table structure with all its indices and foreign keys.
  98032. */
  98033. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  98034. Table *p;
  98035. Db *pDb;
  98036. assert( db!=0 );
  98037. assert( iDb>=0 && iDb<db->nDb );
  98038. assert( zTabName );
  98039. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98040. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  98041. pDb = &db->aDb[iDb];
  98042. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  98043. sqlite3DeleteTable(db, p);
  98044. db->mDbFlags |= DBFLAG_SchemaChange;
  98045. }
  98046. /*
  98047. ** Given a token, return a string that consists of the text of that
  98048. ** token. Space to hold the returned string
  98049. ** is obtained from sqliteMalloc() and must be freed by the calling
  98050. ** function.
  98051. **
  98052. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  98053. ** surround the body of the token are removed.
  98054. **
  98055. ** Tokens are often just pointers into the original SQL text and so
  98056. ** are not \000 terminated and are not persistent. The returned string
  98057. ** is \000 terminated and is persistent.
  98058. */
  98059. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  98060. char *zName;
  98061. if( pName ){
  98062. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  98063. sqlite3Dequote(zName);
  98064. }else{
  98065. zName = 0;
  98066. }
  98067. return zName;
  98068. }
  98069. /*
  98070. ** Open the sqlite_master table stored in database number iDb for
  98071. ** writing. The table is opened using cursor 0.
  98072. */
  98073. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  98074. Vdbe *v = sqlite3GetVdbe(p);
  98075. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  98076. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  98077. if( p->nTab==0 ){
  98078. p->nTab = 1;
  98079. }
  98080. }
  98081. /*
  98082. ** Parameter zName points to a nul-terminated buffer containing the name
  98083. ** of a database ("main", "temp" or the name of an attached db). This
  98084. ** function returns the index of the named database in db->aDb[], or
  98085. ** -1 if the named db cannot be found.
  98086. */
  98087. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  98088. int i = -1; /* Database number */
  98089. if( zName ){
  98090. Db *pDb;
  98091. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  98092. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  98093. /* "main" is always an acceptable alias for the primary database
  98094. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  98095. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  98096. }
  98097. }
  98098. return i;
  98099. }
  98100. /*
  98101. ** The token *pName contains the name of a database (either "main" or
  98102. ** "temp" or the name of an attached db). This routine returns the
  98103. ** index of the named database in db->aDb[], or -1 if the named db
  98104. ** does not exist.
  98105. */
  98106. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  98107. int i; /* Database number */
  98108. char *zName; /* Name we are searching for */
  98109. zName = sqlite3NameFromToken(db, pName);
  98110. i = sqlite3FindDbName(db, zName);
  98111. sqlite3DbFree(db, zName);
  98112. return i;
  98113. }
  98114. /* The table or view or trigger name is passed to this routine via tokens
  98115. ** pName1 and pName2. If the table name was fully qualified, for example:
  98116. **
  98117. ** CREATE TABLE xxx.yyy (...);
  98118. **
  98119. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  98120. ** the table name is not fully qualified, i.e.:
  98121. **
  98122. ** CREATE TABLE yyy(...);
  98123. **
  98124. ** Then pName1 is set to "yyy" and pName2 is "".
  98125. **
  98126. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  98127. ** pName2) that stores the unqualified table name. The index of the
  98128. ** database "xxx" is returned.
  98129. */
  98130. SQLITE_PRIVATE int sqlite3TwoPartName(
  98131. Parse *pParse, /* Parsing and code generating context */
  98132. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  98133. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  98134. Token **pUnqual /* Write the unqualified object name here */
  98135. ){
  98136. int iDb; /* Database holding the object */
  98137. sqlite3 *db = pParse->db;
  98138. assert( pName2!=0 );
  98139. if( pName2->n>0 ){
  98140. if( db->init.busy ) {
  98141. sqlite3ErrorMsg(pParse, "corrupt database");
  98142. return -1;
  98143. }
  98144. *pUnqual = pName2;
  98145. iDb = sqlite3FindDb(db, pName1);
  98146. if( iDb<0 ){
  98147. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  98148. return -1;
  98149. }
  98150. }else{
  98151. assert( db->init.iDb==0 || db->init.busy
  98152. || (db->mDbFlags & DBFLAG_Vacuum)!=0);
  98153. iDb = db->init.iDb;
  98154. *pUnqual = pName1;
  98155. }
  98156. return iDb;
  98157. }
  98158. /*
  98159. ** This routine is used to check if the UTF-8 string zName is a legal
  98160. ** unqualified name for a new schema object (table, index, view or
  98161. ** trigger). All names are legal except those that begin with the string
  98162. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  98163. ** is reserved for internal use.
  98164. */
  98165. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  98166. if( !pParse->db->init.busy && pParse->nested==0
  98167. && (pParse->db->flags & SQLITE_WriteSchema)==0
  98168. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  98169. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  98170. return SQLITE_ERROR;
  98171. }
  98172. return SQLITE_OK;
  98173. }
  98174. /*
  98175. ** Return the PRIMARY KEY index of a table
  98176. */
  98177. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  98178. Index *p;
  98179. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  98180. return p;
  98181. }
  98182. /*
  98183. ** Return the column of index pIdx that corresponds to table
  98184. ** column iCol. Return -1 if not found.
  98185. */
  98186. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  98187. int i;
  98188. for(i=0; i<pIdx->nColumn; i++){
  98189. if( iCol==pIdx->aiColumn[i] ) return i;
  98190. }
  98191. return -1;
  98192. }
  98193. /*
  98194. ** Begin constructing a new table representation in memory. This is
  98195. ** the first of several action routines that get called in response
  98196. ** to a CREATE TABLE statement. In particular, this routine is called
  98197. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  98198. ** flag is true if the table should be stored in the auxiliary database
  98199. ** file instead of in the main database file. This is normally the case
  98200. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  98201. ** CREATE and TABLE.
  98202. **
  98203. ** The new table record is initialized and put in pParse->pNewTable.
  98204. ** As more of the CREATE TABLE statement is parsed, additional action
  98205. ** routines will be called to add more information to this record.
  98206. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  98207. ** is called to complete the construction of the new table record.
  98208. */
  98209. SQLITE_PRIVATE void sqlite3StartTable(
  98210. Parse *pParse, /* Parser context */
  98211. Token *pName1, /* First part of the name of the table or view */
  98212. Token *pName2, /* Second part of the name of the table or view */
  98213. int isTemp, /* True if this is a TEMP table */
  98214. int isView, /* True if this is a VIEW */
  98215. int isVirtual, /* True if this is a VIRTUAL table */
  98216. int noErr /* Do nothing if table already exists */
  98217. ){
  98218. Table *pTable;
  98219. char *zName = 0; /* The name of the new table */
  98220. sqlite3 *db = pParse->db;
  98221. Vdbe *v;
  98222. int iDb; /* Database number to create the table in */
  98223. Token *pName; /* Unqualified name of the table to create */
  98224. if( db->init.busy && db->init.newTnum==1 ){
  98225. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  98226. iDb = db->init.iDb;
  98227. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  98228. pName = pName1;
  98229. }else{
  98230. /* The common case */
  98231. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  98232. if( iDb<0 ) return;
  98233. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  98234. /* If creating a temp table, the name may not be qualified. Unless
  98235. ** the database name is "temp" anyway. */
  98236. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  98237. return;
  98238. }
  98239. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  98240. zName = sqlite3NameFromToken(db, pName);
  98241. }
  98242. pParse->sNameToken = *pName;
  98243. if( zName==0 ) return;
  98244. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  98245. goto begin_table_error;
  98246. }
  98247. if( db->init.iDb==1 ) isTemp = 1;
  98248. #ifndef SQLITE_OMIT_AUTHORIZATION
  98249. assert( isTemp==0 || isTemp==1 );
  98250. assert( isView==0 || isView==1 );
  98251. {
  98252. static const u8 aCode[] = {
  98253. SQLITE_CREATE_TABLE,
  98254. SQLITE_CREATE_TEMP_TABLE,
  98255. SQLITE_CREATE_VIEW,
  98256. SQLITE_CREATE_TEMP_VIEW
  98257. };
  98258. char *zDb = db->aDb[iDb].zDbSName;
  98259. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  98260. goto begin_table_error;
  98261. }
  98262. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  98263. zName, 0, zDb) ){
  98264. goto begin_table_error;
  98265. }
  98266. }
  98267. #endif
  98268. /* Make sure the new table name does not collide with an existing
  98269. ** index or table name in the same database. Issue an error message if
  98270. ** it does. The exception is if the statement being parsed was passed
  98271. ** to an sqlite3_declare_vtab() call. In that case only the column names
  98272. ** and types will be used, so there is no need to test for namespace
  98273. ** collisions.
  98274. */
  98275. if( !IN_DECLARE_VTAB ){
  98276. char *zDb = db->aDb[iDb].zDbSName;
  98277. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  98278. goto begin_table_error;
  98279. }
  98280. pTable = sqlite3FindTable(db, zName, zDb);
  98281. if( pTable ){
  98282. if( !noErr ){
  98283. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  98284. }else{
  98285. assert( !db->init.busy || CORRUPT_DB );
  98286. sqlite3CodeVerifySchema(pParse, iDb);
  98287. }
  98288. goto begin_table_error;
  98289. }
  98290. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  98291. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  98292. goto begin_table_error;
  98293. }
  98294. }
  98295. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  98296. if( pTable==0 ){
  98297. assert( db->mallocFailed );
  98298. pParse->rc = SQLITE_NOMEM_BKPT;
  98299. pParse->nErr++;
  98300. goto begin_table_error;
  98301. }
  98302. pTable->zName = zName;
  98303. pTable->iPKey = -1;
  98304. pTable->pSchema = db->aDb[iDb].pSchema;
  98305. pTable->nTabRef = 1;
  98306. #ifdef SQLITE_DEFAULT_ROWEST
  98307. pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
  98308. #else
  98309. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  98310. #endif
  98311. assert( pParse->pNewTable==0 );
  98312. pParse->pNewTable = pTable;
  98313. /* If this is the magic sqlite_sequence table used by autoincrement,
  98314. ** then record a pointer to this table in the main database structure
  98315. ** so that INSERT can find the table easily.
  98316. */
  98317. #ifndef SQLITE_OMIT_AUTOINCREMENT
  98318. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  98319. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98320. pTable->pSchema->pSeqTab = pTable;
  98321. }
  98322. #endif
  98323. /* Begin generating the code that will insert the table record into
  98324. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  98325. ** and allocate the record number for the table entry now. Before any
  98326. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  98327. ** indices to be created and the table record must come before the
  98328. ** indices. Hence, the record number for the table must be allocated
  98329. ** now.
  98330. */
  98331. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  98332. int addr1;
  98333. int fileFormat;
  98334. int reg1, reg2, reg3;
  98335. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  98336. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  98337. sqlite3BeginWriteOperation(pParse, 1, iDb);
  98338. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98339. if( isVirtual ){
  98340. sqlite3VdbeAddOp0(v, OP_VBegin);
  98341. }
  98342. #endif
  98343. /* If the file format and encoding in the database have not been set,
  98344. ** set them now.
  98345. */
  98346. reg1 = pParse->regRowid = ++pParse->nMem;
  98347. reg2 = pParse->regRoot = ++pParse->nMem;
  98348. reg3 = ++pParse->nMem;
  98349. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  98350. sqlite3VdbeUsesBtree(v, iDb);
  98351. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  98352. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  98353. 1 : SQLITE_MAX_FILE_FORMAT;
  98354. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  98355. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  98356. sqlite3VdbeJumpHere(v, addr1);
  98357. /* This just creates a place-holder record in the sqlite_master table.
  98358. ** The record created does not contain anything yet. It will be replaced
  98359. ** by the real entry in code generated at sqlite3EndTable().
  98360. **
  98361. ** The rowid for the new entry is left in register pParse->regRowid.
  98362. ** The root page number of the new table is left in reg pParse->regRoot.
  98363. ** The rowid and root page number values are needed by the code that
  98364. ** sqlite3EndTable will generate.
  98365. */
  98366. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  98367. if( isView || isVirtual ){
  98368. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  98369. }else
  98370. #endif
  98371. {
  98372. pParse->addrCrTab =
  98373. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
  98374. }
  98375. sqlite3OpenMasterTable(pParse, iDb);
  98376. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  98377. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  98378. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  98379. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  98380. sqlite3VdbeAddOp0(v, OP_Close);
  98381. }
  98382. /* Normal (non-error) return. */
  98383. return;
  98384. /* If an error occurs, we jump here */
  98385. begin_table_error:
  98386. sqlite3DbFree(db, zName);
  98387. return;
  98388. }
  98389. /* Set properties of a table column based on the (magical)
  98390. ** name of the column.
  98391. */
  98392. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  98393. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  98394. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  98395. pCol->colFlags |= COLFLAG_HIDDEN;
  98396. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  98397. pTab->tabFlags |= TF_OOOHidden;
  98398. }
  98399. }
  98400. #endif
  98401. /*
  98402. ** Add a new column to the table currently being constructed.
  98403. **
  98404. ** The parser calls this routine once for each column declaration
  98405. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  98406. ** first to get things going. Then this routine is called for each
  98407. ** column.
  98408. */
  98409. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  98410. Table *p;
  98411. int i;
  98412. char *z;
  98413. char *zType;
  98414. Column *pCol;
  98415. sqlite3 *db = pParse->db;
  98416. if( (p = pParse->pNewTable)==0 ) return;
  98417. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  98418. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  98419. return;
  98420. }
  98421. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  98422. if( z==0 ) return;
  98423. memcpy(z, pName->z, pName->n);
  98424. z[pName->n] = 0;
  98425. sqlite3Dequote(z);
  98426. for(i=0; i<p->nCol; i++){
  98427. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  98428. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  98429. sqlite3DbFree(db, z);
  98430. return;
  98431. }
  98432. }
  98433. if( (p->nCol & 0x7)==0 ){
  98434. Column *aNew;
  98435. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  98436. if( aNew==0 ){
  98437. sqlite3DbFree(db, z);
  98438. return;
  98439. }
  98440. p->aCol = aNew;
  98441. }
  98442. pCol = &p->aCol[p->nCol];
  98443. memset(pCol, 0, sizeof(p->aCol[0]));
  98444. pCol->zName = z;
  98445. sqlite3ColumnPropertiesFromName(p, pCol);
  98446. if( pType->n==0 ){
  98447. /* If there is no type specified, columns have the default affinity
  98448. ** 'BLOB' with a default size of 4 bytes. */
  98449. pCol->affinity = SQLITE_AFF_BLOB;
  98450. pCol->szEst = 1;
  98451. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  98452. if( 4>=sqlite3GlobalConfig.szSorterRef ){
  98453. pCol->colFlags |= COLFLAG_SORTERREF;
  98454. }
  98455. #endif
  98456. }else{
  98457. zType = z + sqlite3Strlen30(z) + 1;
  98458. memcpy(zType, pType->z, pType->n);
  98459. zType[pType->n] = 0;
  98460. sqlite3Dequote(zType);
  98461. pCol->affinity = sqlite3AffinityType(zType, pCol);
  98462. pCol->colFlags |= COLFLAG_HASTYPE;
  98463. }
  98464. p->nCol++;
  98465. pParse->constraintName.n = 0;
  98466. }
  98467. /*
  98468. ** This routine is called by the parser while in the middle of
  98469. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  98470. ** been seen on a column. This routine sets the notNull flag on
  98471. ** the column currently under construction.
  98472. */
  98473. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  98474. Table *p;
  98475. Column *pCol;
  98476. p = pParse->pNewTable;
  98477. if( p==0 || NEVER(p->nCol<1) ) return;
  98478. pCol = &p->aCol[p->nCol-1];
  98479. pCol->notNull = (u8)onError;
  98480. p->tabFlags |= TF_HasNotNull;
  98481. /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
  98482. ** on this column. */
  98483. if( pCol->colFlags & COLFLAG_UNIQUE ){
  98484. Index *pIdx;
  98485. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  98486. assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
  98487. if( pIdx->aiColumn[0]==p->nCol-1 ){
  98488. pIdx->uniqNotNull = 1;
  98489. }
  98490. }
  98491. }
  98492. }
  98493. /*
  98494. ** Scan the column type name zType (length nType) and return the
  98495. ** associated affinity type.
  98496. **
  98497. ** This routine does a case-independent search of zType for the
  98498. ** substrings in the following table. If one of the substrings is
  98499. ** found, the corresponding affinity is returned. If zType contains
  98500. ** more than one of the substrings, entries toward the top of
  98501. ** the table take priority. For example, if zType is 'BLOBINT',
  98502. ** SQLITE_AFF_INTEGER is returned.
  98503. **
  98504. ** Substring | Affinity
  98505. ** --------------------------------
  98506. ** 'INT' | SQLITE_AFF_INTEGER
  98507. ** 'CHAR' | SQLITE_AFF_TEXT
  98508. ** 'CLOB' | SQLITE_AFF_TEXT
  98509. ** 'TEXT' | SQLITE_AFF_TEXT
  98510. ** 'BLOB' | SQLITE_AFF_BLOB
  98511. ** 'REAL' | SQLITE_AFF_REAL
  98512. ** 'FLOA' | SQLITE_AFF_REAL
  98513. ** 'DOUB' | SQLITE_AFF_REAL
  98514. **
  98515. ** If none of the substrings in the above table are found,
  98516. ** SQLITE_AFF_NUMERIC is returned.
  98517. */
  98518. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
  98519. u32 h = 0;
  98520. char aff = SQLITE_AFF_NUMERIC;
  98521. const char *zChar = 0;
  98522. assert( zIn!=0 );
  98523. while( zIn[0] ){
  98524. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  98525. zIn++;
  98526. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  98527. aff = SQLITE_AFF_TEXT;
  98528. zChar = zIn;
  98529. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  98530. aff = SQLITE_AFF_TEXT;
  98531. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  98532. aff = SQLITE_AFF_TEXT;
  98533. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  98534. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  98535. aff = SQLITE_AFF_BLOB;
  98536. if( zIn[0]=='(' ) zChar = zIn;
  98537. #ifndef SQLITE_OMIT_FLOATING_POINT
  98538. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  98539. && aff==SQLITE_AFF_NUMERIC ){
  98540. aff = SQLITE_AFF_REAL;
  98541. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  98542. && aff==SQLITE_AFF_NUMERIC ){
  98543. aff = SQLITE_AFF_REAL;
  98544. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  98545. && aff==SQLITE_AFF_NUMERIC ){
  98546. aff = SQLITE_AFF_REAL;
  98547. #endif
  98548. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  98549. aff = SQLITE_AFF_INTEGER;
  98550. break;
  98551. }
  98552. }
  98553. /* If pCol is not NULL, store an estimate of the field size. The
  98554. ** estimate is scaled so that the size of an integer is 1. */
  98555. if( pCol ){
  98556. int v = 0; /* default size is approx 4 bytes */
  98557. if( aff<SQLITE_AFF_NUMERIC ){
  98558. if( zChar ){
  98559. while( zChar[0] ){
  98560. if( sqlite3Isdigit(zChar[0]) ){
  98561. /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  98562. sqlite3GetInt32(zChar, &v);
  98563. break;
  98564. }
  98565. zChar++;
  98566. }
  98567. }else{
  98568. v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  98569. }
  98570. }
  98571. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  98572. if( v>=sqlite3GlobalConfig.szSorterRef ){
  98573. pCol->colFlags |= COLFLAG_SORTERREF;
  98574. }
  98575. #endif
  98576. v = v/4 + 1;
  98577. if( v>255 ) v = 255;
  98578. pCol->szEst = v;
  98579. }
  98580. return aff;
  98581. }
  98582. /*
  98583. ** The expression is the default value for the most recently added column
  98584. ** of the table currently under construction.
  98585. **
  98586. ** Default value expressions must be constant. Raise an exception if this
  98587. ** is not the case.
  98588. **
  98589. ** This routine is called by the parser while in the middle of
  98590. ** parsing a CREATE TABLE statement.
  98591. */
  98592. SQLITE_PRIVATE void sqlite3AddDefaultValue(
  98593. Parse *pParse, /* Parsing context */
  98594. Expr *pExpr, /* The parsed expression of the default value */
  98595. const char *zStart, /* Start of the default value text */
  98596. const char *zEnd /* First character past end of defaut value text */
  98597. ){
  98598. Table *p;
  98599. Column *pCol;
  98600. sqlite3 *db = pParse->db;
  98601. p = pParse->pNewTable;
  98602. if( p!=0 ){
  98603. pCol = &(p->aCol[p->nCol-1]);
  98604. if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
  98605. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  98606. pCol->zName);
  98607. }else{
  98608. /* A copy of pExpr is used instead of the original, as pExpr contains
  98609. ** tokens that point to volatile memory.
  98610. */
  98611. Expr x;
  98612. sqlite3ExprDelete(db, pCol->pDflt);
  98613. memset(&x, 0, sizeof(x));
  98614. x.op = TK_SPAN;
  98615. x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
  98616. x.pLeft = pExpr;
  98617. x.flags = EP_Skip;
  98618. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  98619. sqlite3DbFree(db, x.u.zToken);
  98620. }
  98621. }
  98622. sqlite3ExprDelete(db, pExpr);
  98623. }
  98624. /*
  98625. ** Backwards Compatibility Hack:
  98626. **
  98627. ** Historical versions of SQLite accepted strings as column names in
  98628. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  98629. **
  98630. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  98631. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  98632. **
  98633. ** This is goofy. But to preserve backwards compatibility we continue to
  98634. ** accept it. This routine does the necessary conversion. It converts
  98635. ** the expression given in its argument from a TK_STRING into a TK_ID
  98636. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  98637. ** If the epxression is anything other than TK_STRING, the expression is
  98638. ** unchanged.
  98639. */
  98640. static void sqlite3StringToId(Expr *p){
  98641. if( p->op==TK_STRING ){
  98642. p->op = TK_ID;
  98643. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  98644. p->pLeft->op = TK_ID;
  98645. }
  98646. }
  98647. /*
  98648. ** Designate the PRIMARY KEY for the table. pList is a list of names
  98649. ** of columns that form the primary key. If pList is NULL, then the
  98650. ** most recently added column of the table is the primary key.
  98651. **
  98652. ** A table can have at most one primary key. If the table already has
  98653. ** a primary key (and this is the second primary key) then create an
  98654. ** error.
  98655. **
  98656. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  98657. ** then we will try to use that column as the rowid. Set the Table.iPKey
  98658. ** field of the table under construction to be the index of the
  98659. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  98660. ** no INTEGER PRIMARY KEY.
  98661. **
  98662. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  98663. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  98664. */
  98665. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  98666. Parse *pParse, /* Parsing context */
  98667. ExprList *pList, /* List of field names to be indexed */
  98668. int onError, /* What to do with a uniqueness conflict */
  98669. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  98670. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  98671. ){
  98672. Table *pTab = pParse->pNewTable;
  98673. Column *pCol = 0;
  98674. int iCol = -1, i;
  98675. int nTerm;
  98676. if( pTab==0 ) goto primary_key_exit;
  98677. if( pTab->tabFlags & TF_HasPrimaryKey ){
  98678. sqlite3ErrorMsg(pParse,
  98679. "table \"%s\" has more than one primary key", pTab->zName);
  98680. goto primary_key_exit;
  98681. }
  98682. pTab->tabFlags |= TF_HasPrimaryKey;
  98683. if( pList==0 ){
  98684. iCol = pTab->nCol - 1;
  98685. pCol = &pTab->aCol[iCol];
  98686. pCol->colFlags |= COLFLAG_PRIMKEY;
  98687. nTerm = 1;
  98688. }else{
  98689. nTerm = pList->nExpr;
  98690. for(i=0; i<nTerm; i++){
  98691. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  98692. assert( pCExpr!=0 );
  98693. sqlite3StringToId(pCExpr);
  98694. if( pCExpr->op==TK_ID ){
  98695. const char *zCName = pCExpr->u.zToken;
  98696. for(iCol=0; iCol<pTab->nCol; iCol++){
  98697. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  98698. pCol = &pTab->aCol[iCol];
  98699. pCol->colFlags |= COLFLAG_PRIMKEY;
  98700. break;
  98701. }
  98702. }
  98703. }
  98704. }
  98705. }
  98706. if( nTerm==1
  98707. && pCol
  98708. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  98709. && sortOrder!=SQLITE_SO_DESC
  98710. ){
  98711. pTab->iPKey = iCol;
  98712. pTab->keyConf = (u8)onError;
  98713. assert( autoInc==0 || autoInc==1 );
  98714. pTab->tabFlags |= autoInc*TF_Autoincrement;
  98715. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  98716. }else if( autoInc ){
  98717. #ifndef SQLITE_OMIT_AUTOINCREMENT
  98718. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  98719. "INTEGER PRIMARY KEY");
  98720. #endif
  98721. }else{
  98722. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  98723. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  98724. pList = 0;
  98725. }
  98726. primary_key_exit:
  98727. sqlite3ExprListDelete(pParse->db, pList);
  98728. return;
  98729. }
  98730. /*
  98731. ** Add a new CHECK constraint to the table currently under construction.
  98732. */
  98733. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  98734. Parse *pParse, /* Parsing context */
  98735. Expr *pCheckExpr /* The check expression */
  98736. ){
  98737. #ifndef SQLITE_OMIT_CHECK
  98738. Table *pTab = pParse->pNewTable;
  98739. sqlite3 *db = pParse->db;
  98740. if( pTab && !IN_DECLARE_VTAB
  98741. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  98742. ){
  98743. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  98744. if( pParse->constraintName.n ){
  98745. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  98746. }
  98747. }else
  98748. #endif
  98749. {
  98750. sqlite3ExprDelete(pParse->db, pCheckExpr);
  98751. }
  98752. }
  98753. /*
  98754. ** Set the collation function of the most recently parsed table column
  98755. ** to the CollSeq given.
  98756. */
  98757. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  98758. Table *p;
  98759. int i;
  98760. char *zColl; /* Dequoted name of collation sequence */
  98761. sqlite3 *db;
  98762. if( (p = pParse->pNewTable)==0 ) return;
  98763. i = p->nCol-1;
  98764. db = pParse->db;
  98765. zColl = sqlite3NameFromToken(db, pToken);
  98766. if( !zColl ) return;
  98767. if( sqlite3LocateCollSeq(pParse, zColl) ){
  98768. Index *pIdx;
  98769. sqlite3DbFree(db, p->aCol[i].zColl);
  98770. p->aCol[i].zColl = zColl;
  98771. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  98772. ** then an index may have been created on this column before the
  98773. ** collation type was added. Correct this if it is the case.
  98774. */
  98775. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  98776. assert( pIdx->nKeyCol==1 );
  98777. if( pIdx->aiColumn[0]==i ){
  98778. pIdx->azColl[0] = p->aCol[i].zColl;
  98779. }
  98780. }
  98781. }else{
  98782. sqlite3DbFree(db, zColl);
  98783. }
  98784. }
  98785. /*
  98786. ** This function returns the collation sequence for database native text
  98787. ** encoding identified by the string zName, length nName.
  98788. **
  98789. ** If the requested collation sequence is not available, or not available
  98790. ** in the database native encoding, the collation factory is invoked to
  98791. ** request it. If the collation factory does not supply such a sequence,
  98792. ** and the sequence is available in another text encoding, then that is
  98793. ** returned instead.
  98794. **
  98795. ** If no versions of the requested collations sequence are available, or
  98796. ** another error occurs, NULL is returned and an error message written into
  98797. ** pParse.
  98798. **
  98799. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  98800. ** invokes the collation factory if the named collation cannot be found
  98801. ** and generates an error message.
  98802. **
  98803. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  98804. */
  98805. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  98806. sqlite3 *db = pParse->db;
  98807. u8 enc = ENC(db);
  98808. u8 initbusy = db->init.busy;
  98809. CollSeq *pColl;
  98810. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  98811. if( !initbusy && (!pColl || !pColl->xCmp) ){
  98812. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  98813. }
  98814. return pColl;
  98815. }
  98816. /*
  98817. ** Generate code that will increment the schema cookie.
  98818. **
  98819. ** The schema cookie is used to determine when the schema for the
  98820. ** database changes. After each schema change, the cookie value
  98821. ** changes. When a process first reads the schema it records the
  98822. ** cookie. Thereafter, whenever it goes to access the database,
  98823. ** it checks the cookie to make sure the schema has not changed
  98824. ** since it was last read.
  98825. **
  98826. ** This plan is not completely bullet-proof. It is possible for
  98827. ** the schema to change multiple times and for the cookie to be
  98828. ** set back to prior value. But schema changes are infrequent
  98829. ** and the probability of hitting the same cookie value is only
  98830. ** 1 chance in 2^32. So we're safe enough.
  98831. **
  98832. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  98833. ** the schema-version whenever the schema changes.
  98834. */
  98835. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  98836. sqlite3 *db = pParse->db;
  98837. Vdbe *v = pParse->pVdbe;
  98838. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98839. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  98840. (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
  98841. }
  98842. /*
  98843. ** Measure the number of characters needed to output the given
  98844. ** identifier. The number returned includes any quotes used
  98845. ** but does not include the null terminator.
  98846. **
  98847. ** The estimate is conservative. It might be larger that what is
  98848. ** really needed.
  98849. */
  98850. static int identLength(const char *z){
  98851. int n;
  98852. for(n=0; *z; n++, z++){
  98853. if( *z=='"' ){ n++; }
  98854. }
  98855. return n + 2;
  98856. }
  98857. /*
  98858. ** The first parameter is a pointer to an output buffer. The second
  98859. ** parameter is a pointer to an integer that contains the offset at
  98860. ** which to write into the output buffer. This function copies the
  98861. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  98862. ** to the specified offset in the buffer and updates *pIdx to refer
  98863. ** to the first byte after the last byte written before returning.
  98864. **
  98865. ** If the string zSignedIdent consists entirely of alpha-numeric
  98866. ** characters, does not begin with a digit and is not an SQL keyword,
  98867. ** then it is copied to the output buffer exactly as it is. Otherwise,
  98868. ** it is quoted using double-quotes.
  98869. */
  98870. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  98871. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  98872. int i, j, needQuote;
  98873. i = *pIdx;
  98874. for(j=0; zIdent[j]; j++){
  98875. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  98876. }
  98877. needQuote = sqlite3Isdigit(zIdent[0])
  98878. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  98879. || zIdent[j]!=0
  98880. || j==0;
  98881. if( needQuote ) z[i++] = '"';
  98882. for(j=0; zIdent[j]; j++){
  98883. z[i++] = zIdent[j];
  98884. if( zIdent[j]=='"' ) z[i++] = '"';
  98885. }
  98886. if( needQuote ) z[i++] = '"';
  98887. z[i] = 0;
  98888. *pIdx = i;
  98889. }
  98890. /*
  98891. ** Generate a CREATE TABLE statement appropriate for the given
  98892. ** table. Memory to hold the text of the statement is obtained
  98893. ** from sqliteMalloc() and must be freed by the calling function.
  98894. */
  98895. static char *createTableStmt(sqlite3 *db, Table *p){
  98896. int i, k, n;
  98897. char *zStmt;
  98898. char *zSep, *zSep2, *zEnd;
  98899. Column *pCol;
  98900. n = 0;
  98901. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  98902. n += identLength(pCol->zName) + 5;
  98903. }
  98904. n += identLength(p->zName);
  98905. if( n<50 ){
  98906. zSep = "";
  98907. zSep2 = ",";
  98908. zEnd = ")";
  98909. }else{
  98910. zSep = "\n ";
  98911. zSep2 = ",\n ";
  98912. zEnd = "\n)";
  98913. }
  98914. n += 35 + 6*p->nCol;
  98915. zStmt = sqlite3DbMallocRaw(0, n);
  98916. if( zStmt==0 ){
  98917. sqlite3OomFault(db);
  98918. return 0;
  98919. }
  98920. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  98921. k = sqlite3Strlen30(zStmt);
  98922. identPut(zStmt, &k, p->zName);
  98923. zStmt[k++] = '(';
  98924. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  98925. static const char * const azType[] = {
  98926. /* SQLITE_AFF_BLOB */ "",
  98927. /* SQLITE_AFF_TEXT */ " TEXT",
  98928. /* SQLITE_AFF_NUMERIC */ " NUM",
  98929. /* SQLITE_AFF_INTEGER */ " INT",
  98930. /* SQLITE_AFF_REAL */ " REAL"
  98931. };
  98932. int len;
  98933. const char *zType;
  98934. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  98935. k += sqlite3Strlen30(&zStmt[k]);
  98936. zSep = zSep2;
  98937. identPut(zStmt, &k, pCol->zName);
  98938. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  98939. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  98940. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  98941. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  98942. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  98943. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  98944. testcase( pCol->affinity==SQLITE_AFF_REAL );
  98945. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  98946. len = sqlite3Strlen30(zType);
  98947. assert( pCol->affinity==SQLITE_AFF_BLOB
  98948. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  98949. memcpy(&zStmt[k], zType, len);
  98950. k += len;
  98951. assert( k<=n );
  98952. }
  98953. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  98954. return zStmt;
  98955. }
  98956. /*
  98957. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  98958. ** on success and SQLITE_NOMEM on an OOM error.
  98959. */
  98960. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  98961. char *zExtra;
  98962. int nByte;
  98963. if( pIdx->nColumn>=N ) return SQLITE_OK;
  98964. assert( pIdx->isResized==0 );
  98965. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  98966. zExtra = sqlite3DbMallocZero(db, nByte);
  98967. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  98968. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  98969. pIdx->azColl = (const char**)zExtra;
  98970. zExtra += sizeof(char*)*N;
  98971. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  98972. pIdx->aiColumn = (i16*)zExtra;
  98973. zExtra += sizeof(i16)*N;
  98974. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  98975. pIdx->aSortOrder = (u8*)zExtra;
  98976. pIdx->nColumn = N;
  98977. pIdx->isResized = 1;
  98978. return SQLITE_OK;
  98979. }
  98980. /*
  98981. ** Estimate the total row width for a table.
  98982. */
  98983. static void estimateTableWidth(Table *pTab){
  98984. unsigned wTable = 0;
  98985. const Column *pTabCol;
  98986. int i;
  98987. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  98988. wTable += pTabCol->szEst;
  98989. }
  98990. if( pTab->iPKey<0 ) wTable++;
  98991. pTab->szTabRow = sqlite3LogEst(wTable*4);
  98992. }
  98993. /*
  98994. ** Estimate the average size of a row for an index.
  98995. */
  98996. static void estimateIndexWidth(Index *pIdx){
  98997. unsigned wIndex = 0;
  98998. int i;
  98999. const Column *aCol = pIdx->pTable->aCol;
  99000. for(i=0; i<pIdx->nColumn; i++){
  99001. i16 x = pIdx->aiColumn[i];
  99002. assert( x<pIdx->pTable->nCol );
  99003. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  99004. }
  99005. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  99006. }
  99007. /* Return true if value x is found any of the first nCol entries of aiCol[]
  99008. */
  99009. static int hasColumn(const i16 *aiCol, int nCol, int x){
  99010. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  99011. return 0;
  99012. }
  99013. /*
  99014. ** This routine runs at the end of parsing a CREATE TABLE statement that
  99015. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  99016. ** internal schema data structures and the generated VDBE code so that they
  99017. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  99018. ** Changes include:
  99019. **
  99020. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  99021. ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
  99022. ** into BTREE_BLOBKEY.
  99023. ** (3) Bypass the creation of the sqlite_master table entry
  99024. ** for the PRIMARY KEY as the primary key index is now
  99025. ** identified by the sqlite_master table entry of the table itself.
  99026. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  99027. ** schema to the rootpage from the main table.
  99028. ** (5) Add all table columns to the PRIMARY KEY Index object
  99029. ** so that the PRIMARY KEY is a covering index. The surplus
  99030. ** columns are part of KeyInfo.nAllField and are not used for
  99031. ** sorting or lookup or uniqueness checks.
  99032. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  99033. ** indices with the PRIMARY KEY columns.
  99034. **
  99035. ** For virtual tables, only (1) is performed.
  99036. */
  99037. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  99038. Index *pIdx;
  99039. Index *pPk;
  99040. int nPk;
  99041. int i, j;
  99042. sqlite3 *db = pParse->db;
  99043. Vdbe *v = pParse->pVdbe;
  99044. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  99045. */
  99046. if( !db->init.imposterTable ){
  99047. for(i=0; i<pTab->nCol; i++){
  99048. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  99049. pTab->aCol[i].notNull = OE_Abort;
  99050. }
  99051. }
  99052. }
  99053. /* The remaining transformations only apply to b-tree tables, not to
  99054. ** virtual tables */
  99055. if( IN_DECLARE_VTAB ) return;
  99056. /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
  99057. ** into BTREE_BLOBKEY.
  99058. */
  99059. if( pParse->addrCrTab ){
  99060. assert( v );
  99061. sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
  99062. }
  99063. /* Locate the PRIMARY KEY index. Or, if this table was originally
  99064. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  99065. */
  99066. if( pTab->iPKey>=0 ){
  99067. ExprList *pList;
  99068. Token ipkToken;
  99069. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  99070. pList = sqlite3ExprListAppend(pParse, 0,
  99071. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  99072. if( pList==0 ) return;
  99073. pList->a[0].sortOrder = pParse->iPkSortOrder;
  99074. assert( pParse->pNewTable==pTab );
  99075. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  99076. SQLITE_IDXTYPE_PRIMARYKEY);
  99077. if( db->mallocFailed ) return;
  99078. pPk = sqlite3PrimaryKeyIndex(pTab);
  99079. pTab->iPKey = -1;
  99080. }else{
  99081. pPk = sqlite3PrimaryKeyIndex(pTab);
  99082. /*
  99083. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  99084. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  99085. ** code assumes the PRIMARY KEY contains no repeated columns.
  99086. */
  99087. for(i=j=1; i<pPk->nKeyCol; i++){
  99088. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  99089. pPk->nColumn--;
  99090. }else{
  99091. pPk->aiColumn[j++] = pPk->aiColumn[i];
  99092. }
  99093. }
  99094. pPk->nKeyCol = j;
  99095. }
  99096. assert( pPk!=0 );
  99097. pPk->isCovering = 1;
  99098. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  99099. nPk = pPk->nKeyCol;
  99100. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  99101. ** table entry. This is only required if currently generating VDBE
  99102. ** code for a CREATE TABLE (not when parsing one as part of reading
  99103. ** a database schema). */
  99104. if( v && pPk->tnum>0 ){
  99105. assert( db->init.busy==0 );
  99106. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  99107. }
  99108. /* The root page of the PRIMARY KEY is the table root page */
  99109. pPk->tnum = pTab->tnum;
  99110. /* Update the in-memory representation of all UNIQUE indices by converting
  99111. ** the final rowid column into one or more columns of the PRIMARY KEY.
  99112. */
  99113. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99114. int n;
  99115. if( IsPrimaryKeyIndex(pIdx) ) continue;
  99116. for(i=n=0; i<nPk; i++){
  99117. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  99118. }
  99119. if( n==0 ){
  99120. /* This index is a superset of the primary key */
  99121. pIdx->nColumn = pIdx->nKeyCol;
  99122. continue;
  99123. }
  99124. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  99125. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  99126. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  99127. pIdx->aiColumn[j] = pPk->aiColumn[i];
  99128. pIdx->azColl[j] = pPk->azColl[i];
  99129. j++;
  99130. }
  99131. }
  99132. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  99133. assert( pIdx->nColumn>=j );
  99134. }
  99135. /* Add all table columns to the PRIMARY KEY index
  99136. */
  99137. if( nPk<pTab->nCol ){
  99138. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  99139. for(i=0, j=nPk; i<pTab->nCol; i++){
  99140. if( !hasColumn(pPk->aiColumn, j, i) ){
  99141. assert( j<pPk->nColumn );
  99142. pPk->aiColumn[j] = i;
  99143. pPk->azColl[j] = sqlite3StrBINARY;
  99144. j++;
  99145. }
  99146. }
  99147. assert( pPk->nColumn==j );
  99148. assert( pTab->nCol==j );
  99149. }else{
  99150. pPk->nColumn = pTab->nCol;
  99151. }
  99152. }
  99153. /*
  99154. ** This routine is called to report the final ")" that terminates
  99155. ** a CREATE TABLE statement.
  99156. **
  99157. ** The table structure that other action routines have been building
  99158. ** is added to the internal hash tables, assuming no errors have
  99159. ** occurred.
  99160. **
  99161. ** An entry for the table is made in the master table on disk, unless
  99162. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  99163. ** it means we are reading the sqlite_master table because we just
  99164. ** connected to the database or because the sqlite_master table has
  99165. ** recently changed, so the entry for this table already exists in
  99166. ** the sqlite_master table. We do not want to create it again.
  99167. **
  99168. ** If the pSelect argument is not NULL, it means that this routine
  99169. ** was called to create a table generated from a
  99170. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  99171. ** the new table will match the result set of the SELECT.
  99172. */
  99173. SQLITE_PRIVATE void sqlite3EndTable(
  99174. Parse *pParse, /* Parse context */
  99175. Token *pCons, /* The ',' token after the last column defn. */
  99176. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  99177. u8 tabOpts, /* Extra table options. Usually 0. */
  99178. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  99179. ){
  99180. Table *p; /* The new table */
  99181. sqlite3 *db = pParse->db; /* The database connection */
  99182. int iDb; /* Database in which the table lives */
  99183. Index *pIdx; /* An implied index of the table */
  99184. if( pEnd==0 && pSelect==0 ){
  99185. return;
  99186. }
  99187. assert( !db->mallocFailed );
  99188. p = pParse->pNewTable;
  99189. if( p==0 ) return;
  99190. /* If the db->init.busy is 1 it means we are reading the SQL off the
  99191. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  99192. ** So do not write to the disk again. Extract the root page number
  99193. ** for the table from the db->init.newTnum field. (The page number
  99194. ** should have been put there by the sqliteOpenCb routine.)
  99195. **
  99196. ** If the root page number is 1, that means this is the sqlite_master
  99197. ** table itself. So mark it read-only.
  99198. */
  99199. if( db->init.busy ){
  99200. if( pSelect ){
  99201. sqlite3ErrorMsg(pParse, "");
  99202. return;
  99203. }
  99204. p->tnum = db->init.newTnum;
  99205. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  99206. }
  99207. /* Special processing for WITHOUT ROWID Tables */
  99208. if( tabOpts & TF_WithoutRowid ){
  99209. if( (p->tabFlags & TF_Autoincrement) ){
  99210. sqlite3ErrorMsg(pParse,
  99211. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  99212. return;
  99213. }
  99214. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  99215. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  99216. }else{
  99217. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  99218. convertToWithoutRowidTable(pParse, p);
  99219. }
  99220. }
  99221. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  99222. #ifndef SQLITE_OMIT_CHECK
  99223. /* Resolve names in all CHECK constraint expressions.
  99224. */
  99225. if( p->pCheck ){
  99226. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  99227. }
  99228. #endif /* !defined(SQLITE_OMIT_CHECK) */
  99229. /* Estimate the average row size for the table and for all implied indices */
  99230. estimateTableWidth(p);
  99231. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  99232. estimateIndexWidth(pIdx);
  99233. }
  99234. /* If not initializing, then create a record for the new table
  99235. ** in the SQLITE_MASTER table of the database.
  99236. **
  99237. ** If this is a TEMPORARY table, write the entry into the auxiliary
  99238. ** file instead of into the main database file.
  99239. */
  99240. if( !db->init.busy ){
  99241. int n;
  99242. Vdbe *v;
  99243. char *zType; /* "view" or "table" */
  99244. char *zType2; /* "VIEW" or "TABLE" */
  99245. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  99246. v = sqlite3GetVdbe(pParse);
  99247. if( NEVER(v==0) ) return;
  99248. sqlite3VdbeAddOp1(v, OP_Close, 0);
  99249. /*
  99250. ** Initialize zType for the new view or table.
  99251. */
  99252. if( p->pSelect==0 ){
  99253. /* A regular table */
  99254. zType = "table";
  99255. zType2 = "TABLE";
  99256. #ifndef SQLITE_OMIT_VIEW
  99257. }else{
  99258. /* A view */
  99259. zType = "view";
  99260. zType2 = "VIEW";
  99261. #endif
  99262. }
  99263. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  99264. ** statement to populate the new table. The root-page number for the
  99265. ** new table is in register pParse->regRoot.
  99266. **
  99267. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  99268. ** suitable state to query for the column names and types to be used
  99269. ** by the new table.
  99270. **
  99271. ** A shared-cache write-lock is not required to write to the new table,
  99272. ** as a schema-lock must have already been obtained to create it. Since
  99273. ** a schema-lock excludes all other database users, the write-lock would
  99274. ** be redundant.
  99275. */
  99276. if( pSelect ){
  99277. SelectDest dest; /* Where the SELECT should store results */
  99278. int regYield; /* Register holding co-routine entry-point */
  99279. int addrTop; /* Top of the co-routine */
  99280. int regRec; /* A record to be insert into the new table */
  99281. int regRowid; /* Rowid of the next row to insert */
  99282. int addrInsLoop; /* Top of the loop for inserting rows */
  99283. Table *pSelTab; /* A table that describes the SELECT results */
  99284. regYield = ++pParse->nMem;
  99285. regRec = ++pParse->nMem;
  99286. regRowid = ++pParse->nMem;
  99287. assert(pParse->nTab==1);
  99288. sqlite3MayAbort(pParse);
  99289. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  99290. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  99291. pParse->nTab = 2;
  99292. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  99293. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  99294. if( pParse->nErr ) return;
  99295. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  99296. if( pSelTab==0 ) return;
  99297. assert( p->aCol==0 );
  99298. p->nCol = pSelTab->nCol;
  99299. p->aCol = pSelTab->aCol;
  99300. pSelTab->nCol = 0;
  99301. pSelTab->aCol = 0;
  99302. sqlite3DeleteTable(db, pSelTab);
  99303. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  99304. sqlite3Select(pParse, pSelect, &dest);
  99305. if( pParse->nErr ) return;
  99306. sqlite3VdbeEndCoroutine(v, regYield);
  99307. sqlite3VdbeJumpHere(v, addrTop - 1);
  99308. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  99309. VdbeCoverage(v);
  99310. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  99311. sqlite3TableAffinity(v, p, 0);
  99312. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  99313. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  99314. sqlite3VdbeGoto(v, addrInsLoop);
  99315. sqlite3VdbeJumpHere(v, addrInsLoop);
  99316. sqlite3VdbeAddOp1(v, OP_Close, 1);
  99317. }
  99318. /* Compute the complete text of the CREATE statement */
  99319. if( pSelect ){
  99320. zStmt = createTableStmt(db, p);
  99321. }else{
  99322. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  99323. n = (int)(pEnd2->z - pParse->sNameToken.z);
  99324. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  99325. zStmt = sqlite3MPrintf(db,
  99326. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  99327. );
  99328. }
  99329. /* A slot for the record has already been allocated in the
  99330. ** SQLITE_MASTER table. We just need to update that slot with all
  99331. ** the information we've collected.
  99332. */
  99333. sqlite3NestedParse(pParse,
  99334. "UPDATE %Q.%s "
  99335. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  99336. "WHERE rowid=#%d",
  99337. db->aDb[iDb].zDbSName, MASTER_NAME,
  99338. zType,
  99339. p->zName,
  99340. p->zName,
  99341. pParse->regRoot,
  99342. zStmt,
  99343. pParse->regRowid
  99344. );
  99345. sqlite3DbFree(db, zStmt);
  99346. sqlite3ChangeCookie(pParse, iDb);
  99347. #ifndef SQLITE_OMIT_AUTOINCREMENT
  99348. /* Check to see if we need to create an sqlite_sequence table for
  99349. ** keeping track of autoincrement keys.
  99350. */
  99351. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  99352. Db *pDb = &db->aDb[iDb];
  99353. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99354. if( pDb->pSchema->pSeqTab==0 ){
  99355. sqlite3NestedParse(pParse,
  99356. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  99357. pDb->zDbSName
  99358. );
  99359. }
  99360. }
  99361. #endif
  99362. /* Reparse everything to update our internal data structures */
  99363. sqlite3VdbeAddParseSchemaOp(v, iDb,
  99364. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  99365. }
  99366. /* Add the table to the in-memory representation of the database.
  99367. */
  99368. if( db->init.busy ){
  99369. Table *pOld;
  99370. Schema *pSchema = p->pSchema;
  99371. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99372. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  99373. if( pOld ){
  99374. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  99375. sqlite3OomFault(db);
  99376. return;
  99377. }
  99378. pParse->pNewTable = 0;
  99379. db->mDbFlags |= DBFLAG_SchemaChange;
  99380. #ifndef SQLITE_OMIT_ALTERTABLE
  99381. if( !p->pSelect ){
  99382. const char *zName = (const char *)pParse->sNameToken.z;
  99383. int nName;
  99384. assert( !pSelect && pCons && pEnd );
  99385. if( pCons->z==0 ){
  99386. pCons = pEnd;
  99387. }
  99388. nName = (int)((const char *)pCons->z - zName);
  99389. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  99390. }
  99391. #endif
  99392. }
  99393. }
  99394. #ifndef SQLITE_OMIT_VIEW
  99395. /*
  99396. ** The parser calls this routine in order to create a new VIEW
  99397. */
  99398. SQLITE_PRIVATE void sqlite3CreateView(
  99399. Parse *pParse, /* The parsing context */
  99400. Token *pBegin, /* The CREATE token that begins the statement */
  99401. Token *pName1, /* The token that holds the name of the view */
  99402. Token *pName2, /* The token that holds the name of the view */
  99403. ExprList *pCNames, /* Optional list of view column names */
  99404. Select *pSelect, /* A SELECT statement that will become the new view */
  99405. int isTemp, /* TRUE for a TEMPORARY view */
  99406. int noErr /* Suppress error messages if VIEW already exists */
  99407. ){
  99408. Table *p;
  99409. int n;
  99410. const char *z;
  99411. Token sEnd;
  99412. DbFixer sFix;
  99413. Token *pName = 0;
  99414. int iDb;
  99415. sqlite3 *db = pParse->db;
  99416. if( pParse->nVar>0 ){
  99417. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  99418. goto create_view_fail;
  99419. }
  99420. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  99421. p = pParse->pNewTable;
  99422. if( p==0 || pParse->nErr ) goto create_view_fail;
  99423. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  99424. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  99425. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  99426. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  99427. /* Make a copy of the entire SELECT statement that defines the view.
  99428. ** This will force all the Expr.token.z values to be dynamically
  99429. ** allocated rather than point to the input string - which means that
  99430. ** they will persist after the current sqlite3_exec() call returns.
  99431. */
  99432. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  99433. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  99434. if( db->mallocFailed ) goto create_view_fail;
  99435. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  99436. ** the end.
  99437. */
  99438. sEnd = pParse->sLastToken;
  99439. assert( sEnd.z[0]!=0 || sEnd.n==0 );
  99440. if( sEnd.z[0]!=';' ){
  99441. sEnd.z += sEnd.n;
  99442. }
  99443. sEnd.n = 0;
  99444. n = (int)(sEnd.z - pBegin->z);
  99445. assert( n>0 );
  99446. z = pBegin->z;
  99447. while( sqlite3Isspace(z[n-1]) ){ n--; }
  99448. sEnd.z = &z[n-1];
  99449. sEnd.n = 1;
  99450. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  99451. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  99452. create_view_fail:
  99453. sqlite3SelectDelete(db, pSelect);
  99454. sqlite3ExprListDelete(db, pCNames);
  99455. return;
  99456. }
  99457. #endif /* SQLITE_OMIT_VIEW */
  99458. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  99459. /*
  99460. ** The Table structure pTable is really a VIEW. Fill in the names of
  99461. ** the columns of the view in the pTable structure. Return the number
  99462. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  99463. */
  99464. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  99465. Table *pSelTab; /* A fake table from which we get the result set */
  99466. Select *pSel; /* Copy of the SELECT that implements the view */
  99467. int nErr = 0; /* Number of errors encountered */
  99468. int n; /* Temporarily holds the number of cursors assigned */
  99469. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  99470. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99471. int rc;
  99472. #endif
  99473. #ifndef SQLITE_OMIT_AUTHORIZATION
  99474. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  99475. #endif
  99476. assert( pTable );
  99477. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99478. db->nSchemaLock++;
  99479. rc = sqlite3VtabCallConnect(pParse, pTable);
  99480. db->nSchemaLock--;
  99481. if( rc ){
  99482. return 1;
  99483. }
  99484. if( IsVirtual(pTable) ) return 0;
  99485. #endif
  99486. #ifndef SQLITE_OMIT_VIEW
  99487. /* A positive nCol means the columns names for this view are
  99488. ** already known.
  99489. */
  99490. if( pTable->nCol>0 ) return 0;
  99491. /* A negative nCol is a special marker meaning that we are currently
  99492. ** trying to compute the column names. If we enter this routine with
  99493. ** a negative nCol, it means two or more views form a loop, like this:
  99494. **
  99495. ** CREATE VIEW one AS SELECT * FROM two;
  99496. ** CREATE VIEW two AS SELECT * FROM one;
  99497. **
  99498. ** Actually, the error above is now caught prior to reaching this point.
  99499. ** But the following test is still important as it does come up
  99500. ** in the following:
  99501. **
  99502. ** CREATE TABLE main.ex1(a);
  99503. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  99504. ** SELECT * FROM temp.ex1;
  99505. */
  99506. if( pTable->nCol<0 ){
  99507. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  99508. return 1;
  99509. }
  99510. assert( pTable->nCol>=0 );
  99511. /* If we get this far, it means we need to compute the table names.
  99512. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  99513. ** "*" elements in the results set of the view and will assign cursors
  99514. ** to the elements of the FROM clause. But we do not want these changes
  99515. ** to be permanent. So the computation is done on a copy of the SELECT
  99516. ** statement that defines the view.
  99517. */
  99518. assert( pTable->pSelect );
  99519. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  99520. if( pSel ){
  99521. n = pParse->nTab;
  99522. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  99523. pTable->nCol = -1;
  99524. db->lookaside.bDisable++;
  99525. #ifndef SQLITE_OMIT_AUTHORIZATION
  99526. xAuth = db->xAuth;
  99527. db->xAuth = 0;
  99528. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  99529. db->xAuth = xAuth;
  99530. #else
  99531. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  99532. #endif
  99533. pParse->nTab = n;
  99534. if( pTable->pCheck ){
  99535. /* CREATE VIEW name(arglist) AS ...
  99536. ** The names of the columns in the table are taken from
  99537. ** arglist which is stored in pTable->pCheck. The pCheck field
  99538. ** normally holds CHECK constraints on an ordinary table, but for
  99539. ** a VIEW it holds the list of column names.
  99540. */
  99541. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  99542. &pTable->nCol, &pTable->aCol);
  99543. if( db->mallocFailed==0
  99544. && pParse->nErr==0
  99545. && pTable->nCol==pSel->pEList->nExpr
  99546. ){
  99547. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  99548. }
  99549. }else if( pSelTab ){
  99550. /* CREATE VIEW name AS... without an argument list. Construct
  99551. ** the column names from the SELECT statement that defines the view.
  99552. */
  99553. assert( pTable->aCol==0 );
  99554. pTable->nCol = pSelTab->nCol;
  99555. pTable->aCol = pSelTab->aCol;
  99556. pSelTab->nCol = 0;
  99557. pSelTab->aCol = 0;
  99558. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  99559. }else{
  99560. pTable->nCol = 0;
  99561. nErr++;
  99562. }
  99563. sqlite3DeleteTable(db, pSelTab);
  99564. sqlite3SelectDelete(db, pSel);
  99565. db->lookaside.bDisable--;
  99566. } else {
  99567. nErr++;
  99568. }
  99569. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  99570. #endif /* SQLITE_OMIT_VIEW */
  99571. return nErr;
  99572. }
  99573. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  99574. #ifndef SQLITE_OMIT_VIEW
  99575. /*
  99576. ** Clear the column names from every VIEW in database idx.
  99577. */
  99578. static void sqliteViewResetAll(sqlite3 *db, int idx){
  99579. HashElem *i;
  99580. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  99581. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  99582. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  99583. Table *pTab = sqliteHashData(i);
  99584. if( pTab->pSelect ){
  99585. sqlite3DeleteColumnNames(db, pTab);
  99586. pTab->aCol = 0;
  99587. pTab->nCol = 0;
  99588. }
  99589. }
  99590. DbClearProperty(db, idx, DB_UnresetViews);
  99591. }
  99592. #else
  99593. # define sqliteViewResetAll(A,B)
  99594. #endif /* SQLITE_OMIT_VIEW */
  99595. /*
  99596. ** This function is called by the VDBE to adjust the internal schema
  99597. ** used by SQLite when the btree layer moves a table root page. The
  99598. ** root-page of a table or index in database iDb has changed from iFrom
  99599. ** to iTo.
  99600. **
  99601. ** Ticket #1728: The symbol table might still contain information
  99602. ** on tables and/or indices that are the process of being deleted.
  99603. ** If you are unlucky, one of those deleted indices or tables might
  99604. ** have the same rootpage number as the real table or index that is
  99605. ** being moved. So we cannot stop searching after the first match
  99606. ** because the first match might be for one of the deleted indices
  99607. ** or tables and not the table/index that is actually being moved.
  99608. ** We must continue looping until all tables and indices with
  99609. ** rootpage==iFrom have been converted to have a rootpage of iTo
  99610. ** in order to be certain that we got the right one.
  99611. */
  99612. #ifndef SQLITE_OMIT_AUTOVACUUM
  99613. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  99614. HashElem *pElem;
  99615. Hash *pHash;
  99616. Db *pDb;
  99617. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99618. pDb = &db->aDb[iDb];
  99619. pHash = &pDb->pSchema->tblHash;
  99620. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  99621. Table *pTab = sqliteHashData(pElem);
  99622. if( pTab->tnum==iFrom ){
  99623. pTab->tnum = iTo;
  99624. }
  99625. }
  99626. pHash = &pDb->pSchema->idxHash;
  99627. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  99628. Index *pIdx = sqliteHashData(pElem);
  99629. if( pIdx->tnum==iFrom ){
  99630. pIdx->tnum = iTo;
  99631. }
  99632. }
  99633. }
  99634. #endif
  99635. /*
  99636. ** Write code to erase the table with root-page iTable from database iDb.
  99637. ** Also write code to modify the sqlite_master table and internal schema
  99638. ** if a root-page of another table is moved by the btree-layer whilst
  99639. ** erasing iTable (this can happen with an auto-vacuum database).
  99640. */
  99641. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  99642. Vdbe *v = sqlite3GetVdbe(pParse);
  99643. int r1 = sqlite3GetTempReg(pParse);
  99644. assert( iTable>1 );
  99645. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  99646. sqlite3MayAbort(pParse);
  99647. #ifndef SQLITE_OMIT_AUTOVACUUM
  99648. /* OP_Destroy stores an in integer r1. If this integer
  99649. ** is non-zero, then it is the root page number of a table moved to
  99650. ** location iTable. The following code modifies the sqlite_master table to
  99651. ** reflect this.
  99652. **
  99653. ** The "#NNN" in the SQL is a special constant that means whatever value
  99654. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  99655. ** token for additional information.
  99656. */
  99657. sqlite3NestedParse(pParse,
  99658. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  99659. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  99660. #endif
  99661. sqlite3ReleaseTempReg(pParse, r1);
  99662. }
  99663. /*
  99664. ** Write VDBE code to erase table pTab and all associated indices on disk.
  99665. ** Code to update the sqlite_master tables and internal schema definitions
  99666. ** in case a root-page belonging to another table is moved by the btree layer
  99667. ** is also added (this can happen with an auto-vacuum database).
  99668. */
  99669. static void destroyTable(Parse *pParse, Table *pTab){
  99670. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  99671. ** is not defined), then it is important to call OP_Destroy on the
  99672. ** table and index root-pages in order, starting with the numerically
  99673. ** largest root-page number. This guarantees that none of the root-pages
  99674. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  99675. ** following were coded:
  99676. **
  99677. ** OP_Destroy 4 0
  99678. ** ...
  99679. ** OP_Destroy 5 0
  99680. **
  99681. ** and root page 5 happened to be the largest root-page number in the
  99682. ** database, then root page 5 would be moved to page 4 by the
  99683. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  99684. ** a free-list page.
  99685. */
  99686. int iTab = pTab->tnum;
  99687. int iDestroyed = 0;
  99688. while( 1 ){
  99689. Index *pIdx;
  99690. int iLargest = 0;
  99691. if( iDestroyed==0 || iTab<iDestroyed ){
  99692. iLargest = iTab;
  99693. }
  99694. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99695. int iIdx = pIdx->tnum;
  99696. assert( pIdx->pSchema==pTab->pSchema );
  99697. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  99698. iLargest = iIdx;
  99699. }
  99700. }
  99701. if( iLargest==0 ){
  99702. return;
  99703. }else{
  99704. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  99705. assert( iDb>=0 && iDb<pParse->db->nDb );
  99706. destroyRootPage(pParse, iLargest, iDb);
  99707. iDestroyed = iLargest;
  99708. }
  99709. }
  99710. }
  99711. /*
  99712. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  99713. ** after a DROP INDEX or DROP TABLE command.
  99714. */
  99715. static void sqlite3ClearStatTables(
  99716. Parse *pParse, /* The parsing context */
  99717. int iDb, /* The database number */
  99718. const char *zType, /* "idx" or "tbl" */
  99719. const char *zName /* Name of index or table */
  99720. ){
  99721. int i;
  99722. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  99723. for(i=1; i<=4; i++){
  99724. char zTab[24];
  99725. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  99726. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  99727. sqlite3NestedParse(pParse,
  99728. "DELETE FROM %Q.%s WHERE %s=%Q",
  99729. zDbName, zTab, zType, zName
  99730. );
  99731. }
  99732. }
  99733. }
  99734. /*
  99735. ** Generate code to drop a table.
  99736. */
  99737. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  99738. Vdbe *v;
  99739. sqlite3 *db = pParse->db;
  99740. Trigger *pTrigger;
  99741. Db *pDb = &db->aDb[iDb];
  99742. v = sqlite3GetVdbe(pParse);
  99743. assert( v!=0 );
  99744. sqlite3BeginWriteOperation(pParse, 1, iDb);
  99745. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99746. if( IsVirtual(pTab) ){
  99747. sqlite3VdbeAddOp0(v, OP_VBegin);
  99748. }
  99749. #endif
  99750. /* Drop all triggers associated with the table being dropped. Code
  99751. ** is generated to remove entries from sqlite_master and/or
  99752. ** sqlite_temp_master if required.
  99753. */
  99754. pTrigger = sqlite3TriggerList(pParse, pTab);
  99755. while( pTrigger ){
  99756. assert( pTrigger->pSchema==pTab->pSchema ||
  99757. pTrigger->pSchema==db->aDb[1].pSchema );
  99758. sqlite3DropTriggerPtr(pParse, pTrigger);
  99759. pTrigger = pTrigger->pNext;
  99760. }
  99761. #ifndef SQLITE_OMIT_AUTOINCREMENT
  99762. /* Remove any entries of the sqlite_sequence table associated with
  99763. ** the table being dropped. This is done before the table is dropped
  99764. ** at the btree level, in case the sqlite_sequence table needs to
  99765. ** move as a result of the drop (can happen in auto-vacuum mode).
  99766. */
  99767. if( pTab->tabFlags & TF_Autoincrement ){
  99768. sqlite3NestedParse(pParse,
  99769. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  99770. pDb->zDbSName, pTab->zName
  99771. );
  99772. }
  99773. #endif
  99774. /* Drop all SQLITE_MASTER table and index entries that refer to the
  99775. ** table. The program name loops through the master table and deletes
  99776. ** every row that refers to a table of the same name as the one being
  99777. ** dropped. Triggers are handled separately because a trigger can be
  99778. ** created in the temp database that refers to a table in another
  99779. ** database.
  99780. */
  99781. sqlite3NestedParse(pParse,
  99782. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  99783. pDb->zDbSName, MASTER_NAME, pTab->zName);
  99784. if( !isView && !IsVirtual(pTab) ){
  99785. destroyTable(pParse, pTab);
  99786. }
  99787. /* Remove the table entry from SQLite's internal schema and modify
  99788. ** the schema cookie.
  99789. */
  99790. if( IsVirtual(pTab) ){
  99791. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  99792. }
  99793. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  99794. sqlite3ChangeCookie(pParse, iDb);
  99795. sqliteViewResetAll(db, iDb);
  99796. }
  99797. /*
  99798. ** This routine is called to do the work of a DROP TABLE statement.
  99799. ** pName is the name of the table to be dropped.
  99800. */
  99801. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  99802. Table *pTab;
  99803. Vdbe *v;
  99804. sqlite3 *db = pParse->db;
  99805. int iDb;
  99806. if( db->mallocFailed ){
  99807. goto exit_drop_table;
  99808. }
  99809. assert( pParse->nErr==0 );
  99810. assert( pName->nSrc==1 );
  99811. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  99812. if( noErr ) db->suppressErr++;
  99813. assert( isView==0 || isView==LOCATE_VIEW );
  99814. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  99815. if( noErr ) db->suppressErr--;
  99816. if( pTab==0 ){
  99817. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  99818. goto exit_drop_table;
  99819. }
  99820. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99821. assert( iDb>=0 && iDb<db->nDb );
  99822. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  99823. ** it is initialized.
  99824. */
  99825. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  99826. goto exit_drop_table;
  99827. }
  99828. #ifndef SQLITE_OMIT_AUTHORIZATION
  99829. {
  99830. int code;
  99831. const char *zTab = SCHEMA_TABLE(iDb);
  99832. const char *zDb = db->aDb[iDb].zDbSName;
  99833. const char *zArg2 = 0;
  99834. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  99835. goto exit_drop_table;
  99836. }
  99837. if( isView ){
  99838. if( !OMIT_TEMPDB && iDb==1 ){
  99839. code = SQLITE_DROP_TEMP_VIEW;
  99840. }else{
  99841. code = SQLITE_DROP_VIEW;
  99842. }
  99843. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99844. }else if( IsVirtual(pTab) ){
  99845. code = SQLITE_DROP_VTABLE;
  99846. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  99847. #endif
  99848. }else{
  99849. if( !OMIT_TEMPDB && iDb==1 ){
  99850. code = SQLITE_DROP_TEMP_TABLE;
  99851. }else{
  99852. code = SQLITE_DROP_TABLE;
  99853. }
  99854. }
  99855. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  99856. goto exit_drop_table;
  99857. }
  99858. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  99859. goto exit_drop_table;
  99860. }
  99861. }
  99862. #endif
  99863. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  99864. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  99865. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  99866. goto exit_drop_table;
  99867. }
  99868. #ifndef SQLITE_OMIT_VIEW
  99869. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  99870. ** on a table.
  99871. */
  99872. if( isView && pTab->pSelect==0 ){
  99873. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  99874. goto exit_drop_table;
  99875. }
  99876. if( !isView && pTab->pSelect ){
  99877. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  99878. goto exit_drop_table;
  99879. }
  99880. #endif
  99881. /* Generate code to remove the table from the master table
  99882. ** on disk.
  99883. */
  99884. v = sqlite3GetVdbe(pParse);
  99885. if( v ){
  99886. sqlite3BeginWriteOperation(pParse, 1, iDb);
  99887. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  99888. sqlite3FkDropTable(pParse, pName, pTab);
  99889. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  99890. }
  99891. exit_drop_table:
  99892. sqlite3SrcListDelete(db, pName);
  99893. }
  99894. /*
  99895. ** This routine is called to create a new foreign key on the table
  99896. ** currently under construction. pFromCol determines which columns
  99897. ** in the current table point to the foreign key. If pFromCol==0 then
  99898. ** connect the key to the last column inserted. pTo is the name of
  99899. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  99900. ** of tables in the parent pTo table. flags contains all
  99901. ** information about the conflict resolution algorithms specified
  99902. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  99903. **
  99904. ** An FKey structure is created and added to the table currently
  99905. ** under construction in the pParse->pNewTable field.
  99906. **
  99907. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  99908. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  99909. */
  99910. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  99911. Parse *pParse, /* Parsing context */
  99912. ExprList *pFromCol, /* Columns in this table that point to other table */
  99913. Token *pTo, /* Name of the other table */
  99914. ExprList *pToCol, /* Columns in the other table */
  99915. int flags /* Conflict resolution algorithms. */
  99916. ){
  99917. sqlite3 *db = pParse->db;
  99918. #ifndef SQLITE_OMIT_FOREIGN_KEY
  99919. FKey *pFKey = 0;
  99920. FKey *pNextTo;
  99921. Table *p = pParse->pNewTable;
  99922. int nByte;
  99923. int i;
  99924. int nCol;
  99925. char *z;
  99926. assert( pTo!=0 );
  99927. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  99928. if( pFromCol==0 ){
  99929. int iCol = p->nCol-1;
  99930. if( NEVER(iCol<0) ) goto fk_end;
  99931. if( pToCol && pToCol->nExpr!=1 ){
  99932. sqlite3ErrorMsg(pParse, "foreign key on %s"
  99933. " should reference only one column of table %T",
  99934. p->aCol[iCol].zName, pTo);
  99935. goto fk_end;
  99936. }
  99937. nCol = 1;
  99938. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  99939. sqlite3ErrorMsg(pParse,
  99940. "number of columns in foreign key does not match the number of "
  99941. "columns in the referenced table");
  99942. goto fk_end;
  99943. }else{
  99944. nCol = pFromCol->nExpr;
  99945. }
  99946. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  99947. if( pToCol ){
  99948. for(i=0; i<pToCol->nExpr; i++){
  99949. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  99950. }
  99951. }
  99952. pFKey = sqlite3DbMallocZero(db, nByte );
  99953. if( pFKey==0 ){
  99954. goto fk_end;
  99955. }
  99956. pFKey->pFrom = p;
  99957. pFKey->pNextFrom = p->pFKey;
  99958. z = (char*)&pFKey->aCol[nCol];
  99959. pFKey->zTo = z;
  99960. memcpy(z, pTo->z, pTo->n);
  99961. z[pTo->n] = 0;
  99962. sqlite3Dequote(z);
  99963. z += pTo->n+1;
  99964. pFKey->nCol = nCol;
  99965. if( pFromCol==0 ){
  99966. pFKey->aCol[0].iFrom = p->nCol-1;
  99967. }else{
  99968. for(i=0; i<nCol; i++){
  99969. int j;
  99970. for(j=0; j<p->nCol; j++){
  99971. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  99972. pFKey->aCol[i].iFrom = j;
  99973. break;
  99974. }
  99975. }
  99976. if( j>=p->nCol ){
  99977. sqlite3ErrorMsg(pParse,
  99978. "unknown column \"%s\" in foreign key definition",
  99979. pFromCol->a[i].zName);
  99980. goto fk_end;
  99981. }
  99982. }
  99983. }
  99984. if( pToCol ){
  99985. for(i=0; i<nCol; i++){
  99986. int n = sqlite3Strlen30(pToCol->a[i].zName);
  99987. pFKey->aCol[i].zCol = z;
  99988. memcpy(z, pToCol->a[i].zName, n);
  99989. z[n] = 0;
  99990. z += n+1;
  99991. }
  99992. }
  99993. pFKey->isDeferred = 0;
  99994. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  99995. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  99996. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  99997. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  99998. pFKey->zTo, (void *)pFKey
  99999. );
  100000. if( pNextTo==pFKey ){
  100001. sqlite3OomFault(db);
  100002. goto fk_end;
  100003. }
  100004. if( pNextTo ){
  100005. assert( pNextTo->pPrevTo==0 );
  100006. pFKey->pNextTo = pNextTo;
  100007. pNextTo->pPrevTo = pFKey;
  100008. }
  100009. /* Link the foreign key to the table as the last step.
  100010. */
  100011. p->pFKey = pFKey;
  100012. pFKey = 0;
  100013. fk_end:
  100014. sqlite3DbFree(db, pFKey);
  100015. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  100016. sqlite3ExprListDelete(db, pFromCol);
  100017. sqlite3ExprListDelete(db, pToCol);
  100018. }
  100019. /*
  100020. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  100021. ** clause is seen as part of a foreign key definition. The isDeferred
  100022. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  100023. ** The behavior of the most recently created foreign key is adjusted
  100024. ** accordingly.
  100025. */
  100026. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  100027. #ifndef SQLITE_OMIT_FOREIGN_KEY
  100028. Table *pTab;
  100029. FKey *pFKey;
  100030. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  100031. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  100032. pFKey->isDeferred = (u8)isDeferred;
  100033. #endif
  100034. }
  100035. /*
  100036. ** Generate code that will erase and refill index *pIdx. This is
  100037. ** used to initialize a newly created index or to recompute the
  100038. ** content of an index in response to a REINDEX command.
  100039. **
  100040. ** if memRootPage is not negative, it means that the index is newly
  100041. ** created. The register specified by memRootPage contains the
  100042. ** root page number of the index. If memRootPage is negative, then
  100043. ** the index already exists and must be cleared before being refilled and
  100044. ** the root page number of the index is taken from pIndex->tnum.
  100045. */
  100046. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  100047. Table *pTab = pIndex->pTable; /* The table that is indexed */
  100048. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  100049. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  100050. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  100051. int addr1; /* Address of top of loop */
  100052. int addr2; /* Address to jump to for next iteration */
  100053. int tnum; /* Root page of index */
  100054. int iPartIdxLabel; /* Jump to this label to skip a row */
  100055. Vdbe *v; /* Generate code into this virtual machine */
  100056. KeyInfo *pKey; /* KeyInfo for index */
  100057. int regRecord; /* Register holding assembled index record */
  100058. sqlite3 *db = pParse->db; /* The database connection */
  100059. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  100060. #ifndef SQLITE_OMIT_AUTHORIZATION
  100061. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  100062. db->aDb[iDb].zDbSName ) ){
  100063. return;
  100064. }
  100065. #endif
  100066. /* Require a write-lock on the table to perform this operation */
  100067. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  100068. v = sqlite3GetVdbe(pParse);
  100069. if( v==0 ) return;
  100070. if( memRootPage>=0 ){
  100071. tnum = memRootPage;
  100072. }else{
  100073. tnum = pIndex->tnum;
  100074. }
  100075. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  100076. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  100077. /* Open the sorter cursor if we are to use one. */
  100078. iSorter = pParse->nTab++;
  100079. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  100080. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  100081. /* Open the table. Loop through all rows of the table, inserting index
  100082. ** records into the sorter. */
  100083. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  100084. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  100085. regRecord = sqlite3GetTempReg(pParse);
  100086. sqlite3MultiWrite(pParse);
  100087. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  100088. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  100089. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  100090. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  100091. sqlite3VdbeJumpHere(v, addr1);
  100092. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  100093. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  100094. (char *)pKey, P4_KEYINFO);
  100095. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  100096. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  100097. if( IsUniqueIndex(pIndex) ){
  100098. int j2 = sqlite3VdbeGoto(v, 1);
  100099. addr2 = sqlite3VdbeCurrentAddr(v);
  100100. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  100101. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  100102. pIndex->nKeyCol); VdbeCoverage(v);
  100103. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  100104. sqlite3VdbeJumpHere(v, j2);
  100105. }else{
  100106. addr2 = sqlite3VdbeCurrentAddr(v);
  100107. }
  100108. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  100109. sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
  100110. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  100111. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  100112. sqlite3ReleaseTempReg(pParse, regRecord);
  100113. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  100114. sqlite3VdbeJumpHere(v, addr1);
  100115. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  100116. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  100117. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  100118. }
  100119. /*
  100120. ** Allocate heap space to hold an Index object with nCol columns.
  100121. **
  100122. ** Increase the allocation size to provide an extra nExtra bytes
  100123. ** of 8-byte aligned space after the Index object and return a
  100124. ** pointer to this extra space in *ppExtra.
  100125. */
  100126. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  100127. sqlite3 *db, /* Database connection */
  100128. i16 nCol, /* Total number of columns in the index */
  100129. int nExtra, /* Number of bytes of extra space to alloc */
  100130. char **ppExtra /* Pointer to the "extra" space */
  100131. ){
  100132. Index *p; /* Allocated index object */
  100133. int nByte; /* Bytes of space for Index object + arrays */
  100134. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  100135. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  100136. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  100137. sizeof(i16)*nCol + /* Index.aiColumn */
  100138. sizeof(u8)*nCol); /* Index.aSortOrder */
  100139. p = sqlite3DbMallocZero(db, nByte + nExtra);
  100140. if( p ){
  100141. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  100142. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  100143. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  100144. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  100145. p->aSortOrder = (u8*)pExtra;
  100146. p->nColumn = nCol;
  100147. p->nKeyCol = nCol - 1;
  100148. *ppExtra = ((char*)p) + nByte;
  100149. }
  100150. return p;
  100151. }
  100152. /*
  100153. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  100154. ** and pTblList is the name of the table that is to be indexed. Both will
  100155. ** be NULL for a primary key or an index that is created to satisfy a
  100156. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  100157. ** as the table to be indexed. pParse->pNewTable is a table that is
  100158. ** currently being constructed by a CREATE TABLE statement.
  100159. **
  100160. ** pList is a list of columns to be indexed. pList will be NULL if this
  100161. ** is a primary key or unique-constraint on the most recent column added
  100162. ** to the table currently under construction.
  100163. */
  100164. SQLITE_PRIVATE void sqlite3CreateIndex(
  100165. Parse *pParse, /* All information about this parse */
  100166. Token *pName1, /* First part of index name. May be NULL */
  100167. Token *pName2, /* Second part of index name. May be NULL */
  100168. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  100169. ExprList *pList, /* A list of columns to be indexed */
  100170. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  100171. Token *pStart, /* The CREATE token that begins this statement */
  100172. Expr *pPIWhere, /* WHERE clause for partial indices */
  100173. int sortOrder, /* Sort order of primary key when pList==NULL */
  100174. int ifNotExist, /* Omit error if index already exists */
  100175. u8 idxType /* The index type */
  100176. ){
  100177. Table *pTab = 0; /* Table to be indexed */
  100178. Index *pIndex = 0; /* The index to be created */
  100179. char *zName = 0; /* Name of the index */
  100180. int nName; /* Number of characters in zName */
  100181. int i, j;
  100182. DbFixer sFix; /* For assigning database names to pTable */
  100183. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  100184. sqlite3 *db = pParse->db;
  100185. Db *pDb; /* The specific table containing the indexed database */
  100186. int iDb; /* Index of the database that is being written */
  100187. Token *pName = 0; /* Unqualified name of the index to create */
  100188. struct ExprList_item *pListItem; /* For looping over pList */
  100189. int nExtra = 0; /* Space allocated for zExtra[] */
  100190. int nExtraCol; /* Number of extra columns needed */
  100191. char *zExtra = 0; /* Extra space after the Index object */
  100192. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  100193. if( db->mallocFailed || pParse->nErr>0 ){
  100194. goto exit_create_index;
  100195. }
  100196. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  100197. goto exit_create_index;
  100198. }
  100199. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  100200. goto exit_create_index;
  100201. }
  100202. /*
  100203. ** Find the table that is to be indexed. Return early if not found.
  100204. */
  100205. if( pTblName!=0 ){
  100206. /* Use the two-part index name to determine the database
  100207. ** to search for the table. 'Fix' the table name to this db
  100208. ** before looking up the table.
  100209. */
  100210. assert( pName1 && pName2 );
  100211. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  100212. if( iDb<0 ) goto exit_create_index;
  100213. assert( pName && pName->z );
  100214. #ifndef SQLITE_OMIT_TEMPDB
  100215. /* If the index name was unqualified, check if the table
  100216. ** is a temp table. If so, set the database to 1. Do not do this
  100217. ** if initialising a database schema.
  100218. */
  100219. if( !db->init.busy ){
  100220. pTab = sqlite3SrcListLookup(pParse, pTblName);
  100221. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  100222. iDb = 1;
  100223. }
  100224. }
  100225. #endif
  100226. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  100227. if( sqlite3FixSrcList(&sFix, pTblName) ){
  100228. /* Because the parser constructs pTblName from a single identifier,
  100229. ** sqlite3FixSrcList can never fail. */
  100230. assert(0);
  100231. }
  100232. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  100233. assert( db->mallocFailed==0 || pTab==0 );
  100234. if( pTab==0 ) goto exit_create_index;
  100235. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  100236. sqlite3ErrorMsg(pParse,
  100237. "cannot create a TEMP index on non-TEMP table \"%s\"",
  100238. pTab->zName);
  100239. goto exit_create_index;
  100240. }
  100241. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  100242. }else{
  100243. assert( pName==0 );
  100244. assert( pStart==0 );
  100245. pTab = pParse->pNewTable;
  100246. if( !pTab ) goto exit_create_index;
  100247. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  100248. }
  100249. pDb = &db->aDb[iDb];
  100250. assert( pTab!=0 );
  100251. assert( pParse->nErr==0 );
  100252. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  100253. && db->init.busy==0
  100254. #if SQLITE_USER_AUTHENTICATION
  100255. && sqlite3UserAuthTable(pTab->zName)==0
  100256. #endif
  100257. #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
  100258. && sqlite3StrICmp(&pTab->zName[7],"master")!=0
  100259. #endif
  100260. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0
  100261. ){
  100262. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  100263. goto exit_create_index;
  100264. }
  100265. #ifndef SQLITE_OMIT_VIEW
  100266. if( pTab->pSelect ){
  100267. sqlite3ErrorMsg(pParse, "views may not be indexed");
  100268. goto exit_create_index;
  100269. }
  100270. #endif
  100271. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100272. if( IsVirtual(pTab) ){
  100273. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  100274. goto exit_create_index;
  100275. }
  100276. #endif
  100277. /*
  100278. ** Find the name of the index. Make sure there is not already another
  100279. ** index or table with the same name.
  100280. **
  100281. ** Exception: If we are reading the names of permanent indices from the
  100282. ** sqlite_master table (because some other process changed the schema) and
  100283. ** one of the index names collides with the name of a temporary table or
  100284. ** index, then we will continue to process this index.
  100285. **
  100286. ** If pName==0 it means that we are
  100287. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  100288. ** own name.
  100289. */
  100290. if( pName ){
  100291. zName = sqlite3NameFromToken(db, pName);
  100292. if( zName==0 ) goto exit_create_index;
  100293. assert( pName->z!=0 );
  100294. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  100295. goto exit_create_index;
  100296. }
  100297. if( !db->init.busy ){
  100298. if( sqlite3FindTable(db, zName, 0)!=0 ){
  100299. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  100300. goto exit_create_index;
  100301. }
  100302. }
  100303. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  100304. if( !ifNotExist ){
  100305. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  100306. }else{
  100307. assert( !db->init.busy );
  100308. sqlite3CodeVerifySchema(pParse, iDb);
  100309. }
  100310. goto exit_create_index;
  100311. }
  100312. }else{
  100313. int n;
  100314. Index *pLoop;
  100315. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  100316. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  100317. if( zName==0 ){
  100318. goto exit_create_index;
  100319. }
  100320. /* Automatic index names generated from within sqlite3_declare_vtab()
  100321. ** must have names that are distinct from normal automatic index names.
  100322. ** The following statement converts "sqlite3_autoindex..." into
  100323. ** "sqlite3_butoindex..." in order to make the names distinct.
  100324. ** The "vtab_err.test" test demonstrates the need of this statement. */
  100325. if( IN_DECLARE_VTAB ) zName[7]++;
  100326. }
  100327. /* Check for authorization to create an index.
  100328. */
  100329. #ifndef SQLITE_OMIT_AUTHORIZATION
  100330. {
  100331. const char *zDb = pDb->zDbSName;
  100332. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  100333. goto exit_create_index;
  100334. }
  100335. i = SQLITE_CREATE_INDEX;
  100336. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  100337. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  100338. goto exit_create_index;
  100339. }
  100340. }
  100341. #endif
  100342. /* If pList==0, it means this routine was called to make a primary
  100343. ** key out of the last column added to the table under construction.
  100344. ** So create a fake list to simulate this.
  100345. */
  100346. if( pList==0 ){
  100347. Token prevCol;
  100348. Column *pCol = &pTab->aCol[pTab->nCol-1];
  100349. pCol->colFlags |= COLFLAG_UNIQUE;
  100350. sqlite3TokenInit(&prevCol, pCol->zName);
  100351. pList = sqlite3ExprListAppend(pParse, 0,
  100352. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  100353. if( pList==0 ) goto exit_create_index;
  100354. assert( pList->nExpr==1 );
  100355. sqlite3ExprListSetSortOrder(pList, sortOrder);
  100356. }else{
  100357. sqlite3ExprListCheckLength(pParse, pList, "index");
  100358. }
  100359. /* Figure out how many bytes of space are required to store explicitly
  100360. ** specified collation sequence names.
  100361. */
  100362. for(i=0; i<pList->nExpr; i++){
  100363. Expr *pExpr = pList->a[i].pExpr;
  100364. assert( pExpr!=0 );
  100365. if( pExpr->op==TK_COLLATE ){
  100366. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  100367. }
  100368. }
  100369. /*
  100370. ** Allocate the index structure.
  100371. */
  100372. nName = sqlite3Strlen30(zName);
  100373. nExtraCol = pPk ? pPk->nKeyCol : 1;
  100374. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  100375. nName + nExtra + 1, &zExtra);
  100376. if( db->mallocFailed ){
  100377. goto exit_create_index;
  100378. }
  100379. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  100380. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  100381. pIndex->zName = zExtra;
  100382. zExtra += nName + 1;
  100383. memcpy(pIndex->zName, zName, nName+1);
  100384. pIndex->pTable = pTab;
  100385. pIndex->onError = (u8)onError;
  100386. pIndex->uniqNotNull = onError!=OE_None;
  100387. pIndex->idxType = idxType;
  100388. pIndex->pSchema = db->aDb[iDb].pSchema;
  100389. pIndex->nKeyCol = pList->nExpr;
  100390. if( pPIWhere ){
  100391. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  100392. pIndex->pPartIdxWhere = pPIWhere;
  100393. pPIWhere = 0;
  100394. }
  100395. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100396. /* Check to see if we should honor DESC requests on index columns
  100397. */
  100398. if( pDb->pSchema->file_format>=4 ){
  100399. sortOrderMask = -1; /* Honor DESC */
  100400. }else{
  100401. sortOrderMask = 0; /* Ignore DESC */
  100402. }
  100403. /* Analyze the list of expressions that form the terms of the index and
  100404. ** report any errors. In the common case where the expression is exactly
  100405. ** a table column, store that column in aiColumn[]. For general expressions,
  100406. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  100407. **
  100408. ** TODO: Issue a warning if two or more columns of the index are identical.
  100409. ** TODO: Issue a warning if the table primary key is used as part of the
  100410. ** index key.
  100411. */
  100412. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  100413. Expr *pCExpr; /* The i-th index expression */
  100414. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  100415. const char *zColl; /* Collation sequence name */
  100416. sqlite3StringToId(pListItem->pExpr);
  100417. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  100418. if( pParse->nErr ) goto exit_create_index;
  100419. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  100420. if( pCExpr->op!=TK_COLUMN ){
  100421. if( pTab==pParse->pNewTable ){
  100422. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  100423. "UNIQUE constraints");
  100424. goto exit_create_index;
  100425. }
  100426. if( pIndex->aColExpr==0 ){
  100427. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  100428. pIndex->aColExpr = pCopy;
  100429. if( !db->mallocFailed ){
  100430. assert( pCopy!=0 );
  100431. pListItem = &pCopy->a[i];
  100432. }
  100433. }
  100434. j = XN_EXPR;
  100435. pIndex->aiColumn[i] = XN_EXPR;
  100436. pIndex->uniqNotNull = 0;
  100437. }else{
  100438. j = pCExpr->iColumn;
  100439. assert( j<=0x7fff );
  100440. if( j<0 ){
  100441. j = pTab->iPKey;
  100442. }else if( pTab->aCol[j].notNull==0 ){
  100443. pIndex->uniqNotNull = 0;
  100444. }
  100445. pIndex->aiColumn[i] = (i16)j;
  100446. }
  100447. zColl = 0;
  100448. if( pListItem->pExpr->op==TK_COLLATE ){
  100449. int nColl;
  100450. zColl = pListItem->pExpr->u.zToken;
  100451. nColl = sqlite3Strlen30(zColl) + 1;
  100452. assert( nExtra>=nColl );
  100453. memcpy(zExtra, zColl, nColl);
  100454. zColl = zExtra;
  100455. zExtra += nColl;
  100456. nExtra -= nColl;
  100457. }else if( j>=0 ){
  100458. zColl = pTab->aCol[j].zColl;
  100459. }
  100460. if( !zColl ) zColl = sqlite3StrBINARY;
  100461. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  100462. goto exit_create_index;
  100463. }
  100464. pIndex->azColl[i] = zColl;
  100465. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  100466. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  100467. }
  100468. /* Append the table key to the end of the index. For WITHOUT ROWID
  100469. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  100470. ** normal tables (when pPk==0) this will be the rowid.
  100471. */
  100472. if( pPk ){
  100473. for(j=0; j<pPk->nKeyCol; j++){
  100474. int x = pPk->aiColumn[j];
  100475. assert( x>=0 );
  100476. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  100477. pIndex->nColumn--;
  100478. }else{
  100479. pIndex->aiColumn[i] = x;
  100480. pIndex->azColl[i] = pPk->azColl[j];
  100481. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  100482. i++;
  100483. }
  100484. }
  100485. assert( i==pIndex->nColumn );
  100486. }else{
  100487. pIndex->aiColumn[i] = XN_ROWID;
  100488. pIndex->azColl[i] = sqlite3StrBINARY;
  100489. }
  100490. sqlite3DefaultRowEst(pIndex);
  100491. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  100492. /* If this index contains every column of its table, then mark
  100493. ** it as a covering index */
  100494. assert( HasRowid(pTab)
  100495. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  100496. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  100497. pIndex->isCovering = 1;
  100498. for(j=0; j<pTab->nCol; j++){
  100499. if( j==pTab->iPKey ) continue;
  100500. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  100501. pIndex->isCovering = 0;
  100502. break;
  100503. }
  100504. }
  100505. if( pTab==pParse->pNewTable ){
  100506. /* This routine has been called to create an automatic index as a
  100507. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  100508. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  100509. ** i.e. one of:
  100510. **
  100511. ** CREATE TABLE t(x PRIMARY KEY, y);
  100512. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  100513. **
  100514. ** Either way, check to see if the table already has such an index. If
  100515. ** so, don't bother creating this one. This only applies to
  100516. ** automatically created indices. Users can do as they wish with
  100517. ** explicit indices.
  100518. **
  100519. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  100520. ** (and thus suppressing the second one) even if they have different
  100521. ** sort orders.
  100522. **
  100523. ** If there are different collating sequences or if the columns of
  100524. ** the constraint occur in different orders, then the constraints are
  100525. ** considered distinct and both result in separate indices.
  100526. */
  100527. Index *pIdx;
  100528. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  100529. int k;
  100530. assert( IsUniqueIndex(pIdx) );
  100531. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  100532. assert( IsUniqueIndex(pIndex) );
  100533. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  100534. for(k=0; k<pIdx->nKeyCol; k++){
  100535. const char *z1;
  100536. const char *z2;
  100537. assert( pIdx->aiColumn[k]>=0 );
  100538. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  100539. z1 = pIdx->azColl[k];
  100540. z2 = pIndex->azColl[k];
  100541. if( sqlite3StrICmp(z1, z2) ) break;
  100542. }
  100543. if( k==pIdx->nKeyCol ){
  100544. if( pIdx->onError!=pIndex->onError ){
  100545. /* This constraint creates the same index as a previous
  100546. ** constraint specified somewhere in the CREATE TABLE statement.
  100547. ** However the ON CONFLICT clauses are different. If both this
  100548. ** constraint and the previous equivalent constraint have explicit
  100549. ** ON CONFLICT clauses this is an error. Otherwise, use the
  100550. ** explicitly specified behavior for the index.
  100551. */
  100552. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  100553. sqlite3ErrorMsg(pParse,
  100554. "conflicting ON CONFLICT clauses specified", 0);
  100555. }
  100556. if( pIdx->onError==OE_Default ){
  100557. pIdx->onError = pIndex->onError;
  100558. }
  100559. }
  100560. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  100561. goto exit_create_index;
  100562. }
  100563. }
  100564. }
  100565. /* Link the new Index structure to its table and to the other
  100566. ** in-memory database structures.
  100567. */
  100568. assert( pParse->nErr==0 );
  100569. if( db->init.busy ){
  100570. Index *p;
  100571. assert( !IN_DECLARE_VTAB );
  100572. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  100573. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  100574. pIndex->zName, pIndex);
  100575. if( p ){
  100576. assert( p==pIndex ); /* Malloc must have failed */
  100577. sqlite3OomFault(db);
  100578. goto exit_create_index;
  100579. }
  100580. db->mDbFlags |= DBFLAG_SchemaChange;
  100581. if( pTblName!=0 ){
  100582. pIndex->tnum = db->init.newTnum;
  100583. }
  100584. }
  100585. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  100586. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  100587. ** emit code to allocate the index rootpage on disk and make an entry for
  100588. ** the index in the sqlite_master table and populate the index with
  100589. ** content. But, do not do this if we are simply reading the sqlite_master
  100590. ** table to parse the schema, or if this index is the PRIMARY KEY index
  100591. ** of a WITHOUT ROWID table.
  100592. **
  100593. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  100594. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  100595. ** has just been created, it contains no data and the index initialization
  100596. ** step can be skipped.
  100597. */
  100598. else if( HasRowid(pTab) || pTblName!=0 ){
  100599. Vdbe *v;
  100600. char *zStmt;
  100601. int iMem = ++pParse->nMem;
  100602. v = sqlite3GetVdbe(pParse);
  100603. if( v==0 ) goto exit_create_index;
  100604. sqlite3BeginWriteOperation(pParse, 1, iDb);
  100605. /* Create the rootpage for the index using CreateIndex. But before
  100606. ** doing so, code a Noop instruction and store its address in
  100607. ** Index.tnum. This is required in case this index is actually a
  100608. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  100609. ** that case the convertToWithoutRowidTable() routine will replace
  100610. ** the Noop with a Goto to jump over the VDBE code generated below. */
  100611. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  100612. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
  100613. /* Gather the complete text of the CREATE INDEX statement into
  100614. ** the zStmt variable
  100615. */
  100616. if( pStart ){
  100617. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  100618. if( pName->z[n-1]==';' ) n--;
  100619. /* A named index with an explicit CREATE INDEX statement */
  100620. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  100621. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  100622. }else{
  100623. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  100624. /* zStmt = sqlite3MPrintf(""); */
  100625. zStmt = 0;
  100626. }
  100627. /* Add an entry in sqlite_master for this index
  100628. */
  100629. sqlite3NestedParse(pParse,
  100630. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  100631. db->aDb[iDb].zDbSName, MASTER_NAME,
  100632. pIndex->zName,
  100633. pTab->zName,
  100634. iMem,
  100635. zStmt
  100636. );
  100637. sqlite3DbFree(db, zStmt);
  100638. /* Fill the index with data and reparse the schema. Code an OP_Expire
  100639. ** to invalidate all pre-compiled statements.
  100640. */
  100641. if( pTblName ){
  100642. sqlite3RefillIndex(pParse, pIndex, iMem);
  100643. sqlite3ChangeCookie(pParse, iDb);
  100644. sqlite3VdbeAddParseSchemaOp(v, iDb,
  100645. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  100646. sqlite3VdbeAddOp0(v, OP_Expire);
  100647. }
  100648. sqlite3VdbeJumpHere(v, pIndex->tnum);
  100649. }
  100650. /* When adding an index to the list of indices for a table, make
  100651. ** sure all indices labeled OE_Replace come after all those labeled
  100652. ** OE_Ignore. This is necessary for the correct constraint check
  100653. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  100654. ** UPDATE and INSERT statements.
  100655. */
  100656. if( db->init.busy || pTblName==0 ){
  100657. if( onError!=OE_Replace || pTab->pIndex==0
  100658. || pTab->pIndex->onError==OE_Replace){
  100659. pIndex->pNext = pTab->pIndex;
  100660. pTab->pIndex = pIndex;
  100661. }else{
  100662. Index *pOther = pTab->pIndex;
  100663. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  100664. pOther = pOther->pNext;
  100665. }
  100666. pIndex->pNext = pOther->pNext;
  100667. pOther->pNext = pIndex;
  100668. }
  100669. pIndex = 0;
  100670. }
  100671. /* Clean up before exiting */
  100672. exit_create_index:
  100673. if( pIndex ) freeIndex(db, pIndex);
  100674. sqlite3ExprDelete(db, pPIWhere);
  100675. sqlite3ExprListDelete(db, pList);
  100676. sqlite3SrcListDelete(db, pTblName);
  100677. sqlite3DbFree(db, zName);
  100678. }
  100679. /*
  100680. ** Fill the Index.aiRowEst[] array with default information - information
  100681. ** to be used when we have not run the ANALYZE command.
  100682. **
  100683. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  100684. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  100685. ** number of rows in the table that match any particular value of the
  100686. ** first column of the index. aiRowEst[2] is an estimate of the number
  100687. ** of rows that match any particular combination of the first 2 columns
  100688. ** of the index. And so forth. It must always be the case that
  100689. *
  100690. ** aiRowEst[N]<=aiRowEst[N-1]
  100691. ** aiRowEst[N]>=1
  100692. **
  100693. ** Apart from that, we have little to go on besides intuition as to
  100694. ** how aiRowEst[] should be initialized. The numbers generated here
  100695. ** are based on typical values found in actual indices.
  100696. */
  100697. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  100698. /* 10, 9, 8, 7, 6 */
  100699. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  100700. LogEst *a = pIdx->aiRowLogEst;
  100701. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  100702. int i;
  100703. /* Indexes with default row estimates should not have stat1 data */
  100704. assert( !pIdx->hasStat1 );
  100705. /* Set the first entry (number of rows in the index) to the estimated
  100706. ** number of rows in the table, or half the number of rows in the table
  100707. ** for a partial index. But do not let the estimate drop below 10. */
  100708. a[0] = pIdx->pTable->nRowLogEst;
  100709. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  100710. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  100711. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  100712. ** 6 and each subsequent value (if any) is 5. */
  100713. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  100714. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  100715. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  100716. }
  100717. assert( 0==sqlite3LogEst(1) );
  100718. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  100719. }
  100720. /*
  100721. ** This routine will drop an existing named index. This routine
  100722. ** implements the DROP INDEX statement.
  100723. */
  100724. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  100725. Index *pIndex;
  100726. Vdbe *v;
  100727. sqlite3 *db = pParse->db;
  100728. int iDb;
  100729. assert( pParse->nErr==0 ); /* Never called with prior errors */
  100730. if( db->mallocFailed ){
  100731. goto exit_drop_index;
  100732. }
  100733. assert( pName->nSrc==1 );
  100734. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  100735. goto exit_drop_index;
  100736. }
  100737. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  100738. if( pIndex==0 ){
  100739. if( !ifExists ){
  100740. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  100741. }else{
  100742. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  100743. }
  100744. pParse->checkSchema = 1;
  100745. goto exit_drop_index;
  100746. }
  100747. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  100748. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  100749. "or PRIMARY KEY constraint cannot be dropped", 0);
  100750. goto exit_drop_index;
  100751. }
  100752. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  100753. #ifndef SQLITE_OMIT_AUTHORIZATION
  100754. {
  100755. int code = SQLITE_DROP_INDEX;
  100756. Table *pTab = pIndex->pTable;
  100757. const char *zDb = db->aDb[iDb].zDbSName;
  100758. const char *zTab = SCHEMA_TABLE(iDb);
  100759. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  100760. goto exit_drop_index;
  100761. }
  100762. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  100763. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  100764. goto exit_drop_index;
  100765. }
  100766. }
  100767. #endif
  100768. /* Generate code to remove the index and from the master table */
  100769. v = sqlite3GetVdbe(pParse);
  100770. if( v ){
  100771. sqlite3BeginWriteOperation(pParse, 1, iDb);
  100772. sqlite3NestedParse(pParse,
  100773. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  100774. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  100775. );
  100776. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  100777. sqlite3ChangeCookie(pParse, iDb);
  100778. destroyRootPage(pParse, pIndex->tnum, iDb);
  100779. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  100780. }
  100781. exit_drop_index:
  100782. sqlite3SrcListDelete(db, pName);
  100783. }
  100784. /*
  100785. ** pArray is a pointer to an array of objects. Each object in the
  100786. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  100787. ** to extend the array so that there is space for a new object at the end.
  100788. **
  100789. ** When this function is called, *pnEntry contains the current size of
  100790. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  100791. ** in total).
  100792. **
  100793. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  100794. ** space allocated for the new object is zeroed, *pnEntry updated to
  100795. ** reflect the new size of the array and a pointer to the new allocation
  100796. ** returned. *pIdx is set to the index of the new array entry in this case.
  100797. **
  100798. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  100799. ** unchanged and a copy of pArray returned.
  100800. */
  100801. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  100802. sqlite3 *db, /* Connection to notify of malloc failures */
  100803. void *pArray, /* Array of objects. Might be reallocated */
  100804. int szEntry, /* Size of each object in the array */
  100805. int *pnEntry, /* Number of objects currently in use */
  100806. int *pIdx /* Write the index of a new slot here */
  100807. ){
  100808. char *z;
  100809. int n = *pnEntry;
  100810. if( (n & (n-1))==0 ){
  100811. int sz = (n==0) ? 1 : 2*n;
  100812. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  100813. if( pNew==0 ){
  100814. *pIdx = -1;
  100815. return pArray;
  100816. }
  100817. pArray = pNew;
  100818. }
  100819. z = (char*)pArray;
  100820. memset(&z[n * szEntry], 0, szEntry);
  100821. *pIdx = n;
  100822. ++*pnEntry;
  100823. return pArray;
  100824. }
  100825. /*
  100826. ** Append a new element to the given IdList. Create a new IdList if
  100827. ** need be.
  100828. **
  100829. ** A new IdList is returned, or NULL if malloc() fails.
  100830. */
  100831. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  100832. int i;
  100833. if( pList==0 ){
  100834. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  100835. if( pList==0 ) return 0;
  100836. }
  100837. pList->a = sqlite3ArrayAllocate(
  100838. db,
  100839. pList->a,
  100840. sizeof(pList->a[0]),
  100841. &pList->nId,
  100842. &i
  100843. );
  100844. if( i<0 ){
  100845. sqlite3IdListDelete(db, pList);
  100846. return 0;
  100847. }
  100848. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  100849. return pList;
  100850. }
  100851. /*
  100852. ** Delete an IdList.
  100853. */
  100854. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  100855. int i;
  100856. if( pList==0 ) return;
  100857. for(i=0; i<pList->nId; i++){
  100858. sqlite3DbFree(db, pList->a[i].zName);
  100859. }
  100860. sqlite3DbFree(db, pList->a);
  100861. sqlite3DbFreeNN(db, pList);
  100862. }
  100863. /*
  100864. ** Return the index in pList of the identifier named zId. Return -1
  100865. ** if not found.
  100866. */
  100867. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  100868. int i;
  100869. if( pList==0 ) return -1;
  100870. for(i=0; i<pList->nId; i++){
  100871. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  100872. }
  100873. return -1;
  100874. }
  100875. /*
  100876. ** Expand the space allocated for the given SrcList object by
  100877. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  100878. ** New slots are zeroed.
  100879. **
  100880. ** For example, suppose a SrcList initially contains two entries: A,B.
  100881. ** To append 3 new entries onto the end, do this:
  100882. **
  100883. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  100884. **
  100885. ** After the call above it would contain: A, B, nil, nil, nil.
  100886. ** If the iStart argument had been 1 instead of 2, then the result
  100887. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  100888. ** the iStart value would be 0. The result then would
  100889. ** be: nil, nil, nil, A, B.
  100890. **
  100891. ** If a memory allocation fails the SrcList is unchanged. The
  100892. ** db->mallocFailed flag will be set to true.
  100893. */
  100894. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  100895. sqlite3 *db, /* Database connection to notify of OOM errors */
  100896. SrcList *pSrc, /* The SrcList to be enlarged */
  100897. int nExtra, /* Number of new slots to add to pSrc->a[] */
  100898. int iStart /* Index in pSrc->a[] of first new slot */
  100899. ){
  100900. int i;
  100901. /* Sanity checking on calling parameters */
  100902. assert( iStart>=0 );
  100903. assert( nExtra>=1 );
  100904. assert( pSrc!=0 );
  100905. assert( iStart<=pSrc->nSrc );
  100906. /* Allocate additional space if needed */
  100907. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  100908. SrcList *pNew;
  100909. int nAlloc = pSrc->nSrc*2+nExtra;
  100910. int nGot;
  100911. pNew = sqlite3DbRealloc(db, pSrc,
  100912. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  100913. if( pNew==0 ){
  100914. assert( db->mallocFailed );
  100915. return pSrc;
  100916. }
  100917. pSrc = pNew;
  100918. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  100919. pSrc->nAlloc = nGot;
  100920. }
  100921. /* Move existing slots that come after the newly inserted slots
  100922. ** out of the way */
  100923. for(i=pSrc->nSrc-1; i>=iStart; i--){
  100924. pSrc->a[i+nExtra] = pSrc->a[i];
  100925. }
  100926. pSrc->nSrc += nExtra;
  100927. /* Zero the newly allocated slots */
  100928. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  100929. for(i=iStart; i<iStart+nExtra; i++){
  100930. pSrc->a[i].iCursor = -1;
  100931. }
  100932. /* Return a pointer to the enlarged SrcList */
  100933. return pSrc;
  100934. }
  100935. /*
  100936. ** Append a new table name to the given SrcList. Create a new SrcList if
  100937. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  100938. **
  100939. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  100940. ** SrcList might be the same as the SrcList that was input or it might be
  100941. ** a new one. If an OOM error does occurs, then the prior value of pList
  100942. ** that is input to this routine is automatically freed.
  100943. **
  100944. ** If pDatabase is not null, it means that the table has an optional
  100945. ** database name prefix. Like this: "database.table". The pDatabase
  100946. ** points to the table name and the pTable points to the database name.
  100947. ** The SrcList.a[].zName field is filled with the table name which might
  100948. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  100949. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  100950. ** or with NULL if no database is specified.
  100951. **
  100952. ** In other words, if call like this:
  100953. **
  100954. ** sqlite3SrcListAppend(D,A,B,0);
  100955. **
  100956. ** Then B is a table name and the database name is unspecified. If called
  100957. ** like this:
  100958. **
  100959. ** sqlite3SrcListAppend(D,A,B,C);
  100960. **
  100961. ** Then C is the table name and B is the database name. If C is defined
  100962. ** then so is B. In other words, we never have a case where:
  100963. **
  100964. ** sqlite3SrcListAppend(D,A,0,C);
  100965. **
  100966. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  100967. ** before being added to the SrcList.
  100968. */
  100969. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  100970. sqlite3 *db, /* Connection to notify of malloc failures */
  100971. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  100972. Token *pTable, /* Table to append */
  100973. Token *pDatabase /* Database of the table */
  100974. ){
  100975. struct SrcList_item *pItem;
  100976. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  100977. assert( db!=0 );
  100978. if( pList==0 ){
  100979. pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  100980. if( pList==0 ) return 0;
  100981. pList->nAlloc = 1;
  100982. pList->nSrc = 1;
  100983. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  100984. pList->a[0].iCursor = -1;
  100985. }else{
  100986. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  100987. }
  100988. if( db->mallocFailed ){
  100989. sqlite3SrcListDelete(db, pList);
  100990. return 0;
  100991. }
  100992. pItem = &pList->a[pList->nSrc-1];
  100993. if( pDatabase && pDatabase->z==0 ){
  100994. pDatabase = 0;
  100995. }
  100996. if( pDatabase ){
  100997. pItem->zName = sqlite3NameFromToken(db, pDatabase);
  100998. pItem->zDatabase = sqlite3NameFromToken(db, pTable);
  100999. }else{
  101000. pItem->zName = sqlite3NameFromToken(db, pTable);
  101001. pItem->zDatabase = 0;
  101002. }
  101003. return pList;
  101004. }
  101005. /*
  101006. ** Assign VdbeCursor index numbers to all tables in a SrcList
  101007. */
  101008. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  101009. int i;
  101010. struct SrcList_item *pItem;
  101011. assert(pList || pParse->db->mallocFailed );
  101012. if( pList ){
  101013. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  101014. if( pItem->iCursor>=0 ) break;
  101015. pItem->iCursor = pParse->nTab++;
  101016. if( pItem->pSelect ){
  101017. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  101018. }
  101019. }
  101020. }
  101021. }
  101022. /*
  101023. ** Delete an entire SrcList including all its substructure.
  101024. */
  101025. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  101026. int i;
  101027. struct SrcList_item *pItem;
  101028. if( pList==0 ) return;
  101029. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  101030. sqlite3DbFree(db, pItem->zDatabase);
  101031. sqlite3DbFree(db, pItem->zName);
  101032. sqlite3DbFree(db, pItem->zAlias);
  101033. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  101034. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  101035. sqlite3DeleteTable(db, pItem->pTab);
  101036. sqlite3SelectDelete(db, pItem->pSelect);
  101037. sqlite3ExprDelete(db, pItem->pOn);
  101038. sqlite3IdListDelete(db, pItem->pUsing);
  101039. }
  101040. sqlite3DbFreeNN(db, pList);
  101041. }
  101042. /*
  101043. ** This routine is called by the parser to add a new term to the
  101044. ** end of a growing FROM clause. The "p" parameter is the part of
  101045. ** the FROM clause that has already been constructed. "p" is NULL
  101046. ** if this is the first term of the FROM clause. pTable and pDatabase
  101047. ** are the name of the table and database named in the FROM clause term.
  101048. ** pDatabase is NULL if the database name qualifier is missing - the
  101049. ** usual case. If the term has an alias, then pAlias points to the
  101050. ** alias token. If the term is a subquery, then pSubquery is the
  101051. ** SELECT statement that the subquery encodes. The pTable and
  101052. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  101053. ** parameters are the content of the ON and USING clauses.
  101054. **
  101055. ** Return a new SrcList which encodes is the FROM with the new
  101056. ** term added.
  101057. */
  101058. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  101059. Parse *pParse, /* Parsing context */
  101060. SrcList *p, /* The left part of the FROM clause already seen */
  101061. Token *pTable, /* Name of the table to add to the FROM clause */
  101062. Token *pDatabase, /* Name of the database containing pTable */
  101063. Token *pAlias, /* The right-hand side of the AS subexpression */
  101064. Select *pSubquery, /* A subquery used in place of a table name */
  101065. Expr *pOn, /* The ON clause of a join */
  101066. IdList *pUsing /* The USING clause of a join */
  101067. ){
  101068. struct SrcList_item *pItem;
  101069. sqlite3 *db = pParse->db;
  101070. if( !p && (pOn || pUsing) ){
  101071. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  101072. (pOn ? "ON" : "USING")
  101073. );
  101074. goto append_from_error;
  101075. }
  101076. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  101077. if( p==0 ){
  101078. goto append_from_error;
  101079. }
  101080. assert( p->nSrc>0 );
  101081. pItem = &p->a[p->nSrc-1];
  101082. assert( pAlias!=0 );
  101083. if( pAlias->n ){
  101084. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  101085. }
  101086. pItem->pSelect = pSubquery;
  101087. pItem->pOn = pOn;
  101088. pItem->pUsing = pUsing;
  101089. return p;
  101090. append_from_error:
  101091. assert( p==0 );
  101092. sqlite3ExprDelete(db, pOn);
  101093. sqlite3IdListDelete(db, pUsing);
  101094. sqlite3SelectDelete(db, pSubquery);
  101095. return 0;
  101096. }
  101097. /*
  101098. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  101099. ** element of the source-list passed as the second argument.
  101100. */
  101101. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  101102. assert( pIndexedBy!=0 );
  101103. if( p && pIndexedBy->n>0 ){
  101104. struct SrcList_item *pItem;
  101105. assert( p->nSrc>0 );
  101106. pItem = &p->a[p->nSrc-1];
  101107. assert( pItem->fg.notIndexed==0 );
  101108. assert( pItem->fg.isIndexedBy==0 );
  101109. assert( pItem->fg.isTabFunc==0 );
  101110. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  101111. /* A "NOT INDEXED" clause was supplied. See parse.y
  101112. ** construct "indexed_opt" for details. */
  101113. pItem->fg.notIndexed = 1;
  101114. }else{
  101115. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  101116. pItem->fg.isIndexedBy = 1;
  101117. }
  101118. }
  101119. }
  101120. /*
  101121. ** Add the list of function arguments to the SrcList entry for a
  101122. ** table-valued-function.
  101123. */
  101124. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  101125. if( p ){
  101126. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  101127. assert( pItem->fg.notIndexed==0 );
  101128. assert( pItem->fg.isIndexedBy==0 );
  101129. assert( pItem->fg.isTabFunc==0 );
  101130. pItem->u1.pFuncArg = pList;
  101131. pItem->fg.isTabFunc = 1;
  101132. }else{
  101133. sqlite3ExprListDelete(pParse->db, pList);
  101134. }
  101135. }
  101136. /*
  101137. ** When building up a FROM clause in the parser, the join operator
  101138. ** is initially attached to the left operand. But the code generator
  101139. ** expects the join operator to be on the right operand. This routine
  101140. ** Shifts all join operators from left to right for an entire FROM
  101141. ** clause.
  101142. **
  101143. ** Example: Suppose the join is like this:
  101144. **
  101145. ** A natural cross join B
  101146. **
  101147. ** The operator is "natural cross join". The A and B operands are stored
  101148. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  101149. ** operator with A. This routine shifts that operator over to B.
  101150. */
  101151. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  101152. if( p ){
  101153. int i;
  101154. for(i=p->nSrc-1; i>0; i--){
  101155. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  101156. }
  101157. p->a[0].fg.jointype = 0;
  101158. }
  101159. }
  101160. /*
  101161. ** Generate VDBE code for a BEGIN statement.
  101162. */
  101163. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  101164. sqlite3 *db;
  101165. Vdbe *v;
  101166. int i;
  101167. assert( pParse!=0 );
  101168. db = pParse->db;
  101169. assert( db!=0 );
  101170. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  101171. return;
  101172. }
  101173. v = sqlite3GetVdbe(pParse);
  101174. if( !v ) return;
  101175. if( type!=TK_DEFERRED ){
  101176. for(i=0; i<db->nDb; i++){
  101177. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  101178. sqlite3VdbeUsesBtree(v, i);
  101179. }
  101180. }
  101181. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  101182. }
  101183. /*
  101184. ** Generate VDBE code for a COMMIT or ROLLBACK statement.
  101185. ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
  101186. ** code is generated for a COMMIT.
  101187. */
  101188. SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
  101189. Vdbe *v;
  101190. int isRollback;
  101191. assert( pParse!=0 );
  101192. assert( pParse->db!=0 );
  101193. assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
  101194. isRollback = eType==TK_ROLLBACK;
  101195. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
  101196. isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
  101197. return;
  101198. }
  101199. v = sqlite3GetVdbe(pParse);
  101200. if( v ){
  101201. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
  101202. }
  101203. }
  101204. /*
  101205. ** This function is called by the parser when it parses a command to create,
  101206. ** release or rollback an SQL savepoint.
  101207. */
  101208. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  101209. char *zName = sqlite3NameFromToken(pParse->db, pName);
  101210. if( zName ){
  101211. Vdbe *v = sqlite3GetVdbe(pParse);
  101212. #ifndef SQLITE_OMIT_AUTHORIZATION
  101213. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  101214. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  101215. #endif
  101216. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  101217. sqlite3DbFree(pParse->db, zName);
  101218. return;
  101219. }
  101220. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  101221. }
  101222. }
  101223. /*
  101224. ** Make sure the TEMP database is open and available for use. Return
  101225. ** the number of errors. Leave any error messages in the pParse structure.
  101226. */
  101227. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  101228. sqlite3 *db = pParse->db;
  101229. if( db->aDb[1].pBt==0 && !pParse->explain ){
  101230. int rc;
  101231. Btree *pBt;
  101232. static const int flags =
  101233. SQLITE_OPEN_READWRITE |
  101234. SQLITE_OPEN_CREATE |
  101235. SQLITE_OPEN_EXCLUSIVE |
  101236. SQLITE_OPEN_DELETEONCLOSE |
  101237. SQLITE_OPEN_TEMP_DB;
  101238. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  101239. if( rc!=SQLITE_OK ){
  101240. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  101241. "file for storing temporary tables");
  101242. pParse->rc = rc;
  101243. return 1;
  101244. }
  101245. db->aDb[1].pBt = pBt;
  101246. assert( db->aDb[1].pSchema );
  101247. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  101248. sqlite3OomFault(db);
  101249. return 1;
  101250. }
  101251. }
  101252. return 0;
  101253. }
  101254. /*
  101255. ** Record the fact that the schema cookie will need to be verified
  101256. ** for database iDb. The code to actually verify the schema cookie
  101257. ** will occur at the end of the top-level VDBE and will be generated
  101258. ** later, by sqlite3FinishCoding().
  101259. */
  101260. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  101261. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  101262. assert( iDb>=0 && iDb<pParse->db->nDb );
  101263. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  101264. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  101265. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  101266. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  101267. DbMaskSet(pToplevel->cookieMask, iDb);
  101268. if( !OMIT_TEMPDB && iDb==1 ){
  101269. sqlite3OpenTempDatabase(pToplevel);
  101270. }
  101271. }
  101272. }
  101273. /*
  101274. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  101275. ** attached database. Otherwise, invoke it for the database named zDb only.
  101276. */
  101277. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  101278. sqlite3 *db = pParse->db;
  101279. int i;
  101280. for(i=0; i<db->nDb; i++){
  101281. Db *pDb = &db->aDb[i];
  101282. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  101283. sqlite3CodeVerifySchema(pParse, i);
  101284. }
  101285. }
  101286. }
  101287. /*
  101288. ** Generate VDBE code that prepares for doing an operation that
  101289. ** might change the database.
  101290. **
  101291. ** This routine starts a new transaction if we are not already within
  101292. ** a transaction. If we are already within a transaction, then a checkpoint
  101293. ** is set if the setStatement parameter is true. A checkpoint should
  101294. ** be set for operations that might fail (due to a constraint) part of
  101295. ** the way through and which will need to undo some writes without having to
  101296. ** rollback the whole transaction. For operations where all constraints
  101297. ** can be checked before any changes are made to the database, it is never
  101298. ** necessary to undo a write and the checkpoint should not be set.
  101299. */
  101300. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  101301. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  101302. sqlite3CodeVerifySchema(pParse, iDb);
  101303. DbMaskSet(pToplevel->writeMask, iDb);
  101304. pToplevel->isMultiWrite |= setStatement;
  101305. }
  101306. /*
  101307. ** Indicate that the statement currently under construction might write
  101308. ** more than one entry (example: deleting one row then inserting another,
  101309. ** inserting multiple rows in a table, or inserting a row and index entries.)
  101310. ** If an abort occurs after some of these writes have completed, then it will
  101311. ** be necessary to undo the completed writes.
  101312. */
  101313. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  101314. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  101315. pToplevel->isMultiWrite = 1;
  101316. }
  101317. /*
  101318. ** The code generator calls this routine if is discovers that it is
  101319. ** possible to abort a statement prior to completion. In order to
  101320. ** perform this abort without corrupting the database, we need to make
  101321. ** sure that the statement is protected by a statement transaction.
  101322. **
  101323. ** Technically, we only need to set the mayAbort flag if the
  101324. ** isMultiWrite flag was previously set. There is a time dependency
  101325. ** such that the abort must occur after the multiwrite. This makes
  101326. ** some statements involving the REPLACE conflict resolution algorithm
  101327. ** go a little faster. But taking advantage of this time dependency
  101328. ** makes it more difficult to prove that the code is correct (in
  101329. ** particular, it prevents us from writing an effective
  101330. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  101331. ** to take the safe route and skip the optimization.
  101332. */
  101333. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  101334. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  101335. pToplevel->mayAbort = 1;
  101336. }
  101337. /*
  101338. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  101339. ** error. The onError parameter determines which (if any) of the statement
  101340. ** and/or current transaction is rolled back.
  101341. */
  101342. SQLITE_PRIVATE void sqlite3HaltConstraint(
  101343. Parse *pParse, /* Parsing context */
  101344. int errCode, /* extended error code */
  101345. int onError, /* Constraint type */
  101346. char *p4, /* Error message */
  101347. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  101348. u8 p5Errmsg /* P5_ErrMsg type */
  101349. ){
  101350. Vdbe *v = sqlite3GetVdbe(pParse);
  101351. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  101352. if( onError==OE_Abort ){
  101353. sqlite3MayAbort(pParse);
  101354. }
  101355. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  101356. sqlite3VdbeChangeP5(v, p5Errmsg);
  101357. }
  101358. /*
  101359. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  101360. */
  101361. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  101362. Parse *pParse, /* Parsing context */
  101363. int onError, /* Constraint type */
  101364. Index *pIdx /* The index that triggers the constraint */
  101365. ){
  101366. char *zErr;
  101367. int j;
  101368. StrAccum errMsg;
  101369. Table *pTab = pIdx->pTable;
  101370. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  101371. if( pIdx->aColExpr ){
  101372. sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
  101373. }else{
  101374. for(j=0; j<pIdx->nKeyCol; j++){
  101375. char *zCol;
  101376. assert( pIdx->aiColumn[j]>=0 );
  101377. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  101378. if( j ) sqlite3_str_append(&errMsg, ", ", 2);
  101379. sqlite3_str_appendall(&errMsg, pTab->zName);
  101380. sqlite3_str_append(&errMsg, ".", 1);
  101381. sqlite3_str_appendall(&errMsg, zCol);
  101382. }
  101383. }
  101384. zErr = sqlite3StrAccumFinish(&errMsg);
  101385. sqlite3HaltConstraint(pParse,
  101386. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  101387. : SQLITE_CONSTRAINT_UNIQUE,
  101388. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  101389. }
  101390. /*
  101391. ** Code an OP_Halt due to non-unique rowid.
  101392. */
  101393. SQLITE_PRIVATE void sqlite3RowidConstraint(
  101394. Parse *pParse, /* Parsing context */
  101395. int onError, /* Conflict resolution algorithm */
  101396. Table *pTab /* The table with the non-unique rowid */
  101397. ){
  101398. char *zMsg;
  101399. int rc;
  101400. if( pTab->iPKey>=0 ){
  101401. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  101402. pTab->aCol[pTab->iPKey].zName);
  101403. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  101404. }else{
  101405. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  101406. rc = SQLITE_CONSTRAINT_ROWID;
  101407. }
  101408. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  101409. P5_ConstraintUnique);
  101410. }
  101411. /*
  101412. ** Check to see if pIndex uses the collating sequence pColl. Return
  101413. ** true if it does and false if it does not.
  101414. */
  101415. #ifndef SQLITE_OMIT_REINDEX
  101416. static int collationMatch(const char *zColl, Index *pIndex){
  101417. int i;
  101418. assert( zColl!=0 );
  101419. for(i=0; i<pIndex->nColumn; i++){
  101420. const char *z = pIndex->azColl[i];
  101421. assert( z!=0 || pIndex->aiColumn[i]<0 );
  101422. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  101423. return 1;
  101424. }
  101425. }
  101426. return 0;
  101427. }
  101428. #endif
  101429. /*
  101430. ** Recompute all indices of pTab that use the collating sequence pColl.
  101431. ** If pColl==0 then recompute all indices of pTab.
  101432. */
  101433. #ifndef SQLITE_OMIT_REINDEX
  101434. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  101435. Index *pIndex; /* An index associated with pTab */
  101436. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  101437. if( zColl==0 || collationMatch(zColl, pIndex) ){
  101438. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  101439. sqlite3BeginWriteOperation(pParse, 0, iDb);
  101440. sqlite3RefillIndex(pParse, pIndex, -1);
  101441. }
  101442. }
  101443. }
  101444. #endif
  101445. /*
  101446. ** Recompute all indices of all tables in all databases where the
  101447. ** indices use the collating sequence pColl. If pColl==0 then recompute
  101448. ** all indices everywhere.
  101449. */
  101450. #ifndef SQLITE_OMIT_REINDEX
  101451. static void reindexDatabases(Parse *pParse, char const *zColl){
  101452. Db *pDb; /* A single database */
  101453. int iDb; /* The database index number */
  101454. sqlite3 *db = pParse->db; /* The database connection */
  101455. HashElem *k; /* For looping over tables in pDb */
  101456. Table *pTab; /* A table in the database */
  101457. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  101458. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  101459. assert( pDb!=0 );
  101460. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  101461. pTab = (Table*)sqliteHashData(k);
  101462. reindexTable(pParse, pTab, zColl);
  101463. }
  101464. }
  101465. }
  101466. #endif
  101467. /*
  101468. ** Generate code for the REINDEX command.
  101469. **
  101470. ** REINDEX -- 1
  101471. ** REINDEX <collation> -- 2
  101472. ** REINDEX ?<database>.?<tablename> -- 3
  101473. ** REINDEX ?<database>.?<indexname> -- 4
  101474. **
  101475. ** Form 1 causes all indices in all attached databases to be rebuilt.
  101476. ** Form 2 rebuilds all indices in all databases that use the named
  101477. ** collating function. Forms 3 and 4 rebuild the named index or all
  101478. ** indices associated with the named table.
  101479. */
  101480. #ifndef SQLITE_OMIT_REINDEX
  101481. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  101482. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  101483. char *z; /* Name of a table or index */
  101484. const char *zDb; /* Name of the database */
  101485. Table *pTab; /* A table in the database */
  101486. Index *pIndex; /* An index associated with pTab */
  101487. int iDb; /* The database index number */
  101488. sqlite3 *db = pParse->db; /* The database connection */
  101489. Token *pObjName; /* Name of the table or index to be reindexed */
  101490. /* Read the database schema. If an error occurs, leave an error message
  101491. ** and code in pParse and return NULL. */
  101492. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  101493. return;
  101494. }
  101495. if( pName1==0 ){
  101496. reindexDatabases(pParse, 0);
  101497. return;
  101498. }else if( NEVER(pName2==0) || pName2->z==0 ){
  101499. char *zColl;
  101500. assert( pName1->z );
  101501. zColl = sqlite3NameFromToken(pParse->db, pName1);
  101502. if( !zColl ) return;
  101503. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  101504. if( pColl ){
  101505. reindexDatabases(pParse, zColl);
  101506. sqlite3DbFree(db, zColl);
  101507. return;
  101508. }
  101509. sqlite3DbFree(db, zColl);
  101510. }
  101511. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  101512. if( iDb<0 ) return;
  101513. z = sqlite3NameFromToken(db, pObjName);
  101514. if( z==0 ) return;
  101515. zDb = db->aDb[iDb].zDbSName;
  101516. pTab = sqlite3FindTable(db, z, zDb);
  101517. if( pTab ){
  101518. reindexTable(pParse, pTab, 0);
  101519. sqlite3DbFree(db, z);
  101520. return;
  101521. }
  101522. pIndex = sqlite3FindIndex(db, z, zDb);
  101523. sqlite3DbFree(db, z);
  101524. if( pIndex ){
  101525. sqlite3BeginWriteOperation(pParse, 0, iDb);
  101526. sqlite3RefillIndex(pParse, pIndex, -1);
  101527. return;
  101528. }
  101529. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  101530. }
  101531. #endif
  101532. /*
  101533. ** Return a KeyInfo structure that is appropriate for the given Index.
  101534. **
  101535. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  101536. ** when it has finished using it.
  101537. */
  101538. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  101539. int i;
  101540. int nCol = pIdx->nColumn;
  101541. int nKey = pIdx->nKeyCol;
  101542. KeyInfo *pKey;
  101543. if( pParse->nErr ) return 0;
  101544. if( pIdx->uniqNotNull ){
  101545. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  101546. }else{
  101547. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  101548. }
  101549. if( pKey ){
  101550. assert( sqlite3KeyInfoIsWriteable(pKey) );
  101551. for(i=0; i<nCol; i++){
  101552. const char *zColl = pIdx->azColl[i];
  101553. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  101554. sqlite3LocateCollSeq(pParse, zColl);
  101555. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  101556. }
  101557. if( pParse->nErr ){
  101558. assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
  101559. if( pIdx->bNoQuery==0 ){
  101560. /* Deactivate the index because it contains an unknown collating
  101561. ** sequence. The only way to reactive the index is to reload the
  101562. ** schema. Adding the missing collating sequence later does not
  101563. ** reactive the index. The application had the chance to register
  101564. ** the missing index using the collation-needed callback. For
  101565. ** simplicity, SQLite will not give the application a second chance.
  101566. */
  101567. pIdx->bNoQuery = 1;
  101568. pParse->rc = SQLITE_ERROR_RETRY;
  101569. }
  101570. sqlite3KeyInfoUnref(pKey);
  101571. pKey = 0;
  101572. }
  101573. }
  101574. return pKey;
  101575. }
  101576. #ifndef SQLITE_OMIT_CTE
  101577. /*
  101578. ** This routine is invoked once per CTE by the parser while parsing a
  101579. ** WITH clause.
  101580. */
  101581. SQLITE_PRIVATE With *sqlite3WithAdd(
  101582. Parse *pParse, /* Parsing context */
  101583. With *pWith, /* Existing WITH clause, or NULL */
  101584. Token *pName, /* Name of the common-table */
  101585. ExprList *pArglist, /* Optional column name list for the table */
  101586. Select *pQuery /* Query used to initialize the table */
  101587. ){
  101588. sqlite3 *db = pParse->db;
  101589. With *pNew;
  101590. char *zName;
  101591. /* Check that the CTE name is unique within this WITH clause. If
  101592. ** not, store an error in the Parse structure. */
  101593. zName = sqlite3NameFromToken(pParse->db, pName);
  101594. if( zName && pWith ){
  101595. int i;
  101596. for(i=0; i<pWith->nCte; i++){
  101597. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  101598. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  101599. }
  101600. }
  101601. }
  101602. if( pWith ){
  101603. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  101604. pNew = sqlite3DbRealloc(db, pWith, nByte);
  101605. }else{
  101606. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  101607. }
  101608. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  101609. if( db->mallocFailed ){
  101610. sqlite3ExprListDelete(db, pArglist);
  101611. sqlite3SelectDelete(db, pQuery);
  101612. sqlite3DbFree(db, zName);
  101613. pNew = pWith;
  101614. }else{
  101615. pNew->a[pNew->nCte].pSelect = pQuery;
  101616. pNew->a[pNew->nCte].pCols = pArglist;
  101617. pNew->a[pNew->nCte].zName = zName;
  101618. pNew->a[pNew->nCte].zCteErr = 0;
  101619. pNew->nCte++;
  101620. }
  101621. return pNew;
  101622. }
  101623. /*
  101624. ** Free the contents of the With object passed as the second argument.
  101625. */
  101626. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  101627. if( pWith ){
  101628. int i;
  101629. for(i=0; i<pWith->nCte; i++){
  101630. struct Cte *pCte = &pWith->a[i];
  101631. sqlite3ExprListDelete(db, pCte->pCols);
  101632. sqlite3SelectDelete(db, pCte->pSelect);
  101633. sqlite3DbFree(db, pCte->zName);
  101634. }
  101635. sqlite3DbFree(db, pWith);
  101636. }
  101637. }
  101638. #endif /* !defined(SQLITE_OMIT_CTE) */
  101639. /************** End of build.c ***********************************************/
  101640. /************** Begin file callback.c ****************************************/
  101641. /*
  101642. ** 2005 May 23
  101643. **
  101644. ** The author disclaims copyright to this source code. In place of
  101645. ** a legal notice, here is a blessing:
  101646. **
  101647. ** May you do good and not evil.
  101648. ** May you find forgiveness for yourself and forgive others.
  101649. ** May you share freely, never taking more than you give.
  101650. **
  101651. *************************************************************************
  101652. **
  101653. ** This file contains functions used to access the internal hash tables
  101654. ** of user defined functions and collation sequences.
  101655. */
  101656. /* #include "sqliteInt.h" */
  101657. /*
  101658. ** Invoke the 'collation needed' callback to request a collation sequence
  101659. ** in the encoding enc of name zName, length nName.
  101660. */
  101661. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  101662. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  101663. if( db->xCollNeeded ){
  101664. char *zExternal = sqlite3DbStrDup(db, zName);
  101665. if( !zExternal ) return;
  101666. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  101667. sqlite3DbFree(db, zExternal);
  101668. }
  101669. #ifndef SQLITE_OMIT_UTF16
  101670. if( db->xCollNeeded16 ){
  101671. char const *zExternal;
  101672. sqlite3_value *pTmp = sqlite3ValueNew(db);
  101673. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  101674. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  101675. if( zExternal ){
  101676. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  101677. }
  101678. sqlite3ValueFree(pTmp);
  101679. }
  101680. #endif
  101681. }
  101682. /*
  101683. ** This routine is called if the collation factory fails to deliver a
  101684. ** collation function in the best encoding but there may be other versions
  101685. ** of this collation function (for other text encodings) available. Use one
  101686. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  101687. ** possible.
  101688. */
  101689. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  101690. CollSeq *pColl2;
  101691. char *z = pColl->zName;
  101692. int i;
  101693. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  101694. for(i=0; i<3; i++){
  101695. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  101696. if( pColl2->xCmp!=0 ){
  101697. memcpy(pColl, pColl2, sizeof(CollSeq));
  101698. pColl->xDel = 0; /* Do not copy the destructor */
  101699. return SQLITE_OK;
  101700. }
  101701. }
  101702. return SQLITE_ERROR;
  101703. }
  101704. /*
  101705. ** This function is responsible for invoking the collation factory callback
  101706. ** or substituting a collation sequence of a different encoding when the
  101707. ** requested collation sequence is not available in the desired encoding.
  101708. **
  101709. ** If it is not NULL, then pColl must point to the database native encoding
  101710. ** collation sequence with name zName, length nName.
  101711. **
  101712. ** The return value is either the collation sequence to be used in database
  101713. ** db for collation type name zName, length nName, or NULL, if no collation
  101714. ** sequence can be found. If no collation is found, leave an error message.
  101715. **
  101716. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  101717. */
  101718. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  101719. Parse *pParse, /* Parsing context */
  101720. u8 enc, /* The desired encoding for the collating sequence */
  101721. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  101722. const char *zName /* Collating sequence name */
  101723. ){
  101724. CollSeq *p;
  101725. sqlite3 *db = pParse->db;
  101726. p = pColl;
  101727. if( !p ){
  101728. p = sqlite3FindCollSeq(db, enc, zName, 0);
  101729. }
  101730. if( !p || !p->xCmp ){
  101731. /* No collation sequence of this type for this encoding is registered.
  101732. ** Call the collation factory to see if it can supply us with one.
  101733. */
  101734. callCollNeeded(db, enc, zName);
  101735. p = sqlite3FindCollSeq(db, enc, zName, 0);
  101736. }
  101737. if( p && !p->xCmp && synthCollSeq(db, p) ){
  101738. p = 0;
  101739. }
  101740. assert( !p || p->xCmp );
  101741. if( p==0 ){
  101742. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  101743. pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
  101744. }
  101745. return p;
  101746. }
  101747. /*
  101748. ** This routine is called on a collation sequence before it is used to
  101749. ** check that it is defined. An undefined collation sequence exists when
  101750. ** a database is loaded that contains references to collation sequences
  101751. ** that have not been defined by sqlite3_create_collation() etc.
  101752. **
  101753. ** If required, this routine calls the 'collation needed' callback to
  101754. ** request a definition of the collating sequence. If this doesn't work,
  101755. ** an equivalent collating sequence that uses a text encoding different
  101756. ** from the main database is substituted, if one is available.
  101757. */
  101758. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  101759. if( pColl && pColl->xCmp==0 ){
  101760. const char *zName = pColl->zName;
  101761. sqlite3 *db = pParse->db;
  101762. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  101763. if( !p ){
  101764. return SQLITE_ERROR;
  101765. }
  101766. assert( p==pColl );
  101767. }
  101768. return SQLITE_OK;
  101769. }
  101770. /*
  101771. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  101772. ** specified by zName and nName is not found and parameter 'create' is
  101773. ** true, then create a new entry. Otherwise return NULL.
  101774. **
  101775. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  101776. ** array of three CollSeq structures. The first is the collation sequence
  101777. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  101778. **
  101779. ** Stored immediately after the three collation sequences is a copy of
  101780. ** the collation sequence name. A pointer to this string is stored in
  101781. ** each collation sequence structure.
  101782. */
  101783. static CollSeq *findCollSeqEntry(
  101784. sqlite3 *db, /* Database connection */
  101785. const char *zName, /* Name of the collating sequence */
  101786. int create /* Create a new entry if true */
  101787. ){
  101788. CollSeq *pColl;
  101789. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  101790. if( 0==pColl && create ){
  101791. int nName = sqlite3Strlen30(zName) + 1;
  101792. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
  101793. if( pColl ){
  101794. CollSeq *pDel = 0;
  101795. pColl[0].zName = (char*)&pColl[3];
  101796. pColl[0].enc = SQLITE_UTF8;
  101797. pColl[1].zName = (char*)&pColl[3];
  101798. pColl[1].enc = SQLITE_UTF16LE;
  101799. pColl[2].zName = (char*)&pColl[3];
  101800. pColl[2].enc = SQLITE_UTF16BE;
  101801. memcpy(pColl[0].zName, zName, nName);
  101802. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  101803. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  101804. ** return the pColl pointer to be deleted (because it wasn't added
  101805. ** to the hash table).
  101806. */
  101807. assert( pDel==0 || pDel==pColl );
  101808. if( pDel!=0 ){
  101809. sqlite3OomFault(db);
  101810. sqlite3DbFree(db, pDel);
  101811. pColl = 0;
  101812. }
  101813. }
  101814. }
  101815. return pColl;
  101816. }
  101817. /*
  101818. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  101819. ** Return the CollSeq* pointer for the collation sequence named zName
  101820. ** for the encoding 'enc' from the database 'db'.
  101821. **
  101822. ** If the entry specified is not found and 'create' is true, then create a
  101823. ** new entry. Otherwise return NULL.
  101824. **
  101825. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  101826. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  101827. ** if necessary and generates an error message if the collating sequence
  101828. ** cannot be found.
  101829. **
  101830. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  101831. */
  101832. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  101833. sqlite3 *db,
  101834. u8 enc,
  101835. const char *zName,
  101836. int create
  101837. ){
  101838. CollSeq *pColl;
  101839. if( zName ){
  101840. pColl = findCollSeqEntry(db, zName, create);
  101841. }else{
  101842. pColl = db->pDfltColl;
  101843. }
  101844. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  101845. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  101846. if( pColl ) pColl += enc-1;
  101847. return pColl;
  101848. }
  101849. /* During the search for the best function definition, this procedure
  101850. ** is called to test how well the function passed as the first argument
  101851. ** matches the request for a function with nArg arguments in a system
  101852. ** that uses encoding enc. The value returned indicates how well the
  101853. ** request is matched. A higher value indicates a better match.
  101854. **
  101855. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  101856. ** is also -1. In other words, we are searching for a function that
  101857. ** takes a variable number of arguments.
  101858. **
  101859. ** If nArg is -2 that means that we are searching for any function
  101860. ** regardless of the number of arguments it uses, so return a positive
  101861. ** match score for any
  101862. **
  101863. ** The returned value is always between 0 and 6, as follows:
  101864. **
  101865. ** 0: Not a match.
  101866. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  101867. ** 2: UTF16 byte order change required and function takes any number of args.
  101868. ** 3: encoding matches and function takes any number of arguments
  101869. ** 4: UTF8/16 conversion required - argument count matches exactly
  101870. ** 5: UTF16 byte order conversion required - argument count matches exactly
  101871. ** 6: Perfect match: encoding and argument count match exactly.
  101872. **
  101873. ** If nArg==(-2) then any function with a non-null xSFunc is
  101874. ** a perfect match and any function with xSFunc NULL is
  101875. ** a non-match.
  101876. */
  101877. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  101878. static int matchQuality(
  101879. FuncDef *p, /* The function we are evaluating for match quality */
  101880. int nArg, /* Desired number of arguments. (-1)==any */
  101881. u8 enc /* Desired text encoding */
  101882. ){
  101883. int match;
  101884. /* nArg of -2 is a special case */
  101885. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  101886. /* Wrong number of arguments means "no match" */
  101887. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  101888. /* Give a better score to a function with a specific number of arguments
  101889. ** than to function that accepts any number of arguments. */
  101890. if( p->nArg==nArg ){
  101891. match = 4;
  101892. }else{
  101893. match = 1;
  101894. }
  101895. /* Bonus points if the text encoding matches */
  101896. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  101897. match += 2; /* Exact encoding match */
  101898. }else if( (enc & p->funcFlags & 2)!=0 ){
  101899. match += 1; /* Both are UTF16, but with different byte orders */
  101900. }
  101901. return match;
  101902. }
  101903. /*
  101904. ** Search a FuncDefHash for a function with the given name. Return
  101905. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  101906. */
  101907. static FuncDef *functionSearch(
  101908. int h, /* Hash of the name */
  101909. const char *zFunc /* Name of function */
  101910. ){
  101911. FuncDef *p;
  101912. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  101913. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  101914. return p;
  101915. }
  101916. }
  101917. return 0;
  101918. }
  101919. /*
  101920. ** Insert a new FuncDef into a FuncDefHash hash table.
  101921. */
  101922. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  101923. FuncDef *aDef, /* List of global functions to be inserted */
  101924. int nDef /* Length of the apDef[] list */
  101925. ){
  101926. int i;
  101927. for(i=0; i<nDef; i++){
  101928. FuncDef *pOther;
  101929. const char *zName = aDef[i].zName;
  101930. int nName = sqlite3Strlen30(zName);
  101931. int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
  101932. assert( zName[0]>='a' && zName[0]<='z' );
  101933. pOther = functionSearch(h, zName);
  101934. if( pOther ){
  101935. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  101936. aDef[i].pNext = pOther->pNext;
  101937. pOther->pNext = &aDef[i];
  101938. }else{
  101939. aDef[i].pNext = 0;
  101940. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  101941. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  101942. }
  101943. }
  101944. }
  101945. /*
  101946. ** Locate a user function given a name, a number of arguments and a flag
  101947. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  101948. ** pointer to the FuncDef structure that defines that function, or return
  101949. ** NULL if the function does not exist.
  101950. **
  101951. ** If the createFlag argument is true, then a new (blank) FuncDef
  101952. ** structure is created and liked into the "db" structure if a
  101953. ** no matching function previously existed.
  101954. **
  101955. ** If nArg is -2, then the first valid function found is returned. A
  101956. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  101957. ** case is used to see if zName is a valid function name for some number
  101958. ** of arguments. If nArg is -2, then createFlag must be 0.
  101959. **
  101960. ** If createFlag is false, then a function with the required name and
  101961. ** number of arguments may be returned even if the eTextRep flag does not
  101962. ** match that requested.
  101963. */
  101964. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  101965. sqlite3 *db, /* An open database */
  101966. const char *zName, /* Name of the function. zero-terminated */
  101967. int nArg, /* Number of arguments. -1 means any number */
  101968. u8 enc, /* Preferred text encoding */
  101969. u8 createFlag /* Create new entry if true and does not otherwise exist */
  101970. ){
  101971. FuncDef *p; /* Iterator variable */
  101972. FuncDef *pBest = 0; /* Best match found so far */
  101973. int bestScore = 0; /* Score of best match */
  101974. int h; /* Hash value */
  101975. int nName; /* Length of the name */
  101976. assert( nArg>=(-2) );
  101977. assert( nArg>=(-1) || createFlag==0 );
  101978. nName = sqlite3Strlen30(zName);
  101979. /* First search for a match amongst the application-defined functions.
  101980. */
  101981. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  101982. while( p ){
  101983. int score = matchQuality(p, nArg, enc);
  101984. if( score>bestScore ){
  101985. pBest = p;
  101986. bestScore = score;
  101987. }
  101988. p = p->pNext;
  101989. }
  101990. /* If no match is found, search the built-in functions.
  101991. **
  101992. ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
  101993. ** functions even if a prior app-defined function was found. And give
  101994. ** priority to built-in functions.
  101995. **
  101996. ** Except, if createFlag is true, that means that we are trying to
  101997. ** install a new function. Whatever FuncDef structure is returned it will
  101998. ** have fields overwritten with new information appropriate for the
  101999. ** new function. But the FuncDefs for built-in functions are read-only.
  102000. ** So we must not search for built-ins when creating a new function.
  102001. */
  102002. if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
  102003. bestScore = 0;
  102004. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  102005. p = functionSearch(h, zName);
  102006. while( p ){
  102007. int score = matchQuality(p, nArg, enc);
  102008. if( score>bestScore ){
  102009. pBest = p;
  102010. bestScore = score;
  102011. }
  102012. p = p->pNext;
  102013. }
  102014. }
  102015. /* If the createFlag parameter is true and the search did not reveal an
  102016. ** exact match for the name, number of arguments and encoding, then add a
  102017. ** new entry to the hash table and return it.
  102018. */
  102019. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  102020. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  102021. FuncDef *pOther;
  102022. u8 *z;
  102023. pBest->zName = (const char*)&pBest[1];
  102024. pBest->nArg = (u16)nArg;
  102025. pBest->funcFlags = enc;
  102026. memcpy((char*)&pBest[1], zName, nName+1);
  102027. for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
  102028. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  102029. if( pOther==pBest ){
  102030. sqlite3DbFree(db, pBest);
  102031. sqlite3OomFault(db);
  102032. return 0;
  102033. }else{
  102034. pBest->pNext = pOther;
  102035. }
  102036. }
  102037. if( pBest && (pBest->xSFunc || createFlag) ){
  102038. return pBest;
  102039. }
  102040. return 0;
  102041. }
  102042. /*
  102043. ** Free all resources held by the schema structure. The void* argument points
  102044. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  102045. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  102046. ** of the schema hash tables).
  102047. **
  102048. ** The Schema.cache_size variable is not cleared.
  102049. */
  102050. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  102051. Hash temp1;
  102052. Hash temp2;
  102053. HashElem *pElem;
  102054. Schema *pSchema = (Schema *)p;
  102055. temp1 = pSchema->tblHash;
  102056. temp2 = pSchema->trigHash;
  102057. sqlite3HashInit(&pSchema->trigHash);
  102058. sqlite3HashClear(&pSchema->idxHash);
  102059. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  102060. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  102061. }
  102062. sqlite3HashClear(&temp2);
  102063. sqlite3HashInit(&pSchema->tblHash);
  102064. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  102065. Table *pTab = sqliteHashData(pElem);
  102066. sqlite3DeleteTable(0, pTab);
  102067. }
  102068. sqlite3HashClear(&temp1);
  102069. sqlite3HashClear(&pSchema->fkeyHash);
  102070. pSchema->pSeqTab = 0;
  102071. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  102072. pSchema->iGeneration++;
  102073. }
  102074. pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
  102075. }
  102076. /*
  102077. ** Find and return the schema associated with a BTree. Create
  102078. ** a new one if necessary.
  102079. */
  102080. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  102081. Schema * p;
  102082. if( pBt ){
  102083. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  102084. }else{
  102085. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  102086. }
  102087. if( !p ){
  102088. sqlite3OomFault(db);
  102089. }else if ( 0==p->file_format ){
  102090. sqlite3HashInit(&p->tblHash);
  102091. sqlite3HashInit(&p->idxHash);
  102092. sqlite3HashInit(&p->trigHash);
  102093. sqlite3HashInit(&p->fkeyHash);
  102094. p->enc = SQLITE_UTF8;
  102095. }
  102096. return p;
  102097. }
  102098. /************** End of callback.c ********************************************/
  102099. /************** Begin file delete.c ******************************************/
  102100. /*
  102101. ** 2001 September 15
  102102. **
  102103. ** The author disclaims copyright to this source code. In place of
  102104. ** a legal notice, here is a blessing:
  102105. **
  102106. ** May you do good and not evil.
  102107. ** May you find forgiveness for yourself and forgive others.
  102108. ** May you share freely, never taking more than you give.
  102109. **
  102110. *************************************************************************
  102111. ** This file contains C code routines that are called by the parser
  102112. ** in order to generate code for DELETE FROM statements.
  102113. */
  102114. /* #include "sqliteInt.h" */
  102115. /*
  102116. ** While a SrcList can in general represent multiple tables and subqueries
  102117. ** (as in the FROM clause of a SELECT statement) in this case it contains
  102118. ** the name of a single table, as one might find in an INSERT, DELETE,
  102119. ** or UPDATE statement. Look up that table in the symbol table and
  102120. ** return a pointer. Set an error message and return NULL if the table
  102121. ** name is not found or if any other error occurs.
  102122. **
  102123. ** The following fields are initialized appropriate in pSrc:
  102124. **
  102125. ** pSrc->a[0].pTab Pointer to the Table object
  102126. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  102127. **
  102128. */
  102129. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  102130. struct SrcList_item *pItem = pSrc->a;
  102131. Table *pTab;
  102132. assert( pItem && pSrc->nSrc==1 );
  102133. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  102134. sqlite3DeleteTable(pParse->db, pItem->pTab);
  102135. pItem->pTab = pTab;
  102136. if( pTab ){
  102137. pTab->nTabRef++;
  102138. }
  102139. if( sqlite3IndexedByLookup(pParse, pItem) ){
  102140. pTab = 0;
  102141. }
  102142. return pTab;
  102143. }
  102144. /*
  102145. ** Check to make sure the given table is writable. If it is not
  102146. ** writable, generate an error message and return 1. If it is
  102147. ** writable return 0;
  102148. */
  102149. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  102150. /* A table is not writable under the following circumstances:
  102151. **
  102152. ** 1) It is a virtual table and no implementation of the xUpdate method
  102153. ** has been provided, or
  102154. ** 2) It is a system table (i.e. sqlite_master), this call is not
  102155. ** part of a nested parse and writable_schema pragma has not
  102156. ** been specified.
  102157. **
  102158. ** In either case leave an error message in pParse and return non-zero.
  102159. */
  102160. if( ( IsVirtual(pTab)
  102161. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  102162. || ( (pTab->tabFlags & TF_Readonly)!=0
  102163. && (pParse->db->flags & SQLITE_WriteSchema)==0
  102164. && pParse->nested==0 )
  102165. ){
  102166. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  102167. return 1;
  102168. }
  102169. #ifndef SQLITE_OMIT_VIEW
  102170. if( !viewOk && pTab->pSelect ){
  102171. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  102172. return 1;
  102173. }
  102174. #endif
  102175. return 0;
  102176. }
  102177. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  102178. /*
  102179. ** Evaluate a view and store its result in an ephemeral table. The
  102180. ** pWhere argument is an optional WHERE clause that restricts the
  102181. ** set of rows in the view that are to be added to the ephemeral table.
  102182. */
  102183. SQLITE_PRIVATE void sqlite3MaterializeView(
  102184. Parse *pParse, /* Parsing context */
  102185. Table *pView, /* View definition */
  102186. Expr *pWhere, /* Optional WHERE clause to be added */
  102187. ExprList *pOrderBy, /* Optional ORDER BY clause */
  102188. Expr *pLimit, /* Optional LIMIT clause */
  102189. int iCur /* Cursor number for ephemeral table */
  102190. ){
  102191. SelectDest dest;
  102192. Select *pSel;
  102193. SrcList *pFrom;
  102194. sqlite3 *db = pParse->db;
  102195. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  102196. pWhere = sqlite3ExprDup(db, pWhere, 0);
  102197. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  102198. if( pFrom ){
  102199. assert( pFrom->nSrc==1 );
  102200. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  102201. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  102202. assert( pFrom->a[0].pOn==0 );
  102203. assert( pFrom->a[0].pUsing==0 );
  102204. }
  102205. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
  102206. SF_IncludeHidden, pLimit);
  102207. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  102208. sqlite3Select(pParse, pSel, &dest);
  102209. sqlite3SelectDelete(db, pSel);
  102210. }
  102211. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  102212. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  102213. /*
  102214. ** Generate an expression tree to implement the WHERE, ORDER BY,
  102215. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  102216. **
  102217. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  102218. ** \__________________________/
  102219. ** pLimitWhere (pInClause)
  102220. */
  102221. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  102222. Parse *pParse, /* The parser context */
  102223. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  102224. Expr *pWhere, /* The WHERE clause. May be null */
  102225. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  102226. Expr *pLimit, /* The LIMIT clause. May be null */
  102227. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  102228. ){
  102229. sqlite3 *db = pParse->db;
  102230. Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
  102231. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  102232. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  102233. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  102234. Select *pSelect = NULL; /* Complete SELECT tree */
  102235. Table *pTab;
  102236. /* Check that there isn't an ORDER BY without a LIMIT clause.
  102237. */
  102238. if( pOrderBy && pLimit==0 ) {
  102239. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  102240. sqlite3ExprDelete(pParse->db, pWhere);
  102241. sqlite3ExprListDelete(pParse->db, pOrderBy);
  102242. return 0;
  102243. }
  102244. /* We only need to generate a select expression if there
  102245. ** is a limit/offset term to enforce.
  102246. */
  102247. if( pLimit == 0 ) {
  102248. return pWhere;
  102249. }
  102250. /* Generate a select expression tree to enforce the limit/offset
  102251. ** term for the DELETE or UPDATE statement. For example:
  102252. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  102253. ** becomes:
  102254. ** DELETE FROM table_a WHERE rowid IN (
  102255. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  102256. ** );
  102257. */
  102258. pTab = pSrc->a[0].pTab;
  102259. if( HasRowid(pTab) ){
  102260. pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  102261. pEList = sqlite3ExprListAppend(
  102262. pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
  102263. );
  102264. }else{
  102265. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  102266. if( pPk->nKeyCol==1 ){
  102267. const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
  102268. pLhs = sqlite3Expr(db, TK_ID, zName);
  102269. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
  102270. }else{
  102271. int i;
  102272. for(i=0; i<pPk->nKeyCol; i++){
  102273. Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
  102274. pEList = sqlite3ExprListAppend(pParse, pEList, p);
  102275. }
  102276. pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  102277. if( pLhs ){
  102278. pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
  102279. }
  102280. }
  102281. }
  102282. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  102283. ** and the SELECT subtree. */
  102284. pSrc->a[0].pTab = 0;
  102285. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  102286. pSrc->a[0].pTab = pTab;
  102287. pSrc->a[0].pIBIndex = 0;
  102288. /* generate the SELECT expression tree. */
  102289. pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
  102290. pOrderBy,0,pLimit
  102291. );
  102292. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  102293. pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
  102294. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  102295. return pInClause;
  102296. }
  102297. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  102298. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  102299. /*
  102300. ** Generate code for a DELETE FROM statement.
  102301. **
  102302. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  102303. ** \________/ \________________/
  102304. ** pTabList pWhere
  102305. */
  102306. SQLITE_PRIVATE void sqlite3DeleteFrom(
  102307. Parse *pParse, /* The parser context */
  102308. SrcList *pTabList, /* The table from which we should delete things */
  102309. Expr *pWhere, /* The WHERE clause. May be null */
  102310. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  102311. Expr *pLimit /* LIMIT clause. May be null */
  102312. ){
  102313. Vdbe *v; /* The virtual database engine */
  102314. Table *pTab; /* The table from which records will be deleted */
  102315. int i; /* Loop counter */
  102316. WhereInfo *pWInfo; /* Information about the WHERE clause */
  102317. Index *pIdx; /* For looping over indices of the table */
  102318. int iTabCur; /* Cursor number for the table */
  102319. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  102320. int iIdxCur = 0; /* Cursor number of the first index */
  102321. int nIdx; /* Number of indices */
  102322. sqlite3 *db; /* Main database structure */
  102323. AuthContext sContext; /* Authorization context */
  102324. NameContext sNC; /* Name context to resolve expressions in */
  102325. int iDb; /* Database number */
  102326. int memCnt = 0; /* Memory cell used for change counting */
  102327. int rcauth; /* Value returned by authorization callback */
  102328. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  102329. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  102330. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  102331. Index *pPk; /* The PRIMARY KEY index on the table */
  102332. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  102333. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  102334. int iKey; /* Memory cell holding key of row to be deleted */
  102335. i16 nKey; /* Number of memory cells in the row key */
  102336. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  102337. int iRowSet = 0; /* Register for rowset of rows to delete */
  102338. int addrBypass = 0; /* Address of jump over the delete logic */
  102339. int addrLoop = 0; /* Top of the delete loop */
  102340. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  102341. int bComplex; /* True if there are triggers or FKs or
  102342. ** subqueries in the WHERE clause */
  102343. #ifndef SQLITE_OMIT_TRIGGER
  102344. int isView; /* True if attempting to delete from a view */
  102345. Trigger *pTrigger; /* List of table triggers, if required */
  102346. #endif
  102347. memset(&sContext, 0, sizeof(sContext));
  102348. db = pParse->db;
  102349. if( pParse->nErr || db->mallocFailed ){
  102350. goto delete_from_cleanup;
  102351. }
  102352. assert( pTabList->nSrc==1 );
  102353. /* Locate the table which we want to delete. This table has to be
  102354. ** put in an SrcList structure because some of the subroutines we
  102355. ** will be calling are designed to work with multiple tables and expect
  102356. ** an SrcList* parameter instead of just a Table* parameter.
  102357. */
  102358. pTab = sqlite3SrcListLookup(pParse, pTabList);
  102359. if( pTab==0 ) goto delete_from_cleanup;
  102360. /* Figure out if we have any triggers and if the table being
  102361. ** deleted from is a view
  102362. */
  102363. #ifndef SQLITE_OMIT_TRIGGER
  102364. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  102365. isView = pTab->pSelect!=0;
  102366. #else
  102367. # define pTrigger 0
  102368. # define isView 0
  102369. #endif
  102370. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  102371. #ifdef SQLITE_OMIT_VIEW
  102372. # undef isView
  102373. # define isView 0
  102374. #endif
  102375. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  102376. if( !isView ){
  102377. pWhere = sqlite3LimitWhere(
  102378. pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
  102379. );
  102380. pOrderBy = 0;
  102381. pLimit = 0;
  102382. }
  102383. #endif
  102384. /* If pTab is really a view, make sure it has been initialized.
  102385. */
  102386. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  102387. goto delete_from_cleanup;
  102388. }
  102389. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  102390. goto delete_from_cleanup;
  102391. }
  102392. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102393. assert( iDb<db->nDb );
  102394. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  102395. db->aDb[iDb].zDbSName);
  102396. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  102397. if( rcauth==SQLITE_DENY ){
  102398. goto delete_from_cleanup;
  102399. }
  102400. assert(!isView || pTrigger);
  102401. /* Assign cursor numbers to the table and all its indices.
  102402. */
  102403. assert( pTabList->nSrc==1 );
  102404. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  102405. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  102406. pParse->nTab++;
  102407. }
  102408. /* Start the view context
  102409. */
  102410. if( isView ){
  102411. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  102412. }
  102413. /* Begin generating code.
  102414. */
  102415. v = sqlite3GetVdbe(pParse);
  102416. if( v==0 ){
  102417. goto delete_from_cleanup;
  102418. }
  102419. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  102420. sqlite3BeginWriteOperation(pParse, bComplex, iDb);
  102421. /* If we are trying to delete from a view, realize that view into
  102422. ** an ephemeral table.
  102423. */
  102424. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  102425. if( isView ){
  102426. sqlite3MaterializeView(pParse, pTab,
  102427. pWhere, pOrderBy, pLimit, iTabCur
  102428. );
  102429. iDataCur = iIdxCur = iTabCur;
  102430. pOrderBy = 0;
  102431. pLimit = 0;
  102432. }
  102433. #endif
  102434. /* Resolve the column names in the WHERE clause.
  102435. */
  102436. memset(&sNC, 0, sizeof(sNC));
  102437. sNC.pParse = pParse;
  102438. sNC.pSrcList = pTabList;
  102439. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  102440. goto delete_from_cleanup;
  102441. }
  102442. /* Initialize the counter of the number of rows deleted, if
  102443. ** we are counting rows.
  102444. */
  102445. if( (db->flags & SQLITE_CountRows)!=0
  102446. && !pParse->nested
  102447. && !pParse->pTriggerTab
  102448. ){
  102449. memCnt = ++pParse->nMem;
  102450. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  102451. }
  102452. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  102453. /* Special case: A DELETE without a WHERE clause deletes everything.
  102454. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  102455. ** this optimization caused the row change count (the value returned by
  102456. ** API function sqlite3_count_changes) to be set incorrectly.
  102457. **
  102458. ** The "rcauth==SQLITE_OK" terms is the
  102459. ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  102460. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  102461. ** the truncate optimization is disabled and all rows are deleted
  102462. ** individually.
  102463. */
  102464. if( rcauth==SQLITE_OK
  102465. && pWhere==0
  102466. && !bComplex
  102467. && !IsVirtual(pTab)
  102468. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  102469. && db->xPreUpdateCallback==0
  102470. #endif
  102471. ){
  102472. assert( !isView );
  102473. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  102474. if( HasRowid(pTab) ){
  102475. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
  102476. pTab->zName, P4_STATIC);
  102477. }
  102478. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  102479. assert( pIdx->pSchema==pTab->pSchema );
  102480. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  102481. }
  102482. }else
  102483. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  102484. {
  102485. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  102486. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  102487. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  102488. if( HasRowid(pTab) ){
  102489. /* For a rowid table, initialize the RowSet to an empty set */
  102490. pPk = 0;
  102491. nPk = 1;
  102492. iRowSet = ++pParse->nMem;
  102493. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  102494. }else{
  102495. /* For a WITHOUT ROWID table, create an ephemeral table used to
  102496. ** hold all primary keys for rows to be deleted. */
  102497. pPk = sqlite3PrimaryKeyIndex(pTab);
  102498. assert( pPk!=0 );
  102499. nPk = pPk->nKeyCol;
  102500. iPk = pParse->nMem+1;
  102501. pParse->nMem += nPk;
  102502. iEphCur = pParse->nTab++;
  102503. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  102504. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  102505. }
  102506. /* Construct a query to find the rowid or primary key for every row
  102507. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  102508. ** to indicate the strategy used to implement this delete:
  102509. **
  102510. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  102511. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  102512. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  102513. */
  102514. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  102515. if( pWInfo==0 ) goto delete_from_cleanup;
  102516. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  102517. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  102518. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  102519. if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
  102520. /* Keep track of the number of rows to be deleted */
  102521. if( memCnt ){
  102522. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  102523. }
  102524. /* Extract the rowid or primary key for the current row */
  102525. if( pPk ){
  102526. for(i=0; i<nPk; i++){
  102527. assert( pPk->aiColumn[i]>=0 );
  102528. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  102529. pPk->aiColumn[i], iPk+i);
  102530. }
  102531. iKey = iPk;
  102532. }else{
  102533. iKey = pParse->nMem + 1;
  102534. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  102535. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  102536. }
  102537. if( eOnePass!=ONEPASS_OFF ){
  102538. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  102539. ** one, so just keep it in its register(s) and fall through to the
  102540. ** delete code. */
  102541. nKey = nPk; /* OP_Found will use an unpacked key */
  102542. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  102543. if( aToOpen==0 ){
  102544. sqlite3WhereEnd(pWInfo);
  102545. goto delete_from_cleanup;
  102546. }
  102547. memset(aToOpen, 1, nIdx+1);
  102548. aToOpen[nIdx+1] = 0;
  102549. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  102550. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  102551. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  102552. }else{
  102553. if( pPk ){
  102554. /* Add the PK key for this row to the temporary table */
  102555. iKey = ++pParse->nMem;
  102556. nKey = 0; /* Zero tells OP_Found to use a composite key */
  102557. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  102558. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  102559. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  102560. }else{
  102561. /* Add the rowid of the row to be deleted to the RowSet */
  102562. nKey = 1; /* OP_DeferredSeek always uses a single rowid */
  102563. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  102564. }
  102565. }
  102566. /* If this DELETE cannot use the ONEPASS strategy, this is the
  102567. ** end of the WHERE loop */
  102568. if( eOnePass!=ONEPASS_OFF ){
  102569. addrBypass = sqlite3VdbeMakeLabel(v);
  102570. }else{
  102571. sqlite3WhereEnd(pWInfo);
  102572. }
  102573. /* Unless this is a view, open cursors for the table we are
  102574. ** deleting from and all its indices. If this is a view, then the
  102575. ** only effect this statement has is to fire the INSTEAD OF
  102576. ** triggers.
  102577. */
  102578. if( !isView ){
  102579. int iAddrOnce = 0;
  102580. if( eOnePass==ONEPASS_MULTI ){
  102581. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  102582. }
  102583. testcase( IsVirtual(pTab) );
  102584. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  102585. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  102586. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  102587. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  102588. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  102589. }
  102590. /* Set up a loop over the rowids/primary-keys that were found in the
  102591. ** where-clause loop above.
  102592. */
  102593. if( eOnePass!=ONEPASS_OFF ){
  102594. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  102595. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  102596. assert( pPk!=0 || pTab->pSelect!=0 );
  102597. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  102598. VdbeCoverage(v);
  102599. }
  102600. }else if( pPk ){
  102601. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  102602. if( IsVirtual(pTab) ){
  102603. sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
  102604. }else{
  102605. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  102606. }
  102607. assert( nKey==0 ); /* OP_Found will use a composite key */
  102608. }else{
  102609. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  102610. VdbeCoverage(v);
  102611. assert( nKey==1 );
  102612. }
  102613. /* Delete the row */
  102614. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102615. if( IsVirtual(pTab) ){
  102616. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  102617. sqlite3VtabMakeWritable(pParse, pTab);
  102618. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  102619. sqlite3MayAbort(pParse);
  102620. if( eOnePass==ONEPASS_SINGLE ){
  102621. sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
  102622. if( sqlite3IsToplevel(pParse) ){
  102623. pParse->isMultiWrite = 0;
  102624. }
  102625. }
  102626. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  102627. sqlite3VdbeChangeP5(v, OE_Abort);
  102628. }else
  102629. #endif
  102630. {
  102631. int count = (pParse->nested==0); /* True to count changes */
  102632. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  102633. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  102634. }
  102635. /* End of the loop over all rowids/primary-keys. */
  102636. if( eOnePass!=ONEPASS_OFF ){
  102637. sqlite3VdbeResolveLabel(v, addrBypass);
  102638. sqlite3WhereEnd(pWInfo);
  102639. }else if( pPk ){
  102640. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  102641. sqlite3VdbeJumpHere(v, addrLoop);
  102642. }else{
  102643. sqlite3VdbeGoto(v, addrLoop);
  102644. sqlite3VdbeJumpHere(v, addrLoop);
  102645. }
  102646. } /* End non-truncate path */
  102647. /* Update the sqlite_sequence table by storing the content of the
  102648. ** maximum rowid counter values recorded while inserting into
  102649. ** autoincrement tables.
  102650. */
  102651. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  102652. sqlite3AutoincrementEnd(pParse);
  102653. }
  102654. /* Return the number of rows that were deleted. If this routine is
  102655. ** generating code because of a call to sqlite3NestedParse(), do not
  102656. ** invoke the callback function.
  102657. */
  102658. if( memCnt ){
  102659. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  102660. sqlite3VdbeSetNumCols(v, 1);
  102661. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  102662. }
  102663. delete_from_cleanup:
  102664. sqlite3AuthContextPop(&sContext);
  102665. sqlite3SrcListDelete(db, pTabList);
  102666. sqlite3ExprDelete(db, pWhere);
  102667. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  102668. sqlite3ExprListDelete(db, pOrderBy);
  102669. sqlite3ExprDelete(db, pLimit);
  102670. #endif
  102671. sqlite3DbFree(db, aToOpen);
  102672. return;
  102673. }
  102674. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  102675. ** they may interfere with compilation of other functions in this file
  102676. ** (or in another file, if this file becomes part of the amalgamation). */
  102677. #ifdef isView
  102678. #undef isView
  102679. #endif
  102680. #ifdef pTrigger
  102681. #undef pTrigger
  102682. #endif
  102683. /*
  102684. ** This routine generates VDBE code that causes a single row of a
  102685. ** single table to be deleted. Both the original table entry and
  102686. ** all indices are removed.
  102687. **
  102688. ** Preconditions:
  102689. **
  102690. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  102691. ** store for the table. (This will be either the table itself,
  102692. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  102693. ** of a WITHOUT ROWID table.)
  102694. **
  102695. ** 2. Read/write cursors for all indices of pTab must be open as
  102696. ** cursor number iIdxCur+i for the i-th index.
  102697. **
  102698. ** 3. The primary key for the row to be deleted must be stored in a
  102699. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  102700. ** that a search record formed from OP_MakeRecord is contained in the
  102701. ** single memory location iPk.
  102702. **
  102703. ** eMode:
  102704. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  102705. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  102706. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  102707. ** then this function must seek iDataCur to the entry identified by iPk
  102708. ** and nPk before reading from it.
  102709. **
  102710. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  102711. ** of a ONEPASS delete that affects multiple rows. In this case, if
  102712. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  102713. ** iDataCur, then its position should be preserved following the delete
  102714. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  102715. ** position of iDataCur should be preserved instead.
  102716. **
  102717. ** iIdxNoSeek:
  102718. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  102719. ** then it identifies an index cursor (from within array of cursors
  102720. ** starting at iIdxCur) that already points to the index entry to be deleted.
  102721. ** Except, this optimization is disabled if there are BEFORE triggers since
  102722. ** the trigger body might have moved the cursor.
  102723. */
  102724. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  102725. Parse *pParse, /* Parsing context */
  102726. Table *pTab, /* Table containing the row to be deleted */
  102727. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  102728. int iDataCur, /* Cursor from which column data is extracted */
  102729. int iIdxCur, /* First index cursor */
  102730. int iPk, /* First memory cell containing the PRIMARY KEY */
  102731. i16 nPk, /* Number of PRIMARY KEY memory cells */
  102732. u8 count, /* If non-zero, increment the row change counter */
  102733. u8 onconf, /* Default ON CONFLICT policy for triggers */
  102734. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  102735. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  102736. ){
  102737. Vdbe *v = pParse->pVdbe; /* Vdbe */
  102738. int iOld = 0; /* First register in OLD.* array */
  102739. int iLabel; /* Label resolved to end of generated code */
  102740. u8 opSeek; /* Seek opcode */
  102741. /* Vdbe is guaranteed to have been allocated by this stage. */
  102742. assert( v );
  102743. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  102744. iDataCur, iIdxCur, iPk, (int)nPk));
  102745. /* Seek cursor iCur to the row to delete. If this row no longer exists
  102746. ** (this can happen if a trigger program has already deleted it), do
  102747. ** not attempt to delete it or fire any DELETE triggers. */
  102748. iLabel = sqlite3VdbeMakeLabel(v);
  102749. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  102750. if( eMode==ONEPASS_OFF ){
  102751. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  102752. VdbeCoverageIf(v, opSeek==OP_NotExists);
  102753. VdbeCoverageIf(v, opSeek==OP_NotFound);
  102754. }
  102755. /* If there are any triggers to fire, allocate a range of registers to
  102756. ** use for the old.* references in the triggers. */
  102757. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  102758. u32 mask; /* Mask of OLD.* columns in use */
  102759. int iCol; /* Iterator used while populating OLD.* */
  102760. int addrStart; /* Start of BEFORE trigger programs */
  102761. /* TODO: Could use temporary registers here. Also could attempt to
  102762. ** avoid copying the contents of the rowid register. */
  102763. mask = sqlite3TriggerColmask(
  102764. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  102765. );
  102766. mask |= sqlite3FkOldmask(pParse, pTab);
  102767. iOld = pParse->nMem+1;
  102768. pParse->nMem += (1 + pTab->nCol);
  102769. /* Populate the OLD.* pseudo-table register array. These values will be
  102770. ** used by any BEFORE and AFTER triggers that exist. */
  102771. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  102772. for(iCol=0; iCol<pTab->nCol; iCol++){
  102773. testcase( mask!=0xffffffff && iCol==31 );
  102774. testcase( mask!=0xffffffff && iCol==32 );
  102775. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  102776. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  102777. }
  102778. }
  102779. /* Invoke BEFORE DELETE trigger programs. */
  102780. addrStart = sqlite3VdbeCurrentAddr(v);
  102781. sqlite3CodeRowTrigger(pParse, pTrigger,
  102782. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  102783. );
  102784. /* If any BEFORE triggers were coded, then seek the cursor to the
  102785. ** row to be deleted again. It may be that the BEFORE triggers moved
  102786. ** the cursor or already deleted the row that the cursor was
  102787. ** pointing to.
  102788. **
  102789. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  102790. ** may have moved that cursor.
  102791. */
  102792. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  102793. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  102794. VdbeCoverageIf(v, opSeek==OP_NotExists);
  102795. VdbeCoverageIf(v, opSeek==OP_NotFound);
  102796. testcase( iIdxNoSeek>=0 );
  102797. iIdxNoSeek = -1;
  102798. }
  102799. /* Do FK processing. This call checks that any FK constraints that
  102800. ** refer to this table (i.e. constraints attached to other tables)
  102801. ** are not violated by deleting this row. */
  102802. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  102803. }
  102804. /* Delete the index and table entries. Skip this step if pTab is really
  102805. ** a view (in which case the only effect of the DELETE statement is to
  102806. ** fire the INSTEAD OF triggers).
  102807. **
  102808. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  102809. ** invoke the update-hook. The pre-update-hook, on the other hand should
  102810. ** be invoked unless table pTab is a system table. The difference is that
  102811. ** the update-hook is not invoked for rows removed by REPLACE, but the
  102812. ** pre-update-hook is.
  102813. */
  102814. if( pTab->pSelect==0 ){
  102815. u8 p5 = 0;
  102816. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  102817. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  102818. if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
  102819. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  102820. }
  102821. if( eMode!=ONEPASS_OFF ){
  102822. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  102823. }
  102824. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  102825. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  102826. }
  102827. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  102828. sqlite3VdbeChangeP5(v, p5);
  102829. }
  102830. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  102831. ** handle rows (possibly in other tables) that refer via a foreign key
  102832. ** to the row just deleted. */
  102833. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  102834. /* Invoke AFTER DELETE trigger programs. */
  102835. sqlite3CodeRowTrigger(pParse, pTrigger,
  102836. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  102837. );
  102838. /* Jump here if the row had already been deleted before any BEFORE
  102839. ** trigger programs were invoked. Or if a trigger program throws a
  102840. ** RAISE(IGNORE) exception. */
  102841. sqlite3VdbeResolveLabel(v, iLabel);
  102842. VdbeModuleComment((v, "END: GenRowDel()"));
  102843. }
  102844. /*
  102845. ** This routine generates VDBE code that causes the deletion of all
  102846. ** index entries associated with a single row of a single table, pTab
  102847. **
  102848. ** Preconditions:
  102849. **
  102850. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  102851. ** btree for the table pTab. (This will be either the table itself
  102852. ** for rowid tables or to the primary key index for WITHOUT ROWID
  102853. ** tables.)
  102854. **
  102855. ** 2. Read/write cursors for all indices of pTab must be open as
  102856. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  102857. ** index is the 0-th index.)
  102858. **
  102859. ** 3. The "iDataCur" cursor must be already be positioned on the row
  102860. ** that is to be deleted.
  102861. */
  102862. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  102863. Parse *pParse, /* Parsing and code generating context */
  102864. Table *pTab, /* Table containing the row to be deleted */
  102865. int iDataCur, /* Cursor of table holding data. */
  102866. int iIdxCur, /* First index cursor */
  102867. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  102868. int iIdxNoSeek /* Do not delete from this cursor */
  102869. ){
  102870. int i; /* Index loop counter */
  102871. int r1 = -1; /* Register holding an index key */
  102872. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  102873. Index *pIdx; /* Current index */
  102874. Index *pPrior = 0; /* Prior index */
  102875. Vdbe *v; /* The prepared statement under construction */
  102876. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  102877. v = pParse->pVdbe;
  102878. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  102879. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  102880. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  102881. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  102882. if( pIdx==pPk ) continue;
  102883. if( iIdxCur+i==iIdxNoSeek ) continue;
  102884. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  102885. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  102886. &iPartIdxLabel, pPrior, r1);
  102887. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  102888. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  102889. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  102890. pPrior = pIdx;
  102891. }
  102892. }
  102893. /*
  102894. ** Generate code that will assemble an index key and stores it in register
  102895. ** regOut. The key with be for index pIdx which is an index on pTab.
  102896. ** iCur is the index of a cursor open on the pTab table and pointing to
  102897. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  102898. ** iCur must be the cursor of the PRIMARY KEY index.
  102899. **
  102900. ** Return a register number which is the first in a block of
  102901. ** registers that holds the elements of the index key. The
  102902. ** block of registers has already been deallocated by the time
  102903. ** this routine returns.
  102904. **
  102905. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  102906. ** to that label if pIdx is a partial index that should be skipped.
  102907. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  102908. ** A partial index should be skipped if its WHERE clause evaluates
  102909. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  102910. ** will be set to zero which is an empty label that is ignored by
  102911. ** sqlite3ResolvePartIdxLabel().
  102912. **
  102913. ** The pPrior and regPrior parameters are used to implement a cache to
  102914. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  102915. ** a pointer to a different index for which an index key has just been
  102916. ** computed into register regPrior. If the current pIdx index is generating
  102917. ** its key into the same sequence of registers and if pPrior and pIdx share
  102918. ** a column in common, then the register corresponding to that column already
  102919. ** holds the correct value and the loading of that register is skipped.
  102920. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  102921. ** on a table with multiple indices, and especially with the ROWID or
  102922. ** PRIMARY KEY columns of the index.
  102923. */
  102924. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  102925. Parse *pParse, /* Parsing context */
  102926. Index *pIdx, /* The index for which to generate a key */
  102927. int iDataCur, /* Cursor number from which to take column data */
  102928. int regOut, /* Put the new key into this register if not 0 */
  102929. int prefixOnly, /* Compute only a unique prefix of the key */
  102930. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  102931. Index *pPrior, /* Previously generated index key */
  102932. int regPrior /* Register holding previous generated key */
  102933. ){
  102934. Vdbe *v = pParse->pVdbe;
  102935. int j;
  102936. int regBase;
  102937. int nCol;
  102938. if( piPartIdxLabel ){
  102939. if( pIdx->pPartIdxWhere ){
  102940. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  102941. pParse->iSelfTab = iDataCur + 1;
  102942. sqlite3ExprCachePush(pParse);
  102943. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  102944. SQLITE_JUMPIFNULL);
  102945. pParse->iSelfTab = 0;
  102946. }else{
  102947. *piPartIdxLabel = 0;
  102948. }
  102949. }
  102950. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  102951. regBase = sqlite3GetTempRange(pParse, nCol);
  102952. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  102953. for(j=0; j<nCol; j++){
  102954. if( pPrior
  102955. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  102956. && pPrior->aiColumn[j]!=XN_EXPR
  102957. ){
  102958. /* This column was already computed by the previous index */
  102959. continue;
  102960. }
  102961. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  102962. /* If the column affinity is REAL but the number is an integer, then it
  102963. ** might be stored in the table as an integer (using a compact
  102964. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  102965. ** But we are getting ready to store this value back into an index, where
  102966. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  102967. ** opcode if it is present */
  102968. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  102969. }
  102970. if( regOut ){
  102971. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  102972. if( pIdx->pTable->pSelect ){
  102973. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  102974. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  102975. }
  102976. }
  102977. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  102978. return regBase;
  102979. }
  102980. /*
  102981. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  102982. ** because it was a partial index, then this routine should be called to
  102983. ** resolve that label.
  102984. */
  102985. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  102986. if( iLabel ){
  102987. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  102988. sqlite3ExprCachePop(pParse);
  102989. }
  102990. }
  102991. /************** End of delete.c **********************************************/
  102992. /************** Begin file func.c ********************************************/
  102993. /*
  102994. ** 2002 February 23
  102995. **
  102996. ** The author disclaims copyright to this source code. In place of
  102997. ** a legal notice, here is a blessing:
  102998. **
  102999. ** May you do good and not evil.
  103000. ** May you find forgiveness for yourself and forgive others.
  103001. ** May you share freely, never taking more than you give.
  103002. **
  103003. *************************************************************************
  103004. ** This file contains the C-language implementations for many of the SQL
  103005. ** functions of SQLite. (Some function, and in particular the date and
  103006. ** time functions, are implemented separately.)
  103007. */
  103008. /* #include "sqliteInt.h" */
  103009. /* #include <stdlib.h> */
  103010. /* #include <assert.h> */
  103011. /* #include "vdbeInt.h" */
  103012. /*
  103013. ** Return the collating function associated with a function.
  103014. */
  103015. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  103016. VdbeOp *pOp;
  103017. assert( context->pVdbe!=0 );
  103018. pOp = &context->pVdbe->aOp[context->iOp-1];
  103019. assert( pOp->opcode==OP_CollSeq );
  103020. assert( pOp->p4type==P4_COLLSEQ );
  103021. return pOp->p4.pColl;
  103022. }
  103023. /*
  103024. ** Indicate that the accumulator load should be skipped on this
  103025. ** iteration of the aggregate loop.
  103026. */
  103027. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  103028. assert( context->isError<=0 );
  103029. context->isError = -1;
  103030. context->skipFlag = 1;
  103031. }
  103032. /*
  103033. ** Implementation of the non-aggregate min() and max() functions
  103034. */
  103035. static void minmaxFunc(
  103036. sqlite3_context *context,
  103037. int argc,
  103038. sqlite3_value **argv
  103039. ){
  103040. int i;
  103041. int mask; /* 0 for min() or 0xffffffff for max() */
  103042. int iBest;
  103043. CollSeq *pColl;
  103044. assert( argc>1 );
  103045. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  103046. pColl = sqlite3GetFuncCollSeq(context);
  103047. assert( pColl );
  103048. assert( mask==-1 || mask==0 );
  103049. iBest = 0;
  103050. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  103051. for(i=1; i<argc; i++){
  103052. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  103053. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  103054. testcase( mask==0 );
  103055. iBest = i;
  103056. }
  103057. }
  103058. sqlite3_result_value(context, argv[iBest]);
  103059. }
  103060. /*
  103061. ** Return the type of the argument.
  103062. */
  103063. static void typeofFunc(
  103064. sqlite3_context *context,
  103065. int NotUsed,
  103066. sqlite3_value **argv
  103067. ){
  103068. static const char *azType[] = { "integer", "real", "text", "blob", "null" };
  103069. int i = sqlite3_value_type(argv[0]) - 1;
  103070. UNUSED_PARAMETER(NotUsed);
  103071. assert( i>=0 && i<ArraySize(azType) );
  103072. assert( SQLITE_INTEGER==1 );
  103073. assert( SQLITE_FLOAT==2 );
  103074. assert( SQLITE_TEXT==3 );
  103075. assert( SQLITE_BLOB==4 );
  103076. assert( SQLITE_NULL==5 );
  103077. /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
  103078. ** the datatype code for the initial datatype of the sqlite3_value object
  103079. ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
  103080. ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
  103081. sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
  103082. }
  103083. /*
  103084. ** Implementation of the length() function
  103085. */
  103086. static void lengthFunc(
  103087. sqlite3_context *context,
  103088. int argc,
  103089. sqlite3_value **argv
  103090. ){
  103091. assert( argc==1 );
  103092. UNUSED_PARAMETER(argc);
  103093. switch( sqlite3_value_type(argv[0]) ){
  103094. case SQLITE_BLOB:
  103095. case SQLITE_INTEGER:
  103096. case SQLITE_FLOAT: {
  103097. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  103098. break;
  103099. }
  103100. case SQLITE_TEXT: {
  103101. const unsigned char *z = sqlite3_value_text(argv[0]);
  103102. const unsigned char *z0;
  103103. unsigned char c;
  103104. if( z==0 ) return;
  103105. z0 = z;
  103106. while( (c = *z)!=0 ){
  103107. z++;
  103108. if( c>=0xc0 ){
  103109. while( (*z & 0xc0)==0x80 ){ z++; z0++; }
  103110. }
  103111. }
  103112. sqlite3_result_int(context, (int)(z-z0));
  103113. break;
  103114. }
  103115. default: {
  103116. sqlite3_result_null(context);
  103117. break;
  103118. }
  103119. }
  103120. }
  103121. /*
  103122. ** Implementation of the abs() function.
  103123. **
  103124. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  103125. ** the numeric argument X.
  103126. */
  103127. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  103128. assert( argc==1 );
  103129. UNUSED_PARAMETER(argc);
  103130. switch( sqlite3_value_type(argv[0]) ){
  103131. case SQLITE_INTEGER: {
  103132. i64 iVal = sqlite3_value_int64(argv[0]);
  103133. if( iVal<0 ){
  103134. if( iVal==SMALLEST_INT64 ){
  103135. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  103136. ** then abs(X) throws an integer overflow error since there is no
  103137. ** equivalent positive 64-bit two complement value. */
  103138. sqlite3_result_error(context, "integer overflow", -1);
  103139. return;
  103140. }
  103141. iVal = -iVal;
  103142. }
  103143. sqlite3_result_int64(context, iVal);
  103144. break;
  103145. }
  103146. case SQLITE_NULL: {
  103147. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  103148. sqlite3_result_null(context);
  103149. break;
  103150. }
  103151. default: {
  103152. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  103153. ** something that can be converted into a number, we have:
  103154. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  103155. ** that cannot be converted to a numeric value.
  103156. */
  103157. double rVal = sqlite3_value_double(argv[0]);
  103158. if( rVal<0 ) rVal = -rVal;
  103159. sqlite3_result_double(context, rVal);
  103160. break;
  103161. }
  103162. }
  103163. }
  103164. /*
  103165. ** Implementation of the instr() function.
  103166. **
  103167. ** instr(haystack,needle) finds the first occurrence of needle
  103168. ** in haystack and returns the number of previous characters plus 1,
  103169. ** or 0 if needle does not occur within haystack.
  103170. **
  103171. ** If both haystack and needle are BLOBs, then the result is one more than
  103172. ** the number of bytes in haystack prior to the first occurrence of needle,
  103173. ** or 0 if needle never occurs in haystack.
  103174. */
  103175. static void instrFunc(
  103176. sqlite3_context *context,
  103177. int argc,
  103178. sqlite3_value **argv
  103179. ){
  103180. const unsigned char *zHaystack;
  103181. const unsigned char *zNeedle;
  103182. int nHaystack;
  103183. int nNeedle;
  103184. int typeHaystack, typeNeedle;
  103185. int N = 1;
  103186. int isText;
  103187. UNUSED_PARAMETER(argc);
  103188. typeHaystack = sqlite3_value_type(argv[0]);
  103189. typeNeedle = sqlite3_value_type(argv[1]);
  103190. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  103191. nHaystack = sqlite3_value_bytes(argv[0]);
  103192. nNeedle = sqlite3_value_bytes(argv[1]);
  103193. if( nNeedle>0 ){
  103194. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  103195. zHaystack = sqlite3_value_blob(argv[0]);
  103196. zNeedle = sqlite3_value_blob(argv[1]);
  103197. isText = 0;
  103198. }else{
  103199. zHaystack = sqlite3_value_text(argv[0]);
  103200. zNeedle = sqlite3_value_text(argv[1]);
  103201. isText = 1;
  103202. }
  103203. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  103204. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  103205. N++;
  103206. do{
  103207. nHaystack--;
  103208. zHaystack++;
  103209. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  103210. }
  103211. if( nNeedle>nHaystack ) N = 0;
  103212. }
  103213. sqlite3_result_int(context, N);
  103214. }
  103215. /*
  103216. ** Implementation of the printf() function.
  103217. */
  103218. static void printfFunc(
  103219. sqlite3_context *context,
  103220. int argc,
  103221. sqlite3_value **argv
  103222. ){
  103223. PrintfArguments x;
  103224. StrAccum str;
  103225. const char *zFormat;
  103226. int n;
  103227. sqlite3 *db = sqlite3_context_db_handle(context);
  103228. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  103229. x.nArg = argc-1;
  103230. x.nUsed = 0;
  103231. x.apArg = argv+1;
  103232. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  103233. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  103234. sqlite3_str_appendf(&str, zFormat, &x);
  103235. n = str.nChar;
  103236. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  103237. SQLITE_DYNAMIC);
  103238. }
  103239. }
  103240. /*
  103241. ** Implementation of the substr() function.
  103242. **
  103243. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  103244. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  103245. ** of x. If x is text, then we actually count UTF-8 characters.
  103246. ** If x is a blob, then we count bytes.
  103247. **
  103248. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  103249. **
  103250. ** If p2 is negative, return the p2 characters preceding p1.
  103251. */
  103252. static void substrFunc(
  103253. sqlite3_context *context,
  103254. int argc,
  103255. sqlite3_value **argv
  103256. ){
  103257. const unsigned char *z;
  103258. const unsigned char *z2;
  103259. int len;
  103260. int p0type;
  103261. i64 p1, p2;
  103262. int negP2 = 0;
  103263. assert( argc==3 || argc==2 );
  103264. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  103265. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  103266. ){
  103267. return;
  103268. }
  103269. p0type = sqlite3_value_type(argv[0]);
  103270. p1 = sqlite3_value_int(argv[1]);
  103271. if( p0type==SQLITE_BLOB ){
  103272. len = sqlite3_value_bytes(argv[0]);
  103273. z = sqlite3_value_blob(argv[0]);
  103274. if( z==0 ) return;
  103275. assert( len==sqlite3_value_bytes(argv[0]) );
  103276. }else{
  103277. z = sqlite3_value_text(argv[0]);
  103278. if( z==0 ) return;
  103279. len = 0;
  103280. if( p1<0 ){
  103281. for(z2=z; *z2; len++){
  103282. SQLITE_SKIP_UTF8(z2);
  103283. }
  103284. }
  103285. }
  103286. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  103287. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  103288. ** as substr(X,1,N) - it returns the first N characters of X. This
  103289. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  103290. ** from 2009-02-02 for compatibility of applications that exploited the
  103291. ** old buggy behavior. */
  103292. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  103293. #endif
  103294. if( argc==3 ){
  103295. p2 = sqlite3_value_int(argv[2]);
  103296. if( p2<0 ){
  103297. p2 = -p2;
  103298. negP2 = 1;
  103299. }
  103300. }else{
  103301. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  103302. }
  103303. if( p1<0 ){
  103304. p1 += len;
  103305. if( p1<0 ){
  103306. p2 += p1;
  103307. if( p2<0 ) p2 = 0;
  103308. p1 = 0;
  103309. }
  103310. }else if( p1>0 ){
  103311. p1--;
  103312. }else if( p2>0 ){
  103313. p2--;
  103314. }
  103315. if( negP2 ){
  103316. p1 -= p2;
  103317. if( p1<0 ){
  103318. p2 += p1;
  103319. p1 = 0;
  103320. }
  103321. }
  103322. assert( p1>=0 && p2>=0 );
  103323. if( p0type!=SQLITE_BLOB ){
  103324. while( *z && p1 ){
  103325. SQLITE_SKIP_UTF8(z);
  103326. p1--;
  103327. }
  103328. for(z2=z; *z2 && p2; p2--){
  103329. SQLITE_SKIP_UTF8(z2);
  103330. }
  103331. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  103332. SQLITE_UTF8);
  103333. }else{
  103334. if( p1+p2>len ){
  103335. p2 = len-p1;
  103336. if( p2<0 ) p2 = 0;
  103337. }
  103338. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  103339. }
  103340. }
  103341. /*
  103342. ** Implementation of the round() function
  103343. */
  103344. #ifndef SQLITE_OMIT_FLOATING_POINT
  103345. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  103346. int n = 0;
  103347. double r;
  103348. char *zBuf;
  103349. assert( argc==1 || argc==2 );
  103350. if( argc==2 ){
  103351. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  103352. n = sqlite3_value_int(argv[1]);
  103353. if( n>30 ) n = 30;
  103354. if( n<0 ) n = 0;
  103355. }
  103356. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  103357. r = sqlite3_value_double(argv[0]);
  103358. /* If Y==0 and X will fit in a 64-bit int,
  103359. ** handle the rounding directly,
  103360. ** otherwise use printf.
  103361. */
  103362. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  103363. r = (double)((sqlite_int64)(r+0.5));
  103364. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  103365. r = -(double)((sqlite_int64)((-r)+0.5));
  103366. }else{
  103367. zBuf = sqlite3_mprintf("%.*f",n,r);
  103368. if( zBuf==0 ){
  103369. sqlite3_result_error_nomem(context);
  103370. return;
  103371. }
  103372. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  103373. sqlite3_free(zBuf);
  103374. }
  103375. sqlite3_result_double(context, r);
  103376. }
  103377. #endif
  103378. /*
  103379. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  103380. ** allocation fails, call sqlite3_result_error_nomem() to notify
  103381. ** the database handle that malloc() has failed and return NULL.
  103382. ** If nByte is larger than the maximum string or blob length, then
  103383. ** raise an SQLITE_TOOBIG exception and return NULL.
  103384. */
  103385. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  103386. char *z;
  103387. sqlite3 *db = sqlite3_context_db_handle(context);
  103388. assert( nByte>0 );
  103389. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  103390. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  103391. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  103392. sqlite3_result_error_toobig(context);
  103393. z = 0;
  103394. }else{
  103395. z = sqlite3Malloc(nByte);
  103396. if( !z ){
  103397. sqlite3_result_error_nomem(context);
  103398. }
  103399. }
  103400. return z;
  103401. }
  103402. /*
  103403. ** Implementation of the upper() and lower() SQL functions.
  103404. */
  103405. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  103406. char *z1;
  103407. const char *z2;
  103408. int i, n;
  103409. UNUSED_PARAMETER(argc);
  103410. z2 = (char*)sqlite3_value_text(argv[0]);
  103411. n = sqlite3_value_bytes(argv[0]);
  103412. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  103413. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  103414. if( z2 ){
  103415. z1 = contextMalloc(context, ((i64)n)+1);
  103416. if( z1 ){
  103417. for(i=0; i<n; i++){
  103418. z1[i] = (char)sqlite3Toupper(z2[i]);
  103419. }
  103420. sqlite3_result_text(context, z1, n, sqlite3_free);
  103421. }
  103422. }
  103423. }
  103424. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  103425. char *z1;
  103426. const char *z2;
  103427. int i, n;
  103428. UNUSED_PARAMETER(argc);
  103429. z2 = (char*)sqlite3_value_text(argv[0]);
  103430. n = sqlite3_value_bytes(argv[0]);
  103431. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  103432. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  103433. if( z2 ){
  103434. z1 = contextMalloc(context, ((i64)n)+1);
  103435. if( z1 ){
  103436. for(i=0; i<n; i++){
  103437. z1[i] = sqlite3Tolower(z2[i]);
  103438. }
  103439. sqlite3_result_text(context, z1, n, sqlite3_free);
  103440. }
  103441. }
  103442. }
  103443. /*
  103444. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  103445. ** as VDBE code so that unused argument values do not have to be computed.
  103446. ** However, we still need some kind of function implementation for this
  103447. ** routines in the function table. The noopFunc macro provides this.
  103448. ** noopFunc will never be called so it doesn't matter what the implementation
  103449. ** is. We might as well use the "version()" function as a substitute.
  103450. */
  103451. #define noopFunc versionFunc /* Substitute function - never called */
  103452. /*
  103453. ** Implementation of random(). Return a random integer.
  103454. */
  103455. static void randomFunc(
  103456. sqlite3_context *context,
  103457. int NotUsed,
  103458. sqlite3_value **NotUsed2
  103459. ){
  103460. sqlite_int64 r;
  103461. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103462. sqlite3_randomness(sizeof(r), &r);
  103463. if( r<0 ){
  103464. /* We need to prevent a random number of 0x8000000000000000
  103465. ** (or -9223372036854775808) since when you do abs() of that
  103466. ** number of you get the same value back again. To do this
  103467. ** in a way that is testable, mask the sign bit off of negative
  103468. ** values, resulting in a positive value. Then take the
  103469. ** 2s complement of that positive value. The end result can
  103470. ** therefore be no less than -9223372036854775807.
  103471. */
  103472. r = -(r & LARGEST_INT64);
  103473. }
  103474. sqlite3_result_int64(context, r);
  103475. }
  103476. /*
  103477. ** Implementation of randomblob(N). Return a random blob
  103478. ** that is N bytes long.
  103479. */
  103480. static void randomBlob(
  103481. sqlite3_context *context,
  103482. int argc,
  103483. sqlite3_value **argv
  103484. ){
  103485. int n;
  103486. unsigned char *p;
  103487. assert( argc==1 );
  103488. UNUSED_PARAMETER(argc);
  103489. n = sqlite3_value_int(argv[0]);
  103490. if( n<1 ){
  103491. n = 1;
  103492. }
  103493. p = contextMalloc(context, n);
  103494. if( p ){
  103495. sqlite3_randomness(n, p);
  103496. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  103497. }
  103498. }
  103499. /*
  103500. ** Implementation of the last_insert_rowid() SQL function. The return
  103501. ** value is the same as the sqlite3_last_insert_rowid() API function.
  103502. */
  103503. static void last_insert_rowid(
  103504. sqlite3_context *context,
  103505. int NotUsed,
  103506. sqlite3_value **NotUsed2
  103507. ){
  103508. sqlite3 *db = sqlite3_context_db_handle(context);
  103509. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103510. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  103511. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  103512. ** function. */
  103513. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  103514. }
  103515. /*
  103516. ** Implementation of the changes() SQL function.
  103517. **
  103518. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  103519. ** around the sqlite3_changes() C/C++ function and hence follows the same
  103520. ** rules for counting changes.
  103521. */
  103522. static void changes(
  103523. sqlite3_context *context,
  103524. int NotUsed,
  103525. sqlite3_value **NotUsed2
  103526. ){
  103527. sqlite3 *db = sqlite3_context_db_handle(context);
  103528. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103529. sqlite3_result_int(context, sqlite3_changes(db));
  103530. }
  103531. /*
  103532. ** Implementation of the total_changes() SQL function. The return value is
  103533. ** the same as the sqlite3_total_changes() API function.
  103534. */
  103535. static void total_changes(
  103536. sqlite3_context *context,
  103537. int NotUsed,
  103538. sqlite3_value **NotUsed2
  103539. ){
  103540. sqlite3 *db = sqlite3_context_db_handle(context);
  103541. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103542. /* IMP: R-52756-41993 This function is a wrapper around the
  103543. ** sqlite3_total_changes() C/C++ interface. */
  103544. sqlite3_result_int(context, sqlite3_total_changes(db));
  103545. }
  103546. /*
  103547. ** A structure defining how to do GLOB-style comparisons.
  103548. */
  103549. struct compareInfo {
  103550. u8 matchAll; /* "*" or "%" */
  103551. u8 matchOne; /* "?" or "_" */
  103552. u8 matchSet; /* "[" or 0 */
  103553. u8 noCase; /* true to ignore case differences */
  103554. };
  103555. /*
  103556. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  103557. ** character is exactly one byte in size. Also, provde the Utf8Read()
  103558. ** macro for fast reading of the next character in the common case where
  103559. ** the next character is ASCII.
  103560. */
  103561. #if defined(SQLITE_EBCDIC)
  103562. # define sqlite3Utf8Read(A) (*((*A)++))
  103563. # define Utf8Read(A) (*(A++))
  103564. #else
  103565. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  103566. #endif
  103567. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  103568. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  103569. ** case. Thus 'a' LIKE 'A' would be true. */
  103570. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  103571. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  103572. ** is case sensitive causing 'a' LIKE 'A' to be false */
  103573. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  103574. /*
  103575. ** Possible error returns from patternMatch()
  103576. */
  103577. #define SQLITE_MATCH 0
  103578. #define SQLITE_NOMATCH 1
  103579. #define SQLITE_NOWILDCARDMATCH 2
  103580. /*
  103581. ** Compare two UTF-8 strings for equality where the first string is
  103582. ** a GLOB or LIKE expression. Return values:
  103583. **
  103584. ** SQLITE_MATCH: Match
  103585. ** SQLITE_NOMATCH: No match
  103586. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  103587. **
  103588. ** Globbing rules:
  103589. **
  103590. ** '*' Matches any sequence of zero or more characters.
  103591. **
  103592. ** '?' Matches exactly one character.
  103593. **
  103594. ** [...] Matches one character from the enclosed list of
  103595. ** characters.
  103596. **
  103597. ** [^...] Matches one character not in the enclosed list.
  103598. **
  103599. ** With the [...] and [^...] matching, a ']' character can be included
  103600. ** in the list by making it the first character after '[' or '^'. A
  103601. ** range of characters can be specified using '-'. Example:
  103602. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  103603. ** it the last character in the list.
  103604. **
  103605. ** Like matching rules:
  103606. **
  103607. ** '%' Matches any sequence of zero or more characters
  103608. **
  103609. *** '_' Matches any one character
  103610. **
  103611. ** Ec Where E is the "esc" character and c is any other
  103612. ** character, including '%', '_', and esc, match exactly c.
  103613. **
  103614. ** The comments within this routine usually assume glob matching.
  103615. **
  103616. ** This routine is usually quick, but can be N**2 in the worst case.
  103617. */
  103618. static int patternCompare(
  103619. const u8 *zPattern, /* The glob pattern */
  103620. const u8 *zString, /* The string to compare against the glob */
  103621. const struct compareInfo *pInfo, /* Information about how to do the compare */
  103622. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  103623. ){
  103624. u32 c, c2; /* Next pattern and input string chars */
  103625. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  103626. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  103627. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  103628. const u8 *zEscaped = 0; /* One past the last escaped input char */
  103629. while( (c = Utf8Read(zPattern))!=0 ){
  103630. if( c==matchAll ){ /* Match "*" */
  103631. /* Skip over multiple "*" characters in the pattern. If there
  103632. ** are also "?" characters, skip those as well, but consume a
  103633. ** single character of the input string for each "?" skipped */
  103634. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  103635. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  103636. return SQLITE_NOWILDCARDMATCH;
  103637. }
  103638. }
  103639. if( c==0 ){
  103640. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  103641. }else if( c==matchOther ){
  103642. if( pInfo->matchSet==0 ){
  103643. c = sqlite3Utf8Read(&zPattern);
  103644. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  103645. }else{
  103646. /* "[...]" immediately follows the "*". We have to do a slow
  103647. ** recursive search in this case, but it is an unusual case. */
  103648. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  103649. while( *zString ){
  103650. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  103651. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  103652. SQLITE_SKIP_UTF8(zString);
  103653. }
  103654. return SQLITE_NOWILDCARDMATCH;
  103655. }
  103656. }
  103657. /* At this point variable c contains the first character of the
  103658. ** pattern string past the "*". Search in the input string for the
  103659. ** first matching character and recursively continue the match from
  103660. ** that point.
  103661. **
  103662. ** For a case-insensitive search, set variable cx to be the same as
  103663. ** c but in the other case and search the input string for either
  103664. ** c or cx.
  103665. */
  103666. if( c<=0x80 ){
  103667. char zStop[3];
  103668. int bMatch;
  103669. if( noCase ){
  103670. zStop[0] = sqlite3Toupper(c);
  103671. zStop[1] = sqlite3Tolower(c);
  103672. zStop[2] = 0;
  103673. }else{
  103674. zStop[0] = c;
  103675. zStop[1] = 0;
  103676. }
  103677. while(1){
  103678. zString += strcspn((const char*)zString, zStop);
  103679. if( zString[0]==0 ) break;
  103680. zString++;
  103681. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  103682. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  103683. }
  103684. }else{
  103685. int bMatch;
  103686. while( (c2 = Utf8Read(zString))!=0 ){
  103687. if( c2!=c ) continue;
  103688. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  103689. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  103690. }
  103691. }
  103692. return SQLITE_NOWILDCARDMATCH;
  103693. }
  103694. if( c==matchOther ){
  103695. if( pInfo->matchSet==0 ){
  103696. c = sqlite3Utf8Read(&zPattern);
  103697. if( c==0 ) return SQLITE_NOMATCH;
  103698. zEscaped = zPattern;
  103699. }else{
  103700. u32 prior_c = 0;
  103701. int seen = 0;
  103702. int invert = 0;
  103703. c = sqlite3Utf8Read(&zString);
  103704. if( c==0 ) return SQLITE_NOMATCH;
  103705. c2 = sqlite3Utf8Read(&zPattern);
  103706. if( c2=='^' ){
  103707. invert = 1;
  103708. c2 = sqlite3Utf8Read(&zPattern);
  103709. }
  103710. if( c2==']' ){
  103711. if( c==']' ) seen = 1;
  103712. c2 = sqlite3Utf8Read(&zPattern);
  103713. }
  103714. while( c2 && c2!=']' ){
  103715. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  103716. c2 = sqlite3Utf8Read(&zPattern);
  103717. if( c>=prior_c && c<=c2 ) seen = 1;
  103718. prior_c = 0;
  103719. }else{
  103720. if( c==c2 ){
  103721. seen = 1;
  103722. }
  103723. prior_c = c2;
  103724. }
  103725. c2 = sqlite3Utf8Read(&zPattern);
  103726. }
  103727. if( c2==0 || (seen ^ invert)==0 ){
  103728. return SQLITE_NOMATCH;
  103729. }
  103730. continue;
  103731. }
  103732. }
  103733. c2 = Utf8Read(zString);
  103734. if( c==c2 ) continue;
  103735. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  103736. continue;
  103737. }
  103738. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  103739. return SQLITE_NOMATCH;
  103740. }
  103741. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  103742. }
  103743. /*
  103744. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  103745. ** non-zero if there is no match.
  103746. */
  103747. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  103748. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  103749. }
  103750. /*
  103751. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  103752. ** a miss - like strcmp().
  103753. */
  103754. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  103755. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  103756. }
  103757. /*
  103758. ** Count the number of times that the LIKE operator (or GLOB which is
  103759. ** just a variation of LIKE) gets called. This is used for testing
  103760. ** only.
  103761. */
  103762. #ifdef SQLITE_TEST
  103763. SQLITE_API int sqlite3_like_count = 0;
  103764. #endif
  103765. /*
  103766. ** Implementation of the like() SQL function. This function implements
  103767. ** the build-in LIKE operator. The first argument to the function is the
  103768. ** pattern and the second argument is the string. So, the SQL statements:
  103769. **
  103770. ** A LIKE B
  103771. **
  103772. ** is implemented as like(B,A).
  103773. **
  103774. ** This same function (with a different compareInfo structure) computes
  103775. ** the GLOB operator.
  103776. */
  103777. static void likeFunc(
  103778. sqlite3_context *context,
  103779. int argc,
  103780. sqlite3_value **argv
  103781. ){
  103782. const unsigned char *zA, *zB;
  103783. u32 escape;
  103784. int nPat;
  103785. sqlite3 *db = sqlite3_context_db_handle(context);
  103786. struct compareInfo *pInfo = sqlite3_user_data(context);
  103787. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  103788. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  103789. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  103790. ){
  103791. #ifdef SQLITE_TEST
  103792. sqlite3_like_count++;
  103793. #endif
  103794. sqlite3_result_int(context, 0);
  103795. return;
  103796. }
  103797. #endif
  103798. zB = sqlite3_value_text(argv[0]);
  103799. zA = sqlite3_value_text(argv[1]);
  103800. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  103801. ** of deep recursion and N*N behavior in patternCompare().
  103802. */
  103803. nPat = sqlite3_value_bytes(argv[0]);
  103804. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  103805. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  103806. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  103807. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  103808. return;
  103809. }
  103810. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  103811. if( argc==3 ){
  103812. /* The escape character string must consist of a single UTF-8 character.
  103813. ** Otherwise, return an error.
  103814. */
  103815. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  103816. if( zEsc==0 ) return;
  103817. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  103818. sqlite3_result_error(context,
  103819. "ESCAPE expression must be a single character", -1);
  103820. return;
  103821. }
  103822. escape = sqlite3Utf8Read(&zEsc);
  103823. }else{
  103824. escape = pInfo->matchSet;
  103825. }
  103826. if( zA && zB ){
  103827. #ifdef SQLITE_TEST
  103828. sqlite3_like_count++;
  103829. #endif
  103830. sqlite3_result_int(context,
  103831. patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  103832. }
  103833. }
  103834. /*
  103835. ** Implementation of the NULLIF(x,y) function. The result is the first
  103836. ** argument if the arguments are different. The result is NULL if the
  103837. ** arguments are equal to each other.
  103838. */
  103839. static void nullifFunc(
  103840. sqlite3_context *context,
  103841. int NotUsed,
  103842. sqlite3_value **argv
  103843. ){
  103844. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  103845. UNUSED_PARAMETER(NotUsed);
  103846. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  103847. sqlite3_result_value(context, argv[0]);
  103848. }
  103849. }
  103850. /*
  103851. ** Implementation of the sqlite_version() function. The result is the version
  103852. ** of the SQLite library that is running.
  103853. */
  103854. static void versionFunc(
  103855. sqlite3_context *context,
  103856. int NotUsed,
  103857. sqlite3_value **NotUsed2
  103858. ){
  103859. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103860. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  103861. ** sqlite3_libversion() C-interface. */
  103862. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  103863. }
  103864. /*
  103865. ** Implementation of the sqlite_source_id() function. The result is a string
  103866. ** that identifies the particular version of the source code used to build
  103867. ** SQLite.
  103868. */
  103869. static void sourceidFunc(
  103870. sqlite3_context *context,
  103871. int NotUsed,
  103872. sqlite3_value **NotUsed2
  103873. ){
  103874. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103875. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  103876. ** sqlite3_sourceid() C interface. */
  103877. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  103878. }
  103879. /*
  103880. ** Implementation of the sqlite_log() function. This is a wrapper around
  103881. ** sqlite3_log(). The return value is NULL. The function exists purely for
  103882. ** its side-effects.
  103883. */
  103884. static void errlogFunc(
  103885. sqlite3_context *context,
  103886. int argc,
  103887. sqlite3_value **argv
  103888. ){
  103889. UNUSED_PARAMETER(argc);
  103890. UNUSED_PARAMETER(context);
  103891. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  103892. }
  103893. /*
  103894. ** Implementation of the sqlite_compileoption_used() function.
  103895. ** The result is an integer that identifies if the compiler option
  103896. ** was used to build SQLite.
  103897. */
  103898. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  103899. static void compileoptionusedFunc(
  103900. sqlite3_context *context,
  103901. int argc,
  103902. sqlite3_value **argv
  103903. ){
  103904. const char *zOptName;
  103905. assert( argc==1 );
  103906. UNUSED_PARAMETER(argc);
  103907. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  103908. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  103909. ** function.
  103910. */
  103911. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  103912. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  103913. }
  103914. }
  103915. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  103916. /*
  103917. ** Implementation of the sqlite_compileoption_get() function.
  103918. ** The result is a string that identifies the compiler options
  103919. ** used to build SQLite.
  103920. */
  103921. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  103922. static void compileoptiongetFunc(
  103923. sqlite3_context *context,
  103924. int argc,
  103925. sqlite3_value **argv
  103926. ){
  103927. int n;
  103928. assert( argc==1 );
  103929. UNUSED_PARAMETER(argc);
  103930. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  103931. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  103932. */
  103933. n = sqlite3_value_int(argv[0]);
  103934. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  103935. }
  103936. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  103937. /* Array for converting from half-bytes (nybbles) into ASCII hex
  103938. ** digits. */
  103939. static const char hexdigits[] = {
  103940. '0', '1', '2', '3', '4', '5', '6', '7',
  103941. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  103942. };
  103943. /*
  103944. ** Implementation of the QUOTE() function. This function takes a single
  103945. ** argument. If the argument is numeric, the return value is the same as
  103946. ** the argument. If the argument is NULL, the return value is the string
  103947. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  103948. ** single-quote escapes.
  103949. */
  103950. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  103951. assert( argc==1 );
  103952. UNUSED_PARAMETER(argc);
  103953. switch( sqlite3_value_type(argv[0]) ){
  103954. case SQLITE_FLOAT: {
  103955. double r1, r2;
  103956. char zBuf[50];
  103957. r1 = sqlite3_value_double(argv[0]);
  103958. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  103959. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  103960. if( r1!=r2 ){
  103961. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  103962. }
  103963. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  103964. break;
  103965. }
  103966. case SQLITE_INTEGER: {
  103967. sqlite3_result_value(context, argv[0]);
  103968. break;
  103969. }
  103970. case SQLITE_BLOB: {
  103971. char *zText = 0;
  103972. char const *zBlob = sqlite3_value_blob(argv[0]);
  103973. int nBlob = sqlite3_value_bytes(argv[0]);
  103974. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  103975. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  103976. if( zText ){
  103977. int i;
  103978. for(i=0; i<nBlob; i++){
  103979. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  103980. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  103981. }
  103982. zText[(nBlob*2)+2] = '\'';
  103983. zText[(nBlob*2)+3] = '\0';
  103984. zText[0] = 'X';
  103985. zText[1] = '\'';
  103986. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  103987. sqlite3_free(zText);
  103988. }
  103989. break;
  103990. }
  103991. case SQLITE_TEXT: {
  103992. int i,j;
  103993. u64 n;
  103994. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  103995. char *z;
  103996. if( zArg==0 ) return;
  103997. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  103998. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  103999. if( z ){
  104000. z[0] = '\'';
  104001. for(i=0, j=1; zArg[i]; i++){
  104002. z[j++] = zArg[i];
  104003. if( zArg[i]=='\'' ){
  104004. z[j++] = '\'';
  104005. }
  104006. }
  104007. z[j++] = '\'';
  104008. z[j] = 0;
  104009. sqlite3_result_text(context, z, j, sqlite3_free);
  104010. }
  104011. break;
  104012. }
  104013. default: {
  104014. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  104015. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  104016. break;
  104017. }
  104018. }
  104019. }
  104020. /*
  104021. ** The unicode() function. Return the integer unicode code-point value
  104022. ** for the first character of the input string.
  104023. */
  104024. static void unicodeFunc(
  104025. sqlite3_context *context,
  104026. int argc,
  104027. sqlite3_value **argv
  104028. ){
  104029. const unsigned char *z = sqlite3_value_text(argv[0]);
  104030. (void)argc;
  104031. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  104032. }
  104033. /*
  104034. ** The char() function takes zero or more arguments, each of which is
  104035. ** an integer. It constructs a string where each character of the string
  104036. ** is the unicode character for the corresponding integer argument.
  104037. */
  104038. static void charFunc(
  104039. sqlite3_context *context,
  104040. int argc,
  104041. sqlite3_value **argv
  104042. ){
  104043. unsigned char *z, *zOut;
  104044. int i;
  104045. zOut = z = sqlite3_malloc64( argc*4+1 );
  104046. if( z==0 ){
  104047. sqlite3_result_error_nomem(context);
  104048. return;
  104049. }
  104050. for(i=0; i<argc; i++){
  104051. sqlite3_int64 x;
  104052. unsigned c;
  104053. x = sqlite3_value_int64(argv[i]);
  104054. if( x<0 || x>0x10ffff ) x = 0xfffd;
  104055. c = (unsigned)(x & 0x1fffff);
  104056. if( c<0x00080 ){
  104057. *zOut++ = (u8)(c&0xFF);
  104058. }else if( c<0x00800 ){
  104059. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  104060. *zOut++ = 0x80 + (u8)(c & 0x3F);
  104061. }else if( c<0x10000 ){
  104062. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  104063. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  104064. *zOut++ = 0x80 + (u8)(c & 0x3F);
  104065. }else{
  104066. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  104067. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  104068. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  104069. *zOut++ = 0x80 + (u8)(c & 0x3F);
  104070. } \
  104071. }
  104072. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  104073. }
  104074. /*
  104075. ** The hex() function. Interpret the argument as a blob. Return
  104076. ** a hexadecimal rendering as text.
  104077. */
  104078. static void hexFunc(
  104079. sqlite3_context *context,
  104080. int argc,
  104081. sqlite3_value **argv
  104082. ){
  104083. int i, n;
  104084. const unsigned char *pBlob;
  104085. char *zHex, *z;
  104086. assert( argc==1 );
  104087. UNUSED_PARAMETER(argc);
  104088. pBlob = sqlite3_value_blob(argv[0]);
  104089. n = sqlite3_value_bytes(argv[0]);
  104090. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  104091. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  104092. if( zHex ){
  104093. for(i=0; i<n; i++, pBlob++){
  104094. unsigned char c = *pBlob;
  104095. *(z++) = hexdigits[(c>>4)&0xf];
  104096. *(z++) = hexdigits[c&0xf];
  104097. }
  104098. *z = 0;
  104099. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  104100. }
  104101. }
  104102. /*
  104103. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  104104. */
  104105. static void zeroblobFunc(
  104106. sqlite3_context *context,
  104107. int argc,
  104108. sqlite3_value **argv
  104109. ){
  104110. i64 n;
  104111. int rc;
  104112. assert( argc==1 );
  104113. UNUSED_PARAMETER(argc);
  104114. n = sqlite3_value_int64(argv[0]);
  104115. if( n<0 ) n = 0;
  104116. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  104117. if( rc ){
  104118. sqlite3_result_error_code(context, rc);
  104119. }
  104120. }
  104121. /*
  104122. ** The replace() function. Three arguments are all strings: call
  104123. ** them A, B, and C. The result is also a string which is derived
  104124. ** from A by replacing every occurrence of B with C. The match
  104125. ** must be exact. Collating sequences are not used.
  104126. */
  104127. static void replaceFunc(
  104128. sqlite3_context *context,
  104129. int argc,
  104130. sqlite3_value **argv
  104131. ){
  104132. const unsigned char *zStr; /* The input string A */
  104133. const unsigned char *zPattern; /* The pattern string B */
  104134. const unsigned char *zRep; /* The replacement string C */
  104135. unsigned char *zOut; /* The output */
  104136. int nStr; /* Size of zStr */
  104137. int nPattern; /* Size of zPattern */
  104138. int nRep; /* Size of zRep */
  104139. i64 nOut; /* Maximum size of zOut */
  104140. int loopLimit; /* Last zStr[] that might match zPattern[] */
  104141. int i, j; /* Loop counters */
  104142. unsigned cntExpand; /* Number zOut expansions */
  104143. sqlite3 *db = sqlite3_context_db_handle(context);
  104144. assert( argc==3 );
  104145. UNUSED_PARAMETER(argc);
  104146. zStr = sqlite3_value_text(argv[0]);
  104147. if( zStr==0 ) return;
  104148. nStr = sqlite3_value_bytes(argv[0]);
  104149. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  104150. zPattern = sqlite3_value_text(argv[1]);
  104151. if( zPattern==0 ){
  104152. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  104153. || sqlite3_context_db_handle(context)->mallocFailed );
  104154. return;
  104155. }
  104156. if( zPattern[0]==0 ){
  104157. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  104158. sqlite3_result_value(context, argv[0]);
  104159. return;
  104160. }
  104161. nPattern = sqlite3_value_bytes(argv[1]);
  104162. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  104163. zRep = sqlite3_value_text(argv[2]);
  104164. if( zRep==0 ) return;
  104165. nRep = sqlite3_value_bytes(argv[2]);
  104166. assert( zRep==sqlite3_value_text(argv[2]) );
  104167. nOut = nStr + 1;
  104168. assert( nOut<SQLITE_MAX_LENGTH );
  104169. zOut = contextMalloc(context, (i64)nOut);
  104170. if( zOut==0 ){
  104171. return;
  104172. }
  104173. loopLimit = nStr - nPattern;
  104174. cntExpand = 0;
  104175. for(i=j=0; i<=loopLimit; i++){
  104176. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  104177. zOut[j++] = zStr[i];
  104178. }else{
  104179. if( nRep>nPattern ){
  104180. nOut += nRep - nPattern;
  104181. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  104182. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  104183. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  104184. sqlite3_result_error_toobig(context);
  104185. sqlite3_free(zOut);
  104186. return;
  104187. }
  104188. cntExpand++;
  104189. if( (cntExpand&(cntExpand-1))==0 ){
  104190. /* Grow the size of the output buffer only on substitutions
  104191. ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
  104192. u8 *zOld;
  104193. zOld = zOut;
  104194. zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1));
  104195. if( zOut==0 ){
  104196. sqlite3_result_error_nomem(context);
  104197. sqlite3_free(zOld);
  104198. return;
  104199. }
  104200. }
  104201. }
  104202. memcpy(&zOut[j], zRep, nRep);
  104203. j += nRep;
  104204. i += nPattern-1;
  104205. }
  104206. }
  104207. assert( j+nStr-i+1<=nOut );
  104208. memcpy(&zOut[j], &zStr[i], nStr-i);
  104209. j += nStr - i;
  104210. assert( j<=nOut );
  104211. zOut[j] = 0;
  104212. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  104213. }
  104214. /*
  104215. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  104216. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  104217. */
  104218. static void trimFunc(
  104219. sqlite3_context *context,
  104220. int argc,
  104221. sqlite3_value **argv
  104222. ){
  104223. const unsigned char *zIn; /* Input string */
  104224. const unsigned char *zCharSet; /* Set of characters to trim */
  104225. int nIn; /* Number of bytes in input */
  104226. int flags; /* 1: trimleft 2: trimright 3: trim */
  104227. int i; /* Loop counter */
  104228. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  104229. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  104230. int nChar; /* Number of characters in zCharSet */
  104231. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  104232. return;
  104233. }
  104234. zIn = sqlite3_value_text(argv[0]);
  104235. if( zIn==0 ) return;
  104236. nIn = sqlite3_value_bytes(argv[0]);
  104237. assert( zIn==sqlite3_value_text(argv[0]) );
  104238. if( argc==1 ){
  104239. static const unsigned char lenOne[] = { 1 };
  104240. static unsigned char * const azOne[] = { (u8*)" " };
  104241. nChar = 1;
  104242. aLen = (u8*)lenOne;
  104243. azChar = (unsigned char **)azOne;
  104244. zCharSet = 0;
  104245. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  104246. return;
  104247. }else{
  104248. const unsigned char *z;
  104249. for(z=zCharSet, nChar=0; *z; nChar++){
  104250. SQLITE_SKIP_UTF8(z);
  104251. }
  104252. if( nChar>0 ){
  104253. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  104254. if( azChar==0 ){
  104255. return;
  104256. }
  104257. aLen = (unsigned char*)&azChar[nChar];
  104258. for(z=zCharSet, nChar=0; *z; nChar++){
  104259. azChar[nChar] = (unsigned char *)z;
  104260. SQLITE_SKIP_UTF8(z);
  104261. aLen[nChar] = (u8)(z - azChar[nChar]);
  104262. }
  104263. }
  104264. }
  104265. if( nChar>0 ){
  104266. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  104267. if( flags & 1 ){
  104268. while( nIn>0 ){
  104269. int len = 0;
  104270. for(i=0; i<nChar; i++){
  104271. len = aLen[i];
  104272. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  104273. }
  104274. if( i>=nChar ) break;
  104275. zIn += len;
  104276. nIn -= len;
  104277. }
  104278. }
  104279. if( flags & 2 ){
  104280. while( nIn>0 ){
  104281. int len = 0;
  104282. for(i=0; i<nChar; i++){
  104283. len = aLen[i];
  104284. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  104285. }
  104286. if( i>=nChar ) break;
  104287. nIn -= len;
  104288. }
  104289. }
  104290. if( zCharSet ){
  104291. sqlite3_free(azChar);
  104292. }
  104293. }
  104294. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  104295. }
  104296. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  104297. /*
  104298. ** The "unknown" function is automatically substituted in place of
  104299. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  104300. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  104301. ** When the "sqlite3" command-line shell is built using this functionality,
  104302. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  104303. ** involving application-defined functions to be examined in a generic
  104304. ** sqlite3 shell.
  104305. */
  104306. static void unknownFunc(
  104307. sqlite3_context *context,
  104308. int argc,
  104309. sqlite3_value **argv
  104310. ){
  104311. /* no-op */
  104312. }
  104313. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  104314. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  104315. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  104316. ** when SQLite is built.
  104317. */
  104318. #ifdef SQLITE_SOUNDEX
  104319. /*
  104320. ** Compute the soundex encoding of a word.
  104321. **
  104322. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  104323. ** soundex encoding of the string X.
  104324. */
  104325. static void soundexFunc(
  104326. sqlite3_context *context,
  104327. int argc,
  104328. sqlite3_value **argv
  104329. ){
  104330. char zResult[8];
  104331. const u8 *zIn;
  104332. int i, j;
  104333. static const unsigned char iCode[] = {
  104334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  104335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  104336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  104337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  104338. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  104339. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  104340. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  104341. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  104342. };
  104343. assert( argc==1 );
  104344. zIn = (u8*)sqlite3_value_text(argv[0]);
  104345. if( zIn==0 ) zIn = (u8*)"";
  104346. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  104347. if( zIn[i] ){
  104348. u8 prevcode = iCode[zIn[i]&0x7f];
  104349. zResult[0] = sqlite3Toupper(zIn[i]);
  104350. for(j=1; j<4 && zIn[i]; i++){
  104351. int code = iCode[zIn[i]&0x7f];
  104352. if( code>0 ){
  104353. if( code!=prevcode ){
  104354. prevcode = code;
  104355. zResult[j++] = code + '0';
  104356. }
  104357. }else{
  104358. prevcode = 0;
  104359. }
  104360. }
  104361. while( j<4 ){
  104362. zResult[j++] = '0';
  104363. }
  104364. zResult[j] = 0;
  104365. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  104366. }else{
  104367. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  104368. ** is NULL or contains no ASCII alphabetic characters. */
  104369. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  104370. }
  104371. }
  104372. #endif /* SQLITE_SOUNDEX */
  104373. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  104374. /*
  104375. ** A function that loads a shared-library extension then returns NULL.
  104376. */
  104377. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  104378. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  104379. const char *zProc;
  104380. sqlite3 *db = sqlite3_context_db_handle(context);
  104381. char *zErrMsg = 0;
  104382. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  104383. ** flag is set. See the sqlite3_enable_load_extension() API.
  104384. */
  104385. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  104386. sqlite3_result_error(context, "not authorized", -1);
  104387. return;
  104388. }
  104389. if( argc==2 ){
  104390. zProc = (const char *)sqlite3_value_text(argv[1]);
  104391. }else{
  104392. zProc = 0;
  104393. }
  104394. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  104395. sqlite3_result_error(context, zErrMsg, -1);
  104396. sqlite3_free(zErrMsg);
  104397. }
  104398. }
  104399. #endif
  104400. /*
  104401. ** An instance of the following structure holds the context of a
  104402. ** sum() or avg() aggregate computation.
  104403. */
  104404. typedef struct SumCtx SumCtx;
  104405. struct SumCtx {
  104406. double rSum; /* Floating point sum */
  104407. i64 iSum; /* Integer sum */
  104408. i64 cnt; /* Number of elements summed */
  104409. u8 overflow; /* True if integer overflow seen */
  104410. u8 approx; /* True if non-integer value was input to the sum */
  104411. };
  104412. /*
  104413. ** Routines used to compute the sum, average, and total.
  104414. **
  104415. ** The SUM() function follows the (broken) SQL standard which means
  104416. ** that it returns NULL if it sums over no inputs. TOTAL returns
  104417. ** 0.0 in that case. In addition, TOTAL always returns a float where
  104418. ** SUM might return an integer if it never encounters a floating point
  104419. ** value. TOTAL never fails, but SUM might through an exception if
  104420. ** it overflows an integer.
  104421. */
  104422. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  104423. SumCtx *p;
  104424. int type;
  104425. assert( argc==1 );
  104426. UNUSED_PARAMETER(argc);
  104427. p = sqlite3_aggregate_context(context, sizeof(*p));
  104428. type = sqlite3_value_numeric_type(argv[0]);
  104429. if( p && type!=SQLITE_NULL ){
  104430. p->cnt++;
  104431. if( type==SQLITE_INTEGER ){
  104432. i64 v = sqlite3_value_int64(argv[0]);
  104433. p->rSum += v;
  104434. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  104435. p->overflow = 1;
  104436. }
  104437. }else{
  104438. p->rSum += sqlite3_value_double(argv[0]);
  104439. p->approx = 1;
  104440. }
  104441. }
  104442. }
  104443. static void sumFinalize(sqlite3_context *context){
  104444. SumCtx *p;
  104445. p = sqlite3_aggregate_context(context, 0);
  104446. if( p && p->cnt>0 ){
  104447. if( p->overflow ){
  104448. sqlite3_result_error(context,"integer overflow",-1);
  104449. }else if( p->approx ){
  104450. sqlite3_result_double(context, p->rSum);
  104451. }else{
  104452. sqlite3_result_int64(context, p->iSum);
  104453. }
  104454. }
  104455. }
  104456. static void avgFinalize(sqlite3_context *context){
  104457. SumCtx *p;
  104458. p = sqlite3_aggregate_context(context, 0);
  104459. if( p && p->cnt>0 ){
  104460. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  104461. }
  104462. }
  104463. static void totalFinalize(sqlite3_context *context){
  104464. SumCtx *p;
  104465. p = sqlite3_aggregate_context(context, 0);
  104466. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  104467. sqlite3_result_double(context, p ? p->rSum : (double)0);
  104468. }
  104469. /*
  104470. ** The following structure keeps track of state information for the
  104471. ** count() aggregate function.
  104472. */
  104473. typedef struct CountCtx CountCtx;
  104474. struct CountCtx {
  104475. i64 n;
  104476. };
  104477. /*
  104478. ** Routines to implement the count() aggregate function.
  104479. */
  104480. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  104481. CountCtx *p;
  104482. p = sqlite3_aggregate_context(context, sizeof(*p));
  104483. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  104484. p->n++;
  104485. }
  104486. #ifndef SQLITE_OMIT_DEPRECATED
  104487. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  104488. ** sure it still operates correctly, verify that its count agrees with our
  104489. ** internal count when using count(*) and when the total count can be
  104490. ** expressed as a 32-bit integer. */
  104491. assert( argc==1 || p==0 || p->n>0x7fffffff
  104492. || p->n==sqlite3_aggregate_count(context) );
  104493. #endif
  104494. }
  104495. static void countFinalize(sqlite3_context *context){
  104496. CountCtx *p;
  104497. p = sqlite3_aggregate_context(context, 0);
  104498. sqlite3_result_int64(context, p ? p->n : 0);
  104499. }
  104500. /*
  104501. ** Routines to implement min() and max() aggregate functions.
  104502. */
  104503. static void minmaxStep(
  104504. sqlite3_context *context,
  104505. int NotUsed,
  104506. sqlite3_value **argv
  104507. ){
  104508. Mem *pArg = (Mem *)argv[0];
  104509. Mem *pBest;
  104510. UNUSED_PARAMETER(NotUsed);
  104511. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  104512. if( !pBest ) return;
  104513. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  104514. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  104515. }else if( pBest->flags ){
  104516. int max;
  104517. int cmp;
  104518. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  104519. /* This step function is used for both the min() and max() aggregates,
  104520. ** the only difference between the two being that the sense of the
  104521. ** comparison is inverted. For the max() aggregate, the
  104522. ** sqlite3_user_data() function returns (void *)-1. For min() it
  104523. ** returns (void *)db, where db is the sqlite3* database pointer.
  104524. ** Therefore the next statement sets variable 'max' to 1 for the max()
  104525. ** aggregate, or 0 for min().
  104526. */
  104527. max = sqlite3_user_data(context)!=0;
  104528. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  104529. if( (max && cmp<0) || (!max && cmp>0) ){
  104530. sqlite3VdbeMemCopy(pBest, pArg);
  104531. }else{
  104532. sqlite3SkipAccumulatorLoad(context);
  104533. }
  104534. }else{
  104535. pBest->db = sqlite3_context_db_handle(context);
  104536. sqlite3VdbeMemCopy(pBest, pArg);
  104537. }
  104538. }
  104539. static void minMaxFinalize(sqlite3_context *context){
  104540. sqlite3_value *pRes;
  104541. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  104542. if( pRes ){
  104543. if( pRes->flags ){
  104544. sqlite3_result_value(context, pRes);
  104545. }
  104546. sqlite3VdbeMemRelease(pRes);
  104547. }
  104548. }
  104549. /*
  104550. ** group_concat(EXPR, ?SEPARATOR?)
  104551. */
  104552. static void groupConcatStep(
  104553. sqlite3_context *context,
  104554. int argc,
  104555. sqlite3_value **argv
  104556. ){
  104557. const char *zVal;
  104558. StrAccum *pAccum;
  104559. const char *zSep;
  104560. int nVal, nSep;
  104561. assert( argc==1 || argc==2 );
  104562. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  104563. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  104564. if( pAccum ){
  104565. sqlite3 *db = sqlite3_context_db_handle(context);
  104566. int firstTerm = pAccum->mxAlloc==0;
  104567. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  104568. if( !firstTerm ){
  104569. if( argc==2 ){
  104570. zSep = (char*)sqlite3_value_text(argv[1]);
  104571. nSep = sqlite3_value_bytes(argv[1]);
  104572. }else{
  104573. zSep = ",";
  104574. nSep = 1;
  104575. }
  104576. if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
  104577. }
  104578. zVal = (char*)sqlite3_value_text(argv[0]);
  104579. nVal = sqlite3_value_bytes(argv[0]);
  104580. if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
  104581. }
  104582. }
  104583. static void groupConcatFinalize(sqlite3_context *context){
  104584. StrAccum *pAccum;
  104585. pAccum = sqlite3_aggregate_context(context, 0);
  104586. if( pAccum ){
  104587. if( pAccum->accError==SQLITE_TOOBIG ){
  104588. sqlite3_result_error_toobig(context);
  104589. }else if( pAccum->accError==SQLITE_NOMEM ){
  104590. sqlite3_result_error_nomem(context);
  104591. }else{
  104592. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  104593. sqlite3_free);
  104594. }
  104595. }
  104596. }
  104597. /*
  104598. ** This routine does per-connection function registration. Most
  104599. ** of the built-in functions above are part of the global function set.
  104600. ** This routine only deals with those that are not global.
  104601. */
  104602. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  104603. int rc = sqlite3_overload_function(db, "MATCH", 2);
  104604. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  104605. if( rc==SQLITE_NOMEM ){
  104606. sqlite3OomFault(db);
  104607. }
  104608. }
  104609. /*
  104610. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  104611. */
  104612. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  104613. FuncDef *pDef;
  104614. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  104615. if( ALWAYS(pDef) ){
  104616. pDef->funcFlags |= flagVal;
  104617. }
  104618. }
  104619. /*
  104620. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  104621. ** parameter determines whether or not the LIKE operator is case
  104622. ** sensitive. GLOB is always case sensitive.
  104623. */
  104624. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  104625. struct compareInfo *pInfo;
  104626. if( caseSensitive ){
  104627. pInfo = (struct compareInfo*)&likeInfoAlt;
  104628. }else{
  104629. pInfo = (struct compareInfo*)&likeInfoNorm;
  104630. }
  104631. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  104632. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  104633. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  104634. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  104635. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  104636. setLikeOptFlag(db, "like",
  104637. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  104638. }
  104639. /*
  104640. ** pExpr points to an expression which implements a function. If
  104641. ** it is appropriate to apply the LIKE optimization to that function
  104642. ** then set aWc[0] through aWc[2] to the wildcard characters and the
  104643. ** escape character and then return TRUE. If the function is not a
  104644. ** LIKE-style function then return FALSE.
  104645. **
  104646. ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
  104647. ** operator if c is a string literal that is exactly one byte in length.
  104648. ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
  104649. ** no ESCAPE clause.
  104650. **
  104651. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  104652. ** the function (default for LIKE). If the function makes the distinction
  104653. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  104654. ** false.
  104655. */
  104656. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  104657. FuncDef *pDef;
  104658. int nExpr;
  104659. if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
  104660. return 0;
  104661. }
  104662. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  104663. nExpr = pExpr->x.pList->nExpr;
  104664. pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
  104665. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  104666. return 0;
  104667. }
  104668. if( nExpr<3 ){
  104669. aWc[3] = 0;
  104670. }else{
  104671. Expr *pEscape = pExpr->x.pList->a[2].pExpr;
  104672. char *zEscape;
  104673. if( pEscape->op!=TK_STRING ) return 0;
  104674. zEscape = pEscape->u.zToken;
  104675. if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
  104676. aWc[3] = zEscape[0];
  104677. }
  104678. /* The memcpy() statement assumes that the wildcard characters are
  104679. ** the first three statements in the compareInfo structure. The
  104680. ** asserts() that follow verify that assumption
  104681. */
  104682. memcpy(aWc, pDef->pUserData, 3);
  104683. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  104684. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  104685. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  104686. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  104687. return 1;
  104688. }
  104689. /*
  104690. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  104691. ** to the global function hash table. This occurs at start-time (as
  104692. ** a consequence of calling sqlite3_initialize()).
  104693. **
  104694. ** After this routine runs
  104695. */
  104696. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  104697. /*
  104698. ** The following array holds FuncDef structures for all of the functions
  104699. ** defined in this file.
  104700. **
  104701. ** The array cannot be constant since changes are made to the
  104702. ** FuncDef.pHash elements at start-time. The elements of this array
  104703. ** are read-only after initialization is complete.
  104704. **
  104705. ** For peak efficiency, put the most frequently used function last.
  104706. */
  104707. static FuncDef aBuiltinFunc[] = {
  104708. #ifdef SQLITE_SOUNDEX
  104709. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  104710. #endif
  104711. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  104712. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  104713. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  104714. #endif
  104715. #if SQLITE_USER_AUTHENTICATION
  104716. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  104717. #endif
  104718. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  104719. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  104720. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  104721. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  104722. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  104723. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  104724. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  104725. #ifdef SQLITE_DEBUG
  104726. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  104727. #endif
  104728. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  104729. FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET|
  104730. SQLITE_FUNC_TYPEOF),
  104731. #endif
  104732. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  104733. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  104734. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  104735. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  104736. FUNCTION(trim, 1, 3, 0, trimFunc ),
  104737. FUNCTION(trim, 2, 3, 0, trimFunc ),
  104738. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  104739. FUNCTION(min, 0, 0, 1, 0 ),
  104740. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  104741. SQLITE_FUNC_MINMAX ),
  104742. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  104743. FUNCTION(max, 0, 1, 1, 0 ),
  104744. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  104745. SQLITE_FUNC_MINMAX ),
  104746. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  104747. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  104748. FUNCTION(instr, 2, 0, 0, instrFunc ),
  104749. FUNCTION(printf, -1, 0, 0, printfFunc ),
  104750. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  104751. FUNCTION(char, -1, 0, 0, charFunc ),
  104752. FUNCTION(abs, 1, 0, 0, absFunc ),
  104753. #ifndef SQLITE_OMIT_FLOATING_POINT
  104754. FUNCTION(round, 1, 0, 0, roundFunc ),
  104755. FUNCTION(round, 2, 0, 0, roundFunc ),
  104756. #endif
  104757. FUNCTION(upper, 1, 0, 0, upperFunc ),
  104758. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  104759. FUNCTION(hex, 1, 0, 0, hexFunc ),
  104760. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  104761. VFUNCTION(random, 0, 0, 0, randomFunc ),
  104762. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  104763. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  104764. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  104765. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  104766. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  104767. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  104768. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  104769. VFUNCTION(changes, 0, 0, 0, changes ),
  104770. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  104771. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  104772. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  104773. FUNCTION(substr, 2, 0, 0, substrFunc ),
  104774. FUNCTION(substr, 3, 0, 0, substrFunc ),
  104775. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  104776. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  104777. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  104778. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  104779. SQLITE_FUNC_COUNT ),
  104780. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  104781. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  104782. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  104783. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  104784. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  104785. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  104786. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  104787. #else
  104788. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  104789. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  104790. #endif
  104791. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  104792. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  104793. #endif
  104794. FUNCTION(coalesce, 1, 0, 0, 0 ),
  104795. FUNCTION(coalesce, 0, 0, 0, 0 ),
  104796. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  104797. };
  104798. #ifndef SQLITE_OMIT_ALTERTABLE
  104799. sqlite3AlterFunctions();
  104800. #endif
  104801. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  104802. sqlite3AnalyzeFunctions();
  104803. #endif
  104804. sqlite3RegisterDateTimeFunctions();
  104805. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  104806. #if 0 /* Enable to print out how the built-in functions are hashed */
  104807. {
  104808. int i;
  104809. FuncDef *p;
  104810. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  104811. printf("FUNC-HASH %02d:", i);
  104812. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  104813. int n = sqlite3Strlen30(p->zName);
  104814. int h = p->zName[0] + n;
  104815. printf(" %s(%d)", p->zName, h);
  104816. }
  104817. printf("\n");
  104818. }
  104819. }
  104820. #endif
  104821. }
  104822. /************** End of func.c ************************************************/
  104823. /************** Begin file fkey.c ********************************************/
  104824. /*
  104825. **
  104826. ** The author disclaims copyright to this source code. In place of
  104827. ** a legal notice, here is a blessing:
  104828. **
  104829. ** May you do good and not evil.
  104830. ** May you find forgiveness for yourself and forgive others.
  104831. ** May you share freely, never taking more than you give.
  104832. **
  104833. *************************************************************************
  104834. ** This file contains code used by the compiler to add foreign key
  104835. ** support to compiled SQL statements.
  104836. */
  104837. /* #include "sqliteInt.h" */
  104838. #ifndef SQLITE_OMIT_FOREIGN_KEY
  104839. #ifndef SQLITE_OMIT_TRIGGER
  104840. /*
  104841. ** Deferred and Immediate FKs
  104842. ** --------------------------
  104843. **
  104844. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  104845. ** If an immediate foreign key constraint is violated,
  104846. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  104847. ** statement transaction rolled back. If a
  104848. ** deferred foreign key constraint is violated, no action is taken
  104849. ** immediately. However if the application attempts to commit the
  104850. ** transaction before fixing the constraint violation, the attempt fails.
  104851. **
  104852. ** Deferred constraints are implemented using a simple counter associated
  104853. ** with the database handle. The counter is set to zero each time a
  104854. ** database transaction is opened. Each time a statement is executed
  104855. ** that causes a foreign key violation, the counter is incremented. Each
  104856. ** time a statement is executed that removes an existing violation from
  104857. ** the database, the counter is decremented. When the transaction is
  104858. ** committed, the commit fails if the current value of the counter is
  104859. ** greater than zero. This scheme has two big drawbacks:
  104860. **
  104861. ** * When a commit fails due to a deferred foreign key constraint,
  104862. ** there is no way to tell which foreign constraint is not satisfied,
  104863. ** or which row it is not satisfied for.
  104864. **
  104865. ** * If the database contains foreign key violations when the
  104866. ** transaction is opened, this may cause the mechanism to malfunction.
  104867. **
  104868. ** Despite these problems, this approach is adopted as it seems simpler
  104869. ** than the alternatives.
  104870. **
  104871. ** INSERT operations:
  104872. **
  104873. ** I.1) For each FK for which the table is the child table, search
  104874. ** the parent table for a match. If none is found increment the
  104875. ** constraint counter.
  104876. **
  104877. ** I.2) For each FK for which the table is the parent table,
  104878. ** search the child table for rows that correspond to the new
  104879. ** row in the parent table. Decrement the counter for each row
  104880. ** found (as the constraint is now satisfied).
  104881. **
  104882. ** DELETE operations:
  104883. **
  104884. ** D.1) For each FK for which the table is the child table,
  104885. ** search the parent table for a row that corresponds to the
  104886. ** deleted row in the child table. If such a row is not found,
  104887. ** decrement the counter.
  104888. **
  104889. ** D.2) For each FK for which the table is the parent table, search
  104890. ** the child table for rows that correspond to the deleted row
  104891. ** in the parent table. For each found increment the counter.
  104892. **
  104893. ** UPDATE operations:
  104894. **
  104895. ** An UPDATE command requires that all 4 steps above are taken, but only
  104896. ** for FK constraints for which the affected columns are actually
  104897. ** modified (values must be compared at runtime).
  104898. **
  104899. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  104900. ** This simplifies the implementation a bit.
  104901. **
  104902. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  104903. ** resolution is considered to delete rows before the new row is inserted.
  104904. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  104905. ** is thrown, even if the FK constraint would be satisfied after the new
  104906. ** row is inserted.
  104907. **
  104908. ** Immediate constraints are usually handled similarly. The only difference
  104909. ** is that the counter used is stored as part of each individual statement
  104910. ** object (struct Vdbe). If, after the statement has run, its immediate
  104911. ** constraint counter is greater than zero,
  104912. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  104913. ** and the statement transaction is rolled back. An exception is an INSERT
  104914. ** statement that inserts a single row only (no triggers). In this case,
  104915. ** instead of using a counter, an exception is thrown immediately if the
  104916. ** INSERT violates a foreign key constraint. This is necessary as such
  104917. ** an INSERT does not open a statement transaction.
  104918. **
  104919. ** TODO: How should dropping a table be handled? How should renaming a
  104920. ** table be handled?
  104921. **
  104922. **
  104923. ** Query API Notes
  104924. ** ---------------
  104925. **
  104926. ** Before coding an UPDATE or DELETE row operation, the code-generator
  104927. ** for those two operations needs to know whether or not the operation
  104928. ** requires any FK processing and, if so, which columns of the original
  104929. ** row are required by the FK processing VDBE code (i.e. if FKs were
  104930. ** implemented using triggers, which of the old.* columns would be
  104931. ** accessed). No information is required by the code-generator before
  104932. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  104933. ** generation code to query for this information are:
  104934. **
  104935. ** sqlite3FkRequired() - Test to see if FK processing is required.
  104936. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  104937. **
  104938. **
  104939. ** Externally accessible module functions
  104940. ** --------------------------------------
  104941. **
  104942. ** sqlite3FkCheck() - Check for foreign key violations.
  104943. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  104944. ** sqlite3FkDelete() - Delete an FKey structure.
  104945. */
  104946. /*
  104947. ** VDBE Calling Convention
  104948. ** -----------------------
  104949. **
  104950. ** Example:
  104951. **
  104952. ** For the following INSERT statement:
  104953. **
  104954. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  104955. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  104956. **
  104957. ** Register (x): 2 (type integer)
  104958. ** Register (x+1): 1 (type integer)
  104959. ** Register (x+2): NULL (type NULL)
  104960. ** Register (x+3): 3.1 (type real)
  104961. */
  104962. /*
  104963. ** A foreign key constraint requires that the key columns in the parent
  104964. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  104965. ** Given that pParent is the parent table for foreign key constraint pFKey,
  104966. ** search the schema for a unique index on the parent key columns.
  104967. **
  104968. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  104969. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  104970. ** is set to point to the unique index.
  104971. **
  104972. ** If the parent key consists of a single column (the foreign key constraint
  104973. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  104974. ** Otherwise, it is set to point to an allocated array of size N, where
  104975. ** N is the number of columns in the parent key. The first element of the
  104976. ** array is the index of the child table column that is mapped by the FK
  104977. ** constraint to the parent table column stored in the left-most column
  104978. ** of index *ppIdx. The second element of the array is the index of the
  104979. ** child table column that corresponds to the second left-most column of
  104980. ** *ppIdx, and so on.
  104981. **
  104982. ** If the required index cannot be found, either because:
  104983. **
  104984. ** 1) The named parent key columns do not exist, or
  104985. **
  104986. ** 2) The named parent key columns do exist, but are not subject to a
  104987. ** UNIQUE or PRIMARY KEY constraint, or
  104988. **
  104989. ** 3) No parent key columns were provided explicitly as part of the
  104990. ** foreign key definition, and the parent table does not have a
  104991. ** PRIMARY KEY, or
  104992. **
  104993. ** 4) No parent key columns were provided explicitly as part of the
  104994. ** foreign key definition, and the PRIMARY KEY of the parent table
  104995. ** consists of a different number of columns to the child key in
  104996. ** the child table.
  104997. **
  104998. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  104999. ** into pParse. If an OOM error occurs, non-zero is returned and the
  105000. ** pParse->db->mallocFailed flag is set.
  105001. */
  105002. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  105003. Parse *pParse, /* Parse context to store any error in */
  105004. Table *pParent, /* Parent table of FK constraint pFKey */
  105005. FKey *pFKey, /* Foreign key to find index for */
  105006. Index **ppIdx, /* OUT: Unique index on parent table */
  105007. int **paiCol /* OUT: Map of index columns in pFKey */
  105008. ){
  105009. Index *pIdx = 0; /* Value to return via *ppIdx */
  105010. int *aiCol = 0; /* Value to return via *paiCol */
  105011. int nCol = pFKey->nCol; /* Number of columns in parent key */
  105012. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  105013. /* The caller is responsible for zeroing output parameters. */
  105014. assert( ppIdx && *ppIdx==0 );
  105015. assert( !paiCol || *paiCol==0 );
  105016. assert( pParse );
  105017. /* If this is a non-composite (single column) foreign key, check if it
  105018. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  105019. ** and *paiCol set to zero and return early.
  105020. **
  105021. ** Otherwise, for a composite foreign key (more than one column), allocate
  105022. ** space for the aiCol array (returned via output parameter *paiCol).
  105023. ** Non-composite foreign keys do not require the aiCol array.
  105024. */
  105025. if( nCol==1 ){
  105026. /* The FK maps to the IPK if any of the following are true:
  105027. **
  105028. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  105029. ** mapped to the primary key of table pParent, or
  105030. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  105031. ** PRIMARY KEY.
  105032. */
  105033. if( pParent->iPKey>=0 ){
  105034. if( !zKey ) return 0;
  105035. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  105036. }
  105037. }else if( paiCol ){
  105038. assert( nCol>1 );
  105039. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  105040. if( !aiCol ) return 1;
  105041. *paiCol = aiCol;
  105042. }
  105043. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  105044. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  105045. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  105046. ** of columns. If each indexed column corresponds to a foreign key
  105047. ** column of pFKey, then this index is a winner. */
  105048. if( zKey==0 ){
  105049. /* If zKey is NULL, then this foreign key is implicitly mapped to
  105050. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  105051. ** identified by the test. */
  105052. if( IsPrimaryKeyIndex(pIdx) ){
  105053. if( aiCol ){
  105054. int i;
  105055. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  105056. }
  105057. break;
  105058. }
  105059. }else{
  105060. /* If zKey is non-NULL, then this foreign key was declared to
  105061. ** map to an explicit list of columns in table pParent. Check if this
  105062. ** index matches those columns. Also, check that the index uses
  105063. ** the default collation sequences for each column. */
  105064. int i, j;
  105065. for(i=0; i<nCol; i++){
  105066. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  105067. const char *zDfltColl; /* Def. collation for column */
  105068. char *zIdxCol; /* Name of indexed column */
  105069. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  105070. /* If the index uses a collation sequence that is different from
  105071. ** the default collation sequence for the column, this index is
  105072. ** unusable. Bail out early in this case. */
  105073. zDfltColl = pParent->aCol[iCol].zColl;
  105074. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  105075. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  105076. zIdxCol = pParent->aCol[iCol].zName;
  105077. for(j=0; j<nCol; j++){
  105078. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  105079. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  105080. break;
  105081. }
  105082. }
  105083. if( j==nCol ) break;
  105084. }
  105085. if( i==nCol ) break; /* pIdx is usable */
  105086. }
  105087. }
  105088. }
  105089. if( !pIdx ){
  105090. if( !pParse->disableTriggers ){
  105091. sqlite3ErrorMsg(pParse,
  105092. "foreign key mismatch - \"%w\" referencing \"%w\"",
  105093. pFKey->pFrom->zName, pFKey->zTo);
  105094. }
  105095. sqlite3DbFree(pParse->db, aiCol);
  105096. return 1;
  105097. }
  105098. *ppIdx = pIdx;
  105099. return 0;
  105100. }
  105101. /*
  105102. ** This function is called when a row is inserted into or deleted from the
  105103. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  105104. ** on the child table of pFKey, this function is invoked twice for each row
  105105. ** affected - once to "delete" the old row, and then again to "insert" the
  105106. ** new row.
  105107. **
  105108. ** Each time it is called, this function generates VDBE code to locate the
  105109. ** row in the parent table that corresponds to the row being inserted into
  105110. ** or deleted from the child table. If the parent row can be found, no
  105111. ** special action is taken. Otherwise, if the parent row can *not* be
  105112. ** found in the parent table:
  105113. **
  105114. ** Operation | FK type | Action taken
  105115. ** --------------------------------------------------------------------------
  105116. ** INSERT immediate Increment the "immediate constraint counter".
  105117. **
  105118. ** DELETE immediate Decrement the "immediate constraint counter".
  105119. **
  105120. ** INSERT deferred Increment the "deferred constraint counter".
  105121. **
  105122. ** DELETE deferred Decrement the "deferred constraint counter".
  105123. **
  105124. ** These operations are identified in the comment at the top of this file
  105125. ** (fkey.c) as "I.1" and "D.1".
  105126. */
  105127. static void fkLookupParent(
  105128. Parse *pParse, /* Parse context */
  105129. int iDb, /* Index of database housing pTab */
  105130. Table *pTab, /* Parent table of FK pFKey */
  105131. Index *pIdx, /* Unique index on parent key columns in pTab */
  105132. FKey *pFKey, /* Foreign key constraint */
  105133. int *aiCol, /* Map from parent key columns to child table columns */
  105134. int regData, /* Address of array containing child table row */
  105135. int nIncr, /* Increment constraint counter by this */
  105136. int isIgnore /* If true, pretend pTab contains all NULL values */
  105137. ){
  105138. int i; /* Iterator variable */
  105139. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  105140. int iCur = pParse->nTab - 1; /* Cursor number to use */
  105141. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  105142. sqlite3VdbeVerifyAbortable(v,
  105143. (!pFKey->isDeferred
  105144. && !(pParse->db->flags & SQLITE_DeferFKs)
  105145. && !pParse->pToplevel
  105146. && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
  105147. /* If nIncr is less than zero, then check at runtime if there are any
  105148. ** outstanding constraints to resolve. If there are not, there is no need
  105149. ** to check if deleting this row resolves any outstanding violations.
  105150. **
  105151. ** Check if any of the key columns in the child table row are NULL. If
  105152. ** any are, then the constraint is considered satisfied. No need to
  105153. ** search for a matching row in the parent table. */
  105154. if( nIncr<0 ){
  105155. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  105156. VdbeCoverage(v);
  105157. }
  105158. for(i=0; i<pFKey->nCol; i++){
  105159. int iReg = aiCol[i] + regData + 1;
  105160. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  105161. }
  105162. if( isIgnore==0 ){
  105163. if( pIdx==0 ){
  105164. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  105165. ** column of the parent table (table pTab). */
  105166. int iMustBeInt; /* Address of MustBeInt instruction */
  105167. int regTemp = sqlite3GetTempReg(pParse);
  105168. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  105169. ** apply the affinity of the parent key). If this fails, then there
  105170. ** is no matching parent key. Before using MustBeInt, make a copy of
  105171. ** the value. Otherwise, the value inserted into the child key column
  105172. ** will have INTEGER affinity applied to it, which may not be correct. */
  105173. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  105174. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  105175. VdbeCoverage(v);
  105176. /* If the parent table is the same as the child table, and we are about
  105177. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  105178. ** then check if the row being inserted matches itself. If so, do not
  105179. ** increment the constraint-counter. */
  105180. if( pTab==pFKey->pFrom && nIncr==1 ){
  105181. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  105182. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  105183. }
  105184. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  105185. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  105186. sqlite3VdbeGoto(v, iOk);
  105187. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  105188. sqlite3VdbeJumpHere(v, iMustBeInt);
  105189. sqlite3ReleaseTempReg(pParse, regTemp);
  105190. }else{
  105191. int nCol = pFKey->nCol;
  105192. int regTemp = sqlite3GetTempRange(pParse, nCol);
  105193. int regRec = sqlite3GetTempReg(pParse);
  105194. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  105195. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  105196. for(i=0; i<nCol; i++){
  105197. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  105198. }
  105199. /* If the parent table is the same as the child table, and we are about
  105200. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  105201. ** then check if the row being inserted matches itself. If so, do not
  105202. ** increment the constraint-counter.
  105203. **
  105204. ** If any of the parent-key values are NULL, then the row cannot match
  105205. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  105206. ** of the parent-key values are NULL (at this point it is known that
  105207. ** none of the child key values are).
  105208. */
  105209. if( pTab==pFKey->pFrom && nIncr==1 ){
  105210. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  105211. for(i=0; i<nCol; i++){
  105212. int iChild = aiCol[i]+1+regData;
  105213. int iParent = pIdx->aiColumn[i]+1+regData;
  105214. assert( pIdx->aiColumn[i]>=0 );
  105215. assert( aiCol[i]!=pTab->iPKey );
  105216. if( pIdx->aiColumn[i]==pTab->iPKey ){
  105217. /* The parent key is a composite key that includes the IPK column */
  105218. iParent = regData;
  105219. }
  105220. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  105221. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  105222. }
  105223. sqlite3VdbeGoto(v, iOk);
  105224. }
  105225. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  105226. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  105227. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  105228. sqlite3ReleaseTempReg(pParse, regRec);
  105229. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  105230. }
  105231. }
  105232. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  105233. && !pParse->pToplevel
  105234. && !pParse->isMultiWrite
  105235. ){
  105236. /* Special case: If this is an INSERT statement that will insert exactly
  105237. ** one row into the table, raise a constraint immediately instead of
  105238. ** incrementing a counter. This is necessary as the VM code is being
  105239. ** generated for will not open a statement transaction. */
  105240. assert( nIncr==1 );
  105241. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  105242. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  105243. }else{
  105244. if( nIncr>0 && pFKey->isDeferred==0 ){
  105245. sqlite3MayAbort(pParse);
  105246. }
  105247. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  105248. }
  105249. sqlite3VdbeResolveLabel(v, iOk);
  105250. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  105251. }
  105252. /*
  105253. ** Return an Expr object that refers to a memory register corresponding
  105254. ** to column iCol of table pTab.
  105255. **
  105256. ** regBase is the first of an array of register that contains the data
  105257. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  105258. ** column. regBase+2 holds the second column, and so forth.
  105259. */
  105260. static Expr *exprTableRegister(
  105261. Parse *pParse, /* Parsing and code generating context */
  105262. Table *pTab, /* The table whose content is at r[regBase]... */
  105263. int regBase, /* Contents of table pTab */
  105264. i16 iCol /* Which column of pTab is desired */
  105265. ){
  105266. Expr *pExpr;
  105267. Column *pCol;
  105268. const char *zColl;
  105269. sqlite3 *db = pParse->db;
  105270. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  105271. if( pExpr ){
  105272. if( iCol>=0 && iCol!=pTab->iPKey ){
  105273. pCol = &pTab->aCol[iCol];
  105274. pExpr->iTable = regBase + iCol + 1;
  105275. pExpr->affinity = pCol->affinity;
  105276. zColl = pCol->zColl;
  105277. if( zColl==0 ) zColl = db->pDfltColl->zName;
  105278. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  105279. }else{
  105280. pExpr->iTable = regBase;
  105281. pExpr->affinity = SQLITE_AFF_INTEGER;
  105282. }
  105283. }
  105284. return pExpr;
  105285. }
  105286. /*
  105287. ** Return an Expr object that refers to column iCol of table pTab which
  105288. ** has cursor iCur.
  105289. */
  105290. static Expr *exprTableColumn(
  105291. sqlite3 *db, /* The database connection */
  105292. Table *pTab, /* The table whose column is desired */
  105293. int iCursor, /* The open cursor on the table */
  105294. i16 iCol /* The column that is wanted */
  105295. ){
  105296. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  105297. if( pExpr ){
  105298. pExpr->pTab = pTab;
  105299. pExpr->iTable = iCursor;
  105300. pExpr->iColumn = iCol;
  105301. }
  105302. return pExpr;
  105303. }
  105304. /*
  105305. ** This function is called to generate code executed when a row is deleted
  105306. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  105307. ** deferred, when a row is inserted into the same table. When generating
  105308. ** code for an SQL UPDATE operation, this function may be called twice -
  105309. ** once to "delete" the old row and once to "insert" the new row.
  105310. **
  105311. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  105312. ** the number of FK violations in the db) or +1 when deleting one (as this
  105313. ** may increase the number of FK constraint problems).
  105314. **
  105315. ** The code generated by this function scans through the rows in the child
  105316. ** table that correspond to the parent table row being deleted or inserted.
  105317. ** For each child row found, one of the following actions is taken:
  105318. **
  105319. ** Operation | FK type | Action taken
  105320. ** --------------------------------------------------------------------------
  105321. ** DELETE immediate Increment the "immediate constraint counter".
  105322. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  105323. ** throw a "FOREIGN KEY constraint failed" exception.
  105324. **
  105325. ** INSERT immediate Decrement the "immediate constraint counter".
  105326. **
  105327. ** DELETE deferred Increment the "deferred constraint counter".
  105328. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  105329. ** throw a "FOREIGN KEY constraint failed" exception.
  105330. **
  105331. ** INSERT deferred Decrement the "deferred constraint counter".
  105332. **
  105333. ** These operations are identified in the comment at the top of this file
  105334. ** (fkey.c) as "I.2" and "D.2".
  105335. */
  105336. static void fkScanChildren(
  105337. Parse *pParse, /* Parse context */
  105338. SrcList *pSrc, /* The child table to be scanned */
  105339. Table *pTab, /* The parent table */
  105340. Index *pIdx, /* Index on parent covering the foreign key */
  105341. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  105342. int *aiCol, /* Map from pIdx cols to child table cols */
  105343. int regData, /* Parent row data starts here */
  105344. int nIncr /* Amount to increment deferred counter by */
  105345. ){
  105346. sqlite3 *db = pParse->db; /* Database handle */
  105347. int i; /* Iterator variable */
  105348. Expr *pWhere = 0; /* WHERE clause to scan with */
  105349. NameContext sNameContext; /* Context used to resolve WHERE clause */
  105350. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  105351. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  105352. Vdbe *v = sqlite3GetVdbe(pParse);
  105353. assert( pIdx==0 || pIdx->pTable==pTab );
  105354. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  105355. assert( pIdx!=0 || pFKey->nCol==1 );
  105356. assert( pIdx!=0 || HasRowid(pTab) );
  105357. if( nIncr<0 ){
  105358. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  105359. VdbeCoverage(v);
  105360. }
  105361. /* Create an Expr object representing an SQL expression like:
  105362. **
  105363. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  105364. **
  105365. ** The collation sequence used for the comparison should be that of
  105366. ** the parent key columns. The affinity of the parent key column should
  105367. ** be applied to each child key value before the comparison takes place.
  105368. */
  105369. for(i=0; i<pFKey->nCol; i++){
  105370. Expr *pLeft; /* Value from parent table row */
  105371. Expr *pRight; /* Column ref to child table */
  105372. Expr *pEq; /* Expression (pLeft = pRight) */
  105373. i16 iCol; /* Index of column in child table */
  105374. const char *zCol; /* Name of column in child table */
  105375. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  105376. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  105377. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  105378. assert( iCol>=0 );
  105379. zCol = pFKey->pFrom->aCol[iCol].zName;
  105380. pRight = sqlite3Expr(db, TK_ID, zCol);
  105381. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  105382. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  105383. }
  105384. /* If the child table is the same as the parent table, then add terms
  105385. ** to the WHERE clause that prevent this entry from being scanned.
  105386. ** The added WHERE clause terms are like this:
  105387. **
  105388. ** $current_rowid!=rowid
  105389. ** NOT( $current_a==a AND $current_b==b AND ... )
  105390. **
  105391. ** The first form is used for rowid tables. The second form is used
  105392. ** for WITHOUT ROWID tables. In the second form, the primary key is
  105393. ** (a,b,...)
  105394. */
  105395. if( pTab==pFKey->pFrom && nIncr>0 ){
  105396. Expr *pNe; /* Expression (pLeft != pRight) */
  105397. Expr *pLeft; /* Value from parent table row */
  105398. Expr *pRight; /* Column ref to child table */
  105399. if( HasRowid(pTab) ){
  105400. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  105401. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  105402. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  105403. }else{
  105404. Expr *pEq, *pAll = 0;
  105405. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  105406. assert( pIdx!=0 );
  105407. for(i=0; i<pPk->nKeyCol; i++){
  105408. i16 iCol = pIdx->aiColumn[i];
  105409. assert( iCol>=0 );
  105410. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  105411. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  105412. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  105413. pAll = sqlite3ExprAnd(db, pAll, pEq);
  105414. }
  105415. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  105416. }
  105417. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  105418. }
  105419. /* Resolve the references in the WHERE clause. */
  105420. memset(&sNameContext, 0, sizeof(NameContext));
  105421. sNameContext.pSrcList = pSrc;
  105422. sNameContext.pParse = pParse;
  105423. sqlite3ResolveExprNames(&sNameContext, pWhere);
  105424. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  105425. ** clause. For each row found, increment either the deferred or immediate
  105426. ** foreign key constraint counter. */
  105427. if( pParse->nErr==0 ){
  105428. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  105429. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  105430. if( pWInfo ){
  105431. sqlite3WhereEnd(pWInfo);
  105432. }
  105433. }
  105434. /* Clean up the WHERE clause constructed above. */
  105435. sqlite3ExprDelete(db, pWhere);
  105436. if( iFkIfZero ){
  105437. sqlite3VdbeJumpHere(v, iFkIfZero);
  105438. }
  105439. }
  105440. /*
  105441. ** This function returns a linked list of FKey objects (connected by
  105442. ** FKey.pNextTo) holding all children of table pTab. For example,
  105443. ** given the following schema:
  105444. **
  105445. ** CREATE TABLE t1(a PRIMARY KEY);
  105446. ** CREATE TABLE t2(b REFERENCES t1(a);
  105447. **
  105448. ** Calling this function with table "t1" as an argument returns a pointer
  105449. ** to the FKey structure representing the foreign key constraint on table
  105450. ** "t2". Calling this function with "t2" as the argument would return a
  105451. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  105452. ** table).
  105453. */
  105454. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  105455. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  105456. }
  105457. /*
  105458. ** The second argument is a Trigger structure allocated by the
  105459. ** fkActionTrigger() routine. This function deletes the Trigger structure
  105460. ** and all of its sub-components.
  105461. **
  105462. ** The Trigger structure or any of its sub-components may be allocated from
  105463. ** the lookaside buffer belonging to database handle dbMem.
  105464. */
  105465. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  105466. if( p ){
  105467. TriggerStep *pStep = p->step_list;
  105468. sqlite3ExprDelete(dbMem, pStep->pWhere);
  105469. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  105470. sqlite3SelectDelete(dbMem, pStep->pSelect);
  105471. sqlite3ExprDelete(dbMem, p->pWhen);
  105472. sqlite3DbFree(dbMem, p);
  105473. }
  105474. }
  105475. /*
  105476. ** This function is called to generate code that runs when table pTab is
  105477. ** being dropped from the database. The SrcList passed as the second argument
  105478. ** to this function contains a single entry guaranteed to resolve to
  105479. ** table pTab.
  105480. **
  105481. ** Normally, no code is required. However, if either
  105482. **
  105483. ** (a) The table is the parent table of a FK constraint, or
  105484. ** (b) The table is the child table of a deferred FK constraint and it is
  105485. ** determined at runtime that there are outstanding deferred FK
  105486. ** constraint violations in the database,
  105487. **
  105488. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  105489. ** the table from the database. Triggers are disabled while running this
  105490. ** DELETE, but foreign key actions are not.
  105491. */
  105492. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  105493. sqlite3 *db = pParse->db;
  105494. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  105495. int iSkip = 0;
  105496. Vdbe *v = sqlite3GetVdbe(pParse);
  105497. assert( v ); /* VDBE has already been allocated */
  105498. if( sqlite3FkReferences(pTab)==0 ){
  105499. /* Search for a deferred foreign key constraint for which this table
  105500. ** is the child table. If one cannot be found, return without
  105501. ** generating any VDBE code. If one can be found, then jump over
  105502. ** the entire DELETE if there are no outstanding deferred constraints
  105503. ** when this statement is run. */
  105504. FKey *p;
  105505. for(p=pTab->pFKey; p; p=p->pNextFrom){
  105506. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  105507. }
  105508. if( !p ) return;
  105509. iSkip = sqlite3VdbeMakeLabel(v);
  105510. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  105511. }
  105512. pParse->disableTriggers = 1;
  105513. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
  105514. pParse->disableTriggers = 0;
  105515. /* If the DELETE has generated immediate foreign key constraint
  105516. ** violations, halt the VDBE and return an error at this point, before
  105517. ** any modifications to the schema are made. This is because statement
  105518. ** transactions are not able to rollback schema changes.
  105519. **
  105520. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  105521. ** the statement transaction will not be rolled back even if FK
  105522. ** constraints are violated.
  105523. */
  105524. if( (db->flags & SQLITE_DeferFKs)==0 ){
  105525. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  105526. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  105527. VdbeCoverage(v);
  105528. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  105529. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  105530. }
  105531. if( iSkip ){
  105532. sqlite3VdbeResolveLabel(v, iSkip);
  105533. }
  105534. }
  105535. }
  105536. /*
  105537. ** The second argument points to an FKey object representing a foreign key
  105538. ** for which pTab is the child table. An UPDATE statement against pTab
  105539. ** is currently being processed. For each column of the table that is
  105540. ** actually updated, the corresponding element in the aChange[] array
  105541. ** is zero or greater (if a column is unmodified the corresponding element
  105542. ** is set to -1). If the rowid column is modified by the UPDATE statement
  105543. ** the bChngRowid argument is non-zero.
  105544. **
  105545. ** This function returns true if any of the columns that are part of the
  105546. ** child key for FK constraint *p are modified.
  105547. */
  105548. static int fkChildIsModified(
  105549. Table *pTab, /* Table being updated */
  105550. FKey *p, /* Foreign key for which pTab is the child */
  105551. int *aChange, /* Array indicating modified columns */
  105552. int bChngRowid /* True if rowid is modified by this update */
  105553. ){
  105554. int i;
  105555. for(i=0; i<p->nCol; i++){
  105556. int iChildKey = p->aCol[i].iFrom;
  105557. if( aChange[iChildKey]>=0 ) return 1;
  105558. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  105559. }
  105560. return 0;
  105561. }
  105562. /*
  105563. ** The second argument points to an FKey object representing a foreign key
  105564. ** for which pTab is the parent table. An UPDATE statement against pTab
  105565. ** is currently being processed. For each column of the table that is
  105566. ** actually updated, the corresponding element in the aChange[] array
  105567. ** is zero or greater (if a column is unmodified the corresponding element
  105568. ** is set to -1). If the rowid column is modified by the UPDATE statement
  105569. ** the bChngRowid argument is non-zero.
  105570. **
  105571. ** This function returns true if any of the columns that are part of the
  105572. ** parent key for FK constraint *p are modified.
  105573. */
  105574. static int fkParentIsModified(
  105575. Table *pTab,
  105576. FKey *p,
  105577. int *aChange,
  105578. int bChngRowid
  105579. ){
  105580. int i;
  105581. for(i=0; i<p->nCol; i++){
  105582. char *zKey = p->aCol[i].zCol;
  105583. int iKey;
  105584. for(iKey=0; iKey<pTab->nCol; iKey++){
  105585. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  105586. Column *pCol = &pTab->aCol[iKey];
  105587. if( zKey ){
  105588. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  105589. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  105590. return 1;
  105591. }
  105592. }
  105593. }
  105594. }
  105595. return 0;
  105596. }
  105597. /*
  105598. ** Return true if the parser passed as the first argument is being
  105599. ** used to code a trigger that is really a "SET NULL" action belonging
  105600. ** to trigger pFKey.
  105601. */
  105602. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  105603. Parse *pTop = sqlite3ParseToplevel(pParse);
  105604. if( pTop->pTriggerPrg ){
  105605. Trigger *p = pTop->pTriggerPrg->pTrigger;
  105606. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  105607. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  105608. ){
  105609. return 1;
  105610. }
  105611. }
  105612. return 0;
  105613. }
  105614. /*
  105615. ** This function is called when inserting, deleting or updating a row of
  105616. ** table pTab to generate VDBE code to perform foreign key constraint
  105617. ** processing for the operation.
  105618. **
  105619. ** For a DELETE operation, parameter regOld is passed the index of the
  105620. ** first register in an array of (pTab->nCol+1) registers containing the
  105621. ** rowid of the row being deleted, followed by each of the column values
  105622. ** of the row being deleted, from left to right. Parameter regNew is passed
  105623. ** zero in this case.
  105624. **
  105625. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  105626. ** first register of an array of (pTab->nCol+1) registers containing the new
  105627. ** row data.
  105628. **
  105629. ** For an UPDATE operation, this function is called twice. Once before
  105630. ** the original record is deleted from the table using the calling convention
  105631. ** described for DELETE. Then again after the original record is deleted
  105632. ** but before the new record is inserted using the INSERT convention.
  105633. */
  105634. SQLITE_PRIVATE void sqlite3FkCheck(
  105635. Parse *pParse, /* Parse context */
  105636. Table *pTab, /* Row is being deleted from this table */
  105637. int regOld, /* Previous row data is stored here */
  105638. int regNew, /* New row data is stored here */
  105639. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  105640. int bChngRowid /* True if rowid is UPDATEd */
  105641. ){
  105642. sqlite3 *db = pParse->db; /* Database handle */
  105643. FKey *pFKey; /* Used to iterate through FKs */
  105644. int iDb; /* Index of database containing pTab */
  105645. const char *zDb; /* Name of database containing pTab */
  105646. int isIgnoreErrors = pParse->disableTriggers;
  105647. /* Exactly one of regOld and regNew should be non-zero. */
  105648. assert( (regOld==0)!=(regNew==0) );
  105649. /* If foreign-keys are disabled, this function is a no-op. */
  105650. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  105651. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105652. zDb = db->aDb[iDb].zDbSName;
  105653. /* Loop through all the foreign key constraints for which pTab is the
  105654. ** child table (the table that the foreign key definition is part of). */
  105655. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  105656. Table *pTo; /* Parent table of foreign key pFKey */
  105657. Index *pIdx = 0; /* Index on key columns in pTo */
  105658. int *aiFree = 0;
  105659. int *aiCol;
  105660. int iCol;
  105661. int i;
  105662. int bIgnore = 0;
  105663. if( aChange
  105664. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  105665. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  105666. ){
  105667. continue;
  105668. }
  105669. /* Find the parent table of this foreign key. Also find a unique index
  105670. ** on the parent key columns in the parent table. If either of these
  105671. ** schema items cannot be located, set an error in pParse and return
  105672. ** early. */
  105673. if( pParse->disableTriggers ){
  105674. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  105675. }else{
  105676. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  105677. }
  105678. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  105679. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  105680. if( !isIgnoreErrors || db->mallocFailed ) return;
  105681. if( pTo==0 ){
  105682. /* If isIgnoreErrors is true, then a table is being dropped. In this
  105683. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  105684. ** before actually dropping it in order to check FK constraints.
  105685. ** If the parent table of an FK constraint on the current table is
  105686. ** missing, behave as if it is empty. i.e. decrement the relevant
  105687. ** FK counter for each row of the current table with non-NULL keys.
  105688. */
  105689. Vdbe *v = sqlite3GetVdbe(pParse);
  105690. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  105691. for(i=0; i<pFKey->nCol; i++){
  105692. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  105693. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  105694. }
  105695. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  105696. }
  105697. continue;
  105698. }
  105699. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  105700. if( aiFree ){
  105701. aiCol = aiFree;
  105702. }else{
  105703. iCol = pFKey->aCol[0].iFrom;
  105704. aiCol = &iCol;
  105705. }
  105706. for(i=0; i<pFKey->nCol; i++){
  105707. if( aiCol[i]==pTab->iPKey ){
  105708. aiCol[i] = -1;
  105709. }
  105710. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  105711. #ifndef SQLITE_OMIT_AUTHORIZATION
  105712. /* Request permission to read the parent key columns. If the
  105713. ** authorization callback returns SQLITE_IGNORE, behave as if any
  105714. ** values read from the parent table are NULL. */
  105715. if( db->xAuth ){
  105716. int rcauth;
  105717. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  105718. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  105719. bIgnore = (rcauth==SQLITE_IGNORE);
  105720. }
  105721. #endif
  105722. }
  105723. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  105724. ** a cursor to use to search the unique index on the parent key columns
  105725. ** in the parent table. */
  105726. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  105727. pParse->nTab++;
  105728. if( regOld!=0 ){
  105729. /* A row is being removed from the child table. Search for the parent.
  105730. ** If the parent does not exist, removing the child row resolves an
  105731. ** outstanding foreign key constraint violation. */
  105732. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  105733. }
  105734. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  105735. /* A row is being added to the child table. If a parent row cannot
  105736. ** be found, adding the child row has violated the FK constraint.
  105737. **
  105738. ** If this operation is being performed as part of a trigger program
  105739. ** that is actually a "SET NULL" action belonging to this very
  105740. ** foreign key, then omit this scan altogether. As all child key
  105741. ** values are guaranteed to be NULL, it is not possible for adding
  105742. ** this row to cause an FK violation. */
  105743. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  105744. }
  105745. sqlite3DbFree(db, aiFree);
  105746. }
  105747. /* Loop through all the foreign key constraints that refer to this table.
  105748. ** (the "child" constraints) */
  105749. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  105750. Index *pIdx = 0; /* Foreign key index for pFKey */
  105751. SrcList *pSrc;
  105752. int *aiCol = 0;
  105753. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  105754. continue;
  105755. }
  105756. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  105757. && !pParse->pToplevel && !pParse->isMultiWrite
  105758. ){
  105759. assert( regOld==0 && regNew!=0 );
  105760. /* Inserting a single row into a parent table cannot cause (or fix)
  105761. ** an immediate foreign key violation. So do nothing in this case. */
  105762. continue;
  105763. }
  105764. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  105765. if( !isIgnoreErrors || db->mallocFailed ) return;
  105766. continue;
  105767. }
  105768. assert( aiCol || pFKey->nCol==1 );
  105769. /* Create a SrcList structure containing the child table. We need the
  105770. ** child table as a SrcList for sqlite3WhereBegin() */
  105771. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  105772. if( pSrc ){
  105773. struct SrcList_item *pItem = pSrc->a;
  105774. pItem->pTab = pFKey->pFrom;
  105775. pItem->zName = pFKey->pFrom->zName;
  105776. pItem->pTab->nTabRef++;
  105777. pItem->iCursor = pParse->nTab++;
  105778. if( regNew!=0 ){
  105779. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  105780. }
  105781. if( regOld!=0 ){
  105782. int eAction = pFKey->aAction[aChange!=0];
  105783. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  105784. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  105785. ** action applies, then any foreign key violations caused by
  105786. ** removing the parent key will be rectified by the action trigger.
  105787. ** So do not set the "may-abort" flag in this case.
  105788. **
  105789. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  105790. ** may-abort flag will eventually be set on this statement anyway
  105791. ** (when this function is called as part of processing the UPDATE
  105792. ** within the action trigger).
  105793. **
  105794. ** Note 2: At first glance it may seem like SQLite could simply omit
  105795. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  105796. ** applies. The trouble starts if the CASCADE or SET NULL action
  105797. ** trigger causes other triggers or action rules attached to the
  105798. ** child table to fire. In these cases the fk constraint counters
  105799. ** might be set incorrectly if any OP_FkCounter related scans are
  105800. ** omitted. */
  105801. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  105802. sqlite3MayAbort(pParse);
  105803. }
  105804. }
  105805. pItem->zName = 0;
  105806. sqlite3SrcListDelete(db, pSrc);
  105807. }
  105808. sqlite3DbFree(db, aiCol);
  105809. }
  105810. }
  105811. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  105812. /*
  105813. ** This function is called before generating code to update or delete a
  105814. ** row contained in table pTab.
  105815. */
  105816. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  105817. Parse *pParse, /* Parse context */
  105818. Table *pTab /* Table being modified */
  105819. ){
  105820. u32 mask = 0;
  105821. if( pParse->db->flags&SQLITE_ForeignKeys ){
  105822. FKey *p;
  105823. int i;
  105824. for(p=pTab->pFKey; p; p=p->pNextFrom){
  105825. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  105826. }
  105827. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  105828. Index *pIdx = 0;
  105829. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  105830. if( pIdx ){
  105831. for(i=0; i<pIdx->nKeyCol; i++){
  105832. assert( pIdx->aiColumn[i]>=0 );
  105833. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  105834. }
  105835. }
  105836. }
  105837. }
  105838. return mask;
  105839. }
  105840. /*
  105841. ** This function is called before generating code to update or delete a
  105842. ** row contained in table pTab. If the operation is a DELETE, then
  105843. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  105844. ** to an array of size N, where N is the number of columns in table pTab.
  105845. ** If the i'th column is not modified by the UPDATE, then the corresponding
  105846. ** entry in the aChange[] array is set to -1. If the column is modified,
  105847. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  105848. ** UPDATE statement modifies the rowid fields of the table.
  105849. **
  105850. ** If any foreign key processing will be required, this function returns
  105851. ** non-zero. If there is no foreign key related processing, this function
  105852. ** returns zero.
  105853. **
  105854. ** For an UPDATE, this function returns 2 if:
  105855. **
  105856. ** * There are any FKs for which pTab is the child and the parent table, or
  105857. ** * the UPDATE modifies one or more parent keys for which the action is
  105858. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  105859. **
  105860. ** Or, assuming some other foreign key processing is required, 1.
  105861. */
  105862. SQLITE_PRIVATE int sqlite3FkRequired(
  105863. Parse *pParse, /* Parse context */
  105864. Table *pTab, /* Table being modified */
  105865. int *aChange, /* Non-NULL for UPDATE operations */
  105866. int chngRowid /* True for UPDATE that affects rowid */
  105867. ){
  105868. int eRet = 0;
  105869. if( pParse->db->flags&SQLITE_ForeignKeys ){
  105870. if( !aChange ){
  105871. /* A DELETE operation. Foreign key processing is required if the
  105872. ** table in question is either the child or parent table for any
  105873. ** foreign key constraint. */
  105874. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  105875. }else{
  105876. /* This is an UPDATE. Foreign key processing is only required if the
  105877. ** operation modifies one or more child or parent key columns. */
  105878. FKey *p;
  105879. /* Check if any child key columns are being modified. */
  105880. for(p=pTab->pFKey; p; p=p->pNextFrom){
  105881. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  105882. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  105883. eRet = 1;
  105884. }
  105885. }
  105886. /* Check if any parent key columns are being modified. */
  105887. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  105888. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  105889. if( p->aAction[1]!=OE_None ) return 2;
  105890. eRet = 1;
  105891. }
  105892. }
  105893. }
  105894. }
  105895. return eRet;
  105896. }
  105897. /*
  105898. ** This function is called when an UPDATE or DELETE operation is being
  105899. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  105900. ** If the current operation is an UPDATE, then the pChanges parameter is
  105901. ** passed a pointer to the list of columns being modified. If it is a
  105902. ** DELETE, pChanges is passed a NULL pointer.
  105903. **
  105904. ** It returns a pointer to a Trigger structure containing a trigger
  105905. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  105906. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  105907. ** returned (these actions require no special handling by the triggers
  105908. ** sub-system, code for them is created by fkScanChildren()).
  105909. **
  105910. ** For example, if pFKey is the foreign key and pTab is table "p" in
  105911. ** the following schema:
  105912. **
  105913. ** CREATE TABLE p(pk PRIMARY KEY);
  105914. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  105915. **
  105916. ** then the returned trigger structure is equivalent to:
  105917. **
  105918. ** CREATE TRIGGER ... DELETE ON p BEGIN
  105919. ** DELETE FROM c WHERE ck = old.pk;
  105920. ** END;
  105921. **
  105922. ** The returned pointer is cached as part of the foreign key object. It
  105923. ** is eventually freed along with the rest of the foreign key object by
  105924. ** sqlite3FkDelete().
  105925. */
  105926. static Trigger *fkActionTrigger(
  105927. Parse *pParse, /* Parse context */
  105928. Table *pTab, /* Table being updated or deleted from */
  105929. FKey *pFKey, /* Foreign key to get action for */
  105930. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  105931. ){
  105932. sqlite3 *db = pParse->db; /* Database handle */
  105933. int action; /* One of OE_None, OE_Cascade etc. */
  105934. Trigger *pTrigger; /* Trigger definition to return */
  105935. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  105936. action = pFKey->aAction[iAction];
  105937. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  105938. return 0;
  105939. }
  105940. pTrigger = pFKey->apTrigger[iAction];
  105941. if( action!=OE_None && !pTrigger ){
  105942. char const *zFrom; /* Name of child table */
  105943. int nFrom; /* Length in bytes of zFrom */
  105944. Index *pIdx = 0; /* Parent key index for this FK */
  105945. int *aiCol = 0; /* child table cols -> parent key cols */
  105946. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  105947. Expr *pWhere = 0; /* WHERE clause of trigger step */
  105948. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  105949. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  105950. int i; /* Iterator variable */
  105951. Expr *pWhen = 0; /* WHEN clause for the trigger */
  105952. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  105953. assert( aiCol || pFKey->nCol==1 );
  105954. for(i=0; i<pFKey->nCol; i++){
  105955. Token tOld = { "old", 3 }; /* Literal "old" token */
  105956. Token tNew = { "new", 3 }; /* Literal "new" token */
  105957. Token tFromCol; /* Name of column in child table */
  105958. Token tToCol; /* Name of column in parent table */
  105959. int iFromCol; /* Idx of column in child table */
  105960. Expr *pEq; /* tFromCol = OLD.tToCol */
  105961. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  105962. assert( iFromCol>=0 );
  105963. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  105964. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  105965. sqlite3TokenInit(&tToCol,
  105966. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  105967. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  105968. /* Create the expression "OLD.zToCol = zFromCol". It is important
  105969. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  105970. ** that the affinity and collation sequence associated with the
  105971. ** parent table are used for the comparison. */
  105972. pEq = sqlite3PExpr(pParse, TK_EQ,
  105973. sqlite3PExpr(pParse, TK_DOT,
  105974. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  105975. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  105976. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  105977. );
  105978. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  105979. /* For ON UPDATE, construct the next term of the WHEN clause.
  105980. ** The final WHEN clause will be like this:
  105981. **
  105982. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  105983. */
  105984. if( pChanges ){
  105985. pEq = sqlite3PExpr(pParse, TK_IS,
  105986. sqlite3PExpr(pParse, TK_DOT,
  105987. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  105988. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  105989. sqlite3PExpr(pParse, TK_DOT,
  105990. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  105991. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  105992. );
  105993. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  105994. }
  105995. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  105996. Expr *pNew;
  105997. if( action==OE_Cascade ){
  105998. pNew = sqlite3PExpr(pParse, TK_DOT,
  105999. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  106000. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  106001. }else if( action==OE_SetDflt ){
  106002. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  106003. if( pDflt ){
  106004. pNew = sqlite3ExprDup(db, pDflt, 0);
  106005. }else{
  106006. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  106007. }
  106008. }else{
  106009. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  106010. }
  106011. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  106012. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  106013. }
  106014. }
  106015. sqlite3DbFree(db, aiCol);
  106016. zFrom = pFKey->pFrom->zName;
  106017. nFrom = sqlite3Strlen30(zFrom);
  106018. if( action==OE_Restrict ){
  106019. Token tFrom;
  106020. Expr *pRaise;
  106021. tFrom.z = zFrom;
  106022. tFrom.n = nFrom;
  106023. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  106024. if( pRaise ){
  106025. pRaise->affinity = OE_Abort;
  106026. }
  106027. pSelect = sqlite3SelectNew(pParse,
  106028. sqlite3ExprListAppend(pParse, 0, pRaise),
  106029. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  106030. pWhere,
  106031. 0, 0, 0, 0, 0
  106032. );
  106033. pWhere = 0;
  106034. }
  106035. /* Disable lookaside memory allocation */
  106036. db->lookaside.bDisable++;
  106037. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  106038. sizeof(Trigger) + /* struct Trigger */
  106039. sizeof(TriggerStep) + /* Single step in trigger program */
  106040. nFrom + 1 /* Space for pStep->zTarget */
  106041. );
  106042. if( pTrigger ){
  106043. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  106044. pStep->zTarget = (char *)&pStep[1];
  106045. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  106046. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  106047. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  106048. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  106049. if( pWhen ){
  106050. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  106051. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  106052. }
  106053. }
  106054. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  106055. db->lookaside.bDisable--;
  106056. sqlite3ExprDelete(db, pWhere);
  106057. sqlite3ExprDelete(db, pWhen);
  106058. sqlite3ExprListDelete(db, pList);
  106059. sqlite3SelectDelete(db, pSelect);
  106060. if( db->mallocFailed==1 ){
  106061. fkTriggerDelete(db, pTrigger);
  106062. return 0;
  106063. }
  106064. assert( pStep!=0 );
  106065. switch( action ){
  106066. case OE_Restrict:
  106067. pStep->op = TK_SELECT;
  106068. break;
  106069. case OE_Cascade:
  106070. if( !pChanges ){
  106071. pStep->op = TK_DELETE;
  106072. break;
  106073. }
  106074. default:
  106075. pStep->op = TK_UPDATE;
  106076. }
  106077. pStep->pTrig = pTrigger;
  106078. pTrigger->pSchema = pTab->pSchema;
  106079. pTrigger->pTabSchema = pTab->pSchema;
  106080. pFKey->apTrigger[iAction] = pTrigger;
  106081. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  106082. }
  106083. return pTrigger;
  106084. }
  106085. /*
  106086. ** This function is called when deleting or updating a row to implement
  106087. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  106088. */
  106089. SQLITE_PRIVATE void sqlite3FkActions(
  106090. Parse *pParse, /* Parse context */
  106091. Table *pTab, /* Table being updated or deleted from */
  106092. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  106093. int regOld, /* Address of array containing old row */
  106094. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  106095. int bChngRowid /* True if rowid is UPDATEd */
  106096. ){
  106097. /* If foreign-key support is enabled, iterate through all FKs that
  106098. ** refer to table pTab. If there is an action associated with the FK
  106099. ** for this operation (either update or delete), invoke the associated
  106100. ** trigger sub-program. */
  106101. if( pParse->db->flags&SQLITE_ForeignKeys ){
  106102. FKey *pFKey; /* Iterator variable */
  106103. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  106104. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  106105. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  106106. if( pAct ){
  106107. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  106108. }
  106109. }
  106110. }
  106111. }
  106112. }
  106113. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  106114. /*
  106115. ** Free all memory associated with foreign key definitions attached to
  106116. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  106117. ** hash table.
  106118. */
  106119. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  106120. FKey *pFKey; /* Iterator variable */
  106121. FKey *pNext; /* Copy of pFKey->pNextFrom */
  106122. assert( db==0 || IsVirtual(pTab)
  106123. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  106124. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  106125. /* Remove the FK from the fkeyHash hash table. */
  106126. if( !db || db->pnBytesFreed==0 ){
  106127. if( pFKey->pPrevTo ){
  106128. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  106129. }else{
  106130. void *p = (void *)pFKey->pNextTo;
  106131. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  106132. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  106133. }
  106134. if( pFKey->pNextTo ){
  106135. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  106136. }
  106137. }
  106138. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  106139. ** classified as either immediate or deferred.
  106140. */
  106141. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  106142. /* Delete any triggers created to implement actions for this FK. */
  106143. #ifndef SQLITE_OMIT_TRIGGER
  106144. fkTriggerDelete(db, pFKey->apTrigger[0]);
  106145. fkTriggerDelete(db, pFKey->apTrigger[1]);
  106146. #endif
  106147. pNext = pFKey->pNextFrom;
  106148. sqlite3DbFree(db, pFKey);
  106149. }
  106150. }
  106151. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  106152. /************** End of fkey.c ************************************************/
  106153. /************** Begin file insert.c ******************************************/
  106154. /*
  106155. ** 2001 September 15
  106156. **
  106157. ** The author disclaims copyright to this source code. In place of
  106158. ** a legal notice, here is a blessing:
  106159. **
  106160. ** May you do good and not evil.
  106161. ** May you find forgiveness for yourself and forgive others.
  106162. ** May you share freely, never taking more than you give.
  106163. **
  106164. *************************************************************************
  106165. ** This file contains C code routines that are called by the parser
  106166. ** to handle INSERT statements in SQLite.
  106167. */
  106168. /* #include "sqliteInt.h" */
  106169. /*
  106170. ** Generate code that will
  106171. **
  106172. ** (1) acquire a lock for table pTab then
  106173. ** (2) open pTab as cursor iCur.
  106174. **
  106175. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  106176. ** for that table that is actually opened.
  106177. */
  106178. SQLITE_PRIVATE void sqlite3OpenTable(
  106179. Parse *pParse, /* Generate code into this VDBE */
  106180. int iCur, /* The cursor number of the table */
  106181. int iDb, /* The database index in sqlite3.aDb[] */
  106182. Table *pTab, /* The table to be opened */
  106183. int opcode /* OP_OpenRead or OP_OpenWrite */
  106184. ){
  106185. Vdbe *v;
  106186. assert( !IsVirtual(pTab) );
  106187. v = sqlite3GetVdbe(pParse);
  106188. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  106189. sqlite3TableLock(pParse, iDb, pTab->tnum,
  106190. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  106191. if( HasRowid(pTab) ){
  106192. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  106193. VdbeComment((v, "%s", pTab->zName));
  106194. }else{
  106195. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  106196. assert( pPk!=0 );
  106197. assert( pPk->tnum==pTab->tnum );
  106198. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  106199. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  106200. VdbeComment((v, "%s", pTab->zName));
  106201. }
  106202. }
  106203. /*
  106204. ** Return a pointer to the column affinity string associated with index
  106205. ** pIdx. A column affinity string has one character for each column in
  106206. ** the table, according to the affinity of the column:
  106207. **
  106208. ** Character Column affinity
  106209. ** ------------------------------
  106210. ** 'A' BLOB
  106211. ** 'B' TEXT
  106212. ** 'C' NUMERIC
  106213. ** 'D' INTEGER
  106214. ** 'F' REAL
  106215. **
  106216. ** An extra 'D' is appended to the end of the string to cover the
  106217. ** rowid that appears as the last column in every index.
  106218. **
  106219. ** Memory for the buffer containing the column index affinity string
  106220. ** is managed along with the rest of the Index structure. It will be
  106221. ** released when sqlite3DeleteIndex() is called.
  106222. */
  106223. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  106224. if( !pIdx->zColAff ){
  106225. /* The first time a column affinity string for a particular index is
  106226. ** required, it is allocated and populated here. It is then stored as
  106227. ** a member of the Index structure for subsequent use.
  106228. **
  106229. ** The column affinity string will eventually be deleted by
  106230. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  106231. ** up.
  106232. */
  106233. int n;
  106234. Table *pTab = pIdx->pTable;
  106235. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  106236. if( !pIdx->zColAff ){
  106237. sqlite3OomFault(db);
  106238. return 0;
  106239. }
  106240. for(n=0; n<pIdx->nColumn; n++){
  106241. i16 x = pIdx->aiColumn[n];
  106242. if( x>=0 ){
  106243. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  106244. }else if( x==XN_ROWID ){
  106245. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  106246. }else{
  106247. char aff;
  106248. assert( x==XN_EXPR );
  106249. assert( pIdx->aColExpr!=0 );
  106250. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  106251. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  106252. pIdx->zColAff[n] = aff;
  106253. }
  106254. }
  106255. pIdx->zColAff[n] = 0;
  106256. }
  106257. return pIdx->zColAff;
  106258. }
  106259. /*
  106260. ** Compute the affinity string for table pTab, if it has not already been
  106261. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  106262. **
  106263. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  106264. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  106265. ** for register iReg and following. Or if affinities exists and iReg==0,
  106266. ** then just set the P4 operand of the previous opcode (which should be
  106267. ** an OP_MakeRecord) to the affinity string.
  106268. **
  106269. ** A column affinity string has one character per column:
  106270. **
  106271. ** Character Column affinity
  106272. ** ------------------------------
  106273. ** 'A' BLOB
  106274. ** 'B' TEXT
  106275. ** 'C' NUMERIC
  106276. ** 'D' INTEGER
  106277. ** 'E' REAL
  106278. */
  106279. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  106280. int i;
  106281. char *zColAff = pTab->zColAff;
  106282. if( zColAff==0 ){
  106283. sqlite3 *db = sqlite3VdbeDb(v);
  106284. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  106285. if( !zColAff ){
  106286. sqlite3OomFault(db);
  106287. return;
  106288. }
  106289. for(i=0; i<pTab->nCol; i++){
  106290. zColAff[i] = pTab->aCol[i].affinity;
  106291. }
  106292. do{
  106293. zColAff[i--] = 0;
  106294. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  106295. pTab->zColAff = zColAff;
  106296. }
  106297. i = sqlite3Strlen30(zColAff);
  106298. if( i ){
  106299. if( iReg ){
  106300. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  106301. }else{
  106302. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  106303. }
  106304. }
  106305. }
  106306. /*
  106307. ** Return non-zero if the table pTab in database iDb or any of its indices
  106308. ** have been opened at any point in the VDBE program. This is used to see if
  106309. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  106310. ** run without using a temporary table for the results of the SELECT.
  106311. */
  106312. static int readsTable(Parse *p, int iDb, Table *pTab){
  106313. Vdbe *v = sqlite3GetVdbe(p);
  106314. int i;
  106315. int iEnd = sqlite3VdbeCurrentAddr(v);
  106316. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106317. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  106318. #endif
  106319. for(i=1; i<iEnd; i++){
  106320. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  106321. assert( pOp!=0 );
  106322. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  106323. Index *pIndex;
  106324. int tnum = pOp->p2;
  106325. if( tnum==pTab->tnum ){
  106326. return 1;
  106327. }
  106328. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  106329. if( tnum==pIndex->tnum ){
  106330. return 1;
  106331. }
  106332. }
  106333. }
  106334. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106335. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  106336. assert( pOp->p4.pVtab!=0 );
  106337. assert( pOp->p4type==P4_VTAB );
  106338. return 1;
  106339. }
  106340. #endif
  106341. }
  106342. return 0;
  106343. }
  106344. #ifndef SQLITE_OMIT_AUTOINCREMENT
  106345. /*
  106346. ** Locate or create an AutoincInfo structure associated with table pTab
  106347. ** which is in database iDb. Return the register number for the register
  106348. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  106349. ** table. (Also return zero when doing a VACUUM since we do not want to
  106350. ** update the AUTOINCREMENT counters during a VACUUM.)
  106351. **
  106352. ** There is at most one AutoincInfo structure per table even if the
  106353. ** same table is autoincremented multiple times due to inserts within
  106354. ** triggers. A new AutoincInfo structure is created if this is the
  106355. ** first use of table pTab. On 2nd and subsequent uses, the original
  106356. ** AutoincInfo structure is used.
  106357. **
  106358. ** Four consecutive registers are allocated:
  106359. **
  106360. ** (1) The name of the pTab table.
  106361. ** (2) The maximum ROWID of pTab.
  106362. ** (3) The rowid in sqlite_sequence of pTab
  106363. ** (4) The original value of the max ROWID in pTab, or NULL if none
  106364. **
  106365. ** The 2nd register is the one that is returned. That is all the
  106366. ** insert routine needs to know about.
  106367. */
  106368. static int autoIncBegin(
  106369. Parse *pParse, /* Parsing context */
  106370. int iDb, /* Index of the database holding pTab */
  106371. Table *pTab /* The table we are writing to */
  106372. ){
  106373. int memId = 0; /* Register holding maximum rowid */
  106374. assert( pParse->db->aDb[iDb].pSchema!=0 );
  106375. if( (pTab->tabFlags & TF_Autoincrement)!=0
  106376. && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
  106377. ){
  106378. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  106379. AutoincInfo *pInfo;
  106380. Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
  106381. /* Verify that the sqlite_sequence table exists and is an ordinary
  106382. ** rowid table with exactly two columns.
  106383. ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
  106384. if( pSeqTab==0
  106385. || !HasRowid(pSeqTab)
  106386. || IsVirtual(pSeqTab)
  106387. || pSeqTab->nCol!=2
  106388. ){
  106389. pParse->nErr++;
  106390. pParse->rc = SQLITE_CORRUPT_SEQUENCE;
  106391. return 0;
  106392. }
  106393. pInfo = pToplevel->pAinc;
  106394. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  106395. if( pInfo==0 ){
  106396. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  106397. if( pInfo==0 ) return 0;
  106398. pInfo->pNext = pToplevel->pAinc;
  106399. pToplevel->pAinc = pInfo;
  106400. pInfo->pTab = pTab;
  106401. pInfo->iDb = iDb;
  106402. pToplevel->nMem++; /* Register to hold name of table */
  106403. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  106404. pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
  106405. }
  106406. memId = pInfo->regCtr;
  106407. }
  106408. return memId;
  106409. }
  106410. /*
  106411. ** This routine generates code that will initialize all of the
  106412. ** register used by the autoincrement tracker.
  106413. */
  106414. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  106415. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  106416. sqlite3 *db = pParse->db; /* The database connection */
  106417. Db *pDb; /* Database only autoinc table */
  106418. int memId; /* Register holding max rowid */
  106419. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  106420. /* This routine is never called during trigger-generation. It is
  106421. ** only called from the top-level */
  106422. assert( pParse->pTriggerTab==0 );
  106423. assert( sqlite3IsToplevel(pParse) );
  106424. assert( v ); /* We failed long ago if this is not so */
  106425. for(p = pParse->pAinc; p; p = p->pNext){
  106426. static const int iLn = VDBE_OFFSET_LINENO(2);
  106427. static const VdbeOpList autoInc[] = {
  106428. /* 0 */ {OP_Null, 0, 0, 0},
  106429. /* 1 */ {OP_Rewind, 0, 10, 0},
  106430. /* 2 */ {OP_Column, 0, 0, 0},
  106431. /* 3 */ {OP_Ne, 0, 9, 0},
  106432. /* 4 */ {OP_Rowid, 0, 0, 0},
  106433. /* 5 */ {OP_Column, 0, 1, 0},
  106434. /* 6 */ {OP_AddImm, 0, 0, 0},
  106435. /* 7 */ {OP_Copy, 0, 0, 0},
  106436. /* 8 */ {OP_Goto, 0, 11, 0},
  106437. /* 9 */ {OP_Next, 0, 2, 0},
  106438. /* 10 */ {OP_Integer, 0, 0, 0},
  106439. /* 11 */ {OP_Close, 0, 0, 0}
  106440. };
  106441. VdbeOp *aOp;
  106442. pDb = &db->aDb[p->iDb];
  106443. memId = p->regCtr;
  106444. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  106445. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  106446. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  106447. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  106448. if( aOp==0 ) break;
  106449. aOp[0].p2 = memId;
  106450. aOp[0].p3 = memId+2;
  106451. aOp[2].p3 = memId;
  106452. aOp[3].p1 = memId-1;
  106453. aOp[3].p3 = memId;
  106454. aOp[3].p5 = SQLITE_JUMPIFNULL;
  106455. aOp[4].p2 = memId+1;
  106456. aOp[5].p3 = memId;
  106457. aOp[6].p1 = memId;
  106458. aOp[7].p2 = memId+2;
  106459. aOp[7].p1 = memId;
  106460. aOp[10].p2 = memId;
  106461. }
  106462. }
  106463. /*
  106464. ** Update the maximum rowid for an autoincrement calculation.
  106465. **
  106466. ** This routine should be called when the regRowid register holds a
  106467. ** new rowid that is about to be inserted. If that new rowid is
  106468. ** larger than the maximum rowid in the memId memory cell, then the
  106469. ** memory cell is updated.
  106470. */
  106471. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  106472. if( memId>0 ){
  106473. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  106474. }
  106475. }
  106476. /*
  106477. ** This routine generates the code needed to write autoincrement
  106478. ** maximum rowid values back into the sqlite_sequence register.
  106479. ** Every statement that might do an INSERT into an autoincrement
  106480. ** table (either directly or through triggers) needs to call this
  106481. ** routine just before the "exit" code.
  106482. */
  106483. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  106484. AutoincInfo *p;
  106485. Vdbe *v = pParse->pVdbe;
  106486. sqlite3 *db = pParse->db;
  106487. assert( v );
  106488. for(p = pParse->pAinc; p; p = p->pNext){
  106489. static const int iLn = VDBE_OFFSET_LINENO(2);
  106490. static const VdbeOpList autoIncEnd[] = {
  106491. /* 0 */ {OP_NotNull, 0, 2, 0},
  106492. /* 1 */ {OP_NewRowid, 0, 0, 0},
  106493. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  106494. /* 3 */ {OP_Insert, 0, 0, 0},
  106495. /* 4 */ {OP_Close, 0, 0, 0}
  106496. };
  106497. VdbeOp *aOp;
  106498. Db *pDb = &db->aDb[p->iDb];
  106499. int iRec;
  106500. int memId = p->regCtr;
  106501. iRec = sqlite3GetTempReg(pParse);
  106502. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  106503. sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
  106504. VdbeCoverage(v);
  106505. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  106506. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  106507. if( aOp==0 ) break;
  106508. aOp[0].p1 = memId+1;
  106509. aOp[1].p2 = memId+1;
  106510. aOp[2].p1 = memId-1;
  106511. aOp[2].p3 = iRec;
  106512. aOp[3].p2 = iRec;
  106513. aOp[3].p3 = memId+1;
  106514. aOp[3].p5 = OPFLAG_APPEND;
  106515. sqlite3ReleaseTempReg(pParse, iRec);
  106516. }
  106517. }
  106518. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  106519. if( pParse->pAinc ) autoIncrementEnd(pParse);
  106520. }
  106521. #else
  106522. /*
  106523. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  106524. ** above are all no-ops
  106525. */
  106526. # define autoIncBegin(A,B,C) (0)
  106527. # define autoIncStep(A,B,C)
  106528. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  106529. /* Forward declaration */
  106530. static int xferOptimization(
  106531. Parse *pParse, /* Parser context */
  106532. Table *pDest, /* The table we are inserting into */
  106533. Select *pSelect, /* A SELECT statement to use as the data source */
  106534. int onError, /* How to handle constraint errors */
  106535. int iDbDest /* The database of pDest */
  106536. );
  106537. /*
  106538. ** This routine is called to handle SQL of the following forms:
  106539. **
  106540. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  106541. ** insert into TABLE (IDLIST) select
  106542. ** insert into TABLE (IDLIST) default values
  106543. **
  106544. ** The IDLIST following the table name is always optional. If omitted,
  106545. ** then a list of all (non-hidden) columns for the table is substituted.
  106546. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  106547. ** is omitted.
  106548. **
  106549. ** For the pSelect parameter holds the values to be inserted for the
  106550. ** first two forms shown above. A VALUES clause is really just short-hand
  106551. ** for a SELECT statement that omits the FROM clause and everything else
  106552. ** that follows. If the pSelect parameter is NULL, that means that the
  106553. ** DEFAULT VALUES form of the INSERT statement is intended.
  106554. **
  106555. ** The code generated follows one of four templates. For a simple
  106556. ** insert with data coming from a single-row VALUES clause, the code executes
  106557. ** once straight down through. Pseudo-code follows (we call this
  106558. ** the "1st template"):
  106559. **
  106560. ** open write cursor to <table> and its indices
  106561. ** put VALUES clause expressions into registers
  106562. ** write the resulting record into <table>
  106563. ** cleanup
  106564. **
  106565. ** The three remaining templates assume the statement is of the form
  106566. **
  106567. ** INSERT INTO <table> SELECT ...
  106568. **
  106569. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  106570. ** in other words if the SELECT pulls all columns from a single table
  106571. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  106572. ** if <table2> and <table1> are distinct tables but have identical
  106573. ** schemas, including all the same indices, then a special optimization
  106574. ** is invoked that copies raw records from <table2> over to <table1>.
  106575. ** See the xferOptimization() function for the implementation of this
  106576. ** template. This is the 2nd template.
  106577. **
  106578. ** open a write cursor to <table>
  106579. ** open read cursor on <table2>
  106580. ** transfer all records in <table2> over to <table>
  106581. ** close cursors
  106582. ** foreach index on <table>
  106583. ** open a write cursor on the <table> index
  106584. ** open a read cursor on the corresponding <table2> index
  106585. ** transfer all records from the read to the write cursors
  106586. ** close cursors
  106587. ** end foreach
  106588. **
  106589. ** The 3rd template is for when the second template does not apply
  106590. ** and the SELECT clause does not read from <table> at any time.
  106591. ** The generated code follows this template:
  106592. **
  106593. ** X <- A
  106594. ** goto B
  106595. ** A: setup for the SELECT
  106596. ** loop over the rows in the SELECT
  106597. ** load values into registers R..R+n
  106598. ** yield X
  106599. ** end loop
  106600. ** cleanup after the SELECT
  106601. ** end-coroutine X
  106602. ** B: open write cursor to <table> and its indices
  106603. ** C: yield X, at EOF goto D
  106604. ** insert the select result into <table> from R..R+n
  106605. ** goto C
  106606. ** D: cleanup
  106607. **
  106608. ** The 4th template is used if the insert statement takes its
  106609. ** values from a SELECT but the data is being inserted into a table
  106610. ** that is also read as part of the SELECT. In the third form,
  106611. ** we have to use an intermediate table to store the results of
  106612. ** the select. The template is like this:
  106613. **
  106614. ** X <- A
  106615. ** goto B
  106616. ** A: setup for the SELECT
  106617. ** loop over the tables in the SELECT
  106618. ** load value into register R..R+n
  106619. ** yield X
  106620. ** end loop
  106621. ** cleanup after the SELECT
  106622. ** end co-routine R
  106623. ** B: open temp table
  106624. ** L: yield X, at EOF goto M
  106625. ** insert row from R..R+n into temp table
  106626. ** goto L
  106627. ** M: open write cursor to <table> and its indices
  106628. ** rewind temp table
  106629. ** C: loop over rows of intermediate table
  106630. ** transfer values form intermediate table into <table>
  106631. ** end loop
  106632. ** D: cleanup
  106633. */
  106634. SQLITE_PRIVATE void sqlite3Insert(
  106635. Parse *pParse, /* Parser context */
  106636. SrcList *pTabList, /* Name of table into which we are inserting */
  106637. Select *pSelect, /* A SELECT statement to use as the data source */
  106638. IdList *pColumn, /* Column names corresponding to IDLIST. */
  106639. int onError, /* How to handle constraint errors */
  106640. Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
  106641. ){
  106642. sqlite3 *db; /* The main database structure */
  106643. Table *pTab; /* The table to insert into. aka TABLE */
  106644. int i, j; /* Loop counters */
  106645. Vdbe *v; /* Generate code into this virtual machine */
  106646. Index *pIdx; /* For looping over indices of the table */
  106647. int nColumn; /* Number of columns in the data */
  106648. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  106649. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  106650. int iIdxCur = 0; /* First index cursor */
  106651. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  106652. int endOfLoop; /* Label for the end of the insertion loop */
  106653. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  106654. int addrInsTop = 0; /* Jump to label "D" */
  106655. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  106656. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  106657. int iDb; /* Index of database holding TABLE */
  106658. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  106659. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  106660. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  106661. u8 bIdListInOrder; /* True if IDLIST is in table order */
  106662. ExprList *pList = 0; /* List of VALUES() to be inserted */
  106663. /* Register allocations */
  106664. int regFromSelect = 0;/* Base register for data coming from SELECT */
  106665. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  106666. int regRowCount = 0; /* Memory cell used for the row counter */
  106667. int regIns; /* Block of regs holding rowid+data being inserted */
  106668. int regRowid; /* registers holding insert rowid */
  106669. int regData; /* register holding first column to insert */
  106670. int *aRegIdx = 0; /* One register allocated to each index */
  106671. #ifndef SQLITE_OMIT_TRIGGER
  106672. int isView; /* True if attempting to insert into a view */
  106673. Trigger *pTrigger; /* List of triggers on pTab, if required */
  106674. int tmask; /* Mask of trigger times */
  106675. #endif
  106676. db = pParse->db;
  106677. if( pParse->nErr || db->mallocFailed ){
  106678. goto insert_cleanup;
  106679. }
  106680. dest.iSDParm = 0; /* Suppress a harmless compiler warning */
  106681. /* If the Select object is really just a simple VALUES() list with a
  106682. ** single row (the common case) then keep that one row of values
  106683. ** and discard the other (unused) parts of the pSelect object
  106684. */
  106685. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  106686. pList = pSelect->pEList;
  106687. pSelect->pEList = 0;
  106688. sqlite3SelectDelete(db, pSelect);
  106689. pSelect = 0;
  106690. }
  106691. /* Locate the table into which we will be inserting new information.
  106692. */
  106693. assert( pTabList->nSrc==1 );
  106694. pTab = sqlite3SrcListLookup(pParse, pTabList);
  106695. if( pTab==0 ){
  106696. goto insert_cleanup;
  106697. }
  106698. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  106699. assert( iDb<db->nDb );
  106700. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  106701. db->aDb[iDb].zDbSName) ){
  106702. goto insert_cleanup;
  106703. }
  106704. withoutRowid = !HasRowid(pTab);
  106705. /* Figure out if we have any triggers and if the table being
  106706. ** inserted into is a view
  106707. */
  106708. #ifndef SQLITE_OMIT_TRIGGER
  106709. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  106710. isView = pTab->pSelect!=0;
  106711. #else
  106712. # define pTrigger 0
  106713. # define tmask 0
  106714. # define isView 0
  106715. #endif
  106716. #ifdef SQLITE_OMIT_VIEW
  106717. # undef isView
  106718. # define isView 0
  106719. #endif
  106720. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  106721. /* If pTab is really a view, make sure it has been initialized.
  106722. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  106723. */
  106724. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  106725. goto insert_cleanup;
  106726. }
  106727. /* Cannot insert into a read-only table.
  106728. */
  106729. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  106730. goto insert_cleanup;
  106731. }
  106732. /* Allocate a VDBE
  106733. */
  106734. v = sqlite3GetVdbe(pParse);
  106735. if( v==0 ) goto insert_cleanup;
  106736. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  106737. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  106738. #ifndef SQLITE_OMIT_XFER_OPT
  106739. /* If the statement is of the form
  106740. **
  106741. ** INSERT INTO <table1> SELECT * FROM <table2>;
  106742. **
  106743. ** Then special optimizations can be applied that make the transfer
  106744. ** very fast and which reduce fragmentation of indices.
  106745. **
  106746. ** This is the 2nd template.
  106747. */
  106748. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  106749. assert( !pTrigger );
  106750. assert( pList==0 );
  106751. goto insert_end;
  106752. }
  106753. #endif /* SQLITE_OMIT_XFER_OPT */
  106754. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  106755. ** sqlite_sequence table and store it in memory cell regAutoinc.
  106756. */
  106757. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  106758. /* Allocate registers for holding the rowid of the new row,
  106759. ** the content of the new row, and the assembled row record.
  106760. */
  106761. regRowid = regIns = pParse->nMem+1;
  106762. pParse->nMem += pTab->nCol + 1;
  106763. if( IsVirtual(pTab) ){
  106764. regRowid++;
  106765. pParse->nMem++;
  106766. }
  106767. regData = regRowid+1;
  106768. /* If the INSERT statement included an IDLIST term, then make sure
  106769. ** all elements of the IDLIST really are columns of the table and
  106770. ** remember the column indices.
  106771. **
  106772. ** If the table has an INTEGER PRIMARY KEY column and that column
  106773. ** is named in the IDLIST, then record in the ipkColumn variable
  106774. ** the index into IDLIST of the primary key column. ipkColumn is
  106775. ** the index of the primary key as it appears in IDLIST, not as
  106776. ** is appears in the original table. (The index of the INTEGER
  106777. ** PRIMARY KEY in the original table is pTab->iPKey.)
  106778. */
  106779. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  106780. if( pColumn ){
  106781. for(i=0; i<pColumn->nId; i++){
  106782. pColumn->a[i].idx = -1;
  106783. }
  106784. for(i=0; i<pColumn->nId; i++){
  106785. for(j=0; j<pTab->nCol; j++){
  106786. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  106787. pColumn->a[i].idx = j;
  106788. if( i!=j ) bIdListInOrder = 0;
  106789. if( j==pTab->iPKey ){
  106790. ipkColumn = i; assert( !withoutRowid );
  106791. }
  106792. break;
  106793. }
  106794. }
  106795. if( j>=pTab->nCol ){
  106796. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  106797. ipkColumn = i;
  106798. bIdListInOrder = 0;
  106799. }else{
  106800. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  106801. pTabList, 0, pColumn->a[i].zName);
  106802. pParse->checkSchema = 1;
  106803. goto insert_cleanup;
  106804. }
  106805. }
  106806. }
  106807. }
  106808. /* Figure out how many columns of data are supplied. If the data
  106809. ** is coming from a SELECT statement, then generate a co-routine that
  106810. ** produces a single row of the SELECT on each invocation. The
  106811. ** co-routine is the common header to the 3rd and 4th templates.
  106812. */
  106813. if( pSelect ){
  106814. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  106815. ** Generate a co-routine to run the SELECT. */
  106816. int regYield; /* Register holding co-routine entry-point */
  106817. int addrTop; /* Top of the co-routine */
  106818. int rc; /* Result code */
  106819. regYield = ++pParse->nMem;
  106820. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  106821. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  106822. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  106823. dest.iSdst = bIdListInOrder ? regData : 0;
  106824. dest.nSdst = pTab->nCol;
  106825. rc = sqlite3Select(pParse, pSelect, &dest);
  106826. regFromSelect = dest.iSdst;
  106827. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  106828. sqlite3VdbeEndCoroutine(v, regYield);
  106829. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  106830. assert( pSelect->pEList );
  106831. nColumn = pSelect->pEList->nExpr;
  106832. /* Set useTempTable to TRUE if the result of the SELECT statement
  106833. ** should be written into a temporary table (template 4). Set to
  106834. ** FALSE if each output row of the SELECT can be written directly into
  106835. ** the destination table (template 3).
  106836. **
  106837. ** A temp table must be used if the table being updated is also one
  106838. ** of the tables being read by the SELECT statement. Also use a
  106839. ** temp table in the case of row triggers.
  106840. */
  106841. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  106842. useTempTable = 1;
  106843. }
  106844. if( useTempTable ){
  106845. /* Invoke the coroutine to extract information from the SELECT
  106846. ** and add it to a transient table srcTab. The code generated
  106847. ** here is from the 4th template:
  106848. **
  106849. ** B: open temp table
  106850. ** L: yield X, goto M at EOF
  106851. ** insert row from R..R+n into temp table
  106852. ** goto L
  106853. ** M: ...
  106854. */
  106855. int regRec; /* Register to hold packed record */
  106856. int regTempRowid; /* Register to hold temp table ROWID */
  106857. int addrL; /* Label "L" */
  106858. srcTab = pParse->nTab++;
  106859. regRec = sqlite3GetTempReg(pParse);
  106860. regTempRowid = sqlite3GetTempReg(pParse);
  106861. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  106862. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  106863. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  106864. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  106865. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  106866. sqlite3VdbeGoto(v, addrL);
  106867. sqlite3VdbeJumpHere(v, addrL);
  106868. sqlite3ReleaseTempReg(pParse, regRec);
  106869. sqlite3ReleaseTempReg(pParse, regTempRowid);
  106870. }
  106871. }else{
  106872. /* This is the case if the data for the INSERT is coming from a
  106873. ** single-row VALUES clause
  106874. */
  106875. NameContext sNC;
  106876. memset(&sNC, 0, sizeof(sNC));
  106877. sNC.pParse = pParse;
  106878. srcTab = -1;
  106879. assert( useTempTable==0 );
  106880. if( pList ){
  106881. nColumn = pList->nExpr;
  106882. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  106883. goto insert_cleanup;
  106884. }
  106885. }else{
  106886. nColumn = 0;
  106887. }
  106888. }
  106889. /* If there is no IDLIST term but the table has an integer primary
  106890. ** key, the set the ipkColumn variable to the integer primary key
  106891. ** column index in the original table definition.
  106892. */
  106893. if( pColumn==0 && nColumn>0 ){
  106894. ipkColumn = pTab->iPKey;
  106895. }
  106896. /* Make sure the number of columns in the source data matches the number
  106897. ** of columns to be inserted into the table.
  106898. */
  106899. for(i=0; i<pTab->nCol; i++){
  106900. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  106901. }
  106902. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  106903. sqlite3ErrorMsg(pParse,
  106904. "table %S has %d columns but %d values were supplied",
  106905. pTabList, 0, pTab->nCol-nHidden, nColumn);
  106906. goto insert_cleanup;
  106907. }
  106908. if( pColumn!=0 && nColumn!=pColumn->nId ){
  106909. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  106910. goto insert_cleanup;
  106911. }
  106912. /* Initialize the count of rows to be inserted
  106913. */
  106914. if( (db->flags & SQLITE_CountRows)!=0
  106915. && !pParse->nested
  106916. && !pParse->pTriggerTab
  106917. ){
  106918. regRowCount = ++pParse->nMem;
  106919. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  106920. }
  106921. /* If this is not a view, open the table and and all indices */
  106922. if( !isView ){
  106923. int nIdx;
  106924. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  106925. &iDataCur, &iIdxCur);
  106926. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  106927. if( aRegIdx==0 ){
  106928. goto insert_cleanup;
  106929. }
  106930. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  106931. assert( pIdx );
  106932. aRegIdx[i] = ++pParse->nMem;
  106933. pParse->nMem += pIdx->nColumn;
  106934. }
  106935. }
  106936. #ifndef SQLITE_OMIT_UPSERT
  106937. if( pUpsert ){
  106938. pTabList->a[0].iCursor = iDataCur;
  106939. pUpsert->pUpsertSrc = pTabList;
  106940. pUpsert->regData = regData;
  106941. pUpsert->iDataCur = iDataCur;
  106942. pUpsert->iIdxCur = iIdxCur;
  106943. if( pUpsert->pUpsertTarget ){
  106944. sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
  106945. }
  106946. }
  106947. #endif
  106948. /* This is the top of the main insertion loop */
  106949. if( useTempTable ){
  106950. /* This block codes the top of loop only. The complete loop is the
  106951. ** following pseudocode (template 4):
  106952. **
  106953. ** rewind temp table, if empty goto D
  106954. ** C: loop over rows of intermediate table
  106955. ** transfer values form intermediate table into <table>
  106956. ** end loop
  106957. ** D: ...
  106958. */
  106959. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  106960. addrCont = sqlite3VdbeCurrentAddr(v);
  106961. }else if( pSelect ){
  106962. /* This block codes the top of loop only. The complete loop is the
  106963. ** following pseudocode (template 3):
  106964. **
  106965. ** C: yield X, at EOF goto D
  106966. ** insert the select result into <table> from R..R+n
  106967. ** goto C
  106968. ** D: ...
  106969. */
  106970. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  106971. VdbeCoverage(v);
  106972. }
  106973. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  106974. */
  106975. endOfLoop = sqlite3VdbeMakeLabel(v);
  106976. if( tmask & TRIGGER_BEFORE ){
  106977. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  106978. /* build the NEW.* reference row. Note that if there is an INTEGER
  106979. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  106980. ** translated into a unique ID for the row. But on a BEFORE trigger,
  106981. ** we do not know what the unique ID will be (because the insert has
  106982. ** not happened yet) so we substitute a rowid of -1
  106983. */
  106984. if( ipkColumn<0 ){
  106985. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  106986. }else{
  106987. int addr1;
  106988. assert( !withoutRowid );
  106989. if( useTempTable ){
  106990. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  106991. }else{
  106992. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  106993. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  106994. }
  106995. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  106996. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  106997. sqlite3VdbeJumpHere(v, addr1);
  106998. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  106999. }
  107000. /* Cannot have triggers on a virtual table. If it were possible,
  107001. ** this block would have to account for hidden column.
  107002. */
  107003. assert( !IsVirtual(pTab) );
  107004. /* Create the new column data
  107005. */
  107006. for(i=j=0; i<pTab->nCol; i++){
  107007. if( pColumn ){
  107008. for(j=0; j<pColumn->nId; j++){
  107009. if( pColumn->a[j].idx==i ) break;
  107010. }
  107011. }
  107012. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  107013. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  107014. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  107015. }else if( useTempTable ){
  107016. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  107017. }else{
  107018. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  107019. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  107020. }
  107021. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  107022. }
  107023. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  107024. ** do not attempt any conversions before assembling the record.
  107025. ** If this is a real table, attempt conversions as required by the
  107026. ** table column affinities.
  107027. */
  107028. if( !isView ){
  107029. sqlite3TableAffinity(v, pTab, regCols+1);
  107030. }
  107031. /* Fire BEFORE or INSTEAD OF triggers */
  107032. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  107033. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  107034. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  107035. }
  107036. /* Compute the content of the next row to insert into a range of
  107037. ** registers beginning at regIns.
  107038. */
  107039. if( !isView ){
  107040. if( IsVirtual(pTab) ){
  107041. /* The row that the VUpdate opcode will delete: none */
  107042. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  107043. }
  107044. if( ipkColumn>=0 ){
  107045. if( useTempTable ){
  107046. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  107047. }else if( pSelect ){
  107048. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  107049. }else{
  107050. VdbeOp *pOp;
  107051. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  107052. pOp = sqlite3VdbeGetOp(v, -1);
  107053. assert( pOp!=0 );
  107054. if( pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  107055. appendFlag = 1;
  107056. pOp->opcode = OP_NewRowid;
  107057. pOp->p1 = iDataCur;
  107058. pOp->p2 = regRowid;
  107059. pOp->p3 = regAutoinc;
  107060. }
  107061. }
  107062. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  107063. ** to generate a unique primary key value.
  107064. */
  107065. if( !appendFlag ){
  107066. int addr1;
  107067. if( !IsVirtual(pTab) ){
  107068. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  107069. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  107070. sqlite3VdbeJumpHere(v, addr1);
  107071. }else{
  107072. addr1 = sqlite3VdbeCurrentAddr(v);
  107073. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  107074. }
  107075. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  107076. }
  107077. }else if( IsVirtual(pTab) || withoutRowid ){
  107078. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  107079. }else{
  107080. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  107081. appendFlag = 1;
  107082. }
  107083. autoIncStep(pParse, regAutoinc, regRowid);
  107084. /* Compute data for all columns of the new entry, beginning
  107085. ** with the first column.
  107086. */
  107087. nHidden = 0;
  107088. for(i=0; i<pTab->nCol; i++){
  107089. int iRegStore = regRowid+1+i;
  107090. if( i==pTab->iPKey ){
  107091. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  107092. ** Whenever this column is read, the rowid will be substituted
  107093. ** in its place. Hence, fill this column with a NULL to avoid
  107094. ** taking up data space with information that will never be used.
  107095. ** As there may be shallow copies of this value, make it a soft-NULL */
  107096. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  107097. continue;
  107098. }
  107099. if( pColumn==0 ){
  107100. if( IsHiddenColumn(&pTab->aCol[i]) ){
  107101. j = -1;
  107102. nHidden++;
  107103. }else{
  107104. j = i - nHidden;
  107105. }
  107106. }else{
  107107. for(j=0; j<pColumn->nId; j++){
  107108. if( pColumn->a[j].idx==i ) break;
  107109. }
  107110. }
  107111. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  107112. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  107113. }else if( useTempTable ){
  107114. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  107115. }else if( pSelect ){
  107116. if( regFromSelect!=regData ){
  107117. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  107118. }
  107119. }else{
  107120. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  107121. }
  107122. }
  107123. /* Generate code to check constraints and generate index keys and
  107124. ** do the insertion.
  107125. */
  107126. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107127. if( IsVirtual(pTab) ){
  107128. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  107129. sqlite3VtabMakeWritable(pParse, pTab);
  107130. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  107131. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  107132. sqlite3MayAbort(pParse);
  107133. }else
  107134. #endif
  107135. {
  107136. int isReplace; /* Set to true if constraints may cause a replace */
  107137. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  107138. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  107139. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
  107140. );
  107141. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  107142. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  107143. ** constraints or (b) there are no triggers and this table is not a
  107144. ** parent table in a foreign key constraint. It is safe to set the
  107145. ** flag in the second case as if any REPLACE constraint is hit, an
  107146. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  107147. ** cursor that is disturbed. And these instructions both clear the
  107148. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  107149. ** functionality. */
  107150. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  107151. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  107152. ));
  107153. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  107154. regIns, aRegIdx, 0, appendFlag, bUseSeek
  107155. );
  107156. }
  107157. }
  107158. /* Update the count of rows that are inserted
  107159. */
  107160. if( regRowCount ){
  107161. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  107162. }
  107163. if( pTrigger ){
  107164. /* Code AFTER triggers */
  107165. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  107166. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  107167. }
  107168. /* The bottom of the main insertion loop, if the data source
  107169. ** is a SELECT statement.
  107170. */
  107171. sqlite3VdbeResolveLabel(v, endOfLoop);
  107172. if( useTempTable ){
  107173. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  107174. sqlite3VdbeJumpHere(v, addrInsTop);
  107175. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  107176. }else if( pSelect ){
  107177. sqlite3VdbeGoto(v, addrCont);
  107178. sqlite3VdbeJumpHere(v, addrInsTop);
  107179. }
  107180. insert_end:
  107181. /* Update the sqlite_sequence table by storing the content of the
  107182. ** maximum rowid counter values recorded while inserting into
  107183. ** autoincrement tables.
  107184. */
  107185. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  107186. sqlite3AutoincrementEnd(pParse);
  107187. }
  107188. /*
  107189. ** Return the number of rows inserted. If this routine is
  107190. ** generating code because of a call to sqlite3NestedParse(), do not
  107191. ** invoke the callback function.
  107192. */
  107193. if( regRowCount ){
  107194. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  107195. sqlite3VdbeSetNumCols(v, 1);
  107196. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  107197. }
  107198. insert_cleanup:
  107199. sqlite3SrcListDelete(db, pTabList);
  107200. sqlite3ExprListDelete(db, pList);
  107201. sqlite3UpsertDelete(db, pUpsert);
  107202. sqlite3SelectDelete(db, pSelect);
  107203. sqlite3IdListDelete(db, pColumn);
  107204. sqlite3DbFree(db, aRegIdx);
  107205. }
  107206. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  107207. ** they may interfere with compilation of other functions in this file
  107208. ** (or in another file, if this file becomes part of the amalgamation). */
  107209. #ifdef isView
  107210. #undef isView
  107211. #endif
  107212. #ifdef pTrigger
  107213. #undef pTrigger
  107214. #endif
  107215. #ifdef tmask
  107216. #undef tmask
  107217. #endif
  107218. /*
  107219. ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
  107220. */
  107221. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  107222. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  107223. /* This is the Walker callback from checkConstraintUnchanged(). Set
  107224. ** bit 0x01 of pWalker->eCode if
  107225. ** pWalker->eCode to 0 if this expression node references any of the
  107226. ** columns that are being modifed by an UPDATE statement.
  107227. */
  107228. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  107229. if( pExpr->op==TK_COLUMN ){
  107230. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  107231. if( pExpr->iColumn>=0 ){
  107232. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  107233. pWalker->eCode |= CKCNSTRNT_COLUMN;
  107234. }
  107235. }else{
  107236. pWalker->eCode |= CKCNSTRNT_ROWID;
  107237. }
  107238. }
  107239. return WRC_Continue;
  107240. }
  107241. /*
  107242. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  107243. ** only columns that are modified by the UPDATE are those for which
  107244. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  107245. **
  107246. ** Return true if CHECK constraint pExpr does not use any of the
  107247. ** changing columns (or the rowid if it is changing). In other words,
  107248. ** return true if this CHECK constraint can be skipped when validating
  107249. ** the new row in the UPDATE statement.
  107250. */
  107251. static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
  107252. Walker w;
  107253. memset(&w, 0, sizeof(w));
  107254. w.eCode = 0;
  107255. w.xExprCallback = checkConstraintExprNode;
  107256. w.u.aiCol = aiChng;
  107257. sqlite3WalkExpr(&w, pExpr);
  107258. if( !chngRowid ){
  107259. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  107260. w.eCode &= ~CKCNSTRNT_ROWID;
  107261. }
  107262. testcase( w.eCode==0 );
  107263. testcase( w.eCode==CKCNSTRNT_COLUMN );
  107264. testcase( w.eCode==CKCNSTRNT_ROWID );
  107265. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  107266. return !w.eCode;
  107267. }
  107268. /*
  107269. ** An instance of the ConstraintAddr object remembers the byte-code addresses
  107270. ** for sections of the constraint checks that deal with uniqueness constraints
  107271. ** on the rowid and on the upsert constraint.
  107272. **
  107273. ** This information is passed into checkReorderConstraintChecks() to insert
  107274. ** some OP_Goto operations so that the rowid and upsert constraints occur
  107275. ** in the correct order relative to other constraints.
  107276. */
  107277. typedef struct ConstraintAddr ConstraintAddr;
  107278. struct ConstraintAddr {
  107279. int ipkTop; /* Subroutine for rowid constraint check */
  107280. int upsertTop; /* Label for upsert constraint check subroutine */
  107281. int upsertTop2; /* Copy of upsertTop not cleared by the call */
  107282. int upsertBtm; /* upsert constraint returns to this label */
  107283. int ipkBtm; /* Return opcode rowid constraint check */
  107284. };
  107285. /*
  107286. ** Generate any OP_Goto operations needed to cause constraints to be
  107287. ** run that haven't already been run.
  107288. */
  107289. static void reorderConstraintChecks(Vdbe *v, ConstraintAddr *p){
  107290. if( p->upsertTop ){
  107291. testcase( sqlite3VdbeLabelHasBeenResolved(v, p->upsertTop) );
  107292. sqlite3VdbeGoto(v, p->upsertTop);
  107293. VdbeComment((v, "call upsert subroutine"));
  107294. sqlite3VdbeResolveLabel(v, p->upsertBtm);
  107295. p->upsertTop = 0;
  107296. }
  107297. if( p->ipkTop ){
  107298. sqlite3VdbeGoto(v, p->ipkTop);
  107299. VdbeComment((v, "call rowid unique-check subroutine"));
  107300. sqlite3VdbeJumpHere(v, p->ipkBtm);
  107301. p->ipkTop = 0;
  107302. }
  107303. }
  107304. /*
  107305. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  107306. ** on table pTab.
  107307. **
  107308. ** The regNewData parameter is the first register in a range that contains
  107309. ** the data to be inserted or the data after the update. There will be
  107310. ** pTab->nCol+1 registers in this range. The first register (the one
  107311. ** that regNewData points to) will contain the new rowid, or NULL in the
  107312. ** case of a WITHOUT ROWID table. The second register in the range will
  107313. ** contain the content of the first table column. The third register will
  107314. ** contain the content of the second table column. And so forth.
  107315. **
  107316. ** The regOldData parameter is similar to regNewData except that it contains
  107317. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  107318. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  107319. ** checking regOldData for zero.
  107320. **
  107321. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  107322. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  107323. ** might be modified by the UPDATE. If pkChng is false, then the key of
  107324. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  107325. **
  107326. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  107327. ** was explicitly specified as part of the INSERT statement. If pkChng
  107328. ** is zero, it means that the either rowid is computed automatically or
  107329. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  107330. ** pkChng will only be true if the INSERT statement provides an integer
  107331. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  107332. **
  107333. ** The code generated by this routine will store new index entries into
  107334. ** registers identified by aRegIdx[]. No index entry is created for
  107335. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  107336. ** the same as the order of indices on the linked list of indices
  107337. ** at pTab->pIndex.
  107338. **
  107339. ** The caller must have already opened writeable cursors on the main
  107340. ** table and all applicable indices (that is to say, all indices for which
  107341. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  107342. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  107343. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  107344. ** for the first index in the pTab->pIndex list. Cursors for other indices
  107345. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  107346. **
  107347. ** This routine also generates code to check constraints. NOT NULL,
  107348. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  107349. ** then the appropriate action is performed. There are five possible
  107350. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  107351. **
  107352. ** Constraint type Action What Happens
  107353. ** --------------- ---------- ----------------------------------------
  107354. ** any ROLLBACK The current transaction is rolled back and
  107355. ** sqlite3_step() returns immediately with a
  107356. ** return code of SQLITE_CONSTRAINT.
  107357. **
  107358. ** any ABORT Back out changes from the current command
  107359. ** only (do not do a complete rollback) then
  107360. ** cause sqlite3_step() to return immediately
  107361. ** with SQLITE_CONSTRAINT.
  107362. **
  107363. ** any FAIL Sqlite3_step() returns immediately with a
  107364. ** return code of SQLITE_CONSTRAINT. The
  107365. ** transaction is not rolled back and any
  107366. ** changes to prior rows are retained.
  107367. **
  107368. ** any IGNORE The attempt in insert or update the current
  107369. ** row is skipped, without throwing an error.
  107370. ** Processing continues with the next row.
  107371. ** (There is an immediate jump to ignoreDest.)
  107372. **
  107373. ** NOT NULL REPLACE The NULL value is replace by the default
  107374. ** value for that column. If the default value
  107375. ** is NULL, the action is the same as ABORT.
  107376. **
  107377. ** UNIQUE REPLACE The other row that conflicts with the row
  107378. ** being inserted is removed.
  107379. **
  107380. ** CHECK REPLACE Illegal. The results in an exception.
  107381. **
  107382. ** Which action to take is determined by the overrideError parameter.
  107383. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  107384. ** is used. Or if pParse->onError==OE_Default then the onError value
  107385. ** for the constraint is used.
  107386. */
  107387. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  107388. Parse *pParse, /* The parser context */
  107389. Table *pTab, /* The table being inserted or updated */
  107390. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  107391. int iDataCur, /* Canonical data cursor (main table or PK index) */
  107392. int iIdxCur, /* First index cursor */
  107393. int regNewData, /* First register in a range holding values to insert */
  107394. int regOldData, /* Previous content. 0 for INSERTs */
  107395. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  107396. u8 overrideError, /* Override onError to this if not OE_Default */
  107397. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  107398. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  107399. int *aiChng, /* column i is unchanged if aiChng[i]<0 */
  107400. Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
  107401. ){
  107402. Vdbe *v; /* VDBE under constrution */
  107403. Index *pIdx; /* Pointer to one of the indices */
  107404. Index *pPk = 0; /* The PRIMARY KEY index */
  107405. sqlite3 *db; /* Database connection */
  107406. int i; /* loop counter */
  107407. int ix; /* Index loop counter */
  107408. int nCol; /* Number of columns */
  107409. int onError; /* Conflict resolution strategy */
  107410. int addr1; /* Address of jump instruction */
  107411. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  107412. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  107413. ConstraintAddr sAddr;/* Address information for constraint reordering */
  107414. Index *pUpIdx = 0; /* Index to which to apply the upsert */
  107415. u8 isUpdate; /* True if this is an UPDATE operation */
  107416. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  107417. int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */
  107418. isUpdate = regOldData!=0;
  107419. db = pParse->db;
  107420. v = sqlite3GetVdbe(pParse);
  107421. assert( v!=0 );
  107422. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  107423. nCol = pTab->nCol;
  107424. memset(&sAddr, 0, sizeof(sAddr));
  107425. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  107426. ** normal rowid tables. nPkField is the number of key fields in the
  107427. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  107428. ** number of fields in the true primary key of the table. */
  107429. if( HasRowid(pTab) ){
  107430. pPk = 0;
  107431. nPkField = 1;
  107432. }else{
  107433. pPk = sqlite3PrimaryKeyIndex(pTab);
  107434. nPkField = pPk->nKeyCol;
  107435. }
  107436. /* Record that this module has started */
  107437. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  107438. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  107439. /* Test all NOT NULL constraints.
  107440. */
  107441. for(i=0; i<nCol; i++){
  107442. if( i==pTab->iPKey ){
  107443. continue; /* ROWID is never NULL */
  107444. }
  107445. if( aiChng && aiChng[i]<0 ){
  107446. /* Don't bother checking for NOT NULL on columns that do not change */
  107447. continue;
  107448. }
  107449. onError = pTab->aCol[i].notNull;
  107450. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  107451. if( overrideError!=OE_Default ){
  107452. onError = overrideError;
  107453. }else if( onError==OE_Default ){
  107454. onError = OE_Abort;
  107455. }
  107456. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  107457. onError = OE_Abort;
  107458. }
  107459. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  107460. || onError==OE_Ignore || onError==OE_Replace );
  107461. switch( onError ){
  107462. case OE_Abort:
  107463. sqlite3MayAbort(pParse);
  107464. /* Fall through */
  107465. case OE_Rollback:
  107466. case OE_Fail: {
  107467. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  107468. pTab->aCol[i].zName);
  107469. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  107470. regNewData+1+i);
  107471. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  107472. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  107473. VdbeCoverage(v);
  107474. break;
  107475. }
  107476. case OE_Ignore: {
  107477. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  107478. VdbeCoverage(v);
  107479. break;
  107480. }
  107481. default: {
  107482. assert( onError==OE_Replace );
  107483. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  107484. VdbeCoverage(v);
  107485. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  107486. sqlite3VdbeJumpHere(v, addr1);
  107487. break;
  107488. }
  107489. }
  107490. }
  107491. /* Test all CHECK constraints
  107492. */
  107493. #ifndef SQLITE_OMIT_CHECK
  107494. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  107495. ExprList *pCheck = pTab->pCheck;
  107496. pParse->iSelfTab = -(regNewData+1);
  107497. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  107498. for(i=0; i<pCheck->nExpr; i++){
  107499. int allOk;
  107500. Expr *pExpr = pCheck->a[i].pExpr;
  107501. if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
  107502. allOk = sqlite3VdbeMakeLabel(v);
  107503. sqlite3VdbeVerifyAbortable(v, onError);
  107504. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  107505. if( onError==OE_Ignore ){
  107506. sqlite3VdbeGoto(v, ignoreDest);
  107507. }else{
  107508. char *zName = pCheck->a[i].zName;
  107509. if( zName==0 ) zName = pTab->zName;
  107510. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  107511. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  107512. onError, zName, P4_TRANSIENT,
  107513. P5_ConstraintCheck);
  107514. }
  107515. sqlite3VdbeResolveLabel(v, allOk);
  107516. }
  107517. pParse->iSelfTab = 0;
  107518. }
  107519. #endif /* !defined(SQLITE_OMIT_CHECK) */
  107520. /* UNIQUE and PRIMARY KEY constraints should be handled in the following
  107521. ** order:
  107522. **
  107523. ** (1) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
  107524. ** (2) OE_Update
  107525. ** (3) OE_Replace
  107526. **
  107527. ** OE_Fail and OE_Ignore must happen before any changes are made.
  107528. ** OE_Update guarantees that only a single row will change, so it
  107529. ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
  107530. ** could happen in any order, but they are grouped up front for
  107531. ** convenience.
  107532. **
  107533. ** Constraint checking code is generated in this order:
  107534. ** (A) The rowid constraint
  107535. ** (B) Unique index constraints that do not have OE_Replace as their
  107536. ** default conflict resolution strategy
  107537. ** (C) Unique index that do use OE_Replace by default.
  107538. **
  107539. ** The ordering of (2) and (3) is accomplished by making sure the linked
  107540. ** list of indexes attached to a table puts all OE_Replace indexes last
  107541. ** in the list. See sqlite3CreateIndex() for where that happens.
  107542. */
  107543. if( pUpsert ){
  107544. if( pUpsert->pUpsertTarget==0 ){
  107545. /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
  107546. ** Make all unique constraint resolution be OE_Ignore */
  107547. assert( pUpsert->pUpsertSet==0 );
  107548. overrideError = OE_Ignore;
  107549. pUpsert = 0;
  107550. }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
  107551. /* If the constraint-target is on some column other than
  107552. ** then ROWID, then we might need to move the UPSERT around
  107553. ** so that it occurs in the correct order. */
  107554. sAddr.upsertTop = sAddr.upsertTop2 = sqlite3VdbeMakeLabel(v);
  107555. sAddr.upsertBtm = sqlite3VdbeMakeLabel(v);
  107556. }
  107557. }
  107558. /* If rowid is changing, make sure the new rowid does not previously
  107559. ** exist in the table.
  107560. */
  107561. if( pkChng && pPk==0 ){
  107562. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  107563. /* Figure out what action to take in case of a rowid collision */
  107564. onError = pTab->keyConf;
  107565. if( overrideError!=OE_Default ){
  107566. onError = overrideError;
  107567. }else if( onError==OE_Default ){
  107568. onError = OE_Abort;
  107569. }
  107570. /* figure out whether or not upsert applies in this case */
  107571. if( pUpsert && pUpsert->pUpsertIdx==0 ){
  107572. if( pUpsert->pUpsertSet==0 ){
  107573. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  107574. }else{
  107575. onError = OE_Update; /* DO UPDATE */
  107576. }
  107577. }
  107578. /* If the response to a rowid conflict is REPLACE but the response
  107579. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  107580. ** to defer the running of the rowid conflict checking until after
  107581. ** the UNIQUE constraints have run.
  107582. */
  107583. assert( OE_Update>OE_Replace );
  107584. assert( OE_Ignore<OE_Replace );
  107585. assert( OE_Fail<OE_Replace );
  107586. assert( OE_Abort<OE_Replace );
  107587. assert( OE_Rollback<OE_Replace );
  107588. if( onError>=OE_Replace
  107589. && (pUpsert || onError!=overrideError)
  107590. && pTab->pIndex
  107591. ){
  107592. sAddr.ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
  107593. }
  107594. if( isUpdate ){
  107595. /* pkChng!=0 does not mean that the rowid has changed, only that
  107596. ** it might have changed. Skip the conflict logic below if the rowid
  107597. ** is unchanged. */
  107598. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  107599. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  107600. VdbeCoverage(v);
  107601. }
  107602. /* Check to see if the new rowid already exists in the table. Skip
  107603. ** the following conflict logic if it does not. */
  107604. VdbeNoopComment((v, "uniqueness check for ROWID"));
  107605. sqlite3VdbeVerifyAbortable(v, onError);
  107606. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  107607. VdbeCoverage(v);
  107608. switch( onError ){
  107609. default: {
  107610. onError = OE_Abort;
  107611. /* Fall thru into the next case */
  107612. }
  107613. case OE_Rollback:
  107614. case OE_Abort:
  107615. case OE_Fail: {
  107616. testcase( onError==OE_Rollback );
  107617. testcase( onError==OE_Abort );
  107618. testcase( onError==OE_Fail );
  107619. sqlite3RowidConstraint(pParse, onError, pTab);
  107620. break;
  107621. }
  107622. case OE_Replace: {
  107623. /* If there are DELETE triggers on this table and the
  107624. ** recursive-triggers flag is set, call GenerateRowDelete() to
  107625. ** remove the conflicting row from the table. This will fire
  107626. ** the triggers and remove both the table and index b-tree entries.
  107627. **
  107628. ** Otherwise, if there are no triggers or the recursive-triggers
  107629. ** flag is not set, but the table has one or more indexes, call
  107630. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  107631. ** only. The table b-tree entry will be replaced by the new entry
  107632. ** when it is inserted.
  107633. **
  107634. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  107635. ** also invoke MultiWrite() to indicate that this VDBE may require
  107636. ** statement rollback (if the statement is aborted after the delete
  107637. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  107638. ** but being more selective here allows statements like:
  107639. **
  107640. ** REPLACE INTO t(rowid) VALUES($newrowid)
  107641. **
  107642. ** to run without a statement journal if there are no indexes on the
  107643. ** table.
  107644. */
  107645. Trigger *pTrigger = 0;
  107646. if( db->flags&SQLITE_RecTriggers ){
  107647. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  107648. }
  107649. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  107650. sqlite3MultiWrite(pParse);
  107651. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  107652. regNewData, 1, 0, OE_Replace, 1, -1);
  107653. }else{
  107654. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  107655. assert( HasRowid(pTab) );
  107656. /* This OP_Delete opcode fires the pre-update-hook only. It does
  107657. ** not modify the b-tree. It is more efficient to let the coming
  107658. ** OP_Insert replace the existing entry than it is to delete the
  107659. ** existing entry and then insert a new one. */
  107660. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  107661. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  107662. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  107663. if( pTab->pIndex ){
  107664. sqlite3MultiWrite(pParse);
  107665. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  107666. }
  107667. }
  107668. seenReplace = 1;
  107669. break;
  107670. }
  107671. #ifndef SQLITE_OMIT_UPSERT
  107672. case OE_Update: {
  107673. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
  107674. /* Fall through */
  107675. }
  107676. #endif
  107677. case OE_Ignore: {
  107678. testcase( onError==OE_Ignore );
  107679. sqlite3VdbeGoto(v, ignoreDest);
  107680. break;
  107681. }
  107682. }
  107683. sqlite3VdbeResolveLabel(v, addrRowidOk);
  107684. if( sAddr.ipkTop ){
  107685. sAddr.ipkBtm = sqlite3VdbeAddOp0(v, OP_Goto);
  107686. sqlite3VdbeJumpHere(v, sAddr.ipkTop-1);
  107687. }
  107688. }
  107689. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  107690. ** index and making sure that duplicate entries do not already exist.
  107691. ** Compute the revised record entries for indices as we go.
  107692. **
  107693. ** This loop also handles the case of the PRIMARY KEY index for a
  107694. ** WITHOUT ROWID table.
  107695. */
  107696. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  107697. int regIdx; /* Range of registers hold conent for pIdx */
  107698. int regR; /* Range of registers holding conflicting PK */
  107699. int iThisCur; /* Cursor for this UNIQUE index */
  107700. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  107701. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  107702. if( pUpIdx==pIdx ){
  107703. addrUniqueOk = sAddr.upsertBtm;
  107704. upsertBypass = sqlite3VdbeGoto(v, 0);
  107705. VdbeComment((v, "Skip upsert subroutine"));
  107706. sqlite3VdbeResolveLabel(v, sAddr.upsertTop2);
  107707. }else{
  107708. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  107709. }
  107710. VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
  107711. if( bAffinityDone==0 ){
  107712. sqlite3TableAffinity(v, pTab, regNewData+1);
  107713. bAffinityDone = 1;
  107714. }
  107715. iThisCur = iIdxCur+ix;
  107716. /* Skip partial indices for which the WHERE clause is not true */
  107717. if( pIdx->pPartIdxWhere ){
  107718. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  107719. pParse->iSelfTab = -(regNewData+1);
  107720. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  107721. SQLITE_JUMPIFNULL);
  107722. pParse->iSelfTab = 0;
  107723. }
  107724. /* Create a record for this index entry as it should appear after
  107725. ** the insert or update. Store that record in the aRegIdx[ix] register
  107726. */
  107727. regIdx = aRegIdx[ix]+1;
  107728. for(i=0; i<pIdx->nColumn; i++){
  107729. int iField = pIdx->aiColumn[i];
  107730. int x;
  107731. if( iField==XN_EXPR ){
  107732. pParse->iSelfTab = -(regNewData+1);
  107733. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  107734. pParse->iSelfTab = 0;
  107735. VdbeComment((v, "%s column %d", pIdx->zName, i));
  107736. }else{
  107737. if( iField==XN_ROWID || iField==pTab->iPKey ){
  107738. x = regNewData;
  107739. }else{
  107740. x = iField + regNewData + 1;
  107741. }
  107742. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  107743. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  107744. }
  107745. }
  107746. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  107747. VdbeComment((v, "for %s", pIdx->zName));
  107748. #ifdef SQLITE_ENABLE_NULL_TRIM
  107749. if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
  107750. #endif
  107751. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  107752. ** of a WITHOUT ROWID table and there has been no change the
  107753. ** primary key, then no collision is possible. The collision detection
  107754. ** logic below can all be skipped. */
  107755. if( isUpdate && pPk==pIdx && pkChng==0 ){
  107756. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  107757. continue;
  107758. }
  107759. /* Find out what action to take in case there is a uniqueness conflict */
  107760. onError = pIdx->onError;
  107761. if( onError==OE_None ){
  107762. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  107763. continue; /* pIdx is not a UNIQUE index */
  107764. }
  107765. if( overrideError!=OE_Default ){
  107766. onError = overrideError;
  107767. }else if( onError==OE_Default ){
  107768. onError = OE_Abort;
  107769. }
  107770. /* Figure out if the upsert clause applies to this index */
  107771. if( pUpIdx==pIdx ){
  107772. if( pUpsert->pUpsertSet==0 ){
  107773. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  107774. }else{
  107775. onError = OE_Update; /* DO UPDATE */
  107776. }
  107777. }
  107778. /* Invoke subroutines to handle IPK replace and upsert prior to running
  107779. ** the first REPLACE constraint check. */
  107780. if( onError==OE_Replace ){
  107781. testcase( sAddr.ipkTop );
  107782. testcase( sAddr.upsertTop
  107783. && sqlite3VdbeLabelHasBeenResolved(v,sAddr.upsertTop) );
  107784. reorderConstraintChecks(v, &sAddr);
  107785. }
  107786. /* Collision detection may be omitted if all of the following are true:
  107787. ** (1) The conflict resolution algorithm is REPLACE
  107788. ** (2) The table is a WITHOUT ROWID table
  107789. ** (3) There are no secondary indexes on the table
  107790. ** (4) No delete triggers need to be fired if there is a conflict
  107791. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  107792. */
  107793. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  107794. && pPk==pIdx /* Condition 2 */
  107795. && onError==OE_Replace /* Condition 1 */
  107796. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  107797. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  107798. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  107799. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  107800. ){
  107801. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  107802. continue;
  107803. }
  107804. /* Check to see if the new index entry will be unique */
  107805. sqlite3ExprCachePush(pParse);
  107806. sqlite3VdbeVerifyAbortable(v, onError);
  107807. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  107808. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  107809. /* Generate code to handle collisions */
  107810. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  107811. if( isUpdate || onError==OE_Replace ){
  107812. if( HasRowid(pTab) ){
  107813. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  107814. /* Conflict only if the rowid of the existing index entry
  107815. ** is different from old-rowid */
  107816. if( isUpdate ){
  107817. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  107818. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  107819. VdbeCoverage(v);
  107820. }
  107821. }else{
  107822. int x;
  107823. /* Extract the PRIMARY KEY from the end of the index entry and
  107824. ** store it in registers regR..regR+nPk-1 */
  107825. if( pIdx!=pPk ){
  107826. for(i=0; i<pPk->nKeyCol; i++){
  107827. assert( pPk->aiColumn[i]>=0 );
  107828. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  107829. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  107830. VdbeComment((v, "%s.%s", pTab->zName,
  107831. pTab->aCol[pPk->aiColumn[i]].zName));
  107832. }
  107833. }
  107834. if( isUpdate ){
  107835. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  107836. ** table, only conflict if the new PRIMARY KEY values are actually
  107837. ** different from the old.
  107838. **
  107839. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  107840. ** of the matched index row are different from the original PRIMARY
  107841. ** KEY values of this row before the update. */
  107842. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  107843. int op = OP_Ne;
  107844. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  107845. for(i=0; i<pPk->nKeyCol; i++){
  107846. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  107847. x = pPk->aiColumn[i];
  107848. assert( x>=0 );
  107849. if( i==(pPk->nKeyCol-1) ){
  107850. addrJump = addrUniqueOk;
  107851. op = OP_Eq;
  107852. }
  107853. sqlite3VdbeAddOp4(v, op,
  107854. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  107855. );
  107856. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  107857. VdbeCoverageIf(v, op==OP_Eq);
  107858. VdbeCoverageIf(v, op==OP_Ne);
  107859. }
  107860. }
  107861. }
  107862. }
  107863. /* Generate code that executes if the new index entry is not unique */
  107864. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  107865. || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
  107866. switch( onError ){
  107867. case OE_Rollback:
  107868. case OE_Abort:
  107869. case OE_Fail: {
  107870. testcase( onError==OE_Rollback );
  107871. testcase( onError==OE_Abort );
  107872. testcase( onError==OE_Fail );
  107873. sqlite3UniqueConstraint(pParse, onError, pIdx);
  107874. break;
  107875. }
  107876. #ifndef SQLITE_OMIT_UPSERT
  107877. case OE_Update: {
  107878. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
  107879. /* Fall through */
  107880. }
  107881. #endif
  107882. case OE_Ignore: {
  107883. testcase( onError==OE_Ignore );
  107884. sqlite3VdbeGoto(v, ignoreDest);
  107885. break;
  107886. }
  107887. default: {
  107888. Trigger *pTrigger = 0;
  107889. assert( onError==OE_Replace );
  107890. if( db->flags&SQLITE_RecTriggers ){
  107891. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  107892. }
  107893. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  107894. sqlite3MultiWrite(pParse);
  107895. }
  107896. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  107897. regR, nPkField, 0, OE_Replace,
  107898. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  107899. seenReplace = 1;
  107900. break;
  107901. }
  107902. }
  107903. if( pUpIdx==pIdx ){
  107904. sqlite3VdbeJumpHere(v, upsertBypass);
  107905. }else{
  107906. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  107907. }
  107908. sqlite3ExprCachePop(pParse);
  107909. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  107910. }
  107911. testcase( sAddr.ipkTop!=0 );
  107912. testcase( sAddr.upsertTop
  107913. && sqlite3VdbeLabelHasBeenResolved(v,sAddr.upsertTop) );
  107914. reorderConstraintChecks(v, &sAddr);
  107915. *pbMayReplace = seenReplace;
  107916. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  107917. }
  107918. #ifdef SQLITE_ENABLE_NULL_TRIM
  107919. /*
  107920. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  107921. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  107922. **
  107923. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  107924. */
  107925. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  107926. u16 i;
  107927. /* Records with omitted columns are only allowed for schema format
  107928. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  107929. if( pTab->pSchema->file_format<2 ) return;
  107930. for(i=pTab->nCol-1; i>0; i--){
  107931. if( pTab->aCol[i].pDflt!=0 ) break;
  107932. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  107933. }
  107934. sqlite3VdbeChangeP5(v, i+1);
  107935. }
  107936. #endif
  107937. /*
  107938. ** This routine generates code to finish the INSERT or UPDATE operation
  107939. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  107940. ** A consecutive range of registers starting at regNewData contains the
  107941. ** rowid and the content to be inserted.
  107942. **
  107943. ** The arguments to this routine should be the same as the first six
  107944. ** arguments to sqlite3GenerateConstraintChecks.
  107945. */
  107946. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  107947. Parse *pParse, /* The parser context */
  107948. Table *pTab, /* the table into which we are inserting */
  107949. int iDataCur, /* Cursor of the canonical data source */
  107950. int iIdxCur, /* First index cursor */
  107951. int regNewData, /* Range of content */
  107952. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  107953. int update_flags, /* True for UPDATE, False for INSERT */
  107954. int appendBias, /* True if this is likely to be an append */
  107955. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  107956. ){
  107957. Vdbe *v; /* Prepared statements under construction */
  107958. Index *pIdx; /* An index being inserted or updated */
  107959. u8 pik_flags; /* flag values passed to the btree insert */
  107960. int regData; /* Content registers (after the rowid) */
  107961. int regRec; /* Register holding assembled record for the table */
  107962. int i; /* Loop counter */
  107963. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  107964. assert( update_flags==0
  107965. || update_flags==OPFLAG_ISUPDATE
  107966. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  107967. );
  107968. v = sqlite3GetVdbe(pParse);
  107969. assert( v!=0 );
  107970. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  107971. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  107972. if( aRegIdx[i]==0 ) continue;
  107973. bAffinityDone = 1;
  107974. if( pIdx->pPartIdxWhere ){
  107975. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  107976. VdbeCoverage(v);
  107977. }
  107978. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  107979. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  107980. assert( pParse->nested==0 );
  107981. pik_flags |= OPFLAG_NCHANGE;
  107982. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  107983. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  107984. if( update_flags==0 ){
  107985. sqlite3VdbeAddOp4(v, OP_InsertInt,
  107986. iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
  107987. );
  107988. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  107989. }
  107990. #endif
  107991. }
  107992. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  107993. aRegIdx[i]+1,
  107994. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  107995. sqlite3VdbeChangeP5(v, pik_flags);
  107996. }
  107997. if( !HasRowid(pTab) ) return;
  107998. regData = regNewData + 1;
  107999. regRec = sqlite3GetTempReg(pParse);
  108000. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  108001. sqlite3SetMakeRecordP5(v, pTab);
  108002. if( !bAffinityDone ){
  108003. sqlite3TableAffinity(v, pTab, 0);
  108004. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  108005. }
  108006. if( pParse->nested ){
  108007. pik_flags = 0;
  108008. }else{
  108009. pik_flags = OPFLAG_NCHANGE;
  108010. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  108011. }
  108012. if( appendBias ){
  108013. pik_flags |= OPFLAG_APPEND;
  108014. }
  108015. if( useSeekResult ){
  108016. pik_flags |= OPFLAG_USESEEKRESULT;
  108017. }
  108018. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  108019. if( !pParse->nested ){
  108020. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  108021. }
  108022. sqlite3VdbeChangeP5(v, pik_flags);
  108023. }
  108024. /*
  108025. ** Allocate cursors for the pTab table and all its indices and generate
  108026. ** code to open and initialized those cursors.
  108027. **
  108028. ** The cursor for the object that contains the complete data (normally
  108029. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  108030. ** ROWID table) is returned in *piDataCur. The first index cursor is
  108031. ** returned in *piIdxCur. The number of indices is returned.
  108032. **
  108033. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  108034. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  108035. ** If iBase is negative, then allocate the next available cursor.
  108036. **
  108037. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  108038. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  108039. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  108040. ** pTab->pIndex list.
  108041. **
  108042. ** If pTab is a virtual table, then this routine is a no-op and the
  108043. ** *piDataCur and *piIdxCur values are left uninitialized.
  108044. */
  108045. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  108046. Parse *pParse, /* Parsing context */
  108047. Table *pTab, /* Table to be opened */
  108048. int op, /* OP_OpenRead or OP_OpenWrite */
  108049. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  108050. int iBase, /* Use this for the table cursor, if there is one */
  108051. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  108052. int *piDataCur, /* Write the database source cursor number here */
  108053. int *piIdxCur /* Write the first index cursor number here */
  108054. ){
  108055. int i;
  108056. int iDb;
  108057. int iDataCur;
  108058. Index *pIdx;
  108059. Vdbe *v;
  108060. assert( op==OP_OpenRead || op==OP_OpenWrite );
  108061. assert( op==OP_OpenWrite || p5==0 );
  108062. if( IsVirtual(pTab) ){
  108063. /* This routine is a no-op for virtual tables. Leave the output
  108064. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  108065. ** can detect if they are used by mistake in the caller. */
  108066. return 0;
  108067. }
  108068. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  108069. v = sqlite3GetVdbe(pParse);
  108070. assert( v!=0 );
  108071. if( iBase<0 ) iBase = pParse->nTab;
  108072. iDataCur = iBase++;
  108073. if( piDataCur ) *piDataCur = iDataCur;
  108074. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  108075. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  108076. }else{
  108077. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  108078. }
  108079. if( piIdxCur ) *piIdxCur = iBase;
  108080. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  108081. int iIdxCur = iBase++;
  108082. assert( pIdx->pSchema==pTab->pSchema );
  108083. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  108084. if( piDataCur ) *piDataCur = iIdxCur;
  108085. p5 = 0;
  108086. }
  108087. if( aToOpen==0 || aToOpen[i+1] ){
  108088. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  108089. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  108090. sqlite3VdbeChangeP5(v, p5);
  108091. VdbeComment((v, "%s", pIdx->zName));
  108092. }
  108093. }
  108094. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  108095. return i;
  108096. }
  108097. #ifdef SQLITE_TEST
  108098. /*
  108099. ** The following global variable is incremented whenever the
  108100. ** transfer optimization is used. This is used for testing
  108101. ** purposes only - to make sure the transfer optimization really
  108102. ** is happening when it is supposed to.
  108103. */
  108104. SQLITE_API int sqlite3_xferopt_count;
  108105. #endif /* SQLITE_TEST */
  108106. #ifndef SQLITE_OMIT_XFER_OPT
  108107. /*
  108108. ** Check to see if index pSrc is compatible as a source of data
  108109. ** for index pDest in an insert transfer optimization. The rules
  108110. ** for a compatible index:
  108111. **
  108112. ** * The index is over the same set of columns
  108113. ** * The same DESC and ASC markings occurs on all columns
  108114. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  108115. ** * The same collating sequence on each column
  108116. ** * The index has the exact same WHERE clause
  108117. */
  108118. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  108119. int i;
  108120. assert( pDest && pSrc );
  108121. assert( pDest->pTable!=pSrc->pTable );
  108122. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  108123. return 0; /* Different number of columns */
  108124. }
  108125. if( pDest->onError!=pSrc->onError ){
  108126. return 0; /* Different conflict resolution strategies */
  108127. }
  108128. for(i=0; i<pSrc->nKeyCol; i++){
  108129. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  108130. return 0; /* Different columns indexed */
  108131. }
  108132. if( pSrc->aiColumn[i]==XN_EXPR ){
  108133. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  108134. if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
  108135. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  108136. return 0; /* Different expressions in the index */
  108137. }
  108138. }
  108139. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  108140. return 0; /* Different sort orders */
  108141. }
  108142. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  108143. return 0; /* Different collating sequences */
  108144. }
  108145. }
  108146. if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  108147. return 0; /* Different WHERE clauses */
  108148. }
  108149. /* If no test above fails then the indices must be compatible */
  108150. return 1;
  108151. }
  108152. /*
  108153. ** Attempt the transfer optimization on INSERTs of the form
  108154. **
  108155. ** INSERT INTO tab1 SELECT * FROM tab2;
  108156. **
  108157. ** The xfer optimization transfers raw records from tab2 over to tab1.
  108158. ** Columns are not decoded and reassembled, which greatly improves
  108159. ** performance. Raw index records are transferred in the same way.
  108160. **
  108161. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  108162. ** There are lots of rules for determining compatibility - see comments
  108163. ** embedded in the code for details.
  108164. **
  108165. ** This routine returns TRUE if the optimization is guaranteed to be used.
  108166. ** Sometimes the xfer optimization will only work if the destination table
  108167. ** is empty - a factor that can only be determined at run-time. In that
  108168. ** case, this routine generates code for the xfer optimization but also
  108169. ** does a test to see if the destination table is empty and jumps over the
  108170. ** xfer optimization code if the test fails. In that case, this routine
  108171. ** returns FALSE so that the caller will know to go ahead and generate
  108172. ** an unoptimized transfer. This routine also returns FALSE if there
  108173. ** is no chance that the xfer optimization can be applied.
  108174. **
  108175. ** This optimization is particularly useful at making VACUUM run faster.
  108176. */
  108177. static int xferOptimization(
  108178. Parse *pParse, /* Parser context */
  108179. Table *pDest, /* The table we are inserting into */
  108180. Select *pSelect, /* A SELECT statement to use as the data source */
  108181. int onError, /* How to handle constraint errors */
  108182. int iDbDest /* The database of pDest */
  108183. ){
  108184. sqlite3 *db = pParse->db;
  108185. ExprList *pEList; /* The result set of the SELECT */
  108186. Table *pSrc; /* The table in the FROM clause of SELECT */
  108187. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  108188. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  108189. int i; /* Loop counter */
  108190. int iDbSrc; /* The database of pSrc */
  108191. int iSrc, iDest; /* Cursors from source and destination */
  108192. int addr1, addr2; /* Loop addresses */
  108193. int emptyDestTest = 0; /* Address of test for empty pDest */
  108194. int emptySrcTest = 0; /* Address of test for empty pSrc */
  108195. Vdbe *v; /* The VDBE we are building */
  108196. int regAutoinc; /* Memory register used by AUTOINC */
  108197. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  108198. int regData, regRowid; /* Registers holding data and rowid */
  108199. if( pSelect==0 ){
  108200. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  108201. }
  108202. if( pParse->pWith || pSelect->pWith ){
  108203. /* Do not attempt to process this query if there are an WITH clauses
  108204. ** attached to it. Proceeding may generate a false "no such table: xxx"
  108205. ** error if pSelect reads from a CTE named "xxx". */
  108206. return 0;
  108207. }
  108208. if( sqlite3TriggerList(pParse, pDest) ){
  108209. return 0; /* tab1 must not have triggers */
  108210. }
  108211. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108212. if( IsVirtual(pDest) ){
  108213. return 0; /* tab1 must not be a virtual table */
  108214. }
  108215. #endif
  108216. if( onError==OE_Default ){
  108217. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  108218. if( onError==OE_Default ) onError = OE_Abort;
  108219. }
  108220. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  108221. if( pSelect->pSrc->nSrc!=1 ){
  108222. return 0; /* FROM clause must have exactly one term */
  108223. }
  108224. if( pSelect->pSrc->a[0].pSelect ){
  108225. return 0; /* FROM clause cannot contain a subquery */
  108226. }
  108227. if( pSelect->pWhere ){
  108228. return 0; /* SELECT may not have a WHERE clause */
  108229. }
  108230. if( pSelect->pOrderBy ){
  108231. return 0; /* SELECT may not have an ORDER BY clause */
  108232. }
  108233. /* Do not need to test for a HAVING clause. If HAVING is present but
  108234. ** there is no ORDER BY, we will get an error. */
  108235. if( pSelect->pGroupBy ){
  108236. return 0; /* SELECT may not have a GROUP BY clause */
  108237. }
  108238. if( pSelect->pLimit ){
  108239. return 0; /* SELECT may not have a LIMIT clause */
  108240. }
  108241. if( pSelect->pPrior ){
  108242. return 0; /* SELECT may not be a compound query */
  108243. }
  108244. if( pSelect->selFlags & SF_Distinct ){
  108245. return 0; /* SELECT may not be DISTINCT */
  108246. }
  108247. pEList = pSelect->pEList;
  108248. assert( pEList!=0 );
  108249. if( pEList->nExpr!=1 ){
  108250. return 0; /* The result set must have exactly one column */
  108251. }
  108252. assert( pEList->a[0].pExpr );
  108253. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  108254. return 0; /* The result set must be the special operator "*" */
  108255. }
  108256. /* At this point we have established that the statement is of the
  108257. ** correct syntactic form to participate in this optimization. Now
  108258. ** we have to check the semantics.
  108259. */
  108260. pItem = pSelect->pSrc->a;
  108261. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  108262. if( pSrc==0 ){
  108263. return 0; /* FROM clause does not contain a real table */
  108264. }
  108265. if( pSrc==pDest ){
  108266. return 0; /* tab1 and tab2 may not be the same table */
  108267. }
  108268. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  108269. return 0; /* source and destination must both be WITHOUT ROWID or not */
  108270. }
  108271. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108272. if( IsVirtual(pSrc) ){
  108273. return 0; /* tab2 must not be a virtual table */
  108274. }
  108275. #endif
  108276. if( pSrc->pSelect ){
  108277. return 0; /* tab2 may not be a view */
  108278. }
  108279. if( pDest->nCol!=pSrc->nCol ){
  108280. return 0; /* Number of columns must be the same in tab1 and tab2 */
  108281. }
  108282. if( pDest->iPKey!=pSrc->iPKey ){
  108283. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  108284. }
  108285. for(i=0; i<pDest->nCol; i++){
  108286. Column *pDestCol = &pDest->aCol[i];
  108287. Column *pSrcCol = &pSrc->aCol[i];
  108288. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  108289. if( (db->mDbFlags & DBFLAG_Vacuum)==0
  108290. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  108291. ){
  108292. return 0; /* Neither table may have __hidden__ columns */
  108293. }
  108294. #endif
  108295. if( pDestCol->affinity!=pSrcCol->affinity ){
  108296. return 0; /* Affinity must be the same on all columns */
  108297. }
  108298. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  108299. return 0; /* Collating sequence must be the same on all columns */
  108300. }
  108301. if( pDestCol->notNull && !pSrcCol->notNull ){
  108302. return 0; /* tab2 must be NOT NULL if tab1 is */
  108303. }
  108304. /* Default values for second and subsequent columns need to match. */
  108305. if( i>0 ){
  108306. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  108307. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  108308. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  108309. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  108310. pSrcCol->pDflt->u.zToken)!=0)
  108311. ){
  108312. return 0; /* Default values must be the same for all columns */
  108313. }
  108314. }
  108315. }
  108316. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  108317. if( IsUniqueIndex(pDestIdx) ){
  108318. destHasUniqueIdx = 1;
  108319. }
  108320. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  108321. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  108322. }
  108323. if( pSrcIdx==0 ){
  108324. return 0; /* pDestIdx has no corresponding index in pSrc */
  108325. }
  108326. }
  108327. #ifndef SQLITE_OMIT_CHECK
  108328. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  108329. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  108330. }
  108331. #endif
  108332. #ifndef SQLITE_OMIT_FOREIGN_KEY
  108333. /* Disallow the transfer optimization if the destination table constains
  108334. ** any foreign key constraints. This is more restrictive than necessary.
  108335. ** But the main beneficiary of the transfer optimization is the VACUUM
  108336. ** command, and the VACUUM command disables foreign key constraints. So
  108337. ** the extra complication to make this rule less restrictive is probably
  108338. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  108339. */
  108340. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  108341. return 0;
  108342. }
  108343. #endif
  108344. if( (db->flags & SQLITE_CountRows)!=0 ){
  108345. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  108346. }
  108347. /* If we get this far, it means that the xfer optimization is at
  108348. ** least a possibility, though it might only work if the destination
  108349. ** table (tab1) is initially empty.
  108350. */
  108351. #ifdef SQLITE_TEST
  108352. sqlite3_xferopt_count++;
  108353. #endif
  108354. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  108355. v = sqlite3GetVdbe(pParse);
  108356. sqlite3CodeVerifySchema(pParse, iDbSrc);
  108357. iSrc = pParse->nTab++;
  108358. iDest = pParse->nTab++;
  108359. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  108360. regData = sqlite3GetTempReg(pParse);
  108361. regRowid = sqlite3GetTempReg(pParse);
  108362. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  108363. assert( HasRowid(pDest) || destHasUniqueIdx );
  108364. if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
  108365. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  108366. || destHasUniqueIdx /* (2) */
  108367. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  108368. )){
  108369. /* In some circumstances, we are able to run the xfer optimization
  108370. ** only if the destination table is initially empty. Unless the
  108371. ** DBFLAG_Vacuum flag is set, this block generates code to make
  108372. ** that determination. If DBFLAG_Vacuum is set, then the destination
  108373. ** table is always empty.
  108374. **
  108375. ** Conditions under which the destination must be empty:
  108376. **
  108377. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  108378. ** (If the destination is not initially empty, the rowid fields
  108379. ** of index entries might need to change.)
  108380. **
  108381. ** (2) The destination has a unique index. (The xfer optimization
  108382. ** is unable to test uniqueness.)
  108383. **
  108384. ** (3) onError is something other than OE_Abort and OE_Rollback.
  108385. */
  108386. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  108387. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  108388. sqlite3VdbeJumpHere(v, addr1);
  108389. }
  108390. if( HasRowid(pSrc) ){
  108391. u8 insFlags;
  108392. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  108393. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  108394. if( pDest->iPKey>=0 ){
  108395. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  108396. sqlite3VdbeVerifyAbortable(v, onError);
  108397. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  108398. VdbeCoverage(v);
  108399. sqlite3RowidConstraint(pParse, onError, pDest);
  108400. sqlite3VdbeJumpHere(v, addr2);
  108401. autoIncStep(pParse, regAutoinc, regRowid);
  108402. }else if( pDest->pIndex==0 ){
  108403. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  108404. }else{
  108405. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  108406. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  108407. }
  108408. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  108409. if( db->mDbFlags & DBFLAG_Vacuum ){
  108410. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  108411. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  108412. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  108413. }else{
  108414. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  108415. }
  108416. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  108417. (char*)pDest, P4_TABLE);
  108418. sqlite3VdbeChangeP5(v, insFlags);
  108419. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  108420. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  108421. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  108422. }else{
  108423. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  108424. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  108425. }
  108426. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  108427. u8 idxInsFlags = 0;
  108428. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  108429. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  108430. }
  108431. assert( pSrcIdx );
  108432. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  108433. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  108434. VdbeComment((v, "%s", pSrcIdx->zName));
  108435. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  108436. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  108437. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  108438. VdbeComment((v, "%s", pDestIdx->zName));
  108439. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  108440. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  108441. if( db->mDbFlags & DBFLAG_Vacuum ){
  108442. /* This INSERT command is part of a VACUUM operation, which guarantees
  108443. ** that the destination table is empty. If all indexed columns use
  108444. ** collation sequence BINARY, then it can also be assumed that the
  108445. ** index will be populated by inserting keys in strictly sorted
  108446. ** order. In this case, instead of seeking within the b-tree as part
  108447. ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
  108448. ** OP_IdxInsert to seek to the point within the b-tree where each key
  108449. ** should be inserted. This is faster.
  108450. **
  108451. ** If any of the indexed columns use a collation sequence other than
  108452. ** BINARY, this optimization is disabled. This is because the user
  108453. ** might change the definition of a collation sequence and then run
  108454. ** a VACUUM command. In that case keys may not be written in strictly
  108455. ** sorted order. */
  108456. for(i=0; i<pSrcIdx->nColumn; i++){
  108457. const char *zColl = pSrcIdx->azColl[i];
  108458. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  108459. }
  108460. if( i==pSrcIdx->nColumn ){
  108461. idxInsFlags = OPFLAG_USESEEKRESULT;
  108462. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  108463. }
  108464. }
  108465. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  108466. idxInsFlags |= OPFLAG_NCHANGE;
  108467. }
  108468. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  108469. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  108470. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  108471. sqlite3VdbeJumpHere(v, addr1);
  108472. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  108473. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  108474. }
  108475. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  108476. sqlite3ReleaseTempReg(pParse, regRowid);
  108477. sqlite3ReleaseTempReg(pParse, regData);
  108478. if( emptyDestTest ){
  108479. sqlite3AutoincrementEnd(pParse);
  108480. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  108481. sqlite3VdbeJumpHere(v, emptyDestTest);
  108482. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  108483. return 0;
  108484. }else{
  108485. return 1;
  108486. }
  108487. }
  108488. #endif /* SQLITE_OMIT_XFER_OPT */
  108489. /************** End of insert.c **********************************************/
  108490. /************** Begin file legacy.c ******************************************/
  108491. /*
  108492. ** 2001 September 15
  108493. **
  108494. ** The author disclaims copyright to this source code. In place of
  108495. ** a legal notice, here is a blessing:
  108496. **
  108497. ** May you do good and not evil.
  108498. ** May you find forgiveness for yourself and forgive others.
  108499. ** May you share freely, never taking more than you give.
  108500. **
  108501. *************************************************************************
  108502. ** Main file for the SQLite library. The routines in this file
  108503. ** implement the programmer interface to the library. Routines in
  108504. ** other files are for internal use by SQLite and should not be
  108505. ** accessed by users of the library.
  108506. */
  108507. /* #include "sqliteInt.h" */
  108508. /*
  108509. ** Execute SQL code. Return one of the SQLITE_ success/failure
  108510. ** codes. Also write an error message into memory obtained from
  108511. ** malloc() and make *pzErrMsg point to that message.
  108512. **
  108513. ** If the SQL is a query, then for each row in the query result
  108514. ** the xCallback() function is called. pArg becomes the first
  108515. ** argument to xCallback(). If xCallback=NULL then no callback
  108516. ** is invoked, even for queries.
  108517. */
  108518. SQLITE_API int sqlite3_exec(
  108519. sqlite3 *db, /* The database on which the SQL executes */
  108520. const char *zSql, /* The SQL to be executed */
  108521. sqlite3_callback xCallback, /* Invoke this callback routine */
  108522. void *pArg, /* First argument to xCallback() */
  108523. char **pzErrMsg /* Write error messages here */
  108524. ){
  108525. int rc = SQLITE_OK; /* Return code */
  108526. const char *zLeftover; /* Tail of unprocessed SQL */
  108527. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  108528. char **azCols = 0; /* Names of result columns */
  108529. int callbackIsInit; /* True if callback data is initialized */
  108530. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  108531. if( zSql==0 ) zSql = "";
  108532. sqlite3_mutex_enter(db->mutex);
  108533. sqlite3Error(db, SQLITE_OK);
  108534. while( rc==SQLITE_OK && zSql[0] ){
  108535. int nCol;
  108536. char **azVals = 0;
  108537. pStmt = 0;
  108538. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  108539. assert( rc==SQLITE_OK || pStmt==0 );
  108540. if( rc!=SQLITE_OK ){
  108541. continue;
  108542. }
  108543. if( !pStmt ){
  108544. /* this happens for a comment or white-space */
  108545. zSql = zLeftover;
  108546. continue;
  108547. }
  108548. callbackIsInit = 0;
  108549. nCol = sqlite3_column_count(pStmt);
  108550. while( 1 ){
  108551. int i;
  108552. rc = sqlite3_step(pStmt);
  108553. /* Invoke the callback function if required */
  108554. if( xCallback && (SQLITE_ROW==rc ||
  108555. (SQLITE_DONE==rc && !callbackIsInit
  108556. && db->flags&SQLITE_NullCallback)) ){
  108557. if( !callbackIsInit ){
  108558. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  108559. if( azCols==0 ){
  108560. goto exec_out;
  108561. }
  108562. for(i=0; i<nCol; i++){
  108563. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  108564. /* sqlite3VdbeSetColName() installs column names as UTF8
  108565. ** strings so there is no way for sqlite3_column_name() to fail. */
  108566. assert( azCols[i]!=0 );
  108567. }
  108568. callbackIsInit = 1;
  108569. }
  108570. if( rc==SQLITE_ROW ){
  108571. azVals = &azCols[nCol];
  108572. for(i=0; i<nCol; i++){
  108573. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  108574. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  108575. sqlite3OomFault(db);
  108576. goto exec_out;
  108577. }
  108578. }
  108579. azVals[i] = 0;
  108580. }
  108581. if( xCallback(pArg, nCol, azVals, azCols) ){
  108582. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  108583. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  108584. ** return SQLITE_ABORT. */
  108585. rc = SQLITE_ABORT;
  108586. sqlite3VdbeFinalize((Vdbe *)pStmt);
  108587. pStmt = 0;
  108588. sqlite3Error(db, SQLITE_ABORT);
  108589. goto exec_out;
  108590. }
  108591. }
  108592. if( rc!=SQLITE_ROW ){
  108593. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  108594. pStmt = 0;
  108595. zSql = zLeftover;
  108596. while( sqlite3Isspace(zSql[0]) ) zSql++;
  108597. break;
  108598. }
  108599. }
  108600. sqlite3DbFree(db, azCols);
  108601. azCols = 0;
  108602. }
  108603. exec_out:
  108604. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  108605. sqlite3DbFree(db, azCols);
  108606. rc = sqlite3ApiExit(db, rc);
  108607. if( rc!=SQLITE_OK && pzErrMsg ){
  108608. *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
  108609. if( *pzErrMsg==0 ){
  108610. rc = SQLITE_NOMEM_BKPT;
  108611. sqlite3Error(db, SQLITE_NOMEM);
  108612. }
  108613. }else if( pzErrMsg ){
  108614. *pzErrMsg = 0;
  108615. }
  108616. assert( (rc&db->errMask)==rc );
  108617. sqlite3_mutex_leave(db->mutex);
  108618. return rc;
  108619. }
  108620. /************** End of legacy.c **********************************************/
  108621. /************** Begin file loadext.c *****************************************/
  108622. /*
  108623. ** 2006 June 7
  108624. **
  108625. ** The author disclaims copyright to this source code. In place of
  108626. ** a legal notice, here is a blessing:
  108627. **
  108628. ** May you do good and not evil.
  108629. ** May you find forgiveness for yourself and forgive others.
  108630. ** May you share freely, never taking more than you give.
  108631. **
  108632. *************************************************************************
  108633. ** This file contains code used to dynamically load extensions into
  108634. ** the SQLite library.
  108635. */
  108636. #ifndef SQLITE_CORE
  108637. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  108638. #endif
  108639. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  108640. /************** Begin file sqlite3ext.h **************************************/
  108641. /*
  108642. ** 2006 June 7
  108643. **
  108644. ** The author disclaims copyright to this source code. In place of
  108645. ** a legal notice, here is a blessing:
  108646. **
  108647. ** May you do good and not evil.
  108648. ** May you find forgiveness for yourself and forgive others.
  108649. ** May you share freely, never taking more than you give.
  108650. **
  108651. *************************************************************************
  108652. ** This header file defines the SQLite interface for use by
  108653. ** shared libraries that want to be imported as extensions into
  108654. ** an SQLite instance. Shared libraries that intend to be loaded
  108655. ** as extensions by SQLite should #include this file instead of
  108656. ** sqlite3.h.
  108657. */
  108658. #ifndef SQLITE3EXT_H
  108659. #define SQLITE3EXT_H
  108660. /* #include "sqlite3.h" */
  108661. /*
  108662. ** The following structure holds pointers to all of the SQLite API
  108663. ** routines.
  108664. **
  108665. ** WARNING: In order to maintain backwards compatibility, add new
  108666. ** interfaces to the end of this structure only. If you insert new
  108667. ** interfaces in the middle of this structure, then older different
  108668. ** versions of SQLite will not be able to load each other's shared
  108669. ** libraries!
  108670. */
  108671. struct sqlite3_api_routines {
  108672. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  108673. int (*aggregate_count)(sqlite3_context*);
  108674. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  108675. int (*bind_double)(sqlite3_stmt*,int,double);
  108676. int (*bind_int)(sqlite3_stmt*,int,int);
  108677. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  108678. int (*bind_null)(sqlite3_stmt*,int);
  108679. int (*bind_parameter_count)(sqlite3_stmt*);
  108680. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  108681. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  108682. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  108683. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  108684. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  108685. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  108686. int (*busy_timeout)(sqlite3*,int ms);
  108687. int (*changes)(sqlite3*);
  108688. int (*close)(sqlite3*);
  108689. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  108690. int eTextRep,const char*));
  108691. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  108692. int eTextRep,const void*));
  108693. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  108694. int (*column_bytes)(sqlite3_stmt*,int iCol);
  108695. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  108696. int (*column_count)(sqlite3_stmt*pStmt);
  108697. const char * (*column_database_name)(sqlite3_stmt*,int);
  108698. const void * (*column_database_name16)(sqlite3_stmt*,int);
  108699. const char * (*column_decltype)(sqlite3_stmt*,int i);
  108700. const void * (*column_decltype16)(sqlite3_stmt*,int);
  108701. double (*column_double)(sqlite3_stmt*,int iCol);
  108702. int (*column_int)(sqlite3_stmt*,int iCol);
  108703. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  108704. const char * (*column_name)(sqlite3_stmt*,int);
  108705. const void * (*column_name16)(sqlite3_stmt*,int);
  108706. const char * (*column_origin_name)(sqlite3_stmt*,int);
  108707. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  108708. const char * (*column_table_name)(sqlite3_stmt*,int);
  108709. const void * (*column_table_name16)(sqlite3_stmt*,int);
  108710. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  108711. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  108712. int (*column_type)(sqlite3_stmt*,int iCol);
  108713. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  108714. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  108715. int (*complete)(const char*sql);
  108716. int (*complete16)(const void*sql);
  108717. int (*create_collation)(sqlite3*,const char*,int,void*,
  108718. int(*)(void*,int,const void*,int,const void*));
  108719. int (*create_collation16)(sqlite3*,const void*,int,void*,
  108720. int(*)(void*,int,const void*,int,const void*));
  108721. int (*create_function)(sqlite3*,const char*,int,int,void*,
  108722. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  108723. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  108724. void (*xFinal)(sqlite3_context*));
  108725. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  108726. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  108727. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  108728. void (*xFinal)(sqlite3_context*));
  108729. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  108730. int (*data_count)(sqlite3_stmt*pStmt);
  108731. sqlite3 * (*db_handle)(sqlite3_stmt*);
  108732. int (*declare_vtab)(sqlite3*,const char*);
  108733. int (*enable_shared_cache)(int);
  108734. int (*errcode)(sqlite3*db);
  108735. const char * (*errmsg)(sqlite3*);
  108736. const void * (*errmsg16)(sqlite3*);
  108737. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  108738. int (*expired)(sqlite3_stmt*);
  108739. int (*finalize)(sqlite3_stmt*pStmt);
  108740. void (*free)(void*);
  108741. void (*free_table)(char**result);
  108742. int (*get_autocommit)(sqlite3*);
  108743. void * (*get_auxdata)(sqlite3_context*,int);
  108744. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  108745. int (*global_recover)(void);
  108746. void (*interruptx)(sqlite3*);
  108747. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  108748. const char * (*libversion)(void);
  108749. int (*libversion_number)(void);
  108750. void *(*malloc)(int);
  108751. char * (*mprintf)(const char*,...);
  108752. int (*open)(const char*,sqlite3**);
  108753. int (*open16)(const void*,sqlite3**);
  108754. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  108755. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  108756. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  108757. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  108758. void *(*realloc)(void*,int);
  108759. int (*reset)(sqlite3_stmt*pStmt);
  108760. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  108761. void (*result_double)(sqlite3_context*,double);
  108762. void (*result_error)(sqlite3_context*,const char*,int);
  108763. void (*result_error16)(sqlite3_context*,const void*,int);
  108764. void (*result_int)(sqlite3_context*,int);
  108765. void (*result_int64)(sqlite3_context*,sqlite_int64);
  108766. void (*result_null)(sqlite3_context*);
  108767. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  108768. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  108769. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  108770. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  108771. void (*result_value)(sqlite3_context*,sqlite3_value*);
  108772. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  108773. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  108774. const char*,const char*),void*);
  108775. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  108776. char * (*xsnprintf)(int,char*,const char*,...);
  108777. int (*step)(sqlite3_stmt*);
  108778. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  108779. char const**,char const**,int*,int*,int*);
  108780. void (*thread_cleanup)(void);
  108781. int (*total_changes)(sqlite3*);
  108782. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  108783. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  108784. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  108785. sqlite_int64),void*);
  108786. void * (*user_data)(sqlite3_context*);
  108787. const void * (*value_blob)(sqlite3_value*);
  108788. int (*value_bytes)(sqlite3_value*);
  108789. int (*value_bytes16)(sqlite3_value*);
  108790. double (*value_double)(sqlite3_value*);
  108791. int (*value_int)(sqlite3_value*);
  108792. sqlite_int64 (*value_int64)(sqlite3_value*);
  108793. int (*value_numeric_type)(sqlite3_value*);
  108794. const unsigned char * (*value_text)(sqlite3_value*);
  108795. const void * (*value_text16)(sqlite3_value*);
  108796. const void * (*value_text16be)(sqlite3_value*);
  108797. const void * (*value_text16le)(sqlite3_value*);
  108798. int (*value_type)(sqlite3_value*);
  108799. char *(*vmprintf)(const char*,va_list);
  108800. /* Added ??? */
  108801. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  108802. /* Added by 3.3.13 */
  108803. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  108804. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  108805. int (*clear_bindings)(sqlite3_stmt*);
  108806. /* Added by 3.4.1 */
  108807. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  108808. void (*xDestroy)(void *));
  108809. /* Added by 3.5.0 */
  108810. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  108811. int (*blob_bytes)(sqlite3_blob*);
  108812. int (*blob_close)(sqlite3_blob*);
  108813. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  108814. int,sqlite3_blob**);
  108815. int (*blob_read)(sqlite3_blob*,void*,int,int);
  108816. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  108817. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  108818. int(*)(void*,int,const void*,int,const void*),
  108819. void(*)(void*));
  108820. int (*file_control)(sqlite3*,const char*,int,void*);
  108821. sqlite3_int64 (*memory_highwater)(int);
  108822. sqlite3_int64 (*memory_used)(void);
  108823. sqlite3_mutex *(*mutex_alloc)(int);
  108824. void (*mutex_enter)(sqlite3_mutex*);
  108825. void (*mutex_free)(sqlite3_mutex*);
  108826. void (*mutex_leave)(sqlite3_mutex*);
  108827. int (*mutex_try)(sqlite3_mutex*);
  108828. int (*open_v2)(const char*,sqlite3**,int,const char*);
  108829. int (*release_memory)(int);
  108830. void (*result_error_nomem)(sqlite3_context*);
  108831. void (*result_error_toobig)(sqlite3_context*);
  108832. int (*sleep)(int);
  108833. void (*soft_heap_limit)(int);
  108834. sqlite3_vfs *(*vfs_find)(const char*);
  108835. int (*vfs_register)(sqlite3_vfs*,int);
  108836. int (*vfs_unregister)(sqlite3_vfs*);
  108837. int (*xthreadsafe)(void);
  108838. void (*result_zeroblob)(sqlite3_context*,int);
  108839. void (*result_error_code)(sqlite3_context*,int);
  108840. int (*test_control)(int, ...);
  108841. void (*randomness)(int,void*);
  108842. sqlite3 *(*context_db_handle)(sqlite3_context*);
  108843. int (*extended_result_codes)(sqlite3*,int);
  108844. int (*limit)(sqlite3*,int,int);
  108845. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  108846. const char *(*sql)(sqlite3_stmt*);
  108847. int (*status)(int,int*,int*,int);
  108848. int (*backup_finish)(sqlite3_backup*);
  108849. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  108850. int (*backup_pagecount)(sqlite3_backup*);
  108851. int (*backup_remaining)(sqlite3_backup*);
  108852. int (*backup_step)(sqlite3_backup*,int);
  108853. const char *(*compileoption_get)(int);
  108854. int (*compileoption_used)(const char*);
  108855. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  108856. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  108857. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  108858. void (*xFinal)(sqlite3_context*),
  108859. void(*xDestroy)(void*));
  108860. int (*db_config)(sqlite3*,int,...);
  108861. sqlite3_mutex *(*db_mutex)(sqlite3*);
  108862. int (*db_status)(sqlite3*,int,int*,int*,int);
  108863. int (*extended_errcode)(sqlite3*);
  108864. void (*log)(int,const char*,...);
  108865. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  108866. const char *(*sourceid)(void);
  108867. int (*stmt_status)(sqlite3_stmt*,int,int);
  108868. int (*strnicmp)(const char*,const char*,int);
  108869. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  108870. int (*wal_autocheckpoint)(sqlite3*,int);
  108871. int (*wal_checkpoint)(sqlite3*,const char*);
  108872. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  108873. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  108874. int (*vtab_config)(sqlite3*,int op,...);
  108875. int (*vtab_on_conflict)(sqlite3*);
  108876. /* Version 3.7.16 and later */
  108877. int (*close_v2)(sqlite3*);
  108878. const char *(*db_filename)(sqlite3*,const char*);
  108879. int (*db_readonly)(sqlite3*,const char*);
  108880. int (*db_release_memory)(sqlite3*);
  108881. const char *(*errstr)(int);
  108882. int (*stmt_busy)(sqlite3_stmt*);
  108883. int (*stmt_readonly)(sqlite3_stmt*);
  108884. int (*stricmp)(const char*,const char*);
  108885. int (*uri_boolean)(const char*,const char*,int);
  108886. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  108887. const char *(*uri_parameter)(const char*,const char*);
  108888. char *(*xvsnprintf)(int,char*,const char*,va_list);
  108889. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  108890. /* Version 3.8.7 and later */
  108891. int (*auto_extension)(void(*)(void));
  108892. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  108893. void(*)(void*));
  108894. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  108895. void(*)(void*),unsigned char);
  108896. int (*cancel_auto_extension)(void(*)(void));
  108897. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  108898. void *(*malloc64)(sqlite3_uint64);
  108899. sqlite3_uint64 (*msize)(void*);
  108900. void *(*realloc64)(void*,sqlite3_uint64);
  108901. void (*reset_auto_extension)(void);
  108902. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  108903. void(*)(void*));
  108904. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  108905. void(*)(void*), unsigned char);
  108906. int (*strglob)(const char*,const char*);
  108907. /* Version 3.8.11 and later */
  108908. sqlite3_value *(*value_dup)(const sqlite3_value*);
  108909. void (*value_free)(sqlite3_value*);
  108910. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  108911. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  108912. /* Version 3.9.0 and later */
  108913. unsigned int (*value_subtype)(sqlite3_value*);
  108914. void (*result_subtype)(sqlite3_context*,unsigned int);
  108915. /* Version 3.10.0 and later */
  108916. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  108917. int (*strlike)(const char*,const char*,unsigned int);
  108918. int (*db_cacheflush)(sqlite3*);
  108919. /* Version 3.12.0 and later */
  108920. int (*system_errno)(sqlite3*);
  108921. /* Version 3.14.0 and later */
  108922. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  108923. char *(*expanded_sql)(sqlite3_stmt*);
  108924. /* Version 3.18.0 and later */
  108925. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  108926. /* Version 3.20.0 and later */
  108927. int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
  108928. sqlite3_stmt**,const char**);
  108929. int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
  108930. sqlite3_stmt**,const void**);
  108931. int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  108932. void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  108933. void *(*value_pointer)(sqlite3_value*,const char*);
  108934. int (*vtab_nochange)(sqlite3_context*);
  108935. int (*value_nochange)(sqlite3_value*);
  108936. const char *(*vtab_collation)(sqlite3_index_info*,int);
  108937. /* Version 3.24.0 and later */
  108938. int (*keyword_count)(void);
  108939. int (*keyword_name)(int,const char**,int*);
  108940. int (*keyword_check)(const char*,int);
  108941. sqlite3_str *(*str_new)(sqlite3*);
  108942. char *(*str_finish)(sqlite3_str*);
  108943. void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
  108944. void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
  108945. void (*str_append)(sqlite3_str*, const char *zIn, int N);
  108946. void (*str_appendall)(sqlite3_str*, const char *zIn);
  108947. void (*str_appendchar)(sqlite3_str*, int N, char C);
  108948. void (*str_reset)(sqlite3_str*);
  108949. int (*str_errcode)(sqlite3_str*);
  108950. int (*str_length)(sqlite3_str*);
  108951. char *(*str_value)(sqlite3_str*);
  108952. };
  108953. /*
  108954. ** This is the function signature used for all extension entry points. It
  108955. ** is also defined in the file "loadext.c".
  108956. */
  108957. typedef int (*sqlite3_loadext_entry)(
  108958. sqlite3 *db, /* Handle to the database. */
  108959. char **pzErrMsg, /* Used to set error string on failure. */
  108960. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  108961. );
  108962. /*
  108963. ** The following macros redefine the API routines so that they are
  108964. ** redirected through the global sqlite3_api structure.
  108965. **
  108966. ** This header file is also used by the loadext.c source file
  108967. ** (part of the main SQLite library - not an extension) so that
  108968. ** it can get access to the sqlite3_api_routines structure
  108969. ** definition. But the main library does not want to redefine
  108970. ** the API. So the redefinition macros are only valid if the
  108971. ** SQLITE_CORE macros is undefined.
  108972. */
  108973. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  108974. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  108975. #ifndef SQLITE_OMIT_DEPRECATED
  108976. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  108977. #endif
  108978. #define sqlite3_bind_blob sqlite3_api->bind_blob
  108979. #define sqlite3_bind_double sqlite3_api->bind_double
  108980. #define sqlite3_bind_int sqlite3_api->bind_int
  108981. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  108982. #define sqlite3_bind_null sqlite3_api->bind_null
  108983. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  108984. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  108985. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  108986. #define sqlite3_bind_text sqlite3_api->bind_text
  108987. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  108988. #define sqlite3_bind_value sqlite3_api->bind_value
  108989. #define sqlite3_busy_handler sqlite3_api->busy_handler
  108990. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  108991. #define sqlite3_changes sqlite3_api->changes
  108992. #define sqlite3_close sqlite3_api->close
  108993. #define sqlite3_collation_needed sqlite3_api->collation_needed
  108994. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  108995. #define sqlite3_column_blob sqlite3_api->column_blob
  108996. #define sqlite3_column_bytes sqlite3_api->column_bytes
  108997. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  108998. #define sqlite3_column_count sqlite3_api->column_count
  108999. #define sqlite3_column_database_name sqlite3_api->column_database_name
  109000. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  109001. #define sqlite3_column_decltype sqlite3_api->column_decltype
  109002. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  109003. #define sqlite3_column_double sqlite3_api->column_double
  109004. #define sqlite3_column_int sqlite3_api->column_int
  109005. #define sqlite3_column_int64 sqlite3_api->column_int64
  109006. #define sqlite3_column_name sqlite3_api->column_name
  109007. #define sqlite3_column_name16 sqlite3_api->column_name16
  109008. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  109009. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  109010. #define sqlite3_column_table_name sqlite3_api->column_table_name
  109011. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  109012. #define sqlite3_column_text sqlite3_api->column_text
  109013. #define sqlite3_column_text16 sqlite3_api->column_text16
  109014. #define sqlite3_column_type sqlite3_api->column_type
  109015. #define sqlite3_column_value sqlite3_api->column_value
  109016. #define sqlite3_commit_hook sqlite3_api->commit_hook
  109017. #define sqlite3_complete sqlite3_api->complete
  109018. #define sqlite3_complete16 sqlite3_api->complete16
  109019. #define sqlite3_create_collation sqlite3_api->create_collation
  109020. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  109021. #define sqlite3_create_function sqlite3_api->create_function
  109022. #define sqlite3_create_function16 sqlite3_api->create_function16
  109023. #define sqlite3_create_module sqlite3_api->create_module
  109024. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  109025. #define sqlite3_data_count sqlite3_api->data_count
  109026. #define sqlite3_db_handle sqlite3_api->db_handle
  109027. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  109028. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  109029. #define sqlite3_errcode sqlite3_api->errcode
  109030. #define sqlite3_errmsg sqlite3_api->errmsg
  109031. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  109032. #define sqlite3_exec sqlite3_api->exec
  109033. #ifndef SQLITE_OMIT_DEPRECATED
  109034. #define sqlite3_expired sqlite3_api->expired
  109035. #endif
  109036. #define sqlite3_finalize sqlite3_api->finalize
  109037. #define sqlite3_free sqlite3_api->free
  109038. #define sqlite3_free_table sqlite3_api->free_table
  109039. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  109040. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  109041. #define sqlite3_get_table sqlite3_api->get_table
  109042. #ifndef SQLITE_OMIT_DEPRECATED
  109043. #define sqlite3_global_recover sqlite3_api->global_recover
  109044. #endif
  109045. #define sqlite3_interrupt sqlite3_api->interruptx
  109046. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  109047. #define sqlite3_libversion sqlite3_api->libversion
  109048. #define sqlite3_libversion_number sqlite3_api->libversion_number
  109049. #define sqlite3_malloc sqlite3_api->malloc
  109050. #define sqlite3_mprintf sqlite3_api->mprintf
  109051. #define sqlite3_open sqlite3_api->open
  109052. #define sqlite3_open16 sqlite3_api->open16
  109053. #define sqlite3_prepare sqlite3_api->prepare
  109054. #define sqlite3_prepare16 sqlite3_api->prepare16
  109055. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  109056. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  109057. #define sqlite3_profile sqlite3_api->profile
  109058. #define sqlite3_progress_handler sqlite3_api->progress_handler
  109059. #define sqlite3_realloc sqlite3_api->realloc
  109060. #define sqlite3_reset sqlite3_api->reset
  109061. #define sqlite3_result_blob sqlite3_api->result_blob
  109062. #define sqlite3_result_double sqlite3_api->result_double
  109063. #define sqlite3_result_error sqlite3_api->result_error
  109064. #define sqlite3_result_error16 sqlite3_api->result_error16
  109065. #define sqlite3_result_int sqlite3_api->result_int
  109066. #define sqlite3_result_int64 sqlite3_api->result_int64
  109067. #define sqlite3_result_null sqlite3_api->result_null
  109068. #define sqlite3_result_text sqlite3_api->result_text
  109069. #define sqlite3_result_text16 sqlite3_api->result_text16
  109070. #define sqlite3_result_text16be sqlite3_api->result_text16be
  109071. #define sqlite3_result_text16le sqlite3_api->result_text16le
  109072. #define sqlite3_result_value sqlite3_api->result_value
  109073. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  109074. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  109075. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  109076. #define sqlite3_snprintf sqlite3_api->xsnprintf
  109077. #define sqlite3_step sqlite3_api->step
  109078. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  109079. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  109080. #define sqlite3_total_changes sqlite3_api->total_changes
  109081. #define sqlite3_trace sqlite3_api->trace
  109082. #ifndef SQLITE_OMIT_DEPRECATED
  109083. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  109084. #endif
  109085. #define sqlite3_update_hook sqlite3_api->update_hook
  109086. #define sqlite3_user_data sqlite3_api->user_data
  109087. #define sqlite3_value_blob sqlite3_api->value_blob
  109088. #define sqlite3_value_bytes sqlite3_api->value_bytes
  109089. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  109090. #define sqlite3_value_double sqlite3_api->value_double
  109091. #define sqlite3_value_int sqlite3_api->value_int
  109092. #define sqlite3_value_int64 sqlite3_api->value_int64
  109093. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  109094. #define sqlite3_value_text sqlite3_api->value_text
  109095. #define sqlite3_value_text16 sqlite3_api->value_text16
  109096. #define sqlite3_value_text16be sqlite3_api->value_text16be
  109097. #define sqlite3_value_text16le sqlite3_api->value_text16le
  109098. #define sqlite3_value_type sqlite3_api->value_type
  109099. #define sqlite3_vmprintf sqlite3_api->vmprintf
  109100. #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
  109101. #define sqlite3_overload_function sqlite3_api->overload_function
  109102. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  109103. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  109104. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  109105. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  109106. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  109107. #define sqlite3_blob_close sqlite3_api->blob_close
  109108. #define sqlite3_blob_open sqlite3_api->blob_open
  109109. #define sqlite3_blob_read sqlite3_api->blob_read
  109110. #define sqlite3_blob_write sqlite3_api->blob_write
  109111. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  109112. #define sqlite3_file_control sqlite3_api->file_control
  109113. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  109114. #define sqlite3_memory_used sqlite3_api->memory_used
  109115. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  109116. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  109117. #define sqlite3_mutex_free sqlite3_api->mutex_free
  109118. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  109119. #define sqlite3_mutex_try sqlite3_api->mutex_try
  109120. #define sqlite3_open_v2 sqlite3_api->open_v2
  109121. #define sqlite3_release_memory sqlite3_api->release_memory
  109122. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  109123. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  109124. #define sqlite3_sleep sqlite3_api->sleep
  109125. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  109126. #define sqlite3_vfs_find sqlite3_api->vfs_find
  109127. #define sqlite3_vfs_register sqlite3_api->vfs_register
  109128. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  109129. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  109130. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  109131. #define sqlite3_result_error_code sqlite3_api->result_error_code
  109132. #define sqlite3_test_control sqlite3_api->test_control
  109133. #define sqlite3_randomness sqlite3_api->randomness
  109134. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  109135. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  109136. #define sqlite3_limit sqlite3_api->limit
  109137. #define sqlite3_next_stmt sqlite3_api->next_stmt
  109138. #define sqlite3_sql sqlite3_api->sql
  109139. #define sqlite3_status sqlite3_api->status
  109140. #define sqlite3_backup_finish sqlite3_api->backup_finish
  109141. #define sqlite3_backup_init sqlite3_api->backup_init
  109142. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  109143. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  109144. #define sqlite3_backup_step sqlite3_api->backup_step
  109145. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  109146. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  109147. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  109148. #define sqlite3_db_config sqlite3_api->db_config
  109149. #define sqlite3_db_mutex sqlite3_api->db_mutex
  109150. #define sqlite3_db_status sqlite3_api->db_status
  109151. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  109152. #define sqlite3_log sqlite3_api->log
  109153. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  109154. #define sqlite3_sourceid sqlite3_api->sourceid
  109155. #define sqlite3_stmt_status sqlite3_api->stmt_status
  109156. #define sqlite3_strnicmp sqlite3_api->strnicmp
  109157. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  109158. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  109159. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  109160. #define sqlite3_wal_hook sqlite3_api->wal_hook
  109161. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  109162. #define sqlite3_vtab_config sqlite3_api->vtab_config
  109163. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  109164. /* Version 3.7.16 and later */
  109165. #define sqlite3_close_v2 sqlite3_api->close_v2
  109166. #define sqlite3_db_filename sqlite3_api->db_filename
  109167. #define sqlite3_db_readonly sqlite3_api->db_readonly
  109168. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  109169. #define sqlite3_errstr sqlite3_api->errstr
  109170. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  109171. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  109172. #define sqlite3_stricmp sqlite3_api->stricmp
  109173. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  109174. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  109175. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  109176. #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
  109177. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  109178. /* Version 3.8.7 and later */
  109179. #define sqlite3_auto_extension sqlite3_api->auto_extension
  109180. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  109181. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  109182. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  109183. #define sqlite3_load_extension sqlite3_api->load_extension
  109184. #define sqlite3_malloc64 sqlite3_api->malloc64
  109185. #define sqlite3_msize sqlite3_api->msize
  109186. #define sqlite3_realloc64 sqlite3_api->realloc64
  109187. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  109188. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  109189. #define sqlite3_result_text64 sqlite3_api->result_text64
  109190. #define sqlite3_strglob sqlite3_api->strglob
  109191. /* Version 3.8.11 and later */
  109192. #define sqlite3_value_dup sqlite3_api->value_dup
  109193. #define sqlite3_value_free sqlite3_api->value_free
  109194. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  109195. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  109196. /* Version 3.9.0 and later */
  109197. #define sqlite3_value_subtype sqlite3_api->value_subtype
  109198. #define sqlite3_result_subtype sqlite3_api->result_subtype
  109199. /* Version 3.10.0 and later */
  109200. #define sqlite3_status64 sqlite3_api->status64
  109201. #define sqlite3_strlike sqlite3_api->strlike
  109202. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  109203. /* Version 3.12.0 and later */
  109204. #define sqlite3_system_errno sqlite3_api->system_errno
  109205. /* Version 3.14.0 and later */
  109206. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  109207. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  109208. /* Version 3.18.0 and later */
  109209. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  109210. /* Version 3.20.0 and later */
  109211. #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
  109212. #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
  109213. #define sqlite3_bind_pointer sqlite3_api->bind_pointer
  109214. #define sqlite3_result_pointer sqlite3_api->result_pointer
  109215. #define sqlite3_value_pointer sqlite3_api->value_pointer
  109216. /* Version 3.22.0 and later */
  109217. #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
  109218. #define sqlite3_value_nochange sqlite3_api->value_nochange
  109219. #define sqlite3_vtab_collation sqlite3_api->vtab_collation
  109220. /* Version 3.24.0 and later */
  109221. #define sqlite3_keyword_count sqlite3_api->keyword_count
  109222. #define sqlite3_keyword_name sqlite3_api->keyword_name
  109223. #define sqlite3_keyword_check sqlite3_api->keyword_check
  109224. #define sqlite3_str_new sqlite3_api->str_new
  109225. #define sqlite3_str_finish sqlite3_api->str_finish
  109226. #define sqlite3_str_appendf sqlite3_api->str_appendf
  109227. #define sqlite3_str_vappendf sqlite3_api->str_vappendf
  109228. #define sqlite3_str_append sqlite3_api->str_append
  109229. #define sqlite3_str_appendall sqlite3_api->str_appendall
  109230. #define sqlite3_str_appendchar sqlite3_api->str_appendchar
  109231. #define sqlite3_str_reset sqlite3_api->str_reset
  109232. #define sqlite3_str_errcode sqlite3_api->str_errcode
  109233. #define sqlite3_str_length sqlite3_api->str_length
  109234. #define sqlite3_str_value sqlite3_api->str_value
  109235. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  109236. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  109237. /* This case when the file really is being compiled as a loadable
  109238. ** extension */
  109239. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  109240. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  109241. # define SQLITE_EXTENSION_INIT3 \
  109242. extern const sqlite3_api_routines *sqlite3_api;
  109243. #else
  109244. /* This case when the file is being statically linked into the
  109245. ** application */
  109246. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  109247. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  109248. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  109249. #endif
  109250. #endif /* SQLITE3EXT_H */
  109251. /************** End of sqlite3ext.h ******************************************/
  109252. /************** Continuing where we left off in loadext.c ********************/
  109253. /* #include "sqliteInt.h" */
  109254. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  109255. /*
  109256. ** Some API routines are omitted when various features are
  109257. ** excluded from a build of SQLite. Substitute a NULL pointer
  109258. ** for any missing APIs.
  109259. */
  109260. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  109261. # define sqlite3_column_database_name 0
  109262. # define sqlite3_column_database_name16 0
  109263. # define sqlite3_column_table_name 0
  109264. # define sqlite3_column_table_name16 0
  109265. # define sqlite3_column_origin_name 0
  109266. # define sqlite3_column_origin_name16 0
  109267. #endif
  109268. #ifdef SQLITE_OMIT_AUTHORIZATION
  109269. # define sqlite3_set_authorizer 0
  109270. #endif
  109271. #ifdef SQLITE_OMIT_UTF16
  109272. # define sqlite3_bind_text16 0
  109273. # define sqlite3_collation_needed16 0
  109274. # define sqlite3_column_decltype16 0
  109275. # define sqlite3_column_name16 0
  109276. # define sqlite3_column_text16 0
  109277. # define sqlite3_complete16 0
  109278. # define sqlite3_create_collation16 0
  109279. # define sqlite3_create_function16 0
  109280. # define sqlite3_errmsg16 0
  109281. # define sqlite3_open16 0
  109282. # define sqlite3_prepare16 0
  109283. # define sqlite3_prepare16_v2 0
  109284. # define sqlite3_prepare16_v3 0
  109285. # define sqlite3_result_error16 0
  109286. # define sqlite3_result_text16 0
  109287. # define sqlite3_result_text16be 0
  109288. # define sqlite3_result_text16le 0
  109289. # define sqlite3_value_text16 0
  109290. # define sqlite3_value_text16be 0
  109291. # define sqlite3_value_text16le 0
  109292. # define sqlite3_column_database_name16 0
  109293. # define sqlite3_column_table_name16 0
  109294. # define sqlite3_column_origin_name16 0
  109295. #endif
  109296. #ifdef SQLITE_OMIT_COMPLETE
  109297. # define sqlite3_complete 0
  109298. # define sqlite3_complete16 0
  109299. #endif
  109300. #ifdef SQLITE_OMIT_DECLTYPE
  109301. # define sqlite3_column_decltype16 0
  109302. # define sqlite3_column_decltype 0
  109303. #endif
  109304. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  109305. # define sqlite3_progress_handler 0
  109306. #endif
  109307. #ifdef SQLITE_OMIT_VIRTUALTABLE
  109308. # define sqlite3_create_module 0
  109309. # define sqlite3_create_module_v2 0
  109310. # define sqlite3_declare_vtab 0
  109311. # define sqlite3_vtab_config 0
  109312. # define sqlite3_vtab_on_conflict 0
  109313. #endif
  109314. #ifdef SQLITE_OMIT_SHARED_CACHE
  109315. # define sqlite3_enable_shared_cache 0
  109316. #endif
  109317. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  109318. # define sqlite3_profile 0
  109319. # define sqlite3_trace 0
  109320. #endif
  109321. #ifdef SQLITE_OMIT_GET_TABLE
  109322. # define sqlite3_free_table 0
  109323. # define sqlite3_get_table 0
  109324. #endif
  109325. #ifdef SQLITE_OMIT_INCRBLOB
  109326. #define sqlite3_bind_zeroblob 0
  109327. #define sqlite3_blob_bytes 0
  109328. #define sqlite3_blob_close 0
  109329. #define sqlite3_blob_open 0
  109330. #define sqlite3_blob_read 0
  109331. #define sqlite3_blob_write 0
  109332. #define sqlite3_blob_reopen 0
  109333. #endif
  109334. #if defined(SQLITE_OMIT_TRACE)
  109335. # define sqlite3_trace_v2 0
  109336. #endif
  109337. /*
  109338. ** The following structure contains pointers to all SQLite API routines.
  109339. ** A pointer to this structure is passed into extensions when they are
  109340. ** loaded so that the extension can make calls back into the SQLite
  109341. ** library.
  109342. **
  109343. ** When adding new APIs, add them to the bottom of this structure
  109344. ** in order to preserve backwards compatibility.
  109345. **
  109346. ** Extensions that use newer APIs should first call the
  109347. ** sqlite3_libversion_number() to make sure that the API they
  109348. ** intend to use is supported by the library. Extensions should
  109349. ** also check to make sure that the pointer to the function is
  109350. ** not NULL before calling it.
  109351. */
  109352. static const sqlite3_api_routines sqlite3Apis = {
  109353. sqlite3_aggregate_context,
  109354. #ifndef SQLITE_OMIT_DEPRECATED
  109355. sqlite3_aggregate_count,
  109356. #else
  109357. 0,
  109358. #endif
  109359. sqlite3_bind_blob,
  109360. sqlite3_bind_double,
  109361. sqlite3_bind_int,
  109362. sqlite3_bind_int64,
  109363. sqlite3_bind_null,
  109364. sqlite3_bind_parameter_count,
  109365. sqlite3_bind_parameter_index,
  109366. sqlite3_bind_parameter_name,
  109367. sqlite3_bind_text,
  109368. sqlite3_bind_text16,
  109369. sqlite3_bind_value,
  109370. sqlite3_busy_handler,
  109371. sqlite3_busy_timeout,
  109372. sqlite3_changes,
  109373. sqlite3_close,
  109374. sqlite3_collation_needed,
  109375. sqlite3_collation_needed16,
  109376. sqlite3_column_blob,
  109377. sqlite3_column_bytes,
  109378. sqlite3_column_bytes16,
  109379. sqlite3_column_count,
  109380. sqlite3_column_database_name,
  109381. sqlite3_column_database_name16,
  109382. sqlite3_column_decltype,
  109383. sqlite3_column_decltype16,
  109384. sqlite3_column_double,
  109385. sqlite3_column_int,
  109386. sqlite3_column_int64,
  109387. sqlite3_column_name,
  109388. sqlite3_column_name16,
  109389. sqlite3_column_origin_name,
  109390. sqlite3_column_origin_name16,
  109391. sqlite3_column_table_name,
  109392. sqlite3_column_table_name16,
  109393. sqlite3_column_text,
  109394. sqlite3_column_text16,
  109395. sqlite3_column_type,
  109396. sqlite3_column_value,
  109397. sqlite3_commit_hook,
  109398. sqlite3_complete,
  109399. sqlite3_complete16,
  109400. sqlite3_create_collation,
  109401. sqlite3_create_collation16,
  109402. sqlite3_create_function,
  109403. sqlite3_create_function16,
  109404. sqlite3_create_module,
  109405. sqlite3_data_count,
  109406. sqlite3_db_handle,
  109407. sqlite3_declare_vtab,
  109408. sqlite3_enable_shared_cache,
  109409. sqlite3_errcode,
  109410. sqlite3_errmsg,
  109411. sqlite3_errmsg16,
  109412. sqlite3_exec,
  109413. #ifndef SQLITE_OMIT_DEPRECATED
  109414. sqlite3_expired,
  109415. #else
  109416. 0,
  109417. #endif
  109418. sqlite3_finalize,
  109419. sqlite3_free,
  109420. sqlite3_free_table,
  109421. sqlite3_get_autocommit,
  109422. sqlite3_get_auxdata,
  109423. sqlite3_get_table,
  109424. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  109425. sqlite3_interrupt,
  109426. sqlite3_last_insert_rowid,
  109427. sqlite3_libversion,
  109428. sqlite3_libversion_number,
  109429. sqlite3_malloc,
  109430. sqlite3_mprintf,
  109431. sqlite3_open,
  109432. sqlite3_open16,
  109433. sqlite3_prepare,
  109434. sqlite3_prepare16,
  109435. sqlite3_profile,
  109436. sqlite3_progress_handler,
  109437. sqlite3_realloc,
  109438. sqlite3_reset,
  109439. sqlite3_result_blob,
  109440. sqlite3_result_double,
  109441. sqlite3_result_error,
  109442. sqlite3_result_error16,
  109443. sqlite3_result_int,
  109444. sqlite3_result_int64,
  109445. sqlite3_result_null,
  109446. sqlite3_result_text,
  109447. sqlite3_result_text16,
  109448. sqlite3_result_text16be,
  109449. sqlite3_result_text16le,
  109450. sqlite3_result_value,
  109451. sqlite3_rollback_hook,
  109452. sqlite3_set_authorizer,
  109453. sqlite3_set_auxdata,
  109454. sqlite3_snprintf,
  109455. sqlite3_step,
  109456. sqlite3_table_column_metadata,
  109457. #ifndef SQLITE_OMIT_DEPRECATED
  109458. sqlite3_thread_cleanup,
  109459. #else
  109460. 0,
  109461. #endif
  109462. sqlite3_total_changes,
  109463. sqlite3_trace,
  109464. #ifndef SQLITE_OMIT_DEPRECATED
  109465. sqlite3_transfer_bindings,
  109466. #else
  109467. 0,
  109468. #endif
  109469. sqlite3_update_hook,
  109470. sqlite3_user_data,
  109471. sqlite3_value_blob,
  109472. sqlite3_value_bytes,
  109473. sqlite3_value_bytes16,
  109474. sqlite3_value_double,
  109475. sqlite3_value_int,
  109476. sqlite3_value_int64,
  109477. sqlite3_value_numeric_type,
  109478. sqlite3_value_text,
  109479. sqlite3_value_text16,
  109480. sqlite3_value_text16be,
  109481. sqlite3_value_text16le,
  109482. sqlite3_value_type,
  109483. sqlite3_vmprintf,
  109484. /*
  109485. ** The original API set ends here. All extensions can call any
  109486. ** of the APIs above provided that the pointer is not NULL. But
  109487. ** before calling APIs that follow, extension should check the
  109488. ** sqlite3_libversion_number() to make sure they are dealing with
  109489. ** a library that is new enough to support that API.
  109490. *************************************************************************
  109491. */
  109492. sqlite3_overload_function,
  109493. /*
  109494. ** Added after 3.3.13
  109495. */
  109496. sqlite3_prepare_v2,
  109497. sqlite3_prepare16_v2,
  109498. sqlite3_clear_bindings,
  109499. /*
  109500. ** Added for 3.4.1
  109501. */
  109502. sqlite3_create_module_v2,
  109503. /*
  109504. ** Added for 3.5.0
  109505. */
  109506. sqlite3_bind_zeroblob,
  109507. sqlite3_blob_bytes,
  109508. sqlite3_blob_close,
  109509. sqlite3_blob_open,
  109510. sqlite3_blob_read,
  109511. sqlite3_blob_write,
  109512. sqlite3_create_collation_v2,
  109513. sqlite3_file_control,
  109514. sqlite3_memory_highwater,
  109515. sqlite3_memory_used,
  109516. #ifdef SQLITE_MUTEX_OMIT
  109517. 0,
  109518. 0,
  109519. 0,
  109520. 0,
  109521. 0,
  109522. #else
  109523. sqlite3_mutex_alloc,
  109524. sqlite3_mutex_enter,
  109525. sqlite3_mutex_free,
  109526. sqlite3_mutex_leave,
  109527. sqlite3_mutex_try,
  109528. #endif
  109529. sqlite3_open_v2,
  109530. sqlite3_release_memory,
  109531. sqlite3_result_error_nomem,
  109532. sqlite3_result_error_toobig,
  109533. sqlite3_sleep,
  109534. sqlite3_soft_heap_limit,
  109535. sqlite3_vfs_find,
  109536. sqlite3_vfs_register,
  109537. sqlite3_vfs_unregister,
  109538. /*
  109539. ** Added for 3.5.8
  109540. */
  109541. sqlite3_threadsafe,
  109542. sqlite3_result_zeroblob,
  109543. sqlite3_result_error_code,
  109544. sqlite3_test_control,
  109545. sqlite3_randomness,
  109546. sqlite3_context_db_handle,
  109547. /*
  109548. ** Added for 3.6.0
  109549. */
  109550. sqlite3_extended_result_codes,
  109551. sqlite3_limit,
  109552. sqlite3_next_stmt,
  109553. sqlite3_sql,
  109554. sqlite3_status,
  109555. /*
  109556. ** Added for 3.7.4
  109557. */
  109558. sqlite3_backup_finish,
  109559. sqlite3_backup_init,
  109560. sqlite3_backup_pagecount,
  109561. sqlite3_backup_remaining,
  109562. sqlite3_backup_step,
  109563. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  109564. sqlite3_compileoption_get,
  109565. sqlite3_compileoption_used,
  109566. #else
  109567. 0,
  109568. 0,
  109569. #endif
  109570. sqlite3_create_function_v2,
  109571. sqlite3_db_config,
  109572. sqlite3_db_mutex,
  109573. sqlite3_db_status,
  109574. sqlite3_extended_errcode,
  109575. sqlite3_log,
  109576. sqlite3_soft_heap_limit64,
  109577. sqlite3_sourceid,
  109578. sqlite3_stmt_status,
  109579. sqlite3_strnicmp,
  109580. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  109581. sqlite3_unlock_notify,
  109582. #else
  109583. 0,
  109584. #endif
  109585. #ifndef SQLITE_OMIT_WAL
  109586. sqlite3_wal_autocheckpoint,
  109587. sqlite3_wal_checkpoint,
  109588. sqlite3_wal_hook,
  109589. #else
  109590. 0,
  109591. 0,
  109592. 0,
  109593. #endif
  109594. sqlite3_blob_reopen,
  109595. sqlite3_vtab_config,
  109596. sqlite3_vtab_on_conflict,
  109597. sqlite3_close_v2,
  109598. sqlite3_db_filename,
  109599. sqlite3_db_readonly,
  109600. sqlite3_db_release_memory,
  109601. sqlite3_errstr,
  109602. sqlite3_stmt_busy,
  109603. sqlite3_stmt_readonly,
  109604. sqlite3_stricmp,
  109605. sqlite3_uri_boolean,
  109606. sqlite3_uri_int64,
  109607. sqlite3_uri_parameter,
  109608. sqlite3_vsnprintf,
  109609. sqlite3_wal_checkpoint_v2,
  109610. /* Version 3.8.7 and later */
  109611. sqlite3_auto_extension,
  109612. sqlite3_bind_blob64,
  109613. sqlite3_bind_text64,
  109614. sqlite3_cancel_auto_extension,
  109615. sqlite3_load_extension,
  109616. sqlite3_malloc64,
  109617. sqlite3_msize,
  109618. sqlite3_realloc64,
  109619. sqlite3_reset_auto_extension,
  109620. sqlite3_result_blob64,
  109621. sqlite3_result_text64,
  109622. sqlite3_strglob,
  109623. /* Version 3.8.11 and later */
  109624. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  109625. sqlite3_value_free,
  109626. sqlite3_result_zeroblob64,
  109627. sqlite3_bind_zeroblob64,
  109628. /* Version 3.9.0 and later */
  109629. sqlite3_value_subtype,
  109630. sqlite3_result_subtype,
  109631. /* Version 3.10.0 and later */
  109632. sqlite3_status64,
  109633. sqlite3_strlike,
  109634. sqlite3_db_cacheflush,
  109635. /* Version 3.12.0 and later */
  109636. sqlite3_system_errno,
  109637. /* Version 3.14.0 and later */
  109638. sqlite3_trace_v2,
  109639. sqlite3_expanded_sql,
  109640. /* Version 3.18.0 and later */
  109641. sqlite3_set_last_insert_rowid,
  109642. /* Version 3.20.0 and later */
  109643. sqlite3_prepare_v3,
  109644. sqlite3_prepare16_v3,
  109645. sqlite3_bind_pointer,
  109646. sqlite3_result_pointer,
  109647. sqlite3_value_pointer,
  109648. /* Version 3.22.0 and later */
  109649. sqlite3_vtab_nochange,
  109650. sqlite3_value_nochange,
  109651. sqlite3_vtab_collation,
  109652. /* Version 3.24.0 and later */
  109653. sqlite3_keyword_count,
  109654. sqlite3_keyword_name,
  109655. sqlite3_keyword_check,
  109656. sqlite3_str_new,
  109657. sqlite3_str_finish,
  109658. sqlite3_str_appendf,
  109659. sqlite3_str_vappendf,
  109660. sqlite3_str_append,
  109661. sqlite3_str_appendall,
  109662. sqlite3_str_appendchar,
  109663. sqlite3_str_reset,
  109664. sqlite3_str_errcode,
  109665. sqlite3_str_length,
  109666. sqlite3_str_value
  109667. };
  109668. /*
  109669. ** Attempt to load an SQLite extension library contained in the file
  109670. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  109671. ** default entry point name (sqlite3_extension_init) is used. Use
  109672. ** of the default name is recommended.
  109673. **
  109674. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  109675. **
  109676. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  109677. ** error message text. The calling function should free this memory
  109678. ** by calling sqlite3DbFree(db, ).
  109679. */
  109680. static int sqlite3LoadExtension(
  109681. sqlite3 *db, /* Load the extension into this database connection */
  109682. const char *zFile, /* Name of the shared library containing extension */
  109683. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  109684. char **pzErrMsg /* Put error message here if not 0 */
  109685. ){
  109686. sqlite3_vfs *pVfs = db->pVfs;
  109687. void *handle;
  109688. sqlite3_loadext_entry xInit;
  109689. char *zErrmsg = 0;
  109690. const char *zEntry;
  109691. char *zAltEntry = 0;
  109692. void **aHandle;
  109693. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  109694. int ii;
  109695. int rc;
  109696. /* Shared library endings to try if zFile cannot be loaded as written */
  109697. static const char *azEndings[] = {
  109698. #if SQLITE_OS_WIN
  109699. "dll"
  109700. #elif defined(__APPLE__)
  109701. "dylib"
  109702. #else
  109703. "so"
  109704. #endif
  109705. };
  109706. if( pzErrMsg ) *pzErrMsg = 0;
  109707. /* Ticket #1863. To avoid a creating security problems for older
  109708. ** applications that relink against newer versions of SQLite, the
  109709. ** ability to run load_extension is turned off by default. One
  109710. ** must call either sqlite3_enable_load_extension(db) or
  109711. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  109712. ** to turn on extension loading.
  109713. */
  109714. if( (db->flags & SQLITE_LoadExtension)==0 ){
  109715. if( pzErrMsg ){
  109716. *pzErrMsg = sqlite3_mprintf("not authorized");
  109717. }
  109718. return SQLITE_ERROR;
  109719. }
  109720. zEntry = zProc ? zProc : "sqlite3_extension_init";
  109721. handle = sqlite3OsDlOpen(pVfs, zFile);
  109722. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  109723. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  109724. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  109725. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  109726. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  109727. sqlite3_free(zAltFile);
  109728. }
  109729. #endif
  109730. if( handle==0 ){
  109731. if( pzErrMsg ){
  109732. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  109733. if( zErrmsg ){
  109734. sqlite3_snprintf(nMsg, zErrmsg,
  109735. "unable to open shared library [%s]", zFile);
  109736. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  109737. }
  109738. }
  109739. return SQLITE_ERROR;
  109740. }
  109741. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  109742. /* If no entry point was specified and the default legacy
  109743. ** entry point name "sqlite3_extension_init" was not found, then
  109744. ** construct an entry point name "sqlite3_X_init" where the X is
  109745. ** replaced by the lowercase value of every ASCII alphabetic
  109746. ** character in the filename after the last "/" upto the first ".",
  109747. ** and eliding the first three characters if they are "lib".
  109748. ** Examples:
  109749. **
  109750. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  109751. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  109752. */
  109753. if( xInit==0 && zProc==0 ){
  109754. int iFile, iEntry, c;
  109755. int ncFile = sqlite3Strlen30(zFile);
  109756. zAltEntry = sqlite3_malloc64(ncFile+30);
  109757. if( zAltEntry==0 ){
  109758. sqlite3OsDlClose(pVfs, handle);
  109759. return SQLITE_NOMEM_BKPT;
  109760. }
  109761. memcpy(zAltEntry, "sqlite3_", 8);
  109762. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  109763. iFile++;
  109764. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  109765. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  109766. if( sqlite3Isalpha(c) ){
  109767. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  109768. }
  109769. }
  109770. memcpy(zAltEntry+iEntry, "_init", 6);
  109771. zEntry = zAltEntry;
  109772. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  109773. }
  109774. if( xInit==0 ){
  109775. if( pzErrMsg ){
  109776. nMsg += sqlite3Strlen30(zEntry);
  109777. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  109778. if( zErrmsg ){
  109779. sqlite3_snprintf(nMsg, zErrmsg,
  109780. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  109781. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  109782. }
  109783. }
  109784. sqlite3OsDlClose(pVfs, handle);
  109785. sqlite3_free(zAltEntry);
  109786. return SQLITE_ERROR;
  109787. }
  109788. sqlite3_free(zAltEntry);
  109789. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  109790. if( rc ){
  109791. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  109792. if( pzErrMsg ){
  109793. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  109794. }
  109795. sqlite3_free(zErrmsg);
  109796. sqlite3OsDlClose(pVfs, handle);
  109797. return SQLITE_ERROR;
  109798. }
  109799. /* Append the new shared library handle to the db->aExtension array. */
  109800. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  109801. if( aHandle==0 ){
  109802. return SQLITE_NOMEM_BKPT;
  109803. }
  109804. if( db->nExtension>0 ){
  109805. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  109806. }
  109807. sqlite3DbFree(db, db->aExtension);
  109808. db->aExtension = aHandle;
  109809. db->aExtension[db->nExtension++] = handle;
  109810. return SQLITE_OK;
  109811. }
  109812. SQLITE_API int sqlite3_load_extension(
  109813. sqlite3 *db, /* Load the extension into this database connection */
  109814. const char *zFile, /* Name of the shared library containing extension */
  109815. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  109816. char **pzErrMsg /* Put error message here if not 0 */
  109817. ){
  109818. int rc;
  109819. sqlite3_mutex_enter(db->mutex);
  109820. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  109821. rc = sqlite3ApiExit(db, rc);
  109822. sqlite3_mutex_leave(db->mutex);
  109823. return rc;
  109824. }
  109825. /*
  109826. ** Call this routine when the database connection is closing in order
  109827. ** to clean up loaded extensions
  109828. */
  109829. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  109830. int i;
  109831. assert( sqlite3_mutex_held(db->mutex) );
  109832. for(i=0; i<db->nExtension; i++){
  109833. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  109834. }
  109835. sqlite3DbFree(db, db->aExtension);
  109836. }
  109837. /*
  109838. ** Enable or disable extension loading. Extension loading is disabled by
  109839. ** default so as not to open security holes in older applications.
  109840. */
  109841. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  109842. sqlite3_mutex_enter(db->mutex);
  109843. if( onoff ){
  109844. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  109845. }else{
  109846. db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  109847. }
  109848. sqlite3_mutex_leave(db->mutex);
  109849. return SQLITE_OK;
  109850. }
  109851. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  109852. /*
  109853. ** The following object holds the list of automatically loaded
  109854. ** extensions.
  109855. **
  109856. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  109857. ** mutex must be held while accessing this list.
  109858. */
  109859. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  109860. static SQLITE_WSD struct sqlite3AutoExtList {
  109861. u32 nExt; /* Number of entries in aExt[] */
  109862. void (**aExt)(void); /* Pointers to the extension init functions */
  109863. } sqlite3Autoext = { 0, 0 };
  109864. /* The "wsdAutoext" macro will resolve to the autoextension
  109865. ** state vector. If writable static data is unsupported on the target,
  109866. ** we have to locate the state vector at run-time. In the more common
  109867. ** case where writable static data is supported, wsdStat can refer directly
  109868. ** to the "sqlite3Autoext" state vector declared above.
  109869. */
  109870. #ifdef SQLITE_OMIT_WSD
  109871. # define wsdAutoextInit \
  109872. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  109873. # define wsdAutoext x[0]
  109874. #else
  109875. # define wsdAutoextInit
  109876. # define wsdAutoext sqlite3Autoext
  109877. #endif
  109878. /*
  109879. ** Register a statically linked extension that is automatically
  109880. ** loaded by every new database connection.
  109881. */
  109882. SQLITE_API int sqlite3_auto_extension(
  109883. void (*xInit)(void)
  109884. ){
  109885. int rc = SQLITE_OK;
  109886. #ifndef SQLITE_OMIT_AUTOINIT
  109887. rc = sqlite3_initialize();
  109888. if( rc ){
  109889. return rc;
  109890. }else
  109891. #endif
  109892. {
  109893. u32 i;
  109894. #if SQLITE_THREADSAFE
  109895. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  109896. #endif
  109897. wsdAutoextInit;
  109898. sqlite3_mutex_enter(mutex);
  109899. for(i=0; i<wsdAutoext.nExt; i++){
  109900. if( wsdAutoext.aExt[i]==xInit ) break;
  109901. }
  109902. if( i==wsdAutoext.nExt ){
  109903. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  109904. void (**aNew)(void);
  109905. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  109906. if( aNew==0 ){
  109907. rc = SQLITE_NOMEM_BKPT;
  109908. }else{
  109909. wsdAutoext.aExt = aNew;
  109910. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  109911. wsdAutoext.nExt++;
  109912. }
  109913. }
  109914. sqlite3_mutex_leave(mutex);
  109915. assert( (rc&0xff)==rc );
  109916. return rc;
  109917. }
  109918. }
  109919. /*
  109920. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  109921. ** set of routines that is invoked for each new database connection, if it
  109922. ** is currently on the list. If xInit is not on the list, then this
  109923. ** routine is a no-op.
  109924. **
  109925. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  109926. ** was not on the list.
  109927. */
  109928. SQLITE_API int sqlite3_cancel_auto_extension(
  109929. void (*xInit)(void)
  109930. ){
  109931. #if SQLITE_THREADSAFE
  109932. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  109933. #endif
  109934. int i;
  109935. int n = 0;
  109936. wsdAutoextInit;
  109937. sqlite3_mutex_enter(mutex);
  109938. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  109939. if( wsdAutoext.aExt[i]==xInit ){
  109940. wsdAutoext.nExt--;
  109941. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  109942. n++;
  109943. break;
  109944. }
  109945. }
  109946. sqlite3_mutex_leave(mutex);
  109947. return n;
  109948. }
  109949. /*
  109950. ** Reset the automatic extension loading mechanism.
  109951. */
  109952. SQLITE_API void sqlite3_reset_auto_extension(void){
  109953. #ifndef SQLITE_OMIT_AUTOINIT
  109954. if( sqlite3_initialize()==SQLITE_OK )
  109955. #endif
  109956. {
  109957. #if SQLITE_THREADSAFE
  109958. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  109959. #endif
  109960. wsdAutoextInit;
  109961. sqlite3_mutex_enter(mutex);
  109962. sqlite3_free(wsdAutoext.aExt);
  109963. wsdAutoext.aExt = 0;
  109964. wsdAutoext.nExt = 0;
  109965. sqlite3_mutex_leave(mutex);
  109966. }
  109967. }
  109968. /*
  109969. ** Load all automatic extensions.
  109970. **
  109971. ** If anything goes wrong, set an error in the database connection.
  109972. */
  109973. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  109974. u32 i;
  109975. int go = 1;
  109976. int rc;
  109977. sqlite3_loadext_entry xInit;
  109978. wsdAutoextInit;
  109979. if( wsdAutoext.nExt==0 ){
  109980. /* Common case: early out without every having to acquire a mutex */
  109981. return;
  109982. }
  109983. for(i=0; go; i++){
  109984. char *zErrmsg;
  109985. #if SQLITE_THREADSAFE
  109986. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  109987. #endif
  109988. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  109989. const sqlite3_api_routines *pThunk = 0;
  109990. #else
  109991. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  109992. #endif
  109993. sqlite3_mutex_enter(mutex);
  109994. if( i>=wsdAutoext.nExt ){
  109995. xInit = 0;
  109996. go = 0;
  109997. }else{
  109998. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  109999. }
  110000. sqlite3_mutex_leave(mutex);
  110001. zErrmsg = 0;
  110002. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  110003. sqlite3ErrorWithMsg(db, rc,
  110004. "automatic extension loading failed: %s", zErrmsg);
  110005. go = 0;
  110006. }
  110007. sqlite3_free(zErrmsg);
  110008. }
  110009. }
  110010. /************** End of loadext.c *********************************************/
  110011. /************** Begin file pragma.c ******************************************/
  110012. /*
  110013. ** 2003 April 6
  110014. **
  110015. ** The author disclaims copyright to this source code. In place of
  110016. ** a legal notice, here is a blessing:
  110017. **
  110018. ** May you do good and not evil.
  110019. ** May you find forgiveness for yourself and forgive others.
  110020. ** May you share freely, never taking more than you give.
  110021. **
  110022. *************************************************************************
  110023. ** This file contains code used to implement the PRAGMA command.
  110024. */
  110025. /* #include "sqliteInt.h" */
  110026. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  110027. # if defined(__APPLE__)
  110028. # define SQLITE_ENABLE_LOCKING_STYLE 1
  110029. # else
  110030. # define SQLITE_ENABLE_LOCKING_STYLE 0
  110031. # endif
  110032. #endif
  110033. /***************************************************************************
  110034. ** The "pragma.h" include file is an automatically generated file that
  110035. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  110036. ** object. This ensures that the aPragmaName[] table is arranged in
  110037. ** lexicographical order to facility a binary search of the pragma name.
  110038. ** Do not edit pragma.h directly. Edit and rerun the script in at
  110039. ** ../tool/mkpragmatab.tcl. */
  110040. /************** Include pragma.h in the middle of pragma.c *******************/
  110041. /************** Begin file pragma.h ******************************************/
  110042. /* DO NOT EDIT!
  110043. ** This file is automatically generated by the script at
  110044. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  110045. ** that script and rerun it.
  110046. */
  110047. /* The various pragma types */
  110048. #define PragTyp_HEADER_VALUE 0
  110049. #define PragTyp_AUTO_VACUUM 1
  110050. #define PragTyp_FLAG 2
  110051. #define PragTyp_BUSY_TIMEOUT 3
  110052. #define PragTyp_CACHE_SIZE 4
  110053. #define PragTyp_CACHE_SPILL 5
  110054. #define PragTyp_CASE_SENSITIVE_LIKE 6
  110055. #define PragTyp_COLLATION_LIST 7
  110056. #define PragTyp_COMPILE_OPTIONS 8
  110057. #define PragTyp_DATA_STORE_DIRECTORY 9
  110058. #define PragTyp_DATABASE_LIST 10
  110059. #define PragTyp_DEFAULT_CACHE_SIZE 11
  110060. #define PragTyp_ENCODING 12
  110061. #define PragTyp_FOREIGN_KEY_CHECK 13
  110062. #define PragTyp_FOREIGN_KEY_LIST 14
  110063. #define PragTyp_FUNCTION_LIST 15
  110064. #define PragTyp_INCREMENTAL_VACUUM 16
  110065. #define PragTyp_INDEX_INFO 17
  110066. #define PragTyp_INDEX_LIST 18
  110067. #define PragTyp_INTEGRITY_CHECK 19
  110068. #define PragTyp_JOURNAL_MODE 20
  110069. #define PragTyp_JOURNAL_SIZE_LIMIT 21
  110070. #define PragTyp_LOCK_PROXY_FILE 22
  110071. #define PragTyp_LOCKING_MODE 23
  110072. #define PragTyp_PAGE_COUNT 24
  110073. #define PragTyp_MMAP_SIZE 25
  110074. #define PragTyp_MODULE_LIST 26
  110075. #define PragTyp_OPTIMIZE 27
  110076. #define PragTyp_PAGE_SIZE 28
  110077. #define PragTyp_PRAGMA_LIST 29
  110078. #define PragTyp_SECURE_DELETE 30
  110079. #define PragTyp_SHRINK_MEMORY 31
  110080. #define PragTyp_SOFT_HEAP_LIMIT 32
  110081. #define PragTyp_SYNCHRONOUS 33
  110082. #define PragTyp_TABLE_INFO 34
  110083. #define PragTyp_TEMP_STORE 35
  110084. #define PragTyp_TEMP_STORE_DIRECTORY 36
  110085. #define PragTyp_THREADS 37
  110086. #define PragTyp_WAL_AUTOCHECKPOINT 38
  110087. #define PragTyp_WAL_CHECKPOINT 39
  110088. #define PragTyp_ACTIVATE_EXTENSIONS 40
  110089. #define PragTyp_HEXKEY 41
  110090. #define PragTyp_KEY 42
  110091. #define PragTyp_REKEY 43
  110092. #define PragTyp_LOCK_STATUS 44
  110093. #define PragTyp_PARSER_TRACE 45
  110094. #define PragTyp_STATS 46
  110095. /* Property flags associated with various pragma. */
  110096. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  110097. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  110098. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  110099. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  110100. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  110101. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  110102. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  110103. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  110104. /* Names of columns for pragmas that return multi-column result
  110105. ** or that return single-column results where the name of the
  110106. ** result column is different from the name of the pragma
  110107. */
  110108. static const char *const pragCName[] = {
  110109. /* 0 */ "cache_size", /* Used by: default_cache_size */
  110110. /* 1 */ "cid", /* Used by: table_info */
  110111. /* 2 */ "name",
  110112. /* 3 */ "type",
  110113. /* 4 */ "notnull",
  110114. /* 5 */ "dflt_value",
  110115. /* 6 */ "pk",
  110116. /* 7 */ "tbl", /* Used by: stats */
  110117. /* 8 */ "idx",
  110118. /* 9 */ "wdth",
  110119. /* 10 */ "hght",
  110120. /* 11 */ "flgs",
  110121. /* 12 */ "seqno", /* Used by: index_info */
  110122. /* 13 */ "cid",
  110123. /* 14 */ "name",
  110124. /* 15 */ "seqno", /* Used by: index_xinfo */
  110125. /* 16 */ "cid",
  110126. /* 17 */ "name",
  110127. /* 18 */ "desc",
  110128. /* 19 */ "coll",
  110129. /* 20 */ "key",
  110130. /* 21 */ "seq", /* Used by: index_list */
  110131. /* 22 */ "name",
  110132. /* 23 */ "unique",
  110133. /* 24 */ "origin",
  110134. /* 25 */ "partial",
  110135. /* 26 */ "seq", /* Used by: database_list */
  110136. /* 27 */ "name",
  110137. /* 28 */ "file",
  110138. /* 29 */ "name", /* Used by: function_list */
  110139. /* 30 */ "builtin",
  110140. /* 31 */ "name", /* Used by: module_list pragma_list */
  110141. /* 32 */ "seq", /* Used by: collation_list */
  110142. /* 33 */ "name",
  110143. /* 34 */ "id", /* Used by: foreign_key_list */
  110144. /* 35 */ "seq",
  110145. /* 36 */ "table",
  110146. /* 37 */ "from",
  110147. /* 38 */ "to",
  110148. /* 39 */ "on_update",
  110149. /* 40 */ "on_delete",
  110150. /* 41 */ "match",
  110151. /* 42 */ "table", /* Used by: foreign_key_check */
  110152. /* 43 */ "rowid",
  110153. /* 44 */ "parent",
  110154. /* 45 */ "fkid",
  110155. /* 46 */ "busy", /* Used by: wal_checkpoint */
  110156. /* 47 */ "log",
  110157. /* 48 */ "checkpointed",
  110158. /* 49 */ "timeout", /* Used by: busy_timeout */
  110159. /* 50 */ "database", /* Used by: lock_status */
  110160. /* 51 */ "status",
  110161. };
  110162. /* Definitions of all built-in pragmas */
  110163. typedef struct PragmaName {
  110164. const char *const zName; /* Name of pragma */
  110165. u8 ePragTyp; /* PragTyp_XXX value */
  110166. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  110167. u8 iPragCName; /* Start of column names in pragCName[] */
  110168. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  110169. u32 iArg; /* Extra argument */
  110170. } PragmaName;
  110171. static const PragmaName aPragmaName[] = {
  110172. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  110173. {/* zName: */ "activate_extensions",
  110174. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  110175. /* ePragFlg: */ 0,
  110176. /* ColNames: */ 0, 0,
  110177. /* iArg: */ 0 },
  110178. #endif
  110179. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  110180. {/* zName: */ "application_id",
  110181. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  110182. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  110183. /* ColNames: */ 0, 0,
  110184. /* iArg: */ BTREE_APPLICATION_ID },
  110185. #endif
  110186. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  110187. {/* zName: */ "auto_vacuum",
  110188. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  110189. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  110190. /* ColNames: */ 0, 0,
  110191. /* iArg: */ 0 },
  110192. #endif
  110193. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110194. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  110195. {/* zName: */ "automatic_index",
  110196. /* ePragTyp: */ PragTyp_FLAG,
  110197. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110198. /* ColNames: */ 0, 0,
  110199. /* iArg: */ SQLITE_AutoIndex },
  110200. #endif
  110201. #endif
  110202. {/* zName: */ "busy_timeout",
  110203. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  110204. /* ePragFlg: */ PragFlg_Result0,
  110205. /* ColNames: */ 49, 1,
  110206. /* iArg: */ 0 },
  110207. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110208. {/* zName: */ "cache_size",
  110209. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  110210. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  110211. /* ColNames: */ 0, 0,
  110212. /* iArg: */ 0 },
  110213. #endif
  110214. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110215. {/* zName: */ "cache_spill",
  110216. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  110217. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  110218. /* ColNames: */ 0, 0,
  110219. /* iArg: */ 0 },
  110220. #endif
  110221. {/* zName: */ "case_sensitive_like",
  110222. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  110223. /* ePragFlg: */ PragFlg_NoColumns,
  110224. /* ColNames: */ 0, 0,
  110225. /* iArg: */ 0 },
  110226. {/* zName: */ "cell_size_check",
  110227. /* ePragTyp: */ PragTyp_FLAG,
  110228. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110229. /* ColNames: */ 0, 0,
  110230. /* iArg: */ SQLITE_CellSizeCk },
  110231. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110232. {/* zName: */ "checkpoint_fullfsync",
  110233. /* ePragTyp: */ PragTyp_FLAG,
  110234. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110235. /* ColNames: */ 0, 0,
  110236. /* iArg: */ SQLITE_CkptFullFSync },
  110237. #endif
  110238. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  110239. {/* zName: */ "collation_list",
  110240. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  110241. /* ePragFlg: */ PragFlg_Result0,
  110242. /* ColNames: */ 32, 2,
  110243. /* iArg: */ 0 },
  110244. #endif
  110245. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  110246. {/* zName: */ "compile_options",
  110247. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  110248. /* ePragFlg: */ PragFlg_Result0,
  110249. /* ColNames: */ 0, 0,
  110250. /* iArg: */ 0 },
  110251. #endif
  110252. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110253. {/* zName: */ "count_changes",
  110254. /* ePragTyp: */ PragTyp_FLAG,
  110255. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110256. /* ColNames: */ 0, 0,
  110257. /* iArg: */ SQLITE_CountRows },
  110258. #endif
  110259. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  110260. {/* zName: */ "data_store_directory",
  110261. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  110262. /* ePragFlg: */ PragFlg_NoColumns1,
  110263. /* ColNames: */ 0, 0,
  110264. /* iArg: */ 0 },
  110265. #endif
  110266. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  110267. {/* zName: */ "data_version",
  110268. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  110269. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  110270. /* ColNames: */ 0, 0,
  110271. /* iArg: */ BTREE_DATA_VERSION },
  110272. #endif
  110273. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  110274. {/* zName: */ "database_list",
  110275. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  110276. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  110277. /* ColNames: */ 26, 3,
  110278. /* iArg: */ 0 },
  110279. #endif
  110280. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  110281. {/* zName: */ "default_cache_size",
  110282. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  110283. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  110284. /* ColNames: */ 0, 1,
  110285. /* iArg: */ 0 },
  110286. #endif
  110287. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110288. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  110289. {/* zName: */ "defer_foreign_keys",
  110290. /* ePragTyp: */ PragTyp_FLAG,
  110291. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110292. /* ColNames: */ 0, 0,
  110293. /* iArg: */ SQLITE_DeferFKs },
  110294. #endif
  110295. #endif
  110296. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110297. {/* zName: */ "empty_result_callbacks",
  110298. /* ePragTyp: */ PragTyp_FLAG,
  110299. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110300. /* ColNames: */ 0, 0,
  110301. /* iArg: */ SQLITE_NullCallback },
  110302. #endif
  110303. #if !defined(SQLITE_OMIT_UTF16)
  110304. {/* zName: */ "encoding",
  110305. /* ePragTyp: */ PragTyp_ENCODING,
  110306. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110307. /* ColNames: */ 0, 0,
  110308. /* iArg: */ 0 },
  110309. #endif
  110310. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  110311. {/* zName: */ "foreign_key_check",
  110312. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  110313. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  110314. /* ColNames: */ 42, 4,
  110315. /* iArg: */ 0 },
  110316. #endif
  110317. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  110318. {/* zName: */ "foreign_key_list",
  110319. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  110320. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  110321. /* ColNames: */ 34, 8,
  110322. /* iArg: */ 0 },
  110323. #endif
  110324. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110325. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  110326. {/* zName: */ "foreign_keys",
  110327. /* ePragTyp: */ PragTyp_FLAG,
  110328. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110329. /* ColNames: */ 0, 0,
  110330. /* iArg: */ SQLITE_ForeignKeys },
  110331. #endif
  110332. #endif
  110333. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  110334. {/* zName: */ "freelist_count",
  110335. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  110336. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  110337. /* ColNames: */ 0, 0,
  110338. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  110339. #endif
  110340. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110341. {/* zName: */ "full_column_names",
  110342. /* ePragTyp: */ PragTyp_FLAG,
  110343. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110344. /* ColNames: */ 0, 0,
  110345. /* iArg: */ SQLITE_FullColNames },
  110346. {/* zName: */ "fullfsync",
  110347. /* ePragTyp: */ PragTyp_FLAG,
  110348. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110349. /* ColNames: */ 0, 0,
  110350. /* iArg: */ SQLITE_FullFSync },
  110351. #endif
  110352. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  110353. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  110354. {/* zName: */ "function_list",
  110355. /* ePragTyp: */ PragTyp_FUNCTION_LIST,
  110356. /* ePragFlg: */ PragFlg_Result0,
  110357. /* ColNames: */ 29, 2,
  110358. /* iArg: */ 0 },
  110359. #endif
  110360. #endif
  110361. #if defined(SQLITE_HAS_CODEC)
  110362. {/* zName: */ "hexkey",
  110363. /* ePragTyp: */ PragTyp_HEXKEY,
  110364. /* ePragFlg: */ 0,
  110365. /* ColNames: */ 0, 0,
  110366. /* iArg: */ 0 },
  110367. {/* zName: */ "hexrekey",
  110368. /* ePragTyp: */ PragTyp_HEXKEY,
  110369. /* ePragFlg: */ 0,
  110370. /* ColNames: */ 0, 0,
  110371. /* iArg: */ 0 },
  110372. #endif
  110373. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110374. #if !defined(SQLITE_OMIT_CHECK)
  110375. {/* zName: */ "ignore_check_constraints",
  110376. /* ePragTyp: */ PragTyp_FLAG,
  110377. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110378. /* ColNames: */ 0, 0,
  110379. /* iArg: */ SQLITE_IgnoreChecks },
  110380. #endif
  110381. #endif
  110382. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  110383. {/* zName: */ "incremental_vacuum",
  110384. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  110385. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  110386. /* ColNames: */ 0, 0,
  110387. /* iArg: */ 0 },
  110388. #endif
  110389. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  110390. {/* zName: */ "index_info",
  110391. /* ePragTyp: */ PragTyp_INDEX_INFO,
  110392. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  110393. /* ColNames: */ 12, 3,
  110394. /* iArg: */ 0 },
  110395. {/* zName: */ "index_list",
  110396. /* ePragTyp: */ PragTyp_INDEX_LIST,
  110397. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  110398. /* ColNames: */ 21, 5,
  110399. /* iArg: */ 0 },
  110400. {/* zName: */ "index_xinfo",
  110401. /* ePragTyp: */ PragTyp_INDEX_INFO,
  110402. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  110403. /* ColNames: */ 15, 6,
  110404. /* iArg: */ 1 },
  110405. #endif
  110406. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  110407. {/* zName: */ "integrity_check",
  110408. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  110409. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  110410. /* ColNames: */ 0, 0,
  110411. /* iArg: */ 0 },
  110412. #endif
  110413. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110414. {/* zName: */ "journal_mode",
  110415. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  110416. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  110417. /* ColNames: */ 0, 0,
  110418. /* iArg: */ 0 },
  110419. {/* zName: */ "journal_size_limit",
  110420. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  110421. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  110422. /* ColNames: */ 0, 0,
  110423. /* iArg: */ 0 },
  110424. #endif
  110425. #if defined(SQLITE_HAS_CODEC)
  110426. {/* zName: */ "key",
  110427. /* ePragTyp: */ PragTyp_KEY,
  110428. /* ePragFlg: */ 0,
  110429. /* ColNames: */ 0, 0,
  110430. /* iArg: */ 0 },
  110431. #endif
  110432. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110433. {/* zName: */ "legacy_file_format",
  110434. /* ePragTyp: */ PragTyp_FLAG,
  110435. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110436. /* ColNames: */ 0, 0,
  110437. /* iArg: */ SQLITE_LegacyFileFmt },
  110438. #endif
  110439. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  110440. {/* zName: */ "lock_proxy_file",
  110441. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  110442. /* ePragFlg: */ PragFlg_NoColumns1,
  110443. /* ColNames: */ 0, 0,
  110444. /* iArg: */ 0 },
  110445. #endif
  110446. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  110447. {/* zName: */ "lock_status",
  110448. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  110449. /* ePragFlg: */ PragFlg_Result0,
  110450. /* ColNames: */ 50, 2,
  110451. /* iArg: */ 0 },
  110452. #endif
  110453. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110454. {/* zName: */ "locking_mode",
  110455. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  110456. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  110457. /* ColNames: */ 0, 0,
  110458. /* iArg: */ 0 },
  110459. {/* zName: */ "max_page_count",
  110460. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  110461. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  110462. /* ColNames: */ 0, 0,
  110463. /* iArg: */ 0 },
  110464. {/* zName: */ "mmap_size",
  110465. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  110466. /* ePragFlg: */ 0,
  110467. /* ColNames: */ 0, 0,
  110468. /* iArg: */ 0 },
  110469. #endif
  110470. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  110471. #if !defined(SQLITE_OMIT_VIRTUALTABLE)
  110472. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  110473. {/* zName: */ "module_list",
  110474. /* ePragTyp: */ PragTyp_MODULE_LIST,
  110475. /* ePragFlg: */ PragFlg_Result0,
  110476. /* ColNames: */ 31, 1,
  110477. /* iArg: */ 0 },
  110478. #endif
  110479. #endif
  110480. #endif
  110481. {/* zName: */ "optimize",
  110482. /* ePragTyp: */ PragTyp_OPTIMIZE,
  110483. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  110484. /* ColNames: */ 0, 0,
  110485. /* iArg: */ 0 },
  110486. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110487. {/* zName: */ "page_count",
  110488. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  110489. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  110490. /* ColNames: */ 0, 0,
  110491. /* iArg: */ 0 },
  110492. {/* zName: */ "page_size",
  110493. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  110494. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  110495. /* ColNames: */ 0, 0,
  110496. /* iArg: */ 0 },
  110497. #endif
  110498. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  110499. {/* zName: */ "parser_trace",
  110500. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  110501. /* ePragFlg: */ 0,
  110502. /* ColNames: */ 0, 0,
  110503. /* iArg: */ 0 },
  110504. #endif
  110505. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  110506. {/* zName: */ "pragma_list",
  110507. /* ePragTyp: */ PragTyp_PRAGMA_LIST,
  110508. /* ePragFlg: */ PragFlg_Result0,
  110509. /* ColNames: */ 31, 1,
  110510. /* iArg: */ 0 },
  110511. #endif
  110512. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110513. {/* zName: */ "query_only",
  110514. /* ePragTyp: */ PragTyp_FLAG,
  110515. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110516. /* ColNames: */ 0, 0,
  110517. /* iArg: */ SQLITE_QueryOnly },
  110518. #endif
  110519. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  110520. {/* zName: */ "quick_check",
  110521. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  110522. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  110523. /* ColNames: */ 0, 0,
  110524. /* iArg: */ 0 },
  110525. #endif
  110526. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110527. {/* zName: */ "read_uncommitted",
  110528. /* ePragTyp: */ PragTyp_FLAG,
  110529. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110530. /* ColNames: */ 0, 0,
  110531. /* iArg: */ SQLITE_ReadUncommit },
  110532. {/* zName: */ "recursive_triggers",
  110533. /* ePragTyp: */ PragTyp_FLAG,
  110534. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110535. /* ColNames: */ 0, 0,
  110536. /* iArg: */ SQLITE_RecTriggers },
  110537. #endif
  110538. #if defined(SQLITE_HAS_CODEC)
  110539. {/* zName: */ "rekey",
  110540. /* ePragTyp: */ PragTyp_REKEY,
  110541. /* ePragFlg: */ 0,
  110542. /* ColNames: */ 0, 0,
  110543. /* iArg: */ 0 },
  110544. #endif
  110545. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110546. {/* zName: */ "reverse_unordered_selects",
  110547. /* ePragTyp: */ PragTyp_FLAG,
  110548. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110549. /* ColNames: */ 0, 0,
  110550. /* iArg: */ SQLITE_ReverseOrder },
  110551. #endif
  110552. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  110553. {/* zName: */ "schema_version",
  110554. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  110555. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  110556. /* ColNames: */ 0, 0,
  110557. /* iArg: */ BTREE_SCHEMA_VERSION },
  110558. #endif
  110559. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110560. {/* zName: */ "secure_delete",
  110561. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  110562. /* ePragFlg: */ PragFlg_Result0,
  110563. /* ColNames: */ 0, 0,
  110564. /* iArg: */ 0 },
  110565. #endif
  110566. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110567. {/* zName: */ "short_column_names",
  110568. /* ePragTyp: */ PragTyp_FLAG,
  110569. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110570. /* ColNames: */ 0, 0,
  110571. /* iArg: */ SQLITE_ShortColNames },
  110572. #endif
  110573. {/* zName: */ "shrink_memory",
  110574. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  110575. /* ePragFlg: */ PragFlg_NoColumns,
  110576. /* ColNames: */ 0, 0,
  110577. /* iArg: */ 0 },
  110578. {/* zName: */ "soft_heap_limit",
  110579. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  110580. /* ePragFlg: */ PragFlg_Result0,
  110581. /* ColNames: */ 0, 0,
  110582. /* iArg: */ 0 },
  110583. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110584. #if defined(SQLITE_DEBUG)
  110585. {/* zName: */ "sql_trace",
  110586. /* ePragTyp: */ PragTyp_FLAG,
  110587. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110588. /* ColNames: */ 0, 0,
  110589. /* iArg: */ SQLITE_SqlTrace },
  110590. #endif
  110591. #endif
  110592. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  110593. {/* zName: */ "stats",
  110594. /* ePragTyp: */ PragTyp_STATS,
  110595. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  110596. /* ColNames: */ 7, 5,
  110597. /* iArg: */ 0 },
  110598. #endif
  110599. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110600. {/* zName: */ "synchronous",
  110601. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  110602. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  110603. /* ColNames: */ 0, 0,
  110604. /* iArg: */ 0 },
  110605. #endif
  110606. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  110607. {/* zName: */ "table_info",
  110608. /* ePragTyp: */ PragTyp_TABLE_INFO,
  110609. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  110610. /* ColNames: */ 1, 6,
  110611. /* iArg: */ 0 },
  110612. #endif
  110613. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110614. {/* zName: */ "temp_store",
  110615. /* ePragTyp: */ PragTyp_TEMP_STORE,
  110616. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110617. /* ColNames: */ 0, 0,
  110618. /* iArg: */ 0 },
  110619. {/* zName: */ "temp_store_directory",
  110620. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  110621. /* ePragFlg: */ PragFlg_NoColumns1,
  110622. /* ColNames: */ 0, 0,
  110623. /* iArg: */ 0 },
  110624. #endif
  110625. {/* zName: */ "threads",
  110626. /* ePragTyp: */ PragTyp_THREADS,
  110627. /* ePragFlg: */ PragFlg_Result0,
  110628. /* ColNames: */ 0, 0,
  110629. /* iArg: */ 0 },
  110630. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  110631. {/* zName: */ "user_version",
  110632. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  110633. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  110634. /* ColNames: */ 0, 0,
  110635. /* iArg: */ BTREE_USER_VERSION },
  110636. #endif
  110637. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110638. #if defined(SQLITE_DEBUG)
  110639. {/* zName: */ "vdbe_addoptrace",
  110640. /* ePragTyp: */ PragTyp_FLAG,
  110641. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110642. /* ColNames: */ 0, 0,
  110643. /* iArg: */ SQLITE_VdbeAddopTrace },
  110644. {/* zName: */ "vdbe_debug",
  110645. /* ePragTyp: */ PragTyp_FLAG,
  110646. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110647. /* ColNames: */ 0, 0,
  110648. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  110649. {/* zName: */ "vdbe_eqp",
  110650. /* ePragTyp: */ PragTyp_FLAG,
  110651. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110652. /* ColNames: */ 0, 0,
  110653. /* iArg: */ SQLITE_VdbeEQP },
  110654. {/* zName: */ "vdbe_listing",
  110655. /* ePragTyp: */ PragTyp_FLAG,
  110656. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110657. /* ColNames: */ 0, 0,
  110658. /* iArg: */ SQLITE_VdbeListing },
  110659. {/* zName: */ "vdbe_trace",
  110660. /* ePragTyp: */ PragTyp_FLAG,
  110661. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110662. /* ColNames: */ 0, 0,
  110663. /* iArg: */ SQLITE_VdbeTrace },
  110664. #endif
  110665. #endif
  110666. #if !defined(SQLITE_OMIT_WAL)
  110667. {/* zName: */ "wal_autocheckpoint",
  110668. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  110669. /* ePragFlg: */ 0,
  110670. /* ColNames: */ 0, 0,
  110671. /* iArg: */ 0 },
  110672. {/* zName: */ "wal_checkpoint",
  110673. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  110674. /* ePragFlg: */ PragFlg_NeedSchema,
  110675. /* ColNames: */ 46, 3,
  110676. /* iArg: */ 0 },
  110677. #endif
  110678. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  110679. {/* zName: */ "writable_schema",
  110680. /* ePragTyp: */ PragTyp_FLAG,
  110681. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  110682. /* ColNames: */ 0, 0,
  110683. /* iArg: */ SQLITE_WriteSchema },
  110684. #endif
  110685. };
  110686. /* Number of pragmas: 60 on by default, 77 total. */
  110687. /************** End of pragma.h **********************************************/
  110688. /************** Continuing where we left off in pragma.c *********************/
  110689. /*
  110690. ** Interpret the given string as a safety level. Return 0 for OFF,
  110691. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  110692. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  110693. ** if the omitFull parameter it 1.
  110694. **
  110695. ** Note that the values returned are one less that the values that
  110696. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  110697. ** to support legacy SQL code. The safety level used to be boolean
  110698. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  110699. */
  110700. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  110701. /* 123456789 123456789 123 */
  110702. static const char zText[] = "onoffalseyestruextrafull";
  110703. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  110704. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  110705. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  110706. /* on no off false yes true extra full */
  110707. int i, n;
  110708. if( sqlite3Isdigit(*z) ){
  110709. return (u8)sqlite3Atoi(z);
  110710. }
  110711. n = sqlite3Strlen30(z);
  110712. for(i=0; i<ArraySize(iLength); i++){
  110713. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  110714. && (!omitFull || iValue[i]<=1)
  110715. ){
  110716. return iValue[i];
  110717. }
  110718. }
  110719. return dflt;
  110720. }
  110721. /*
  110722. ** Interpret the given string as a boolean value.
  110723. */
  110724. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  110725. return getSafetyLevel(z,1,dflt)!=0;
  110726. }
  110727. /* The sqlite3GetBoolean() function is used by other modules but the
  110728. ** remainder of this file is specific to PRAGMA processing. So omit
  110729. ** the rest of the file if PRAGMAs are omitted from the build.
  110730. */
  110731. #if !defined(SQLITE_OMIT_PRAGMA)
  110732. /*
  110733. ** Interpret the given string as a locking mode value.
  110734. */
  110735. static int getLockingMode(const char *z){
  110736. if( z ){
  110737. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  110738. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  110739. }
  110740. return PAGER_LOCKINGMODE_QUERY;
  110741. }
  110742. #ifndef SQLITE_OMIT_AUTOVACUUM
  110743. /*
  110744. ** Interpret the given string as an auto-vacuum mode value.
  110745. **
  110746. ** The following strings, "none", "full" and "incremental" are
  110747. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  110748. */
  110749. static int getAutoVacuum(const char *z){
  110750. int i;
  110751. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  110752. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  110753. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  110754. i = sqlite3Atoi(z);
  110755. return (u8)((i>=0&&i<=2)?i:0);
  110756. }
  110757. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  110758. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  110759. /*
  110760. ** Interpret the given string as a temp db location. Return 1 for file
  110761. ** backed temporary databases, 2 for the Red-Black tree in memory database
  110762. ** and 0 to use the compile-time default.
  110763. */
  110764. static int getTempStore(const char *z){
  110765. if( z[0]>='0' && z[0]<='2' ){
  110766. return z[0] - '0';
  110767. }else if( sqlite3StrICmp(z, "file")==0 ){
  110768. return 1;
  110769. }else if( sqlite3StrICmp(z, "memory")==0 ){
  110770. return 2;
  110771. }else{
  110772. return 0;
  110773. }
  110774. }
  110775. #endif /* SQLITE_PAGER_PRAGMAS */
  110776. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  110777. /*
  110778. ** Invalidate temp storage, either when the temp storage is changed
  110779. ** from default, or when 'file' and the temp_store_directory has changed
  110780. */
  110781. static int invalidateTempStorage(Parse *pParse){
  110782. sqlite3 *db = pParse->db;
  110783. if( db->aDb[1].pBt!=0 ){
  110784. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  110785. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  110786. "from within a transaction");
  110787. return SQLITE_ERROR;
  110788. }
  110789. sqlite3BtreeClose(db->aDb[1].pBt);
  110790. db->aDb[1].pBt = 0;
  110791. sqlite3ResetAllSchemasOfConnection(db);
  110792. }
  110793. return SQLITE_OK;
  110794. }
  110795. #endif /* SQLITE_PAGER_PRAGMAS */
  110796. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  110797. /*
  110798. ** If the TEMP database is open, close it and mark the database schema
  110799. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  110800. ** or DEFAULT_TEMP_STORE pragmas.
  110801. */
  110802. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  110803. int ts = getTempStore(zStorageType);
  110804. sqlite3 *db = pParse->db;
  110805. if( db->temp_store==ts ) return SQLITE_OK;
  110806. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  110807. return SQLITE_ERROR;
  110808. }
  110809. db->temp_store = (u8)ts;
  110810. return SQLITE_OK;
  110811. }
  110812. #endif /* SQLITE_PAGER_PRAGMAS */
  110813. /*
  110814. ** Set result column names for a pragma.
  110815. */
  110816. static void setPragmaResultColumnNames(
  110817. Vdbe *v, /* The query under construction */
  110818. const PragmaName *pPragma /* The pragma */
  110819. ){
  110820. u8 n = pPragma->nPragCName;
  110821. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  110822. if( n==0 ){
  110823. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  110824. }else{
  110825. int i, j;
  110826. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  110827. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  110828. }
  110829. }
  110830. }
  110831. /*
  110832. ** Generate code to return a single integer value.
  110833. */
  110834. static void returnSingleInt(Vdbe *v, i64 value){
  110835. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  110836. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  110837. }
  110838. /*
  110839. ** Generate code to return a single text value.
  110840. */
  110841. static void returnSingleText(
  110842. Vdbe *v, /* Prepared statement under construction */
  110843. const char *zValue /* Value to be returned */
  110844. ){
  110845. if( zValue ){
  110846. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  110847. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  110848. }
  110849. }
  110850. /*
  110851. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  110852. ** set these values for all pagers.
  110853. */
  110854. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  110855. static void setAllPagerFlags(sqlite3 *db){
  110856. if( db->autoCommit ){
  110857. Db *pDb = db->aDb;
  110858. int n = db->nDb;
  110859. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  110860. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  110861. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  110862. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  110863. == PAGER_FLAGS_MASK );
  110864. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  110865. while( (n--) > 0 ){
  110866. if( pDb->pBt ){
  110867. sqlite3BtreeSetPagerFlags(pDb->pBt,
  110868. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  110869. }
  110870. pDb++;
  110871. }
  110872. }
  110873. }
  110874. #else
  110875. # define setAllPagerFlags(X) /* no-op */
  110876. #endif
  110877. /*
  110878. ** Return a human-readable name for a constraint resolution action.
  110879. */
  110880. #ifndef SQLITE_OMIT_FOREIGN_KEY
  110881. static const char *actionName(u8 action){
  110882. const char *zName;
  110883. switch( action ){
  110884. case OE_SetNull: zName = "SET NULL"; break;
  110885. case OE_SetDflt: zName = "SET DEFAULT"; break;
  110886. case OE_Cascade: zName = "CASCADE"; break;
  110887. case OE_Restrict: zName = "RESTRICT"; break;
  110888. default: zName = "NO ACTION";
  110889. assert( action==OE_None ); break;
  110890. }
  110891. return zName;
  110892. }
  110893. #endif
  110894. /*
  110895. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  110896. ** defined in pager.h. This function returns the associated lowercase
  110897. ** journal-mode name.
  110898. */
  110899. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  110900. static char * const azModeName[] = {
  110901. "delete", "persist", "off", "truncate", "memory"
  110902. #ifndef SQLITE_OMIT_WAL
  110903. , "wal"
  110904. #endif
  110905. };
  110906. assert( PAGER_JOURNALMODE_DELETE==0 );
  110907. assert( PAGER_JOURNALMODE_PERSIST==1 );
  110908. assert( PAGER_JOURNALMODE_OFF==2 );
  110909. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  110910. assert( PAGER_JOURNALMODE_MEMORY==4 );
  110911. assert( PAGER_JOURNALMODE_WAL==5 );
  110912. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  110913. if( eMode==ArraySize(azModeName) ) return 0;
  110914. return azModeName[eMode];
  110915. }
  110916. /*
  110917. ** Locate a pragma in the aPragmaName[] array.
  110918. */
  110919. static const PragmaName *pragmaLocate(const char *zName){
  110920. int upr, lwr, mid = 0, rc;
  110921. lwr = 0;
  110922. upr = ArraySize(aPragmaName)-1;
  110923. while( lwr<=upr ){
  110924. mid = (lwr+upr)/2;
  110925. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  110926. if( rc==0 ) break;
  110927. if( rc<0 ){
  110928. upr = mid - 1;
  110929. }else{
  110930. lwr = mid + 1;
  110931. }
  110932. }
  110933. return lwr>upr ? 0 : &aPragmaName[mid];
  110934. }
  110935. /*
  110936. ** Helper subroutine for PRAGMA integrity_check:
  110937. **
  110938. ** Generate code to output a single-column result row with a value of the
  110939. ** string held in register 3. Decrement the result count in register 1
  110940. ** and halt if the maximum number of result rows have been issued.
  110941. */
  110942. static int integrityCheckResultRow(Vdbe *v){
  110943. int addr;
  110944. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  110945. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  110946. VdbeCoverage(v);
  110947. sqlite3VdbeAddOp0(v, OP_Halt);
  110948. return addr;
  110949. }
  110950. /*
  110951. ** Process a pragma statement.
  110952. **
  110953. ** Pragmas are of this form:
  110954. **
  110955. ** PRAGMA [schema.]id [= value]
  110956. **
  110957. ** The identifier might also be a string. The value is a string, and
  110958. ** identifier, or a number. If minusFlag is true, then the value is
  110959. ** a number that was preceded by a minus sign.
  110960. **
  110961. ** If the left side is "database.id" then pId1 is the database name
  110962. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  110963. ** id and pId2 is any empty string.
  110964. */
  110965. SQLITE_PRIVATE void sqlite3Pragma(
  110966. Parse *pParse,
  110967. Token *pId1, /* First part of [schema.]id field */
  110968. Token *pId2, /* Second part of [schema.]id field, or NULL */
  110969. Token *pValue, /* Token for <value>, or NULL */
  110970. int minusFlag /* True if a '-' sign preceded <value> */
  110971. ){
  110972. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  110973. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  110974. const char *zDb = 0; /* The database name */
  110975. Token *pId; /* Pointer to <id> token */
  110976. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  110977. int iDb; /* Database index for <database> */
  110978. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  110979. sqlite3 *db = pParse->db; /* The database connection */
  110980. Db *pDb; /* The specific database being pragmaed */
  110981. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  110982. const PragmaName *pPragma; /* The pragma */
  110983. if( v==0 ) return;
  110984. sqlite3VdbeRunOnlyOnce(v);
  110985. pParse->nMem = 2;
  110986. /* Interpret the [schema.] part of the pragma statement. iDb is the
  110987. ** index of the database this pragma is being applied to in db.aDb[]. */
  110988. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  110989. if( iDb<0 ) return;
  110990. pDb = &db->aDb[iDb];
  110991. /* If the temp database has been explicitly named as part of the
  110992. ** pragma, make sure it is open.
  110993. */
  110994. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  110995. return;
  110996. }
  110997. zLeft = sqlite3NameFromToken(db, pId);
  110998. if( !zLeft ) return;
  110999. if( minusFlag ){
  111000. zRight = sqlite3MPrintf(db, "-%T", pValue);
  111001. }else{
  111002. zRight = sqlite3NameFromToken(db, pValue);
  111003. }
  111004. assert( pId2 );
  111005. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  111006. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  111007. goto pragma_out;
  111008. }
  111009. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  111010. ** connection. If it returns SQLITE_OK, then assume that the VFS
  111011. ** handled the pragma and generate a no-op prepared statement.
  111012. **
  111013. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  111014. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  111015. ** object corresponding to the database file to which the pragma
  111016. ** statement refers.
  111017. **
  111018. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  111019. ** file control is an array of pointers to strings (char**) in which the
  111020. ** second element of the array is the name of the pragma and the third
  111021. ** element is the argument to the pragma or NULL if the pragma has no
  111022. ** argument.
  111023. */
  111024. aFcntl[0] = 0;
  111025. aFcntl[1] = zLeft;
  111026. aFcntl[2] = zRight;
  111027. aFcntl[3] = 0;
  111028. db->busyHandler.nBusy = 0;
  111029. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  111030. if( rc==SQLITE_OK ){
  111031. sqlite3VdbeSetNumCols(v, 1);
  111032. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  111033. returnSingleText(v, aFcntl[0]);
  111034. sqlite3_free(aFcntl[0]);
  111035. goto pragma_out;
  111036. }
  111037. if( rc!=SQLITE_NOTFOUND ){
  111038. if( aFcntl[0] ){
  111039. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  111040. sqlite3_free(aFcntl[0]);
  111041. }
  111042. pParse->nErr++;
  111043. pParse->rc = rc;
  111044. goto pragma_out;
  111045. }
  111046. /* Locate the pragma in the lookup table */
  111047. pPragma = pragmaLocate(zLeft);
  111048. if( pPragma==0 ) goto pragma_out;
  111049. /* Make sure the database schema is loaded if the pragma requires that */
  111050. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  111051. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  111052. }
  111053. /* Register the result column names for pragmas that return results */
  111054. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  111055. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  111056. ){
  111057. setPragmaResultColumnNames(v, pPragma);
  111058. }
  111059. /* Jump to the appropriate pragma handler */
  111060. switch( pPragma->ePragTyp ){
  111061. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  111062. /*
  111063. ** PRAGMA [schema.]default_cache_size
  111064. ** PRAGMA [schema.]default_cache_size=N
  111065. **
  111066. ** The first form reports the current persistent setting for the
  111067. ** page cache size. The value returned is the maximum number of
  111068. ** pages in the page cache. The second form sets both the current
  111069. ** page cache size value and the persistent page cache size value
  111070. ** stored in the database file.
  111071. **
  111072. ** Older versions of SQLite would set the default cache size to a
  111073. ** negative number to indicate synchronous=OFF. These days, synchronous
  111074. ** is always on by default regardless of the sign of the default cache
  111075. ** size. But continue to take the absolute value of the default cache
  111076. ** size of historical compatibility.
  111077. */
  111078. case PragTyp_DEFAULT_CACHE_SIZE: {
  111079. static const int iLn = VDBE_OFFSET_LINENO(2);
  111080. static const VdbeOpList getCacheSize[] = {
  111081. { OP_Transaction, 0, 0, 0}, /* 0 */
  111082. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  111083. { OP_IfPos, 1, 8, 0},
  111084. { OP_Integer, 0, 2, 0},
  111085. { OP_Subtract, 1, 2, 1},
  111086. { OP_IfPos, 1, 8, 0},
  111087. { OP_Integer, 0, 1, 0}, /* 6 */
  111088. { OP_Noop, 0, 0, 0},
  111089. { OP_ResultRow, 1, 1, 0},
  111090. };
  111091. VdbeOp *aOp;
  111092. sqlite3VdbeUsesBtree(v, iDb);
  111093. if( !zRight ){
  111094. pParse->nMem += 2;
  111095. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  111096. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  111097. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  111098. aOp[0].p1 = iDb;
  111099. aOp[1].p1 = iDb;
  111100. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  111101. }else{
  111102. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  111103. sqlite3BeginWriteOperation(pParse, 0, iDb);
  111104. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  111105. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  111106. pDb->pSchema->cache_size = size;
  111107. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  111108. }
  111109. break;
  111110. }
  111111. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  111112. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  111113. /*
  111114. ** PRAGMA [schema.]page_size
  111115. ** PRAGMA [schema.]page_size=N
  111116. **
  111117. ** The first form reports the current setting for the
  111118. ** database page size in bytes. The second form sets the
  111119. ** database page size value. The value can only be set if
  111120. ** the database has not yet been created.
  111121. */
  111122. case PragTyp_PAGE_SIZE: {
  111123. Btree *pBt = pDb->pBt;
  111124. assert( pBt!=0 );
  111125. if( !zRight ){
  111126. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  111127. returnSingleInt(v, size);
  111128. }else{
  111129. /* Malloc may fail when setting the page-size, as there is an internal
  111130. ** buffer that the pager module resizes using sqlite3_realloc().
  111131. */
  111132. db->nextPagesize = sqlite3Atoi(zRight);
  111133. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  111134. sqlite3OomFault(db);
  111135. }
  111136. }
  111137. break;
  111138. }
  111139. /*
  111140. ** PRAGMA [schema.]secure_delete
  111141. ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
  111142. **
  111143. ** The first form reports the current setting for the
  111144. ** secure_delete flag. The second form changes the secure_delete
  111145. ** flag setting and reports the new value.
  111146. */
  111147. case PragTyp_SECURE_DELETE: {
  111148. Btree *pBt = pDb->pBt;
  111149. int b = -1;
  111150. assert( pBt!=0 );
  111151. if( zRight ){
  111152. if( sqlite3_stricmp(zRight, "fast")==0 ){
  111153. b = 2;
  111154. }else{
  111155. b = sqlite3GetBoolean(zRight, 0);
  111156. }
  111157. }
  111158. if( pId2->n==0 && b>=0 ){
  111159. int ii;
  111160. for(ii=0; ii<db->nDb; ii++){
  111161. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  111162. }
  111163. }
  111164. b = sqlite3BtreeSecureDelete(pBt, b);
  111165. returnSingleInt(v, b);
  111166. break;
  111167. }
  111168. /*
  111169. ** PRAGMA [schema.]max_page_count
  111170. ** PRAGMA [schema.]max_page_count=N
  111171. **
  111172. ** The first form reports the current setting for the
  111173. ** maximum number of pages in the database file. The
  111174. ** second form attempts to change this setting. Both
  111175. ** forms return the current setting.
  111176. **
  111177. ** The absolute value of N is used. This is undocumented and might
  111178. ** change. The only purpose is to provide an easy way to test
  111179. ** the sqlite3AbsInt32() function.
  111180. **
  111181. ** PRAGMA [schema.]page_count
  111182. **
  111183. ** Return the number of pages in the specified database.
  111184. */
  111185. case PragTyp_PAGE_COUNT: {
  111186. int iReg;
  111187. sqlite3CodeVerifySchema(pParse, iDb);
  111188. iReg = ++pParse->nMem;
  111189. if( sqlite3Tolower(zLeft[0])=='p' ){
  111190. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  111191. }else{
  111192. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  111193. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  111194. }
  111195. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  111196. break;
  111197. }
  111198. /*
  111199. ** PRAGMA [schema.]locking_mode
  111200. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  111201. */
  111202. case PragTyp_LOCKING_MODE: {
  111203. const char *zRet = "normal";
  111204. int eMode = getLockingMode(zRight);
  111205. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  111206. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  111207. ** the current default locking mode (which may be different to
  111208. ** the locking-mode of the main database).
  111209. */
  111210. eMode = db->dfltLockMode;
  111211. }else{
  111212. Pager *pPager;
  111213. if( pId2->n==0 ){
  111214. /* This indicates that no database name was specified as part
  111215. ** of the PRAGMA command. In this case the locking-mode must be
  111216. ** set on all attached databases, as well as the main db file.
  111217. **
  111218. ** Also, the sqlite3.dfltLockMode variable is set so that
  111219. ** any subsequently attached databases also use the specified
  111220. ** locking mode.
  111221. */
  111222. int ii;
  111223. assert(pDb==&db->aDb[0]);
  111224. for(ii=2; ii<db->nDb; ii++){
  111225. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  111226. sqlite3PagerLockingMode(pPager, eMode);
  111227. }
  111228. db->dfltLockMode = (u8)eMode;
  111229. }
  111230. pPager = sqlite3BtreePager(pDb->pBt);
  111231. eMode = sqlite3PagerLockingMode(pPager, eMode);
  111232. }
  111233. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  111234. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  111235. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  111236. zRet = "exclusive";
  111237. }
  111238. returnSingleText(v, zRet);
  111239. break;
  111240. }
  111241. /*
  111242. ** PRAGMA [schema.]journal_mode
  111243. ** PRAGMA [schema.]journal_mode =
  111244. ** (delete|persist|off|truncate|memory|wal|off)
  111245. */
  111246. case PragTyp_JOURNAL_MODE: {
  111247. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  111248. int ii; /* Loop counter */
  111249. if( zRight==0 ){
  111250. /* If there is no "=MODE" part of the pragma, do a query for the
  111251. ** current mode */
  111252. eMode = PAGER_JOURNALMODE_QUERY;
  111253. }else{
  111254. const char *zMode;
  111255. int n = sqlite3Strlen30(zRight);
  111256. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  111257. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  111258. }
  111259. if( !zMode ){
  111260. /* If the "=MODE" part does not match any known journal mode,
  111261. ** then do a query */
  111262. eMode = PAGER_JOURNALMODE_QUERY;
  111263. }
  111264. }
  111265. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  111266. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  111267. iDb = 0;
  111268. pId2->n = 1;
  111269. }
  111270. for(ii=db->nDb-1; ii>=0; ii--){
  111271. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  111272. sqlite3VdbeUsesBtree(v, ii);
  111273. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  111274. }
  111275. }
  111276. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  111277. break;
  111278. }
  111279. /*
  111280. ** PRAGMA [schema.]journal_size_limit
  111281. ** PRAGMA [schema.]journal_size_limit=N
  111282. **
  111283. ** Get or set the size limit on rollback journal files.
  111284. */
  111285. case PragTyp_JOURNAL_SIZE_LIMIT: {
  111286. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  111287. i64 iLimit = -2;
  111288. if( zRight ){
  111289. sqlite3DecOrHexToI64(zRight, &iLimit);
  111290. if( iLimit<-1 ) iLimit = -1;
  111291. }
  111292. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  111293. returnSingleInt(v, iLimit);
  111294. break;
  111295. }
  111296. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  111297. /*
  111298. ** PRAGMA [schema.]auto_vacuum
  111299. ** PRAGMA [schema.]auto_vacuum=N
  111300. **
  111301. ** Get or set the value of the database 'auto-vacuum' parameter.
  111302. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  111303. */
  111304. #ifndef SQLITE_OMIT_AUTOVACUUM
  111305. case PragTyp_AUTO_VACUUM: {
  111306. Btree *pBt = pDb->pBt;
  111307. assert( pBt!=0 );
  111308. if( !zRight ){
  111309. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  111310. }else{
  111311. int eAuto = getAutoVacuum(zRight);
  111312. assert( eAuto>=0 && eAuto<=2 );
  111313. db->nextAutovac = (u8)eAuto;
  111314. /* Call SetAutoVacuum() to set initialize the internal auto and
  111315. ** incr-vacuum flags. This is required in case this connection
  111316. ** creates the database file. It is important that it is created
  111317. ** as an auto-vacuum capable db.
  111318. */
  111319. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  111320. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  111321. /* When setting the auto_vacuum mode to either "full" or
  111322. ** "incremental", write the value of meta[6] in the database
  111323. ** file. Before writing to meta[6], check that meta[3] indicates
  111324. ** that this really is an auto-vacuum capable database.
  111325. */
  111326. static const int iLn = VDBE_OFFSET_LINENO(2);
  111327. static const VdbeOpList setMeta6[] = {
  111328. { OP_Transaction, 0, 1, 0}, /* 0 */
  111329. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  111330. { OP_If, 1, 0, 0}, /* 2 */
  111331. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  111332. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  111333. };
  111334. VdbeOp *aOp;
  111335. int iAddr = sqlite3VdbeCurrentAddr(v);
  111336. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  111337. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  111338. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  111339. aOp[0].p1 = iDb;
  111340. aOp[1].p1 = iDb;
  111341. aOp[2].p2 = iAddr+4;
  111342. aOp[4].p1 = iDb;
  111343. aOp[4].p3 = eAuto - 1;
  111344. sqlite3VdbeUsesBtree(v, iDb);
  111345. }
  111346. }
  111347. break;
  111348. }
  111349. #endif
  111350. /*
  111351. ** PRAGMA [schema.]incremental_vacuum(N)
  111352. **
  111353. ** Do N steps of incremental vacuuming on a database.
  111354. */
  111355. #ifndef SQLITE_OMIT_AUTOVACUUM
  111356. case PragTyp_INCREMENTAL_VACUUM: {
  111357. int iLimit, addr;
  111358. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  111359. iLimit = 0x7fffffff;
  111360. }
  111361. sqlite3BeginWriteOperation(pParse, 0, iDb);
  111362. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  111363. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  111364. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  111365. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  111366. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  111367. sqlite3VdbeJumpHere(v, addr);
  111368. break;
  111369. }
  111370. #endif
  111371. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  111372. /*
  111373. ** PRAGMA [schema.]cache_size
  111374. ** PRAGMA [schema.]cache_size=N
  111375. **
  111376. ** The first form reports the current local setting for the
  111377. ** page cache size. The second form sets the local
  111378. ** page cache size value. If N is positive then that is the
  111379. ** number of pages in the cache. If N is negative, then the
  111380. ** number of pages is adjusted so that the cache uses -N kibibytes
  111381. ** of memory.
  111382. */
  111383. case PragTyp_CACHE_SIZE: {
  111384. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  111385. if( !zRight ){
  111386. returnSingleInt(v, pDb->pSchema->cache_size);
  111387. }else{
  111388. int size = sqlite3Atoi(zRight);
  111389. pDb->pSchema->cache_size = size;
  111390. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  111391. }
  111392. break;
  111393. }
  111394. /*
  111395. ** PRAGMA [schema.]cache_spill
  111396. ** PRAGMA cache_spill=BOOLEAN
  111397. ** PRAGMA [schema.]cache_spill=N
  111398. **
  111399. ** The first form reports the current local setting for the
  111400. ** page cache spill size. The second form turns cache spill on
  111401. ** or off. When turnning cache spill on, the size is set to the
  111402. ** current cache_size. The third form sets a spill size that
  111403. ** may be different form the cache size.
  111404. ** If N is positive then that is the
  111405. ** number of pages in the cache. If N is negative, then the
  111406. ** number of pages is adjusted so that the cache uses -N kibibytes
  111407. ** of memory.
  111408. **
  111409. ** If the number of cache_spill pages is less then the number of
  111410. ** cache_size pages, no spilling occurs until the page count exceeds
  111411. ** the number of cache_size pages.
  111412. **
  111413. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  111414. ** not just the schema specified.
  111415. */
  111416. case PragTyp_CACHE_SPILL: {
  111417. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  111418. if( !zRight ){
  111419. returnSingleInt(v,
  111420. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  111421. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  111422. }else{
  111423. int size = 1;
  111424. if( sqlite3GetInt32(zRight, &size) ){
  111425. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  111426. }
  111427. if( sqlite3GetBoolean(zRight, size!=0) ){
  111428. db->flags |= SQLITE_CacheSpill;
  111429. }else{
  111430. db->flags &= ~SQLITE_CacheSpill;
  111431. }
  111432. setAllPagerFlags(db);
  111433. }
  111434. break;
  111435. }
  111436. /*
  111437. ** PRAGMA [schema.]mmap_size(N)
  111438. **
  111439. ** Used to set mapping size limit. The mapping size limit is
  111440. ** used to limit the aggregate size of all memory mapped regions of the
  111441. ** database file. If this parameter is set to zero, then memory mapping
  111442. ** is not used at all. If N is negative, then the default memory map
  111443. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  111444. ** The parameter N is measured in bytes.
  111445. **
  111446. ** This value is advisory. The underlying VFS is free to memory map
  111447. ** as little or as much as it wants. Except, if N is set to 0 then the
  111448. ** upper layers will never invoke the xFetch interfaces to the VFS.
  111449. */
  111450. case PragTyp_MMAP_SIZE: {
  111451. sqlite3_int64 sz;
  111452. #if SQLITE_MAX_MMAP_SIZE>0
  111453. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  111454. if( zRight ){
  111455. int ii;
  111456. sqlite3DecOrHexToI64(zRight, &sz);
  111457. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  111458. if( pId2->n==0 ) db->szMmap = sz;
  111459. for(ii=db->nDb-1; ii>=0; ii--){
  111460. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  111461. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  111462. }
  111463. }
  111464. }
  111465. sz = -1;
  111466. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  111467. #else
  111468. sz = 0;
  111469. rc = SQLITE_OK;
  111470. #endif
  111471. if( rc==SQLITE_OK ){
  111472. returnSingleInt(v, sz);
  111473. }else if( rc!=SQLITE_NOTFOUND ){
  111474. pParse->nErr++;
  111475. pParse->rc = rc;
  111476. }
  111477. break;
  111478. }
  111479. /*
  111480. ** PRAGMA temp_store
  111481. ** PRAGMA temp_store = "default"|"memory"|"file"
  111482. **
  111483. ** Return or set the local value of the temp_store flag. Changing
  111484. ** the local value does not make changes to the disk file and the default
  111485. ** value will be restored the next time the database is opened.
  111486. **
  111487. ** Note that it is possible for the library compile-time options to
  111488. ** override this setting
  111489. */
  111490. case PragTyp_TEMP_STORE: {
  111491. if( !zRight ){
  111492. returnSingleInt(v, db->temp_store);
  111493. }else{
  111494. changeTempStorage(pParse, zRight);
  111495. }
  111496. break;
  111497. }
  111498. /*
  111499. ** PRAGMA temp_store_directory
  111500. ** PRAGMA temp_store_directory = ""|"directory_name"
  111501. **
  111502. ** Return or set the local value of the temp_store_directory flag. Changing
  111503. ** the value sets a specific directory to be used for temporary files.
  111504. ** Setting to a null string reverts to the default temporary directory search.
  111505. ** If temporary directory is changed, then invalidateTempStorage.
  111506. **
  111507. */
  111508. case PragTyp_TEMP_STORE_DIRECTORY: {
  111509. if( !zRight ){
  111510. returnSingleText(v, sqlite3_temp_directory);
  111511. }else{
  111512. #ifndef SQLITE_OMIT_WSD
  111513. if( zRight[0] ){
  111514. int res;
  111515. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  111516. if( rc!=SQLITE_OK || res==0 ){
  111517. sqlite3ErrorMsg(pParse, "not a writable directory");
  111518. goto pragma_out;
  111519. }
  111520. }
  111521. if( SQLITE_TEMP_STORE==0
  111522. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  111523. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  111524. ){
  111525. invalidateTempStorage(pParse);
  111526. }
  111527. sqlite3_free(sqlite3_temp_directory);
  111528. if( zRight[0] ){
  111529. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  111530. }else{
  111531. sqlite3_temp_directory = 0;
  111532. }
  111533. #endif /* SQLITE_OMIT_WSD */
  111534. }
  111535. break;
  111536. }
  111537. #if SQLITE_OS_WIN
  111538. /*
  111539. ** PRAGMA data_store_directory
  111540. ** PRAGMA data_store_directory = ""|"directory_name"
  111541. **
  111542. ** Return or set the local value of the data_store_directory flag. Changing
  111543. ** the value sets a specific directory to be used for database files that
  111544. ** were specified with a relative pathname. Setting to a null string reverts
  111545. ** to the default database directory, which for database files specified with
  111546. ** a relative path will probably be based on the current directory for the
  111547. ** process. Database file specified with an absolute path are not impacted
  111548. ** by this setting, regardless of its value.
  111549. **
  111550. */
  111551. case PragTyp_DATA_STORE_DIRECTORY: {
  111552. if( !zRight ){
  111553. returnSingleText(v, sqlite3_data_directory);
  111554. }else{
  111555. #ifndef SQLITE_OMIT_WSD
  111556. if( zRight[0] ){
  111557. int res;
  111558. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  111559. if( rc!=SQLITE_OK || res==0 ){
  111560. sqlite3ErrorMsg(pParse, "not a writable directory");
  111561. goto pragma_out;
  111562. }
  111563. }
  111564. sqlite3_free(sqlite3_data_directory);
  111565. if( zRight[0] ){
  111566. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  111567. }else{
  111568. sqlite3_data_directory = 0;
  111569. }
  111570. #endif /* SQLITE_OMIT_WSD */
  111571. }
  111572. break;
  111573. }
  111574. #endif
  111575. #if SQLITE_ENABLE_LOCKING_STYLE
  111576. /*
  111577. ** PRAGMA [schema.]lock_proxy_file
  111578. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  111579. **
  111580. ** Return or set the value of the lock_proxy_file flag. Changing
  111581. ** the value sets a specific file to be used for database access locks.
  111582. **
  111583. */
  111584. case PragTyp_LOCK_PROXY_FILE: {
  111585. if( !zRight ){
  111586. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  111587. char *proxy_file_path = NULL;
  111588. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  111589. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  111590. &proxy_file_path);
  111591. returnSingleText(v, proxy_file_path);
  111592. }else{
  111593. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  111594. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  111595. int res;
  111596. if( zRight[0] ){
  111597. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  111598. zRight);
  111599. } else {
  111600. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  111601. NULL);
  111602. }
  111603. if( res!=SQLITE_OK ){
  111604. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  111605. goto pragma_out;
  111606. }
  111607. }
  111608. break;
  111609. }
  111610. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  111611. /*
  111612. ** PRAGMA [schema.]synchronous
  111613. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  111614. **
  111615. ** Return or set the local value of the synchronous flag. Changing
  111616. ** the local value does not make changes to the disk file and the
  111617. ** default value will be restored the next time the database is
  111618. ** opened.
  111619. */
  111620. case PragTyp_SYNCHRONOUS: {
  111621. if( !zRight ){
  111622. returnSingleInt(v, pDb->safety_level-1);
  111623. }else{
  111624. if( !db->autoCommit ){
  111625. sqlite3ErrorMsg(pParse,
  111626. "Safety level may not be changed inside a transaction");
  111627. }else if( iDb!=1 ){
  111628. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  111629. if( iLevel==0 ) iLevel = 1;
  111630. pDb->safety_level = iLevel;
  111631. pDb->bSyncSet = 1;
  111632. setAllPagerFlags(db);
  111633. }
  111634. }
  111635. break;
  111636. }
  111637. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  111638. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  111639. case PragTyp_FLAG: {
  111640. if( zRight==0 ){
  111641. setPragmaResultColumnNames(v, pPragma);
  111642. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  111643. }else{
  111644. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  111645. if( db->autoCommit==0 ){
  111646. /* Foreign key support may not be enabled or disabled while not
  111647. ** in auto-commit mode. */
  111648. mask &= ~(SQLITE_ForeignKeys);
  111649. }
  111650. #if SQLITE_USER_AUTHENTICATION
  111651. if( db->auth.authLevel==UAUTH_User ){
  111652. /* Do not allow non-admin users to modify the schema arbitrarily */
  111653. mask &= ~(SQLITE_WriteSchema);
  111654. }
  111655. #endif
  111656. if( sqlite3GetBoolean(zRight, 0) ){
  111657. db->flags |= mask;
  111658. }else{
  111659. db->flags &= ~mask;
  111660. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  111661. }
  111662. /* Many of the flag-pragmas modify the code generated by the SQL
  111663. ** compiler (eg. count_changes). So add an opcode to expire all
  111664. ** compiled SQL statements after modifying a pragma value.
  111665. */
  111666. sqlite3VdbeAddOp0(v, OP_Expire);
  111667. setAllPagerFlags(db);
  111668. }
  111669. break;
  111670. }
  111671. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  111672. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  111673. /*
  111674. ** PRAGMA table_info(<table>)
  111675. **
  111676. ** Return a single row for each column of the named table. The columns of
  111677. ** the returned data set are:
  111678. **
  111679. ** cid: Column id (numbered from left to right, starting at 0)
  111680. ** name: Column name
  111681. ** type: Column declaration type.
  111682. ** notnull: True if 'NOT NULL' is part of column declaration
  111683. ** dflt_value: The default value for the column, if any.
  111684. ** pk: Non-zero for PK fields.
  111685. */
  111686. case PragTyp_TABLE_INFO: if( zRight ){
  111687. Table *pTab;
  111688. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  111689. if( pTab ){
  111690. int i, k;
  111691. int nHidden = 0;
  111692. Column *pCol;
  111693. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  111694. pParse->nMem = 6;
  111695. sqlite3CodeVerifySchema(pParse, iDb);
  111696. sqlite3ViewGetColumnNames(pParse, pTab);
  111697. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  111698. if( IsHiddenColumn(pCol) ){
  111699. nHidden++;
  111700. continue;
  111701. }
  111702. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  111703. k = 0;
  111704. }else if( pPk==0 ){
  111705. k = 1;
  111706. }else{
  111707. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  111708. }
  111709. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  111710. sqlite3VdbeMultiLoad(v, 1, "issisi",
  111711. i-nHidden,
  111712. pCol->zName,
  111713. sqlite3ColumnType(pCol,""),
  111714. pCol->notNull ? 1 : 0,
  111715. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  111716. k);
  111717. }
  111718. }
  111719. }
  111720. break;
  111721. #ifdef SQLITE_DEBUG
  111722. case PragTyp_STATS: {
  111723. Index *pIdx;
  111724. HashElem *i;
  111725. pParse->nMem = 5;
  111726. sqlite3CodeVerifySchema(pParse, iDb);
  111727. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  111728. Table *pTab = sqliteHashData(i);
  111729. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  111730. pTab->zName,
  111731. 0,
  111732. pTab->szTabRow,
  111733. pTab->nRowLogEst,
  111734. pTab->tabFlags);
  111735. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  111736. sqlite3VdbeMultiLoad(v, 2, "siiiX",
  111737. pIdx->zName,
  111738. pIdx->szIdxRow,
  111739. pIdx->aiRowLogEst[0],
  111740. pIdx->hasStat1);
  111741. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  111742. }
  111743. }
  111744. }
  111745. break;
  111746. #endif
  111747. case PragTyp_INDEX_INFO: if( zRight ){
  111748. Index *pIdx;
  111749. Table *pTab;
  111750. pIdx = sqlite3FindIndex(db, zRight, zDb);
  111751. if( pIdx ){
  111752. int i;
  111753. int mx;
  111754. if( pPragma->iArg ){
  111755. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  111756. mx = pIdx->nColumn;
  111757. pParse->nMem = 6;
  111758. }else{
  111759. /* PRAGMA index_info (legacy version) */
  111760. mx = pIdx->nKeyCol;
  111761. pParse->nMem = 3;
  111762. }
  111763. pTab = pIdx->pTable;
  111764. sqlite3CodeVerifySchema(pParse, iDb);
  111765. assert( pParse->nMem<=pPragma->nPragCName );
  111766. for(i=0; i<mx; i++){
  111767. i16 cnum = pIdx->aiColumn[i];
  111768. sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
  111769. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  111770. if( pPragma->iArg ){
  111771. sqlite3VdbeMultiLoad(v, 4, "isiX",
  111772. pIdx->aSortOrder[i],
  111773. pIdx->azColl[i],
  111774. i<pIdx->nKeyCol);
  111775. }
  111776. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  111777. }
  111778. }
  111779. }
  111780. break;
  111781. case PragTyp_INDEX_LIST: if( zRight ){
  111782. Index *pIdx;
  111783. Table *pTab;
  111784. int i;
  111785. pTab = sqlite3FindTable(db, zRight, zDb);
  111786. if( pTab ){
  111787. pParse->nMem = 5;
  111788. sqlite3CodeVerifySchema(pParse, iDb);
  111789. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  111790. const char *azOrigin[] = { "c", "u", "pk" };
  111791. sqlite3VdbeMultiLoad(v, 1, "isisi",
  111792. i,
  111793. pIdx->zName,
  111794. IsUniqueIndex(pIdx),
  111795. azOrigin[pIdx->idxType],
  111796. pIdx->pPartIdxWhere!=0);
  111797. }
  111798. }
  111799. }
  111800. break;
  111801. case PragTyp_DATABASE_LIST: {
  111802. int i;
  111803. pParse->nMem = 3;
  111804. for(i=0; i<db->nDb; i++){
  111805. if( db->aDb[i].pBt==0 ) continue;
  111806. assert( db->aDb[i].zDbSName!=0 );
  111807. sqlite3VdbeMultiLoad(v, 1, "iss",
  111808. i,
  111809. db->aDb[i].zDbSName,
  111810. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  111811. }
  111812. }
  111813. break;
  111814. case PragTyp_COLLATION_LIST: {
  111815. int i = 0;
  111816. HashElem *p;
  111817. pParse->nMem = 2;
  111818. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  111819. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  111820. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  111821. }
  111822. }
  111823. break;
  111824. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  111825. case PragTyp_FUNCTION_LIST: {
  111826. int i;
  111827. HashElem *j;
  111828. FuncDef *p;
  111829. pParse->nMem = 2;
  111830. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  111831. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
  111832. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
  111833. }
  111834. }
  111835. for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
  111836. p = (FuncDef*)sqliteHashData(j);
  111837. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
  111838. }
  111839. }
  111840. break;
  111841. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111842. case PragTyp_MODULE_LIST: {
  111843. HashElem *j;
  111844. pParse->nMem = 1;
  111845. for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
  111846. Module *pMod = (Module*)sqliteHashData(j);
  111847. sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
  111848. }
  111849. }
  111850. break;
  111851. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  111852. case PragTyp_PRAGMA_LIST: {
  111853. int i;
  111854. for(i=0; i<ArraySize(aPragmaName); i++){
  111855. sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
  111856. }
  111857. }
  111858. break;
  111859. #endif /* SQLITE_INTROSPECTION_PRAGMAS */
  111860. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  111861. #ifndef SQLITE_OMIT_FOREIGN_KEY
  111862. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  111863. FKey *pFK;
  111864. Table *pTab;
  111865. pTab = sqlite3FindTable(db, zRight, zDb);
  111866. if( pTab ){
  111867. pFK = pTab->pFKey;
  111868. if( pFK ){
  111869. int i = 0;
  111870. pParse->nMem = 8;
  111871. sqlite3CodeVerifySchema(pParse, iDb);
  111872. while(pFK){
  111873. int j;
  111874. for(j=0; j<pFK->nCol; j++){
  111875. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  111876. i,
  111877. j,
  111878. pFK->zTo,
  111879. pTab->aCol[pFK->aCol[j].iFrom].zName,
  111880. pFK->aCol[j].zCol,
  111881. actionName(pFK->aAction[1]), /* ON UPDATE */
  111882. actionName(pFK->aAction[0]), /* ON DELETE */
  111883. "NONE");
  111884. }
  111885. ++i;
  111886. pFK = pFK->pNextFrom;
  111887. }
  111888. }
  111889. }
  111890. }
  111891. break;
  111892. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  111893. #ifndef SQLITE_OMIT_FOREIGN_KEY
  111894. #ifndef SQLITE_OMIT_TRIGGER
  111895. case PragTyp_FOREIGN_KEY_CHECK: {
  111896. FKey *pFK; /* A foreign key constraint */
  111897. Table *pTab; /* Child table contain "REFERENCES" keyword */
  111898. Table *pParent; /* Parent table that child points to */
  111899. Index *pIdx; /* Index in the parent table */
  111900. int i; /* Loop counter: Foreign key number for pTab */
  111901. int j; /* Loop counter: Field of the foreign key */
  111902. HashElem *k; /* Loop counter: Next table in schema */
  111903. int x; /* result variable */
  111904. int regResult; /* 3 registers to hold a result row */
  111905. int regKey; /* Register to hold key for checking the FK */
  111906. int regRow; /* Registers to hold a row from pTab */
  111907. int addrTop; /* Top of a loop checking foreign keys */
  111908. int addrOk; /* Jump here if the key is OK */
  111909. int *aiCols; /* child to parent column mapping */
  111910. regResult = pParse->nMem+1;
  111911. pParse->nMem += 4;
  111912. regKey = ++pParse->nMem;
  111913. regRow = ++pParse->nMem;
  111914. sqlite3CodeVerifySchema(pParse, iDb);
  111915. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  111916. while( k ){
  111917. if( zRight ){
  111918. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  111919. k = 0;
  111920. }else{
  111921. pTab = (Table*)sqliteHashData(k);
  111922. k = sqliteHashNext(k);
  111923. }
  111924. if( pTab==0 || pTab->pFKey==0 ) continue;
  111925. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  111926. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  111927. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  111928. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  111929. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  111930. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  111931. if( pParent==0 ) continue;
  111932. pIdx = 0;
  111933. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  111934. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  111935. if( x==0 ){
  111936. if( pIdx==0 ){
  111937. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  111938. }else{
  111939. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  111940. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  111941. }
  111942. }else{
  111943. k = 0;
  111944. break;
  111945. }
  111946. }
  111947. assert( pParse->nErr>0 || pFK==0 );
  111948. if( pFK ) break;
  111949. if( pParse->nTab<i ) pParse->nTab = i;
  111950. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  111951. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  111952. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  111953. pIdx = 0;
  111954. aiCols = 0;
  111955. if( pParent ){
  111956. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  111957. assert( x==0 );
  111958. }
  111959. addrOk = sqlite3VdbeMakeLabel(v);
  111960. /* Generate code to read the child key values into registers
  111961. ** regRow..regRow+n. If any of the child key values are NULL, this
  111962. ** row cannot cause an FK violation. Jump directly to addrOk in
  111963. ** this case. */
  111964. for(j=0; j<pFK->nCol; j++){
  111965. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  111966. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  111967. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  111968. }
  111969. /* Generate code to query the parent index for a matching parent
  111970. ** key. If a match is found, jump to addrOk. */
  111971. if( pIdx ){
  111972. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  111973. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  111974. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  111975. VdbeCoverage(v);
  111976. }else if( pParent ){
  111977. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  111978. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  111979. sqlite3VdbeGoto(v, addrOk);
  111980. assert( pFK->nCol==1 );
  111981. }
  111982. /* Generate code to report an FK violation to the caller. */
  111983. if( HasRowid(pTab) ){
  111984. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  111985. }else{
  111986. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  111987. }
  111988. sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
  111989. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  111990. sqlite3VdbeResolveLabel(v, addrOk);
  111991. sqlite3DbFree(db, aiCols);
  111992. }
  111993. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  111994. sqlite3VdbeJumpHere(v, addrTop);
  111995. }
  111996. }
  111997. break;
  111998. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  111999. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  112000. #ifndef NDEBUG
  112001. case PragTyp_PARSER_TRACE: {
  112002. if( zRight ){
  112003. if( sqlite3GetBoolean(zRight, 0) ){
  112004. sqlite3ParserTrace(stdout, "parser: ");
  112005. }else{
  112006. sqlite3ParserTrace(0, 0);
  112007. }
  112008. }
  112009. }
  112010. break;
  112011. #endif
  112012. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  112013. ** used will be case sensitive or not depending on the RHS.
  112014. */
  112015. case PragTyp_CASE_SENSITIVE_LIKE: {
  112016. if( zRight ){
  112017. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  112018. }
  112019. }
  112020. break;
  112021. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  112022. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  112023. #endif
  112024. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  112025. /* PRAGMA integrity_check
  112026. ** PRAGMA integrity_check(N)
  112027. ** PRAGMA quick_check
  112028. ** PRAGMA quick_check(N)
  112029. **
  112030. ** Verify the integrity of the database.
  112031. **
  112032. ** The "quick_check" is reduced version of
  112033. ** integrity_check designed to detect most database corruption
  112034. ** without the overhead of cross-checking indexes. Quick_check
  112035. ** is linear time wherease integrity_check is O(NlogN).
  112036. */
  112037. case PragTyp_INTEGRITY_CHECK: {
  112038. int i, j, addr, mxErr;
  112039. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  112040. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  112041. ** then iDb is set to the index of the database identified by <db>.
  112042. ** In this case, the integrity of database iDb only is verified by
  112043. ** the VDBE created below.
  112044. **
  112045. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  112046. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  112047. ** to -1 here, to indicate that the VDBE should verify the integrity
  112048. ** of all attached databases. */
  112049. assert( iDb>=0 );
  112050. assert( iDb==0 || pId2->z );
  112051. if( pId2->z==0 ) iDb = -1;
  112052. /* Initialize the VDBE program */
  112053. pParse->nMem = 6;
  112054. /* Set the maximum error count */
  112055. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  112056. if( zRight ){
  112057. sqlite3GetInt32(zRight, &mxErr);
  112058. if( mxErr<=0 ){
  112059. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  112060. }
  112061. }
  112062. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  112063. /* Do an integrity check on each database file */
  112064. for(i=0; i<db->nDb; i++){
  112065. HashElem *x; /* For looping over tables in the schema */
  112066. Hash *pTbls; /* Set of all tables in the schema */
  112067. int *aRoot; /* Array of root page numbers of all btrees */
  112068. int cnt = 0; /* Number of entries in aRoot[] */
  112069. int mxIdx = 0; /* Maximum number of indexes for any table */
  112070. if( OMIT_TEMPDB && i==1 ) continue;
  112071. if( iDb>=0 && i!=iDb ) continue;
  112072. sqlite3CodeVerifySchema(pParse, i);
  112073. /* Do an integrity check of the B-Tree
  112074. **
  112075. ** Begin by finding the root pages numbers
  112076. ** for all tables and indices in the database.
  112077. */
  112078. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  112079. pTbls = &db->aDb[i].pSchema->tblHash;
  112080. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  112081. Table *pTab = sqliteHashData(x); /* Current table */
  112082. Index *pIdx; /* An index on pTab */
  112083. int nIdx; /* Number of indexes on pTab */
  112084. if( HasRowid(pTab) ) cnt++;
  112085. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  112086. if( nIdx>mxIdx ) mxIdx = nIdx;
  112087. }
  112088. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  112089. if( aRoot==0 ) break;
  112090. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  112091. Table *pTab = sqliteHashData(x);
  112092. Index *pIdx;
  112093. if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
  112094. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  112095. aRoot[++cnt] = pIdx->tnum;
  112096. }
  112097. }
  112098. aRoot[0] = cnt;
  112099. /* Make sure sufficient number of registers have been allocated */
  112100. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  112101. sqlite3ClearTempRegCache(pParse);
  112102. /* Do the b-tree integrity checks */
  112103. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  112104. sqlite3VdbeChangeP5(v, (u8)i);
  112105. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  112106. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  112107. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  112108. P4_DYNAMIC);
  112109. sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
  112110. integrityCheckResultRow(v);
  112111. sqlite3VdbeJumpHere(v, addr);
  112112. /* Make sure all the indices are constructed correctly.
  112113. */
  112114. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  112115. Table *pTab = sqliteHashData(x);
  112116. Index *pIdx, *pPk;
  112117. Index *pPrior = 0;
  112118. int loopTop;
  112119. int iDataCur, iIdxCur;
  112120. int r1 = -1;
  112121. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  112122. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  112123. sqlite3ExprCacheClear(pParse);
  112124. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  112125. 1, 0, &iDataCur, &iIdxCur);
  112126. /* reg[7] counts the number of entries in the table.
  112127. ** reg[8+i] counts the number of entries in the i-th index
  112128. */
  112129. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  112130. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  112131. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  112132. }
  112133. assert( pParse->nMem>=8+j );
  112134. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  112135. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  112136. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  112137. /* Verify that all NOT NULL columns really are NOT NULL */
  112138. for(j=0; j<pTab->nCol; j++){
  112139. char *zErr;
  112140. int jmp2;
  112141. if( j==pTab->iPKey ) continue;
  112142. if( pTab->aCol[j].notNull==0 ) continue;
  112143. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  112144. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  112145. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  112146. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  112147. pTab->aCol[j].zName);
  112148. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  112149. integrityCheckResultRow(v);
  112150. sqlite3VdbeJumpHere(v, jmp2);
  112151. }
  112152. /* Verify CHECK constraints */
  112153. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  112154. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  112155. if( db->mallocFailed==0 ){
  112156. int addrCkFault = sqlite3VdbeMakeLabel(v);
  112157. int addrCkOk = sqlite3VdbeMakeLabel(v);
  112158. char *zErr;
  112159. int k;
  112160. pParse->iSelfTab = iDataCur + 1;
  112161. sqlite3ExprCachePush(pParse);
  112162. for(k=pCheck->nExpr-1; k>0; k--){
  112163. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  112164. }
  112165. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  112166. SQLITE_JUMPIFNULL);
  112167. sqlite3VdbeResolveLabel(v, addrCkFault);
  112168. pParse->iSelfTab = 0;
  112169. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  112170. pTab->zName);
  112171. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  112172. integrityCheckResultRow(v);
  112173. sqlite3VdbeResolveLabel(v, addrCkOk);
  112174. sqlite3ExprCachePop(pParse);
  112175. }
  112176. sqlite3ExprListDelete(db, pCheck);
  112177. }
  112178. if( !isQuick ){ /* Omit the remaining tests for quick_check */
  112179. /* Sanity check on record header decoding */
  112180. sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
  112181. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  112182. /* Validate index entries for the current row */
  112183. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  112184. int jmp2, jmp3, jmp4, jmp5;
  112185. int ckUniq = sqlite3VdbeMakeLabel(v);
  112186. if( pPk==pIdx ) continue;
  112187. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  112188. pPrior, r1);
  112189. pPrior = pIdx;
  112190. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
  112191. /* Verify that an index entry exists for the current table row */
  112192. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  112193. pIdx->nColumn); VdbeCoverage(v);
  112194. sqlite3VdbeLoadString(v, 3, "row ");
  112195. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  112196. sqlite3VdbeLoadString(v, 4, " missing from index ");
  112197. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  112198. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  112199. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  112200. jmp4 = integrityCheckResultRow(v);
  112201. sqlite3VdbeJumpHere(v, jmp2);
  112202. /* For UNIQUE indexes, verify that only one entry exists with the
  112203. ** current key. The entry is unique if (1) any column is NULL
  112204. ** or (2) the next entry has a different key */
  112205. if( IsUniqueIndex(pIdx) ){
  112206. int uniqOk = sqlite3VdbeMakeLabel(v);
  112207. int jmp6;
  112208. int kk;
  112209. for(kk=0; kk<pIdx->nKeyCol; kk++){
  112210. int iCol = pIdx->aiColumn[kk];
  112211. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  112212. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  112213. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  112214. VdbeCoverage(v);
  112215. }
  112216. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  112217. sqlite3VdbeGoto(v, uniqOk);
  112218. sqlite3VdbeJumpHere(v, jmp6);
  112219. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  112220. pIdx->nKeyCol); VdbeCoverage(v);
  112221. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  112222. sqlite3VdbeGoto(v, jmp5);
  112223. sqlite3VdbeResolveLabel(v, uniqOk);
  112224. }
  112225. sqlite3VdbeJumpHere(v, jmp4);
  112226. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  112227. }
  112228. }
  112229. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  112230. sqlite3VdbeJumpHere(v, loopTop-1);
  112231. #ifndef SQLITE_OMIT_BTREECOUNT
  112232. if( !isQuick ){
  112233. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  112234. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  112235. if( pPk==pIdx ) continue;
  112236. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  112237. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  112238. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  112239. sqlite3VdbeLoadString(v, 4, pIdx->zName);
  112240. sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
  112241. integrityCheckResultRow(v);
  112242. sqlite3VdbeJumpHere(v, addr);
  112243. }
  112244. }
  112245. #endif /* SQLITE_OMIT_BTREECOUNT */
  112246. }
  112247. }
  112248. {
  112249. static const int iLn = VDBE_OFFSET_LINENO(2);
  112250. static const VdbeOpList endCode[] = {
  112251. { OP_AddImm, 1, 0, 0}, /* 0 */
  112252. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  112253. { OP_String8, 0, 3, 0}, /* 2 */
  112254. { OP_ResultRow, 3, 1, 0}, /* 3 */
  112255. { OP_Halt, 0, 0, 0}, /* 4 */
  112256. { OP_String8, 0, 3, 0}, /* 5 */
  112257. { OP_Goto, 0, 3, 0}, /* 6 */
  112258. };
  112259. VdbeOp *aOp;
  112260. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  112261. if( aOp ){
  112262. aOp[0].p2 = 1-mxErr;
  112263. aOp[2].p4type = P4_STATIC;
  112264. aOp[2].p4.z = "ok";
  112265. aOp[5].p4type = P4_STATIC;
  112266. aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
  112267. }
  112268. sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
  112269. }
  112270. }
  112271. break;
  112272. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  112273. #ifndef SQLITE_OMIT_UTF16
  112274. /*
  112275. ** PRAGMA encoding
  112276. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  112277. **
  112278. ** In its first form, this pragma returns the encoding of the main
  112279. ** database. If the database is not initialized, it is initialized now.
  112280. **
  112281. ** The second form of this pragma is a no-op if the main database file
  112282. ** has not already been initialized. In this case it sets the default
  112283. ** encoding that will be used for the main database file if a new file
  112284. ** is created. If an existing main database file is opened, then the
  112285. ** default text encoding for the existing database is used.
  112286. **
  112287. ** In all cases new databases created using the ATTACH command are
  112288. ** created to use the same default text encoding as the main database. If
  112289. ** the main database has not been initialized and/or created when ATTACH
  112290. ** is executed, this is done before the ATTACH operation.
  112291. **
  112292. ** In the second form this pragma sets the text encoding to be used in
  112293. ** new database files created using this database handle. It is only
  112294. ** useful if invoked immediately after the main database i
  112295. */
  112296. case PragTyp_ENCODING: {
  112297. static const struct EncName {
  112298. char *zName;
  112299. u8 enc;
  112300. } encnames[] = {
  112301. { "UTF8", SQLITE_UTF8 },
  112302. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  112303. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  112304. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  112305. { "UTF16le", SQLITE_UTF16LE },
  112306. { "UTF16be", SQLITE_UTF16BE },
  112307. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  112308. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  112309. { 0, 0 }
  112310. };
  112311. const struct EncName *pEnc;
  112312. if( !zRight ){ /* "PRAGMA encoding" */
  112313. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  112314. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  112315. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  112316. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  112317. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  112318. }else{ /* "PRAGMA encoding = XXX" */
  112319. /* Only change the value of sqlite.enc if the database handle is not
  112320. ** initialized. If the main database exists, the new sqlite.enc value
  112321. ** will be overwritten when the schema is next loaded. If it does not
  112322. ** already exists, it will be created to use the new encoding value.
  112323. */
  112324. if(
  112325. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  112326. DbHasProperty(db, 0, DB_Empty)
  112327. ){
  112328. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  112329. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  112330. SCHEMA_ENC(db) = ENC(db) =
  112331. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  112332. break;
  112333. }
  112334. }
  112335. if( !pEnc->zName ){
  112336. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  112337. }
  112338. }
  112339. }
  112340. }
  112341. break;
  112342. #endif /* SQLITE_OMIT_UTF16 */
  112343. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  112344. /*
  112345. ** PRAGMA [schema.]schema_version
  112346. ** PRAGMA [schema.]schema_version = <integer>
  112347. **
  112348. ** PRAGMA [schema.]user_version
  112349. ** PRAGMA [schema.]user_version = <integer>
  112350. **
  112351. ** PRAGMA [schema.]freelist_count
  112352. **
  112353. ** PRAGMA [schema.]data_version
  112354. **
  112355. ** PRAGMA [schema.]application_id
  112356. ** PRAGMA [schema.]application_id = <integer>
  112357. **
  112358. ** The pragma's schema_version and user_version are used to set or get
  112359. ** the value of the schema-version and user-version, respectively. Both
  112360. ** the schema-version and the user-version are 32-bit signed integers
  112361. ** stored in the database header.
  112362. **
  112363. ** The schema-cookie is usually only manipulated internally by SQLite. It
  112364. ** is incremented by SQLite whenever the database schema is modified (by
  112365. ** creating or dropping a table or index). The schema version is used by
  112366. ** SQLite each time a query is executed to ensure that the internal cache
  112367. ** of the schema used when compiling the SQL query matches the schema of
  112368. ** the database against which the compiled query is actually executed.
  112369. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  112370. ** the schema-version is potentially dangerous and may lead to program
  112371. ** crashes or database corruption. Use with caution!
  112372. **
  112373. ** The user-version is not used internally by SQLite. It may be used by
  112374. ** applications for any purpose.
  112375. */
  112376. case PragTyp_HEADER_VALUE: {
  112377. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  112378. sqlite3VdbeUsesBtree(v, iDb);
  112379. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  112380. /* Write the specified cookie value */
  112381. static const VdbeOpList setCookie[] = {
  112382. { OP_Transaction, 0, 1, 0}, /* 0 */
  112383. { OP_SetCookie, 0, 0, 0}, /* 1 */
  112384. };
  112385. VdbeOp *aOp;
  112386. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  112387. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  112388. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  112389. aOp[0].p1 = iDb;
  112390. aOp[1].p1 = iDb;
  112391. aOp[1].p2 = iCookie;
  112392. aOp[1].p3 = sqlite3Atoi(zRight);
  112393. }else{
  112394. /* Read the specified cookie value */
  112395. static const VdbeOpList readCookie[] = {
  112396. { OP_Transaction, 0, 0, 0}, /* 0 */
  112397. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  112398. { OP_ResultRow, 1, 1, 0}
  112399. };
  112400. VdbeOp *aOp;
  112401. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  112402. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  112403. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  112404. aOp[0].p1 = iDb;
  112405. aOp[1].p1 = iDb;
  112406. aOp[1].p3 = iCookie;
  112407. sqlite3VdbeReusable(v);
  112408. }
  112409. }
  112410. break;
  112411. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  112412. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  112413. /*
  112414. ** PRAGMA compile_options
  112415. **
  112416. ** Return the names of all compile-time options used in this build,
  112417. ** one option per row.
  112418. */
  112419. case PragTyp_COMPILE_OPTIONS: {
  112420. int i = 0;
  112421. const char *zOpt;
  112422. pParse->nMem = 1;
  112423. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  112424. sqlite3VdbeLoadString(v, 1, zOpt);
  112425. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  112426. }
  112427. sqlite3VdbeReusable(v);
  112428. }
  112429. break;
  112430. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  112431. #ifndef SQLITE_OMIT_WAL
  112432. /*
  112433. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  112434. **
  112435. ** Checkpoint the database.
  112436. */
  112437. case PragTyp_WAL_CHECKPOINT: {
  112438. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  112439. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  112440. if( zRight ){
  112441. if( sqlite3StrICmp(zRight, "full")==0 ){
  112442. eMode = SQLITE_CHECKPOINT_FULL;
  112443. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  112444. eMode = SQLITE_CHECKPOINT_RESTART;
  112445. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  112446. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  112447. }
  112448. }
  112449. pParse->nMem = 3;
  112450. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  112451. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  112452. }
  112453. break;
  112454. /*
  112455. ** PRAGMA wal_autocheckpoint
  112456. ** PRAGMA wal_autocheckpoint = N
  112457. **
  112458. ** Configure a database connection to automatically checkpoint a database
  112459. ** after accumulating N frames in the log. Or query for the current value
  112460. ** of N.
  112461. */
  112462. case PragTyp_WAL_AUTOCHECKPOINT: {
  112463. if( zRight ){
  112464. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  112465. }
  112466. returnSingleInt(v,
  112467. db->xWalCallback==sqlite3WalDefaultHook ?
  112468. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  112469. }
  112470. break;
  112471. #endif
  112472. /*
  112473. ** PRAGMA shrink_memory
  112474. **
  112475. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  112476. ** connection on which it is invoked to free up as much memory as it
  112477. ** can, by calling sqlite3_db_release_memory().
  112478. */
  112479. case PragTyp_SHRINK_MEMORY: {
  112480. sqlite3_db_release_memory(db);
  112481. break;
  112482. }
  112483. /*
  112484. ** PRAGMA optimize
  112485. ** PRAGMA optimize(MASK)
  112486. ** PRAGMA schema.optimize
  112487. ** PRAGMA schema.optimize(MASK)
  112488. **
  112489. ** Attempt to optimize the database. All schemas are optimized in the first
  112490. ** two forms, and only the specified schema is optimized in the latter two.
  112491. **
  112492. ** The details of optimizations performed by this pragma are expected
  112493. ** to change and improve over time. Applications should anticipate that
  112494. ** this pragma will perform new optimizations in future releases.
  112495. **
  112496. ** The optional argument is a bitmask of optimizations to perform:
  112497. **
  112498. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  112499. ** but instead return one line of text for each optimization
  112500. ** that would have been done. Off by default.
  112501. **
  112502. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  112503. ** See below for additional information.
  112504. **
  112505. ** 0x0004 (Not yet implemented) Record usage and performance
  112506. ** information from the current session in the
  112507. ** database file so that it will be available to "optimize"
  112508. ** pragmas run by future database connections.
  112509. **
  112510. ** 0x0008 (Not yet implemented) Create indexes that might have
  112511. ** been helpful to recent queries
  112512. **
  112513. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
  112514. ** of the optimizations listed above except Debug Mode, including new
  112515. ** optimizations that have not yet been invented. If new optimizations are
  112516. ** ever added that should be off by default, those off-by-default
  112517. ** optimizations will have bitmasks of 0x10000 or larger.
  112518. **
  112519. ** DETERMINATION OF WHEN TO RUN ANALYZE
  112520. **
  112521. ** In the current implementation, a table is analyzed if only if all of
  112522. ** the following are true:
  112523. **
  112524. ** (1) MASK bit 0x02 is set.
  112525. **
  112526. ** (2) The query planner used sqlite_stat1-style statistics for one or
  112527. ** more indexes of the table at some point during the lifetime of
  112528. ** the current connection.
  112529. **
  112530. ** (3) One or more indexes of the table are currently unanalyzed OR
  112531. ** the number of rows in the table has increased by 25 times or more
  112532. ** since the last time ANALYZE was run.
  112533. **
  112534. ** The rules for when tables are analyzed are likely to change in
  112535. ** future releases.
  112536. */
  112537. case PragTyp_OPTIMIZE: {
  112538. int iDbLast; /* Loop termination point for the schema loop */
  112539. int iTabCur; /* Cursor for a table whose size needs checking */
  112540. HashElem *k; /* Loop over tables of a schema */
  112541. Schema *pSchema; /* The current schema */
  112542. Table *pTab; /* A table in the schema */
  112543. Index *pIdx; /* An index of the table */
  112544. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  112545. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  112546. u32 opMask; /* Mask of operations to perform */
  112547. if( zRight ){
  112548. opMask = (u32)sqlite3Atoi(zRight);
  112549. if( (opMask & 0x02)==0 ) break;
  112550. }else{
  112551. opMask = 0xfffe;
  112552. }
  112553. iTabCur = pParse->nTab++;
  112554. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  112555. if( iDb==1 ) continue;
  112556. sqlite3CodeVerifySchema(pParse, iDb);
  112557. pSchema = db->aDb[iDb].pSchema;
  112558. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  112559. pTab = (Table*)sqliteHashData(k);
  112560. /* If table pTab has not been used in a way that would benefit from
  112561. ** having analysis statistics during the current session, then skip it.
  112562. ** This also has the effect of skipping virtual tables and views */
  112563. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  112564. /* Reanalyze if the table is 25 times larger than the last analysis */
  112565. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  112566. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  112567. if( !pIdx->hasStat1 ){
  112568. szThreshold = 0; /* Always analyze if any index lacks statistics */
  112569. break;
  112570. }
  112571. }
  112572. if( szThreshold ){
  112573. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  112574. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  112575. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  112576. VdbeCoverage(v);
  112577. }
  112578. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  112579. db->aDb[iDb].zDbSName, pTab->zName);
  112580. if( opMask & 0x01 ){
  112581. int r1 = sqlite3GetTempReg(pParse);
  112582. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  112583. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  112584. }else{
  112585. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  112586. }
  112587. }
  112588. }
  112589. sqlite3VdbeAddOp0(v, OP_Expire);
  112590. break;
  112591. }
  112592. /*
  112593. ** PRAGMA busy_timeout
  112594. ** PRAGMA busy_timeout = N
  112595. **
  112596. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  112597. ** if one is set. If no busy handler or a different busy handler is set
  112598. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  112599. ** disables the timeout.
  112600. */
  112601. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  112602. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  112603. if( zRight ){
  112604. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  112605. }
  112606. returnSingleInt(v, db->busyTimeout);
  112607. break;
  112608. }
  112609. /*
  112610. ** PRAGMA soft_heap_limit
  112611. ** PRAGMA soft_heap_limit = N
  112612. **
  112613. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  112614. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  112615. ** specified and is a non-negative integer.
  112616. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  112617. ** returns the same integer that would be returned by the
  112618. ** sqlite3_soft_heap_limit64(-1) C-language function.
  112619. */
  112620. case PragTyp_SOFT_HEAP_LIMIT: {
  112621. sqlite3_int64 N;
  112622. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  112623. sqlite3_soft_heap_limit64(N);
  112624. }
  112625. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  112626. break;
  112627. }
  112628. /*
  112629. ** PRAGMA threads
  112630. ** PRAGMA threads = N
  112631. **
  112632. ** Configure the maximum number of worker threads. Return the new
  112633. ** maximum, which might be less than requested.
  112634. */
  112635. case PragTyp_THREADS: {
  112636. sqlite3_int64 N;
  112637. if( zRight
  112638. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  112639. && N>=0
  112640. ){
  112641. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  112642. }
  112643. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  112644. break;
  112645. }
  112646. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  112647. /*
  112648. ** Report the current state of file logs for all databases
  112649. */
  112650. case PragTyp_LOCK_STATUS: {
  112651. static const char *const azLockName[] = {
  112652. "unlocked", "shared", "reserved", "pending", "exclusive"
  112653. };
  112654. int i;
  112655. pParse->nMem = 2;
  112656. for(i=0; i<db->nDb; i++){
  112657. Btree *pBt;
  112658. const char *zState = "unknown";
  112659. int j;
  112660. if( db->aDb[i].zDbSName==0 ) continue;
  112661. pBt = db->aDb[i].pBt;
  112662. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  112663. zState = "closed";
  112664. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  112665. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  112666. zState = azLockName[j];
  112667. }
  112668. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  112669. }
  112670. break;
  112671. }
  112672. #endif
  112673. #ifdef SQLITE_HAS_CODEC
  112674. case PragTyp_KEY: {
  112675. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  112676. break;
  112677. }
  112678. case PragTyp_REKEY: {
  112679. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  112680. break;
  112681. }
  112682. case PragTyp_HEXKEY: {
  112683. if( zRight ){
  112684. u8 iByte;
  112685. int i;
  112686. char zKey[40];
  112687. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  112688. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  112689. if( (i&1)!=0 ) zKey[i/2] = iByte;
  112690. }
  112691. if( (zLeft[3] & 0xf)==0xb ){
  112692. sqlite3_key_v2(db, zDb, zKey, i/2);
  112693. }else{
  112694. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  112695. }
  112696. }
  112697. break;
  112698. }
  112699. #endif
  112700. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  112701. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  112702. #ifdef SQLITE_HAS_CODEC
  112703. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  112704. sqlite3_activate_see(&zRight[4]);
  112705. }
  112706. #endif
  112707. #ifdef SQLITE_ENABLE_CEROD
  112708. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  112709. sqlite3_activate_cerod(&zRight[6]);
  112710. }
  112711. #endif
  112712. }
  112713. break;
  112714. #endif
  112715. } /* End of the PRAGMA switch */
  112716. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  112717. ** purpose is to execute assert() statements to verify that if the
  112718. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  112719. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  112720. ** instructions to the VM. */
  112721. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  112722. sqlite3VdbeVerifyNoResultRow(v);
  112723. }
  112724. pragma_out:
  112725. sqlite3DbFree(db, zLeft);
  112726. sqlite3DbFree(db, zRight);
  112727. }
  112728. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112729. /*****************************************************************************
  112730. ** Implementation of an eponymous virtual table that runs a pragma.
  112731. **
  112732. */
  112733. typedef struct PragmaVtab PragmaVtab;
  112734. typedef struct PragmaVtabCursor PragmaVtabCursor;
  112735. struct PragmaVtab {
  112736. sqlite3_vtab base; /* Base class. Must be first */
  112737. sqlite3 *db; /* The database connection to which it belongs */
  112738. const PragmaName *pName; /* Name of the pragma */
  112739. u8 nHidden; /* Number of hidden columns */
  112740. u8 iHidden; /* Index of the first hidden column */
  112741. };
  112742. struct PragmaVtabCursor {
  112743. sqlite3_vtab_cursor base; /* Base class. Must be first */
  112744. sqlite3_stmt *pPragma; /* The pragma statement to run */
  112745. sqlite_int64 iRowid; /* Current rowid */
  112746. char *azArg[2]; /* Value of the argument and schema */
  112747. };
  112748. /*
  112749. ** Pragma virtual table module xConnect method.
  112750. */
  112751. static int pragmaVtabConnect(
  112752. sqlite3 *db,
  112753. void *pAux,
  112754. int argc, const char *const*argv,
  112755. sqlite3_vtab **ppVtab,
  112756. char **pzErr
  112757. ){
  112758. const PragmaName *pPragma = (const PragmaName*)pAux;
  112759. PragmaVtab *pTab = 0;
  112760. int rc;
  112761. int i, j;
  112762. char cSep = '(';
  112763. StrAccum acc;
  112764. char zBuf[200];
  112765. UNUSED_PARAMETER(argc);
  112766. UNUSED_PARAMETER(argv);
  112767. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  112768. sqlite3_str_appendall(&acc, "CREATE TABLE x");
  112769. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  112770. sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  112771. cSep = ',';
  112772. }
  112773. if( i==0 ){
  112774. sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
  112775. cSep = ',';
  112776. i++;
  112777. }
  112778. j = 0;
  112779. if( pPragma->mPragFlg & PragFlg_Result1 ){
  112780. sqlite3_str_appendall(&acc, ",arg HIDDEN");
  112781. j++;
  112782. }
  112783. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  112784. sqlite3_str_appendall(&acc, ",schema HIDDEN");
  112785. j++;
  112786. }
  112787. sqlite3_str_append(&acc, ")", 1);
  112788. sqlite3StrAccumFinish(&acc);
  112789. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  112790. rc = sqlite3_declare_vtab(db, zBuf);
  112791. if( rc==SQLITE_OK ){
  112792. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  112793. if( pTab==0 ){
  112794. rc = SQLITE_NOMEM;
  112795. }else{
  112796. memset(pTab, 0, sizeof(PragmaVtab));
  112797. pTab->pName = pPragma;
  112798. pTab->db = db;
  112799. pTab->iHidden = i;
  112800. pTab->nHidden = j;
  112801. }
  112802. }else{
  112803. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  112804. }
  112805. *ppVtab = (sqlite3_vtab*)pTab;
  112806. return rc;
  112807. }
  112808. /*
  112809. ** Pragma virtual table module xDisconnect method.
  112810. */
  112811. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  112812. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  112813. sqlite3_free(pTab);
  112814. return SQLITE_OK;
  112815. }
  112816. /* Figure out the best index to use to search a pragma virtual table.
  112817. **
  112818. ** There are not really any index choices. But we want to encourage the
  112819. ** query planner to give == constraints on as many hidden parameters as
  112820. ** possible, and especially on the first hidden parameter. So return a
  112821. ** high cost if hidden parameters are unconstrained.
  112822. */
  112823. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  112824. PragmaVtab *pTab = (PragmaVtab*)tab;
  112825. const struct sqlite3_index_constraint *pConstraint;
  112826. int i, j;
  112827. int seen[2];
  112828. pIdxInfo->estimatedCost = (double)1;
  112829. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  112830. pConstraint = pIdxInfo->aConstraint;
  112831. seen[0] = 0;
  112832. seen[1] = 0;
  112833. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  112834. if( pConstraint->usable==0 ) continue;
  112835. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  112836. if( pConstraint->iColumn < pTab->iHidden ) continue;
  112837. j = pConstraint->iColumn - pTab->iHidden;
  112838. assert( j < 2 );
  112839. seen[j] = i+1;
  112840. }
  112841. if( seen[0]==0 ){
  112842. pIdxInfo->estimatedCost = (double)2147483647;
  112843. pIdxInfo->estimatedRows = 2147483647;
  112844. return SQLITE_OK;
  112845. }
  112846. j = seen[0]-1;
  112847. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  112848. pIdxInfo->aConstraintUsage[j].omit = 1;
  112849. if( seen[1]==0 ) return SQLITE_OK;
  112850. pIdxInfo->estimatedCost = (double)20;
  112851. pIdxInfo->estimatedRows = 20;
  112852. j = seen[1]-1;
  112853. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  112854. pIdxInfo->aConstraintUsage[j].omit = 1;
  112855. return SQLITE_OK;
  112856. }
  112857. /* Create a new cursor for the pragma virtual table */
  112858. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  112859. PragmaVtabCursor *pCsr;
  112860. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  112861. if( pCsr==0 ) return SQLITE_NOMEM;
  112862. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  112863. pCsr->base.pVtab = pVtab;
  112864. *ppCursor = &pCsr->base;
  112865. return SQLITE_OK;
  112866. }
  112867. /* Clear all content from pragma virtual table cursor. */
  112868. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  112869. int i;
  112870. sqlite3_finalize(pCsr->pPragma);
  112871. pCsr->pPragma = 0;
  112872. for(i=0; i<ArraySize(pCsr->azArg); i++){
  112873. sqlite3_free(pCsr->azArg[i]);
  112874. pCsr->azArg[i] = 0;
  112875. }
  112876. }
  112877. /* Close a pragma virtual table cursor */
  112878. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  112879. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  112880. pragmaVtabCursorClear(pCsr);
  112881. sqlite3_free(pCsr);
  112882. return SQLITE_OK;
  112883. }
  112884. /* Advance the pragma virtual table cursor to the next row */
  112885. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  112886. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  112887. int rc = SQLITE_OK;
  112888. /* Increment the xRowid value */
  112889. pCsr->iRowid++;
  112890. assert( pCsr->pPragma );
  112891. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  112892. rc = sqlite3_finalize(pCsr->pPragma);
  112893. pCsr->pPragma = 0;
  112894. pragmaVtabCursorClear(pCsr);
  112895. }
  112896. return rc;
  112897. }
  112898. /*
  112899. ** Pragma virtual table module xFilter method.
  112900. */
  112901. static int pragmaVtabFilter(
  112902. sqlite3_vtab_cursor *pVtabCursor,
  112903. int idxNum, const char *idxStr,
  112904. int argc, sqlite3_value **argv
  112905. ){
  112906. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  112907. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  112908. int rc;
  112909. int i, j;
  112910. StrAccum acc;
  112911. char *zSql;
  112912. UNUSED_PARAMETER(idxNum);
  112913. UNUSED_PARAMETER(idxStr);
  112914. pragmaVtabCursorClear(pCsr);
  112915. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  112916. for(i=0; i<argc; i++, j++){
  112917. const char *zText = (const char*)sqlite3_value_text(argv[i]);
  112918. assert( j<ArraySize(pCsr->azArg) );
  112919. assert( pCsr->azArg[j]==0 );
  112920. if( zText ){
  112921. pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
  112922. if( pCsr->azArg[j]==0 ){
  112923. return SQLITE_NOMEM;
  112924. }
  112925. }
  112926. }
  112927. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  112928. sqlite3_str_appendall(&acc, "PRAGMA ");
  112929. if( pCsr->azArg[1] ){
  112930. sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
  112931. }
  112932. sqlite3_str_appendall(&acc, pTab->pName->zName);
  112933. if( pCsr->azArg[0] ){
  112934. sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
  112935. }
  112936. zSql = sqlite3StrAccumFinish(&acc);
  112937. if( zSql==0 ) return SQLITE_NOMEM;
  112938. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  112939. sqlite3_free(zSql);
  112940. if( rc!=SQLITE_OK ){
  112941. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  112942. return rc;
  112943. }
  112944. return pragmaVtabNext(pVtabCursor);
  112945. }
  112946. /*
  112947. ** Pragma virtual table module xEof method.
  112948. */
  112949. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  112950. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  112951. return (pCsr->pPragma==0);
  112952. }
  112953. /* The xColumn method simply returns the corresponding column from
  112954. ** the PRAGMA.
  112955. */
  112956. static int pragmaVtabColumn(
  112957. sqlite3_vtab_cursor *pVtabCursor,
  112958. sqlite3_context *ctx,
  112959. int i
  112960. ){
  112961. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  112962. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  112963. if( i<pTab->iHidden ){
  112964. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  112965. }else{
  112966. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  112967. }
  112968. return SQLITE_OK;
  112969. }
  112970. /*
  112971. ** Pragma virtual table module xRowid method.
  112972. */
  112973. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  112974. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  112975. *p = pCsr->iRowid;
  112976. return SQLITE_OK;
  112977. }
  112978. /* The pragma virtual table object */
  112979. static const sqlite3_module pragmaVtabModule = {
  112980. 0, /* iVersion */
  112981. 0, /* xCreate - create a table */
  112982. pragmaVtabConnect, /* xConnect - connect to an existing table */
  112983. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  112984. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  112985. 0, /* xDestroy - Drop a table */
  112986. pragmaVtabOpen, /* xOpen - open a cursor */
  112987. pragmaVtabClose, /* xClose - close a cursor */
  112988. pragmaVtabFilter, /* xFilter - configure scan constraints */
  112989. pragmaVtabNext, /* xNext - advance a cursor */
  112990. pragmaVtabEof, /* xEof */
  112991. pragmaVtabColumn, /* xColumn - read data */
  112992. pragmaVtabRowid, /* xRowid - read data */
  112993. 0, /* xUpdate - write data */
  112994. 0, /* xBegin - begin transaction */
  112995. 0, /* xSync - sync transaction */
  112996. 0, /* xCommit - commit transaction */
  112997. 0, /* xRollback - rollback transaction */
  112998. 0, /* xFindFunction - function overloading */
  112999. 0, /* xRename - rename the table */
  113000. 0, /* xSavepoint */
  113001. 0, /* xRelease */
  113002. 0 /* xRollbackTo */
  113003. };
  113004. /*
  113005. ** Check to see if zTabName is really the name of a pragma. If it is,
  113006. ** then register an eponymous virtual table for that pragma and return
  113007. ** a pointer to the Module object for the new virtual table.
  113008. */
  113009. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  113010. const PragmaName *pName;
  113011. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  113012. pName = pragmaLocate(zName+7);
  113013. if( pName==0 ) return 0;
  113014. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  113015. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  113016. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  113017. }
  113018. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  113019. #endif /* SQLITE_OMIT_PRAGMA */
  113020. /************** End of pragma.c **********************************************/
  113021. /************** Begin file prepare.c *****************************************/
  113022. /*
  113023. ** 2005 May 25
  113024. **
  113025. ** The author disclaims copyright to this source code. In place of
  113026. ** a legal notice, here is a blessing:
  113027. **
  113028. ** May you do good and not evil.
  113029. ** May you find forgiveness for yourself and forgive others.
  113030. ** May you share freely, never taking more than you give.
  113031. **
  113032. *************************************************************************
  113033. ** This file contains the implementation of the sqlite3_prepare()
  113034. ** interface, and routines that contribute to loading the database schema
  113035. ** from disk.
  113036. */
  113037. /* #include "sqliteInt.h" */
  113038. /*
  113039. ** Fill the InitData structure with an error message that indicates
  113040. ** that the database is corrupt.
  113041. */
  113042. static void corruptSchema(
  113043. InitData *pData, /* Initialization context */
  113044. const char *zObj, /* Object being parsed at the point of error */
  113045. const char *zExtra /* Error information */
  113046. ){
  113047. sqlite3 *db = pData->db;
  113048. if( !db->mallocFailed && (db->flags & SQLITE_WriteSchema)==0 ){
  113049. char *z;
  113050. if( zObj==0 ) zObj = "?";
  113051. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  113052. if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  113053. sqlite3DbFree(db, *pData->pzErrMsg);
  113054. *pData->pzErrMsg = z;
  113055. }
  113056. pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
  113057. }
  113058. /*
  113059. ** This is the callback routine for the code that initializes the
  113060. ** database. See sqlite3Init() below for additional information.
  113061. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  113062. **
  113063. ** Each callback contains the following information:
  113064. **
  113065. ** argv[0] = name of thing being created
  113066. ** argv[1] = root page number for table or index. 0 for trigger or view.
  113067. ** argv[2] = SQL text for the CREATE statement.
  113068. **
  113069. */
  113070. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  113071. InitData *pData = (InitData*)pInit;
  113072. sqlite3 *db = pData->db;
  113073. int iDb = pData->iDb;
  113074. assert( argc==3 );
  113075. UNUSED_PARAMETER2(NotUsed, argc);
  113076. assert( sqlite3_mutex_held(db->mutex) );
  113077. DbClearProperty(db, iDb, DB_Empty);
  113078. if( db->mallocFailed ){
  113079. corruptSchema(pData, argv[0], 0);
  113080. return 1;
  113081. }
  113082. assert( iDb>=0 && iDb<db->nDb );
  113083. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  113084. if( argv[1]==0 ){
  113085. corruptSchema(pData, argv[0], 0);
  113086. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  113087. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  113088. ** But because db->init.busy is set to 1, no VDBE code is generated
  113089. ** or executed. All the parser does is build the internal data
  113090. ** structures that describe the table, index, or view.
  113091. */
  113092. int rc;
  113093. u8 saved_iDb = db->init.iDb;
  113094. sqlite3_stmt *pStmt;
  113095. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  113096. assert( db->init.busy );
  113097. db->init.iDb = iDb;
  113098. db->init.newTnum = sqlite3Atoi(argv[1]);
  113099. db->init.orphanTrigger = 0;
  113100. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  113101. rc = db->errCode;
  113102. assert( (rc&0xFF)==(rcp&0xFF) );
  113103. db->init.iDb = saved_iDb;
  113104. assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  113105. if( SQLITE_OK!=rc ){
  113106. if( db->init.orphanTrigger ){
  113107. assert( iDb==1 );
  113108. }else{
  113109. pData->rc = rc;
  113110. if( rc==SQLITE_NOMEM ){
  113111. sqlite3OomFault(db);
  113112. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  113113. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  113114. }
  113115. }
  113116. }
  113117. sqlite3_finalize(pStmt);
  113118. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  113119. corruptSchema(pData, argv[0], 0);
  113120. }else{
  113121. /* If the SQL column is blank it means this is an index that
  113122. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  113123. ** constraint for a CREATE TABLE. The index should have already
  113124. ** been created when we processed the CREATE TABLE. All we have
  113125. ** to do here is record the root page number for that index.
  113126. */
  113127. Index *pIndex;
  113128. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  113129. if( pIndex==0 ){
  113130. /* This can occur if there exists an index on a TEMP table which
  113131. ** has the same name as another index on a permanent index. Since
  113132. ** the permanent table is hidden by the TEMP table, we can also
  113133. ** safely ignore the index on the permanent table.
  113134. */
  113135. /* Do Nothing */;
  113136. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  113137. corruptSchema(pData, argv[0], "invalid rootpage");
  113138. }
  113139. }
  113140. return 0;
  113141. }
  113142. /*
  113143. ** Attempt to read the database schema and initialize internal
  113144. ** data structures for a single database file. The index of the
  113145. ** database file is given by iDb. iDb==0 is used for the main
  113146. ** database. iDb==1 should never be used. iDb>=2 is used for
  113147. ** auxiliary databases. Return one of the SQLITE_ error codes to
  113148. ** indicate success or failure.
  113149. */
  113150. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  113151. int rc;
  113152. int i;
  113153. #ifndef SQLITE_OMIT_DEPRECATED
  113154. int size;
  113155. #endif
  113156. Db *pDb;
  113157. char const *azArg[4];
  113158. int meta[5];
  113159. InitData initData;
  113160. const char *zMasterName;
  113161. int openedTransaction = 0;
  113162. assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
  113163. assert( iDb>=0 && iDb<db->nDb );
  113164. assert( db->aDb[iDb].pSchema );
  113165. assert( sqlite3_mutex_held(db->mutex) );
  113166. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  113167. db->init.busy = 1;
  113168. /* Construct the in-memory representation schema tables (sqlite_master or
  113169. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  113170. ** table name will be inserted automatically by the parser so we can just
  113171. ** use the abbreviation "x" here. The parser will also automatically tag
  113172. ** the schema table as read-only. */
  113173. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  113174. azArg[1] = "1";
  113175. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  113176. "rootpage int,sql text)";
  113177. azArg[3] = 0;
  113178. initData.db = db;
  113179. initData.iDb = iDb;
  113180. initData.rc = SQLITE_OK;
  113181. initData.pzErrMsg = pzErrMsg;
  113182. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  113183. if( initData.rc ){
  113184. rc = initData.rc;
  113185. goto error_out;
  113186. }
  113187. /* Create a cursor to hold the database open
  113188. */
  113189. pDb = &db->aDb[iDb];
  113190. if( pDb->pBt==0 ){
  113191. assert( iDb==1 );
  113192. DbSetProperty(db, 1, DB_SchemaLoaded);
  113193. rc = SQLITE_OK;
  113194. goto error_out;
  113195. }
  113196. /* If there is not already a read-only (or read-write) transaction opened
  113197. ** on the b-tree database, open one now. If a transaction is opened, it
  113198. ** will be closed before this function returns. */
  113199. sqlite3BtreeEnter(pDb->pBt);
  113200. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  113201. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  113202. if( rc!=SQLITE_OK ){
  113203. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  113204. goto initone_error_out;
  113205. }
  113206. openedTransaction = 1;
  113207. }
  113208. /* Get the database meta information.
  113209. **
  113210. ** Meta values are as follows:
  113211. ** meta[0] Schema cookie. Changes with each schema change.
  113212. ** meta[1] File format of schema layer.
  113213. ** meta[2] Size of the page cache.
  113214. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  113215. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  113216. ** meta[5] User version
  113217. ** meta[6] Incremental vacuum mode
  113218. ** meta[7] unused
  113219. ** meta[8] unused
  113220. ** meta[9] unused
  113221. **
  113222. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  113223. ** the possible values of meta[4].
  113224. */
  113225. for(i=0; i<ArraySize(meta); i++){
  113226. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  113227. }
  113228. if( (db->flags & SQLITE_ResetDatabase)!=0 ){
  113229. memset(meta, 0, sizeof(meta));
  113230. }
  113231. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  113232. /* If opening a non-empty database, check the text encoding. For the
  113233. ** main database, set sqlite3.enc to the encoding of the main database.
  113234. ** For an attached db, it is an error if the encoding is not the same
  113235. ** as sqlite3.enc.
  113236. */
  113237. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  113238. if( iDb==0 ){
  113239. #ifndef SQLITE_OMIT_UTF16
  113240. u8 encoding;
  113241. /* If opening the main database, set ENC(db). */
  113242. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  113243. if( encoding==0 ) encoding = SQLITE_UTF8;
  113244. ENC(db) = encoding;
  113245. #else
  113246. ENC(db) = SQLITE_UTF8;
  113247. #endif
  113248. }else{
  113249. /* If opening an attached database, the encoding much match ENC(db) */
  113250. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  113251. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  113252. " text encoding as main database");
  113253. rc = SQLITE_ERROR;
  113254. goto initone_error_out;
  113255. }
  113256. }
  113257. }else{
  113258. DbSetProperty(db, iDb, DB_Empty);
  113259. }
  113260. pDb->pSchema->enc = ENC(db);
  113261. if( pDb->pSchema->cache_size==0 ){
  113262. #ifndef SQLITE_OMIT_DEPRECATED
  113263. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  113264. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  113265. pDb->pSchema->cache_size = size;
  113266. #else
  113267. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  113268. #endif
  113269. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  113270. }
  113271. /*
  113272. ** file_format==1 Version 3.0.0.
  113273. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  113274. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  113275. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  113276. */
  113277. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  113278. if( pDb->pSchema->file_format==0 ){
  113279. pDb->pSchema->file_format = 1;
  113280. }
  113281. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  113282. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  113283. rc = SQLITE_ERROR;
  113284. goto initone_error_out;
  113285. }
  113286. /* Ticket #2804: When we open a database in the newer file format,
  113287. ** clear the legacy_file_format pragma flag so that a VACUUM will
  113288. ** not downgrade the database and thus invalidate any descending
  113289. ** indices that the user might have created.
  113290. */
  113291. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  113292. db->flags &= ~SQLITE_LegacyFileFmt;
  113293. }
  113294. /* Read the schema information out of the schema tables
  113295. */
  113296. assert( db->init.busy );
  113297. {
  113298. char *zSql;
  113299. zSql = sqlite3MPrintf(db,
  113300. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  113301. db->aDb[iDb].zDbSName, zMasterName);
  113302. #ifndef SQLITE_OMIT_AUTHORIZATION
  113303. {
  113304. sqlite3_xauth xAuth;
  113305. xAuth = db->xAuth;
  113306. db->xAuth = 0;
  113307. #endif
  113308. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  113309. #ifndef SQLITE_OMIT_AUTHORIZATION
  113310. db->xAuth = xAuth;
  113311. }
  113312. #endif
  113313. if( rc==SQLITE_OK ) rc = initData.rc;
  113314. sqlite3DbFree(db, zSql);
  113315. #ifndef SQLITE_OMIT_ANALYZE
  113316. if( rc==SQLITE_OK ){
  113317. sqlite3AnalysisLoad(db, iDb);
  113318. }
  113319. #endif
  113320. }
  113321. if( db->mallocFailed ){
  113322. rc = SQLITE_NOMEM_BKPT;
  113323. sqlite3ResetAllSchemasOfConnection(db);
  113324. }
  113325. if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
  113326. /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
  113327. ** the schema loaded, even if errors occurred. In this situation the
  113328. ** current sqlite3_prepare() operation will fail, but the following one
  113329. ** will attempt to compile the supplied statement against whatever subset
  113330. ** of the schema was loaded before the error occurred. The primary
  113331. ** purpose of this is to allow access to the sqlite_master table
  113332. ** even when its contents have been corrupted.
  113333. */
  113334. DbSetProperty(db, iDb, DB_SchemaLoaded);
  113335. rc = SQLITE_OK;
  113336. }
  113337. /* Jump here for an error that occurs after successfully allocating
  113338. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  113339. ** before that point, jump to error_out.
  113340. */
  113341. initone_error_out:
  113342. if( openedTransaction ){
  113343. sqlite3BtreeCommit(pDb->pBt);
  113344. }
  113345. sqlite3BtreeLeave(pDb->pBt);
  113346. error_out:
  113347. if( rc ){
  113348. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  113349. sqlite3OomFault(db);
  113350. }
  113351. sqlite3ResetOneSchema(db, iDb);
  113352. }
  113353. db->init.busy = 0;
  113354. return rc;
  113355. }
  113356. /*
  113357. ** Initialize all database files - the main database file, the file
  113358. ** used to store temporary tables, and any additional database files
  113359. ** created using ATTACH statements. Return a success code. If an
  113360. ** error occurs, write an error message into *pzErrMsg.
  113361. **
  113362. ** After a database is initialized, the DB_SchemaLoaded bit is set
  113363. ** bit is set in the flags field of the Db structure. If the database
  113364. ** file was of zero-length, then the DB_Empty flag is also set.
  113365. */
  113366. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  113367. int i, rc;
  113368. int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
  113369. assert( sqlite3_mutex_held(db->mutex) );
  113370. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  113371. assert( db->init.busy==0 );
  113372. ENC(db) = SCHEMA_ENC(db);
  113373. assert( db->nDb>0 );
  113374. /* Do the main schema first */
  113375. if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
  113376. rc = sqlite3InitOne(db, 0, pzErrMsg);
  113377. if( rc ) return rc;
  113378. }
  113379. /* All other schemas after the main schema. The "temp" schema must be last */
  113380. for(i=db->nDb-1; i>0; i--){
  113381. assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
  113382. if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
  113383. rc = sqlite3InitOne(db, i, pzErrMsg);
  113384. if( rc ) return rc;
  113385. }
  113386. }
  113387. if( commit_internal ){
  113388. sqlite3CommitInternalChanges(db);
  113389. }
  113390. return SQLITE_OK;
  113391. }
  113392. /*
  113393. ** This routine is a no-op if the database schema is already initialized.
  113394. ** Otherwise, the schema is loaded. An error code is returned.
  113395. */
  113396. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  113397. int rc = SQLITE_OK;
  113398. sqlite3 *db = pParse->db;
  113399. assert( sqlite3_mutex_held(db->mutex) );
  113400. if( !db->init.busy ){
  113401. rc = sqlite3Init(db, &pParse->zErrMsg);
  113402. if( rc!=SQLITE_OK ){
  113403. pParse->rc = rc;
  113404. pParse->nErr++;
  113405. }else if( db->noSharedCache ){
  113406. db->mDbFlags |= DBFLAG_SchemaKnownOk;
  113407. }
  113408. }
  113409. return rc;
  113410. }
  113411. /*
  113412. ** Check schema cookies in all databases. If any cookie is out
  113413. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  113414. ** make no changes to pParse->rc.
  113415. */
  113416. static void schemaIsValid(Parse *pParse){
  113417. sqlite3 *db = pParse->db;
  113418. int iDb;
  113419. int rc;
  113420. int cookie;
  113421. assert( pParse->checkSchema );
  113422. assert( sqlite3_mutex_held(db->mutex) );
  113423. for(iDb=0; iDb<db->nDb; iDb++){
  113424. int openedTransaction = 0; /* True if a transaction is opened */
  113425. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  113426. if( pBt==0 ) continue;
  113427. /* If there is not already a read-only (or read-write) transaction opened
  113428. ** on the b-tree database, open one now. If a transaction is opened, it
  113429. ** will be closed immediately after reading the meta-value. */
  113430. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  113431. rc = sqlite3BtreeBeginTrans(pBt, 0);
  113432. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  113433. sqlite3OomFault(db);
  113434. }
  113435. if( rc!=SQLITE_OK ) return;
  113436. openedTransaction = 1;
  113437. }
  113438. /* Read the schema cookie from the database. If it does not match the
  113439. ** value stored as part of the in-memory schema representation,
  113440. ** set Parse.rc to SQLITE_SCHEMA. */
  113441. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  113442. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  113443. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  113444. sqlite3ResetOneSchema(db, iDb);
  113445. pParse->rc = SQLITE_SCHEMA;
  113446. }
  113447. /* Close the transaction, if one was opened. */
  113448. if( openedTransaction ){
  113449. sqlite3BtreeCommit(pBt);
  113450. }
  113451. }
  113452. }
  113453. /*
  113454. ** Convert a schema pointer into the iDb index that indicates
  113455. ** which database file in db->aDb[] the schema refers to.
  113456. **
  113457. ** If the same database is attached more than once, the first
  113458. ** attached database is returned.
  113459. */
  113460. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  113461. int i = -1000000;
  113462. /* If pSchema is NULL, then return -1000000. This happens when code in
  113463. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  113464. ** created by a sub-select). In this case the return value of this
  113465. ** function should never be used.
  113466. **
  113467. ** We return -1000000 instead of the more usual -1 simply because using
  113468. ** -1000000 as the incorrect index into db->aDb[] is much
  113469. ** more likely to cause a segfault than -1 (of course there are assert()
  113470. ** statements too, but it never hurts to play the odds).
  113471. */
  113472. assert( sqlite3_mutex_held(db->mutex) );
  113473. if( pSchema ){
  113474. for(i=0; 1; i++){
  113475. assert( i<db->nDb );
  113476. if( db->aDb[i].pSchema==pSchema ){
  113477. break;
  113478. }
  113479. }
  113480. assert( i>=0 && i<db->nDb );
  113481. }
  113482. return i;
  113483. }
  113484. /*
  113485. ** Free all memory allocations in the pParse object
  113486. */
  113487. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  113488. sqlite3 *db = pParse->db;
  113489. sqlite3DbFree(db, pParse->aLabel);
  113490. sqlite3ExprListDelete(db, pParse->pConstExpr);
  113491. if( db ){
  113492. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  113493. db->lookaside.bDisable -= pParse->disableLookaside;
  113494. }
  113495. pParse->disableLookaside = 0;
  113496. }
  113497. /*
  113498. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  113499. */
  113500. static int sqlite3Prepare(
  113501. sqlite3 *db, /* Database handle. */
  113502. const char *zSql, /* UTF-8 encoded SQL statement. */
  113503. int nBytes, /* Length of zSql in bytes. */
  113504. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  113505. Vdbe *pReprepare, /* VM being reprepared */
  113506. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113507. const char **pzTail /* OUT: End of parsed string */
  113508. ){
  113509. char *zErrMsg = 0; /* Error message */
  113510. int rc = SQLITE_OK; /* Result code */
  113511. int i; /* Loop counter */
  113512. Parse sParse; /* Parsing context */
  113513. memset(&sParse, 0, PARSE_HDR_SZ);
  113514. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  113515. sParse.pReprepare = pReprepare;
  113516. assert( ppStmt && *ppStmt==0 );
  113517. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  113518. assert( sqlite3_mutex_held(db->mutex) );
  113519. /* For a long-term use prepared statement avoid the use of
  113520. ** lookaside memory.
  113521. */
  113522. if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
  113523. sParse.disableLookaside++;
  113524. db->lookaside.bDisable++;
  113525. }
  113526. /* Check to verify that it is possible to get a read lock on all
  113527. ** database schemas. The inability to get a read lock indicates that
  113528. ** some other database connection is holding a write-lock, which in
  113529. ** turn means that the other connection has made uncommitted changes
  113530. ** to the schema.
  113531. **
  113532. ** Were we to proceed and prepare the statement against the uncommitted
  113533. ** schema changes and if those schema changes are subsequently rolled
  113534. ** back and different changes are made in their place, then when this
  113535. ** prepared statement goes to run the schema cookie would fail to detect
  113536. ** the schema change. Disaster would follow.
  113537. **
  113538. ** This thread is currently holding mutexes on all Btrees (because
  113539. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  113540. ** is not possible for another thread to start a new schema change
  113541. ** while this routine is running. Hence, we do not need to hold
  113542. ** locks on the schema, we just need to make sure nobody else is
  113543. ** holding them.
  113544. **
  113545. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  113546. ** but it does *not* override schema lock detection, so this all still
  113547. ** works even if READ_UNCOMMITTED is set.
  113548. */
  113549. for(i=0; i<db->nDb; i++) {
  113550. Btree *pBt = db->aDb[i].pBt;
  113551. if( pBt ){
  113552. assert( sqlite3BtreeHoldsMutex(pBt) );
  113553. rc = sqlite3BtreeSchemaLocked(pBt);
  113554. if( rc ){
  113555. const char *zDb = db->aDb[i].zDbSName;
  113556. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  113557. testcase( db->flags & SQLITE_ReadUncommit );
  113558. goto end_prepare;
  113559. }
  113560. }
  113561. }
  113562. sqlite3VtabUnlockList(db);
  113563. sParse.db = db;
  113564. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  113565. char *zSqlCopy;
  113566. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  113567. testcase( nBytes==mxLen );
  113568. testcase( nBytes==mxLen+1 );
  113569. if( nBytes>mxLen ){
  113570. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  113571. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  113572. goto end_prepare;
  113573. }
  113574. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  113575. if( zSqlCopy ){
  113576. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  113577. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  113578. sqlite3DbFree(db, zSqlCopy);
  113579. }else{
  113580. sParse.zTail = &zSql[nBytes];
  113581. }
  113582. }else{
  113583. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  113584. }
  113585. assert( 0==sParse.nQueryLoop );
  113586. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  113587. if( sParse.checkSchema ){
  113588. schemaIsValid(&sParse);
  113589. }
  113590. if( db->mallocFailed ){
  113591. sParse.rc = SQLITE_NOMEM_BKPT;
  113592. }
  113593. if( pzTail ){
  113594. *pzTail = sParse.zTail;
  113595. }
  113596. rc = sParse.rc;
  113597. #ifndef SQLITE_OMIT_EXPLAIN
  113598. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  113599. static const char * const azColName[] = {
  113600. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  113601. "id", "parent", "notused", "detail"
  113602. };
  113603. int iFirst, mx;
  113604. if( sParse.explain==2 ){
  113605. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  113606. iFirst = 8;
  113607. mx = 12;
  113608. }else{
  113609. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  113610. iFirst = 0;
  113611. mx = 8;
  113612. }
  113613. for(i=iFirst; i<mx; i++){
  113614. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  113615. azColName[i], SQLITE_STATIC);
  113616. }
  113617. }
  113618. #endif
  113619. if( db->init.busy==0 ){
  113620. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
  113621. }
  113622. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  113623. sqlite3VdbeFinalize(sParse.pVdbe);
  113624. assert(!(*ppStmt));
  113625. }else{
  113626. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  113627. }
  113628. if( zErrMsg ){
  113629. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  113630. sqlite3DbFree(db, zErrMsg);
  113631. }else{
  113632. sqlite3Error(db, rc);
  113633. }
  113634. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  113635. while( sParse.pTriggerPrg ){
  113636. TriggerPrg *pT = sParse.pTriggerPrg;
  113637. sParse.pTriggerPrg = pT->pNext;
  113638. sqlite3DbFree(db, pT);
  113639. }
  113640. end_prepare:
  113641. sqlite3ParserReset(&sParse);
  113642. return rc;
  113643. }
  113644. static int sqlite3LockAndPrepare(
  113645. sqlite3 *db, /* Database handle. */
  113646. const char *zSql, /* UTF-8 encoded SQL statement. */
  113647. int nBytes, /* Length of zSql in bytes. */
  113648. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  113649. Vdbe *pOld, /* VM being reprepared */
  113650. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113651. const char **pzTail /* OUT: End of parsed string */
  113652. ){
  113653. int rc;
  113654. int cnt = 0;
  113655. #ifdef SQLITE_ENABLE_API_ARMOR
  113656. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  113657. #endif
  113658. *ppStmt = 0;
  113659. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  113660. return SQLITE_MISUSE_BKPT;
  113661. }
  113662. sqlite3_mutex_enter(db->mutex);
  113663. sqlite3BtreeEnterAll(db);
  113664. do{
  113665. /* Make multiple attempts to compile the SQL, until it either succeeds
  113666. ** or encounters a permanent error. A schema problem after one schema
  113667. ** reset is considered a permanent error. */
  113668. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  113669. assert( rc==SQLITE_OK || *ppStmt==0 );
  113670. }while( rc==SQLITE_ERROR_RETRY
  113671. || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
  113672. sqlite3BtreeLeaveAll(db);
  113673. rc = sqlite3ApiExit(db, rc);
  113674. assert( (rc&db->errMask)==rc );
  113675. sqlite3_mutex_leave(db->mutex);
  113676. return rc;
  113677. }
  113678. /*
  113679. ** Rerun the compilation of a statement after a schema change.
  113680. **
  113681. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  113682. ** if the statement cannot be recompiled because another connection has
  113683. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  113684. ** occurs, return SQLITE_SCHEMA.
  113685. */
  113686. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  113687. int rc;
  113688. sqlite3_stmt *pNew;
  113689. const char *zSql;
  113690. sqlite3 *db;
  113691. u8 prepFlags;
  113692. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  113693. zSql = sqlite3_sql((sqlite3_stmt *)p);
  113694. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  113695. db = sqlite3VdbeDb(p);
  113696. assert( sqlite3_mutex_held(db->mutex) );
  113697. prepFlags = sqlite3VdbePrepareFlags(p);
  113698. rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
  113699. if( rc ){
  113700. if( rc==SQLITE_NOMEM ){
  113701. sqlite3OomFault(db);
  113702. }
  113703. assert( pNew==0 );
  113704. return rc;
  113705. }else{
  113706. assert( pNew!=0 );
  113707. }
  113708. sqlite3VdbeSwap((Vdbe*)pNew, p);
  113709. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  113710. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  113711. sqlite3VdbeFinalize((Vdbe*)pNew);
  113712. return SQLITE_OK;
  113713. }
  113714. /*
  113715. ** Two versions of the official API. Legacy and new use. In the legacy
  113716. ** version, the original SQL text is not saved in the prepared statement
  113717. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  113718. ** sqlite3_step(). In the new version, the original SQL text is retained
  113719. ** and the statement is automatically recompiled if an schema change
  113720. ** occurs.
  113721. */
  113722. SQLITE_API int sqlite3_prepare(
  113723. sqlite3 *db, /* Database handle. */
  113724. const char *zSql, /* UTF-8 encoded SQL statement. */
  113725. int nBytes, /* Length of zSql in bytes. */
  113726. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113727. const char **pzTail /* OUT: End of parsed string */
  113728. ){
  113729. int rc;
  113730. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  113731. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  113732. return rc;
  113733. }
  113734. SQLITE_API int sqlite3_prepare_v2(
  113735. sqlite3 *db, /* Database handle. */
  113736. const char *zSql, /* UTF-8 encoded SQL statement. */
  113737. int nBytes, /* Length of zSql in bytes. */
  113738. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113739. const char **pzTail /* OUT: End of parsed string */
  113740. ){
  113741. int rc;
  113742. /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
  113743. ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
  113744. ** parameter.
  113745. **
  113746. ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
  113747. rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
  113748. ppStmt,pzTail);
  113749. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  113750. return rc;
  113751. }
  113752. SQLITE_API int sqlite3_prepare_v3(
  113753. sqlite3 *db, /* Database handle. */
  113754. const char *zSql, /* UTF-8 encoded SQL statement. */
  113755. int nBytes, /* Length of zSql in bytes. */
  113756. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  113757. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113758. const char **pzTail /* OUT: End of parsed string */
  113759. ){
  113760. int rc;
  113761. /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
  113762. ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
  113763. ** which is a bit array consisting of zero or more of the
  113764. ** SQLITE_PREPARE_* flags.
  113765. **
  113766. ** Proof by comparison to the implementation of sqlite3_prepare_v2()
  113767. ** directly above. */
  113768. rc = sqlite3LockAndPrepare(db,zSql,nBytes,
  113769. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  113770. 0,ppStmt,pzTail);
  113771. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  113772. return rc;
  113773. }
  113774. #ifndef SQLITE_OMIT_UTF16
  113775. /*
  113776. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  113777. */
  113778. static int sqlite3Prepare16(
  113779. sqlite3 *db, /* Database handle. */
  113780. const void *zSql, /* UTF-16 encoded SQL statement. */
  113781. int nBytes, /* Length of zSql in bytes. */
  113782. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  113783. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113784. const void **pzTail /* OUT: End of parsed string */
  113785. ){
  113786. /* This function currently works by first transforming the UTF-16
  113787. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  113788. ** tricky bit is figuring out the pointer to return in *pzTail.
  113789. */
  113790. char *zSql8;
  113791. const char *zTail8 = 0;
  113792. int rc = SQLITE_OK;
  113793. #ifdef SQLITE_ENABLE_API_ARMOR
  113794. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  113795. #endif
  113796. *ppStmt = 0;
  113797. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  113798. return SQLITE_MISUSE_BKPT;
  113799. }
  113800. if( nBytes>=0 ){
  113801. int sz;
  113802. const char *z = (const char*)zSql;
  113803. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  113804. nBytes = sz;
  113805. }
  113806. sqlite3_mutex_enter(db->mutex);
  113807. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  113808. if( zSql8 ){
  113809. rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
  113810. }
  113811. if( zTail8 && pzTail ){
  113812. /* If sqlite3_prepare returns a tail pointer, we calculate the
  113813. ** equivalent pointer into the UTF-16 string by counting the unicode
  113814. ** characters between zSql8 and zTail8, and then returning a pointer
  113815. ** the same number of characters into the UTF-16 string.
  113816. */
  113817. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  113818. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  113819. }
  113820. sqlite3DbFree(db, zSql8);
  113821. rc = sqlite3ApiExit(db, rc);
  113822. sqlite3_mutex_leave(db->mutex);
  113823. return rc;
  113824. }
  113825. /*
  113826. ** Two versions of the official API. Legacy and new use. In the legacy
  113827. ** version, the original SQL text is not saved in the prepared statement
  113828. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  113829. ** sqlite3_step(). In the new version, the original SQL text is retained
  113830. ** and the statement is automatically recompiled if an schema change
  113831. ** occurs.
  113832. */
  113833. SQLITE_API int sqlite3_prepare16(
  113834. sqlite3 *db, /* Database handle. */
  113835. const void *zSql, /* UTF-16 encoded SQL statement. */
  113836. int nBytes, /* Length of zSql in bytes. */
  113837. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113838. const void **pzTail /* OUT: End of parsed string */
  113839. ){
  113840. int rc;
  113841. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  113842. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  113843. return rc;
  113844. }
  113845. SQLITE_API int sqlite3_prepare16_v2(
  113846. sqlite3 *db, /* Database handle. */
  113847. const void *zSql, /* UTF-16 encoded SQL statement. */
  113848. int nBytes, /* Length of zSql in bytes. */
  113849. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113850. const void **pzTail /* OUT: End of parsed string */
  113851. ){
  113852. int rc;
  113853. rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
  113854. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  113855. return rc;
  113856. }
  113857. SQLITE_API int sqlite3_prepare16_v3(
  113858. sqlite3 *db, /* Database handle. */
  113859. const void *zSql, /* UTF-16 encoded SQL statement. */
  113860. int nBytes, /* Length of zSql in bytes. */
  113861. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  113862. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  113863. const void **pzTail /* OUT: End of parsed string */
  113864. ){
  113865. int rc;
  113866. rc = sqlite3Prepare16(db,zSql,nBytes,
  113867. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  113868. ppStmt,pzTail);
  113869. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  113870. return rc;
  113871. }
  113872. #endif /* SQLITE_OMIT_UTF16 */
  113873. /************** End of prepare.c *********************************************/
  113874. /************** Begin file select.c ******************************************/
  113875. /*
  113876. ** 2001 September 15
  113877. **
  113878. ** The author disclaims copyright to this source code. In place of
  113879. ** a legal notice, here is a blessing:
  113880. **
  113881. ** May you do good and not evil.
  113882. ** May you find forgiveness for yourself and forgive others.
  113883. ** May you share freely, never taking more than you give.
  113884. **
  113885. *************************************************************************
  113886. ** This file contains C code routines that are called by the parser
  113887. ** to handle SELECT statements in SQLite.
  113888. */
  113889. /* #include "sqliteInt.h" */
  113890. /*
  113891. ** Trace output macros
  113892. */
  113893. #if SELECTTRACE_ENABLED
  113894. /***/ int sqlite3SelectTrace = 0;
  113895. # define SELECTTRACE(K,P,S,X) \
  113896. if(sqlite3SelectTrace&(K)) \
  113897. sqlite3DebugPrintf("%s/%d/%p: ",(S)->zSelName,(P)->addrExplain,(S)),\
  113898. sqlite3DebugPrintf X
  113899. #else
  113900. # define SELECTTRACE(K,P,S,X)
  113901. #endif
  113902. /*
  113903. ** An instance of the following object is used to record information about
  113904. ** how to process the DISTINCT keyword, to simplify passing that information
  113905. ** into the selectInnerLoop() routine.
  113906. */
  113907. typedef struct DistinctCtx DistinctCtx;
  113908. struct DistinctCtx {
  113909. u8 isTnct; /* True if the DISTINCT keyword is present */
  113910. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  113911. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  113912. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  113913. };
  113914. /*
  113915. ** An instance of the following object is used to record information about
  113916. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  113917. **
  113918. ** The aDefer[] array is used by the sorter-references optimization. For
  113919. ** example, assuming there is no index that can be used for the ORDER BY,
  113920. ** for the query:
  113921. **
  113922. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
  113923. **
  113924. ** it may be more efficient to add just the "a" values to the sorter, and
  113925. ** retrieve the associated "bigblob" values directly from table t1 as the
  113926. ** 10 smallest "a" values are extracted from the sorter.
  113927. **
  113928. ** When the sorter-reference optimization is used, there is one entry in the
  113929. ** aDefer[] array for each database table that may be read as values are
  113930. ** extracted from the sorter.
  113931. */
  113932. typedef struct SortCtx SortCtx;
  113933. struct SortCtx {
  113934. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  113935. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  113936. int iECursor; /* Cursor number for the sorter */
  113937. int regReturn; /* Register holding block-output return address */
  113938. int labelBkOut; /* Start label for the block-output subroutine */
  113939. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  113940. int labelDone; /* Jump here when done, ex: LIMIT reached */
  113941. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  113942. u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
  113943. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  113944. u8 nDefer; /* Number of valid entries in aDefer[] */
  113945. struct DeferredCsr {
  113946. Table *pTab; /* Table definition */
  113947. int iCsr; /* Cursor number for table */
  113948. int nKey; /* Number of PK columns for table pTab (>=1) */
  113949. } aDefer[4];
  113950. #endif
  113951. struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
  113952. };
  113953. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  113954. /*
  113955. ** Delete all the content of a Select structure. Deallocate the structure
  113956. ** itself only if bFree is true.
  113957. */
  113958. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  113959. while( p ){
  113960. Select *pPrior = p->pPrior;
  113961. sqlite3ExprListDelete(db, p->pEList);
  113962. sqlite3SrcListDelete(db, p->pSrc);
  113963. sqlite3ExprDelete(db, p->pWhere);
  113964. sqlite3ExprListDelete(db, p->pGroupBy);
  113965. sqlite3ExprDelete(db, p->pHaving);
  113966. sqlite3ExprListDelete(db, p->pOrderBy);
  113967. sqlite3ExprDelete(db, p->pLimit);
  113968. if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
  113969. if( bFree ) sqlite3DbFreeNN(db, p);
  113970. p = pPrior;
  113971. bFree = 1;
  113972. }
  113973. }
  113974. /*
  113975. ** Initialize a SelectDest structure.
  113976. */
  113977. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  113978. pDest->eDest = (u8)eDest;
  113979. pDest->iSDParm = iParm;
  113980. pDest->zAffSdst = 0;
  113981. pDest->iSdst = 0;
  113982. pDest->nSdst = 0;
  113983. }
  113984. /*
  113985. ** Allocate a new Select structure and return a pointer to that
  113986. ** structure.
  113987. */
  113988. SQLITE_PRIVATE Select *sqlite3SelectNew(
  113989. Parse *pParse, /* Parsing context */
  113990. ExprList *pEList, /* which columns to include in the result */
  113991. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  113992. Expr *pWhere, /* the WHERE clause */
  113993. ExprList *pGroupBy, /* the GROUP BY clause */
  113994. Expr *pHaving, /* the HAVING clause */
  113995. ExprList *pOrderBy, /* the ORDER BY clause */
  113996. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  113997. Expr *pLimit /* LIMIT value. NULL means not used */
  113998. ){
  113999. Select *pNew;
  114000. Select standin;
  114001. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  114002. if( pNew==0 ){
  114003. assert( pParse->db->mallocFailed );
  114004. pNew = &standin;
  114005. }
  114006. if( pEList==0 ){
  114007. pEList = sqlite3ExprListAppend(pParse, 0,
  114008. sqlite3Expr(pParse->db,TK_ASTERISK,0));
  114009. }
  114010. pNew->pEList = pEList;
  114011. pNew->op = TK_SELECT;
  114012. pNew->selFlags = selFlags;
  114013. pNew->iLimit = 0;
  114014. pNew->iOffset = 0;
  114015. #if SELECTTRACE_ENABLED
  114016. pNew->zSelName[0] = 0;
  114017. #endif
  114018. pNew->addrOpenEphm[0] = -1;
  114019. pNew->addrOpenEphm[1] = -1;
  114020. pNew->nSelectRow = 0;
  114021. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  114022. pNew->pSrc = pSrc;
  114023. pNew->pWhere = pWhere;
  114024. pNew->pGroupBy = pGroupBy;
  114025. pNew->pHaving = pHaving;
  114026. pNew->pOrderBy = pOrderBy;
  114027. pNew->pPrior = 0;
  114028. pNew->pNext = 0;
  114029. pNew->pLimit = pLimit;
  114030. pNew->pWith = 0;
  114031. if( pParse->db->mallocFailed ) {
  114032. clearSelect(pParse->db, pNew, pNew!=&standin);
  114033. pNew = 0;
  114034. }else{
  114035. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  114036. }
  114037. assert( pNew!=&standin );
  114038. return pNew;
  114039. }
  114040. #if SELECTTRACE_ENABLED
  114041. /*
  114042. ** Set the name of a Select object
  114043. */
  114044. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  114045. if( p && zName ){
  114046. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  114047. }
  114048. }
  114049. #endif
  114050. /*
  114051. ** Delete the given Select structure and all of its substructures.
  114052. */
  114053. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  114054. if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
  114055. }
  114056. /*
  114057. ** Return a pointer to the right-most SELECT statement in a compound.
  114058. */
  114059. static Select *findRightmost(Select *p){
  114060. while( p->pNext ) p = p->pNext;
  114061. return p;
  114062. }
  114063. /*
  114064. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  114065. ** type of join. Return an integer constant that expresses that type
  114066. ** in terms of the following bit values:
  114067. **
  114068. ** JT_INNER
  114069. ** JT_CROSS
  114070. ** JT_OUTER
  114071. ** JT_NATURAL
  114072. ** JT_LEFT
  114073. ** JT_RIGHT
  114074. **
  114075. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  114076. **
  114077. ** If an illegal or unsupported join type is seen, then still return
  114078. ** a join type, but put an error in the pParse structure.
  114079. */
  114080. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  114081. int jointype = 0;
  114082. Token *apAll[3];
  114083. Token *p;
  114084. /* 0123456789 123456789 123456789 123 */
  114085. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  114086. static const struct {
  114087. u8 i; /* Beginning of keyword text in zKeyText[] */
  114088. u8 nChar; /* Length of the keyword in characters */
  114089. u8 code; /* Join type mask */
  114090. } aKeyword[] = {
  114091. /* natural */ { 0, 7, JT_NATURAL },
  114092. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  114093. /* outer */ { 10, 5, JT_OUTER },
  114094. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  114095. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  114096. /* inner */ { 23, 5, JT_INNER },
  114097. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  114098. };
  114099. int i, j;
  114100. apAll[0] = pA;
  114101. apAll[1] = pB;
  114102. apAll[2] = pC;
  114103. for(i=0; i<3 && apAll[i]; i++){
  114104. p = apAll[i];
  114105. for(j=0; j<ArraySize(aKeyword); j++){
  114106. if( p->n==aKeyword[j].nChar
  114107. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  114108. jointype |= aKeyword[j].code;
  114109. break;
  114110. }
  114111. }
  114112. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  114113. if( j>=ArraySize(aKeyword) ){
  114114. jointype |= JT_ERROR;
  114115. break;
  114116. }
  114117. }
  114118. if(
  114119. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  114120. (jointype & JT_ERROR)!=0
  114121. ){
  114122. const char *zSp = " ";
  114123. assert( pB!=0 );
  114124. if( pC==0 ){ zSp++; }
  114125. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  114126. "%T %T%s%T", pA, pB, zSp, pC);
  114127. jointype = JT_INNER;
  114128. }else if( (jointype & JT_OUTER)!=0
  114129. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  114130. sqlite3ErrorMsg(pParse,
  114131. "RIGHT and FULL OUTER JOINs are not currently supported");
  114132. jointype = JT_INNER;
  114133. }
  114134. return jointype;
  114135. }
  114136. /*
  114137. ** Return the index of a column in a table. Return -1 if the column
  114138. ** is not contained in the table.
  114139. */
  114140. static int columnIndex(Table *pTab, const char *zCol){
  114141. int i;
  114142. for(i=0; i<pTab->nCol; i++){
  114143. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  114144. }
  114145. return -1;
  114146. }
  114147. /*
  114148. ** Search the first N tables in pSrc, from left to right, looking for a
  114149. ** table that has a column named zCol.
  114150. **
  114151. ** When found, set *piTab and *piCol to the table index and column index
  114152. ** of the matching column and return TRUE.
  114153. **
  114154. ** If not found, return FALSE.
  114155. */
  114156. static int tableAndColumnIndex(
  114157. SrcList *pSrc, /* Array of tables to search */
  114158. int N, /* Number of tables in pSrc->a[] to search */
  114159. const char *zCol, /* Name of the column we are looking for */
  114160. int *piTab, /* Write index of pSrc->a[] here */
  114161. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  114162. ){
  114163. int i; /* For looping over tables in pSrc */
  114164. int iCol; /* Index of column matching zCol */
  114165. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  114166. for(i=0; i<N; i++){
  114167. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  114168. if( iCol>=0 ){
  114169. if( piTab ){
  114170. *piTab = i;
  114171. *piCol = iCol;
  114172. }
  114173. return 1;
  114174. }
  114175. }
  114176. return 0;
  114177. }
  114178. /*
  114179. ** This function is used to add terms implied by JOIN syntax to the
  114180. ** WHERE clause expression of a SELECT statement. The new term, which
  114181. ** is ANDed with the existing WHERE clause, is of the form:
  114182. **
  114183. ** (tab1.col1 = tab2.col2)
  114184. **
  114185. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  114186. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  114187. ** column iColRight of tab2.
  114188. */
  114189. static void addWhereTerm(
  114190. Parse *pParse, /* Parsing context */
  114191. SrcList *pSrc, /* List of tables in FROM clause */
  114192. int iLeft, /* Index of first table to join in pSrc */
  114193. int iColLeft, /* Index of column in first table */
  114194. int iRight, /* Index of second table in pSrc */
  114195. int iColRight, /* Index of column in second table */
  114196. int isOuterJoin, /* True if this is an OUTER join */
  114197. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  114198. ){
  114199. sqlite3 *db = pParse->db;
  114200. Expr *pE1;
  114201. Expr *pE2;
  114202. Expr *pEq;
  114203. assert( iLeft<iRight );
  114204. assert( pSrc->nSrc>iRight );
  114205. assert( pSrc->a[iLeft].pTab );
  114206. assert( pSrc->a[iRight].pTab );
  114207. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  114208. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  114209. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  114210. if( pEq && isOuterJoin ){
  114211. ExprSetProperty(pEq, EP_FromJoin);
  114212. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  114213. ExprSetVVAProperty(pEq, EP_NoReduce);
  114214. pEq->iRightJoinTable = (i16)pE2->iTable;
  114215. }
  114216. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  114217. }
  114218. /*
  114219. ** Set the EP_FromJoin property on all terms of the given expression.
  114220. ** And set the Expr.iRightJoinTable to iTable for every term in the
  114221. ** expression.
  114222. **
  114223. ** The EP_FromJoin property is used on terms of an expression to tell
  114224. ** the LEFT OUTER JOIN processing logic that this term is part of the
  114225. ** join restriction specified in the ON or USING clause and not a part
  114226. ** of the more general WHERE clause. These terms are moved over to the
  114227. ** WHERE clause during join processing but we need to remember that they
  114228. ** originated in the ON or USING clause.
  114229. **
  114230. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  114231. ** expression depends on table iRightJoinTable even if that table is not
  114232. ** explicitly mentioned in the expression. That information is needed
  114233. ** for cases like this:
  114234. **
  114235. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  114236. **
  114237. ** The where clause needs to defer the handling of the t1.x=5
  114238. ** term until after the t2 loop of the join. In that way, a
  114239. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  114240. ** defer the handling of t1.x=5, it will be processed immediately
  114241. ** after the t1 loop and rows with t1.x!=5 will never appear in
  114242. ** the output, which is incorrect.
  114243. */
  114244. static void setJoinExpr(Expr *p, int iTable){
  114245. while( p ){
  114246. ExprSetProperty(p, EP_FromJoin);
  114247. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  114248. ExprSetVVAProperty(p, EP_NoReduce);
  114249. p->iRightJoinTable = (i16)iTable;
  114250. if( p->op==TK_FUNCTION && p->x.pList ){
  114251. int i;
  114252. for(i=0; i<p->x.pList->nExpr; i++){
  114253. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  114254. }
  114255. }
  114256. setJoinExpr(p->pLeft, iTable);
  114257. p = p->pRight;
  114258. }
  114259. }
  114260. /* Undo the work of setJoinExpr(). In the expression tree p, convert every
  114261. ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
  114262. ** an ordinary term that omits the EP_FromJoin mark.
  114263. **
  114264. ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
  114265. */
  114266. static void unsetJoinExpr(Expr *p, int iTable){
  114267. while( p ){
  114268. if( ExprHasProperty(p, EP_FromJoin)
  114269. && (iTable<0 || p->iRightJoinTable==iTable) ){
  114270. ExprClearProperty(p, EP_FromJoin);
  114271. }
  114272. if( p->op==TK_FUNCTION && p->x.pList ){
  114273. int i;
  114274. for(i=0; i<p->x.pList->nExpr; i++){
  114275. unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
  114276. }
  114277. }
  114278. unsetJoinExpr(p->pLeft, iTable);
  114279. p = p->pRight;
  114280. }
  114281. }
  114282. /*
  114283. ** This routine processes the join information for a SELECT statement.
  114284. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  114285. ** NATURAL joins also create extra WHERE clause terms.
  114286. **
  114287. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  114288. ** The left most table is the first entry in Select.pSrc. The right-most
  114289. ** table is the last entry. The join operator is held in the entry to
  114290. ** the left. Thus entry 0 contains the join operator for the join between
  114291. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  114292. ** also attached to the left entry.
  114293. **
  114294. ** This routine returns the number of errors encountered.
  114295. */
  114296. static int sqliteProcessJoin(Parse *pParse, Select *p){
  114297. SrcList *pSrc; /* All tables in the FROM clause */
  114298. int i, j; /* Loop counters */
  114299. struct SrcList_item *pLeft; /* Left table being joined */
  114300. struct SrcList_item *pRight; /* Right table being joined */
  114301. pSrc = p->pSrc;
  114302. pLeft = &pSrc->a[0];
  114303. pRight = &pLeft[1];
  114304. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  114305. Table *pRightTab = pRight->pTab;
  114306. int isOuter;
  114307. if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
  114308. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  114309. /* When the NATURAL keyword is present, add WHERE clause terms for
  114310. ** every column that the two tables have in common.
  114311. */
  114312. if( pRight->fg.jointype & JT_NATURAL ){
  114313. if( pRight->pOn || pRight->pUsing ){
  114314. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  114315. "an ON or USING clause", 0);
  114316. return 1;
  114317. }
  114318. for(j=0; j<pRightTab->nCol; j++){
  114319. char *zName; /* Name of column in the right table */
  114320. int iLeft; /* Matching left table */
  114321. int iLeftCol; /* Matching column in the left table */
  114322. zName = pRightTab->aCol[j].zName;
  114323. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  114324. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  114325. isOuter, &p->pWhere);
  114326. }
  114327. }
  114328. }
  114329. /* Disallow both ON and USING clauses in the same join
  114330. */
  114331. if( pRight->pOn && pRight->pUsing ){
  114332. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  114333. "clauses in the same join");
  114334. return 1;
  114335. }
  114336. /* Add the ON clause to the end of the WHERE clause, connected by
  114337. ** an AND operator.
  114338. */
  114339. if( pRight->pOn ){
  114340. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  114341. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  114342. pRight->pOn = 0;
  114343. }
  114344. /* Create extra terms on the WHERE clause for each column named
  114345. ** in the USING clause. Example: If the two tables to be joined are
  114346. ** A and B and the USING clause names X, Y, and Z, then add this
  114347. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  114348. ** Report an error if any column mentioned in the USING clause is
  114349. ** not contained in both tables to be joined.
  114350. */
  114351. if( pRight->pUsing ){
  114352. IdList *pList = pRight->pUsing;
  114353. for(j=0; j<pList->nId; j++){
  114354. char *zName; /* Name of the term in the USING clause */
  114355. int iLeft; /* Table on the left with matching column name */
  114356. int iLeftCol; /* Column number of matching column on the left */
  114357. int iRightCol; /* Column number of matching column on the right */
  114358. zName = pList->a[j].zName;
  114359. iRightCol = columnIndex(pRightTab, zName);
  114360. if( iRightCol<0
  114361. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  114362. ){
  114363. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  114364. "not present in both tables", zName);
  114365. return 1;
  114366. }
  114367. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  114368. isOuter, &p->pWhere);
  114369. }
  114370. }
  114371. }
  114372. return 0;
  114373. }
  114374. /* Forward reference */
  114375. static KeyInfo *keyInfoFromExprList(
  114376. Parse *pParse, /* Parsing context */
  114377. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  114378. int iStart, /* Begin with this column of pList */
  114379. int nExtra /* Add this many extra columns to the end */
  114380. );
  114381. /*
  114382. ** An instance of this object holds information (beyond pParse and pSelect)
  114383. ** needed to load the next result row that is to be added to the sorter.
  114384. */
  114385. typedef struct RowLoadInfo RowLoadInfo;
  114386. struct RowLoadInfo {
  114387. int regResult; /* Store results in array of registers here */
  114388. u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
  114389. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  114390. ExprList *pExtra; /* Extra columns needed by sorter refs */
  114391. int regExtraResult; /* Where to load the extra columns */
  114392. #endif
  114393. };
  114394. /*
  114395. ** This routine does the work of loading query data into an array of
  114396. ** registers so that it can be added to the sorter.
  114397. */
  114398. static void innerLoopLoadRow(
  114399. Parse *pParse, /* Statement under construction */
  114400. Select *pSelect, /* The query being coded */
  114401. RowLoadInfo *pInfo /* Info needed to complete the row load */
  114402. ){
  114403. sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
  114404. 0, pInfo->ecelFlags);
  114405. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  114406. if( pInfo->pExtra ){
  114407. sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
  114408. sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
  114409. }
  114410. #endif
  114411. }
  114412. /*
  114413. ** Code the OP_MakeRecord instruction that generates the entry to be
  114414. ** added into the sorter.
  114415. **
  114416. ** Return the register in which the result is stored.
  114417. */
  114418. static int makeSorterRecord(
  114419. Parse *pParse,
  114420. SortCtx *pSort,
  114421. Select *pSelect,
  114422. int regBase,
  114423. int nBase
  114424. ){
  114425. int nOBSat = pSort->nOBSat;
  114426. Vdbe *v = pParse->pVdbe;
  114427. int regOut = ++pParse->nMem;
  114428. if( pSort->pDeferredRowLoad ){
  114429. innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
  114430. }
  114431. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
  114432. return regOut;
  114433. }
  114434. /*
  114435. ** Generate code that will push the record in registers regData
  114436. ** through regData+nData-1 onto the sorter.
  114437. */
  114438. static void pushOntoSorter(
  114439. Parse *pParse, /* Parser context */
  114440. SortCtx *pSort, /* Information about the ORDER BY clause */
  114441. Select *pSelect, /* The whole SELECT statement */
  114442. int regData, /* First register holding data to be sorted */
  114443. int regOrigData, /* First register holding data before packing */
  114444. int nData, /* Number of elements in the regData data array */
  114445. int nPrefixReg /* No. of reg prior to regData available for use */
  114446. ){
  114447. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  114448. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  114449. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  114450. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  114451. int regBase; /* Regs for sorter record */
  114452. int regRecord = 0; /* Assembled sorter record */
  114453. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  114454. int op; /* Opcode to add sorter record to sorter */
  114455. int iLimit; /* LIMIT counter */
  114456. int iSkip = 0; /* End of the sorter insert loop */
  114457. assert( bSeq==0 || bSeq==1 );
  114458. /* Three cases:
  114459. ** (1) The data to be sorted has already been packed into a Record
  114460. ** by a prior OP_MakeRecord. In this case nData==1 and regData
  114461. ** will be completely unrelated to regOrigData.
  114462. ** (2) All output columns are included in the sort record. In that
  114463. ** case regData==regOrigData.
  114464. ** (3) Some output columns are omitted from the sort record due to
  114465. ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
  114466. ** SQLITE_ECEL_OMITREF optimization, or due to the
  114467. ** SortCtx.pDeferredRowLoad optimiation. In any of these cases
  114468. ** regOrigData is 0 to prevent this routine from trying to copy
  114469. ** values that might not yet exist.
  114470. */
  114471. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  114472. if( nPrefixReg ){
  114473. assert( nPrefixReg==nExpr+bSeq );
  114474. regBase = regData - nPrefixReg;
  114475. }else{
  114476. regBase = pParse->nMem + 1;
  114477. pParse->nMem += nBase;
  114478. }
  114479. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  114480. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  114481. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  114482. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  114483. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  114484. if( bSeq ){
  114485. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  114486. }
  114487. if( nPrefixReg==0 && nData>0 ){
  114488. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  114489. }
  114490. if( nOBSat>0 ){
  114491. int regPrevKey; /* The first nOBSat columns of the previous row */
  114492. int addrFirst; /* Address of the OP_IfNot opcode */
  114493. int addrJmp; /* Address of the OP_Jump opcode */
  114494. VdbeOp *pOp; /* Opcode that opens the sorter */
  114495. int nKey; /* Number of sorting key columns, including OP_Sequence */
  114496. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  114497. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  114498. regPrevKey = pParse->nMem+1;
  114499. pParse->nMem += pSort->nOBSat;
  114500. nKey = nExpr - pSort->nOBSat + bSeq;
  114501. if( bSeq ){
  114502. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  114503. }else{
  114504. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  114505. }
  114506. VdbeCoverage(v);
  114507. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  114508. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  114509. if( pParse->db->mallocFailed ) return;
  114510. pOp->p2 = nKey + nData;
  114511. pKI = pOp->p4.pKeyInfo;
  114512. memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
  114513. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  114514. testcase( pKI->nAllField > pKI->nKeyField+2 );
  114515. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  114516. pKI->nAllField-pKI->nKeyField-1);
  114517. addrJmp = sqlite3VdbeCurrentAddr(v);
  114518. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  114519. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  114520. pSort->regReturn = ++pParse->nMem;
  114521. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  114522. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  114523. if( iLimit ){
  114524. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  114525. VdbeCoverage(v);
  114526. }
  114527. sqlite3VdbeJumpHere(v, addrFirst);
  114528. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  114529. sqlite3VdbeJumpHere(v, addrJmp);
  114530. }
  114531. if( iLimit ){
  114532. /* At this point the values for the new sorter entry are stored
  114533. ** in an array of registers. They need to be composed into a record
  114534. ** and inserted into the sorter if either (a) there are currently
  114535. ** less than LIMIT+OFFSET items or (b) the new record is smaller than
  114536. ** the largest record currently in the sorter. If (b) is true and there
  114537. ** are already LIMIT+OFFSET items in the sorter, delete the largest
  114538. ** entry before inserting the new one. This way there are never more
  114539. ** than LIMIT+OFFSET items in the sorter.
  114540. **
  114541. ** If the new record does not need to be inserted into the sorter,
  114542. ** jump to the next iteration of the loop. Or, if the
  114543. ** pSort->bOrderedInnerLoop flag is set to indicate that the inner
  114544. ** loop delivers items in sorted order, jump to the next iteration
  114545. ** of the outer loop.
  114546. */
  114547. int iCsr = pSort->iECursor;
  114548. sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
  114549. VdbeCoverage(v);
  114550. sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
  114551. iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
  114552. iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
  114553. VdbeCoverage(v);
  114554. sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
  114555. }
  114556. if( regRecord==0 ){
  114557. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  114558. }
  114559. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  114560. op = OP_SorterInsert;
  114561. }else{
  114562. op = OP_IdxInsert;
  114563. }
  114564. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  114565. regBase+nOBSat, nBase-nOBSat);
  114566. if( iSkip ){
  114567. assert( pSort->bOrderedInnerLoop==0 || pSort->bOrderedInnerLoop==1 );
  114568. sqlite3VdbeChangeP2(v, iSkip,
  114569. sqlite3VdbeCurrentAddr(v) + pSort->bOrderedInnerLoop);
  114570. }
  114571. }
  114572. /*
  114573. ** Add code to implement the OFFSET
  114574. */
  114575. static void codeOffset(
  114576. Vdbe *v, /* Generate code into this VM */
  114577. int iOffset, /* Register holding the offset counter */
  114578. int iContinue /* Jump here to skip the current record */
  114579. ){
  114580. if( iOffset>0 ){
  114581. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  114582. VdbeComment((v, "OFFSET"));
  114583. }
  114584. }
  114585. /*
  114586. ** Add code that will check to make sure the N registers starting at iMem
  114587. ** form a distinct entry. iTab is a sorting index that holds previously
  114588. ** seen combinations of the N values. A new entry is made in iTab
  114589. ** if the current N values are new.
  114590. **
  114591. ** A jump to addrRepeat is made and the N+1 values are popped from the
  114592. ** stack if the top N elements are not distinct.
  114593. */
  114594. static void codeDistinct(
  114595. Parse *pParse, /* Parsing and code generating context */
  114596. int iTab, /* A sorting index used to test for distinctness */
  114597. int addrRepeat, /* Jump to here if not distinct */
  114598. int N, /* Number of elements */
  114599. int iMem /* First element */
  114600. ){
  114601. Vdbe *v;
  114602. int r1;
  114603. v = pParse->pVdbe;
  114604. r1 = sqlite3GetTempReg(pParse);
  114605. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  114606. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  114607. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  114608. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  114609. sqlite3ReleaseTempReg(pParse, r1);
  114610. }
  114611. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  114612. /*
  114613. ** This function is called as part of inner-loop generation for a SELECT
  114614. ** statement with an ORDER BY that is not optimized by an index. It
  114615. ** determines the expressions, if any, that the sorter-reference
  114616. ** optimization should be used for. The sorter-reference optimization
  114617. ** is used for SELECT queries like:
  114618. **
  114619. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
  114620. **
  114621. ** If the optimization is used for expression "bigblob", then instead of
  114622. ** storing values read from that column in the sorter records, the PK of
  114623. ** the row from table t1 is stored instead. Then, as records are extracted from
  114624. ** the sorter to return to the user, the required value of bigblob is
  114625. ** retrieved directly from table t1. If the values are very large, this
  114626. ** can be more efficient than storing them directly in the sorter records.
  114627. **
  114628. ** The ExprList_item.bSorterRef flag is set for each expression in pEList
  114629. ** for which the sorter-reference optimization should be enabled.
  114630. ** Additionally, the pSort->aDefer[] array is populated with entries
  114631. ** for all cursors required to evaluate all selected expressions. Finally.
  114632. ** output variable (*ppExtra) is set to an expression list containing
  114633. ** expressions for all extra PK values that should be stored in the
  114634. ** sorter records.
  114635. */
  114636. static void selectExprDefer(
  114637. Parse *pParse, /* Leave any error here */
  114638. SortCtx *pSort, /* Sorter context */
  114639. ExprList *pEList, /* Expressions destined for sorter */
  114640. ExprList **ppExtra /* Expressions to append to sorter record */
  114641. ){
  114642. int i;
  114643. int nDefer = 0;
  114644. ExprList *pExtra = 0;
  114645. for(i=0; i<pEList->nExpr; i++){
  114646. struct ExprList_item *pItem = &pEList->a[i];
  114647. if( pItem->u.x.iOrderByCol==0 ){
  114648. Expr *pExpr = pItem->pExpr;
  114649. Table *pTab = pExpr->pTab;
  114650. if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
  114651. && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
  114652. ){
  114653. int j;
  114654. for(j=0; j<nDefer; j++){
  114655. if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
  114656. }
  114657. if( j==nDefer ){
  114658. if( nDefer==ArraySize(pSort->aDefer) ){
  114659. continue;
  114660. }else{
  114661. int nKey = 1;
  114662. int k;
  114663. Index *pPk = 0;
  114664. if( !HasRowid(pTab) ){
  114665. pPk = sqlite3PrimaryKeyIndex(pTab);
  114666. nKey = pPk->nKeyCol;
  114667. }
  114668. for(k=0; k<nKey; k++){
  114669. Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
  114670. if( pNew ){
  114671. pNew->iTable = pExpr->iTable;
  114672. pNew->pTab = pExpr->pTab;
  114673. pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
  114674. pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
  114675. }
  114676. }
  114677. pSort->aDefer[nDefer].pTab = pExpr->pTab;
  114678. pSort->aDefer[nDefer].iCsr = pExpr->iTable;
  114679. pSort->aDefer[nDefer].nKey = nKey;
  114680. nDefer++;
  114681. }
  114682. }
  114683. pItem->bSorterRef = 1;
  114684. }
  114685. }
  114686. }
  114687. pSort->nDefer = (u8)nDefer;
  114688. *ppExtra = pExtra;
  114689. }
  114690. #endif
  114691. /*
  114692. ** This routine generates the code for the inside of the inner loop
  114693. ** of a SELECT.
  114694. **
  114695. ** If srcTab is negative, then the p->pEList expressions
  114696. ** are evaluated in order to get the data for this row. If srcTab is
  114697. ** zero or more, then data is pulled from srcTab and p->pEList is used only
  114698. ** to get the number of columns and the collation sequence for each column.
  114699. */
  114700. static void selectInnerLoop(
  114701. Parse *pParse, /* The parser context */
  114702. Select *p, /* The complete select statement being coded */
  114703. int srcTab, /* Pull data from this table if non-negative */
  114704. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  114705. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  114706. SelectDest *pDest, /* How to dispose of the results */
  114707. int iContinue, /* Jump here to continue with next row */
  114708. int iBreak /* Jump here to break out of the inner loop */
  114709. ){
  114710. Vdbe *v = pParse->pVdbe;
  114711. int i;
  114712. int hasDistinct; /* True if the DISTINCT keyword is present */
  114713. int eDest = pDest->eDest; /* How to dispose of results */
  114714. int iParm = pDest->iSDParm; /* First argument to disposal method */
  114715. int nResultCol; /* Number of result columns */
  114716. int nPrefixReg = 0; /* Number of extra registers before regResult */
  114717. RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
  114718. /* Usually, regResult is the first cell in an array of memory cells
  114719. ** containing the current result row. In this case regOrig is set to the
  114720. ** same value. However, if the results are being sent to the sorter, the
  114721. ** values for any expressions that are also part of the sort-key are omitted
  114722. ** from this array. In this case regOrig is set to zero. */
  114723. int regResult; /* Start of memory holding current results */
  114724. int regOrig; /* Start of memory holding full result (or 0) */
  114725. assert( v );
  114726. assert( p->pEList!=0 );
  114727. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  114728. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  114729. if( pSort==0 && !hasDistinct ){
  114730. assert( iContinue!=0 );
  114731. codeOffset(v, p->iOffset, iContinue);
  114732. }
  114733. /* Pull the requested columns.
  114734. */
  114735. nResultCol = p->pEList->nExpr;
  114736. if( pDest->iSdst==0 ){
  114737. if( pSort ){
  114738. nPrefixReg = pSort->pOrderBy->nExpr;
  114739. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  114740. pParse->nMem += nPrefixReg;
  114741. }
  114742. pDest->iSdst = pParse->nMem+1;
  114743. pParse->nMem += nResultCol;
  114744. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  114745. /* This is an error condition that can result, for example, when a SELECT
  114746. ** on the right-hand side of an INSERT contains more result columns than
  114747. ** there are columns in the table on the left. The error will be caught
  114748. ** and reported later. But we need to make sure enough memory is allocated
  114749. ** to avoid other spurious errors in the meantime. */
  114750. pParse->nMem += nResultCol;
  114751. }
  114752. pDest->nSdst = nResultCol;
  114753. regOrig = regResult = pDest->iSdst;
  114754. if( srcTab>=0 ){
  114755. for(i=0; i<nResultCol; i++){
  114756. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  114757. VdbeComment((v, "%s", p->pEList->a[i].zName));
  114758. }
  114759. }else if( eDest!=SRT_Exists ){
  114760. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  114761. ExprList *pExtra = 0;
  114762. #endif
  114763. /* If the destination is an EXISTS(...) expression, the actual
  114764. ** values returned by the SELECT are not required.
  114765. */
  114766. u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
  114767. ExprList *pEList;
  114768. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  114769. ecelFlags = SQLITE_ECEL_DUP;
  114770. }else{
  114771. ecelFlags = 0;
  114772. }
  114773. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  114774. /* For each expression in p->pEList that is a copy of an expression in
  114775. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  114776. ** iOrderByCol value to one more than the index of the ORDER BY
  114777. ** expression within the sort-key that pushOntoSorter() will generate.
  114778. ** This allows the p->pEList field to be omitted from the sorted record,
  114779. ** saving space and CPU cycles. */
  114780. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  114781. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  114782. int j;
  114783. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  114784. p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  114785. }
  114786. }
  114787. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  114788. selectExprDefer(pParse, pSort, p->pEList, &pExtra);
  114789. if( pExtra && pParse->db->mallocFailed==0 ){
  114790. /* If there are any extra PK columns to add to the sorter records,
  114791. ** allocate extra memory cells and adjust the OpenEphemeral
  114792. ** instruction to account for the larger records. This is only
  114793. ** required if there are one or more WITHOUT ROWID tables with
  114794. ** composite primary keys in the SortCtx.aDefer[] array. */
  114795. VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  114796. pOp->p2 += (pExtra->nExpr - pSort->nDefer);
  114797. pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
  114798. pParse->nMem += pExtra->nExpr;
  114799. }
  114800. #endif
  114801. /* Adjust nResultCol to account for columns that are omitted
  114802. ** from the sorter by the optimizations in this branch */
  114803. pEList = p->pEList;
  114804. for(i=0; i<pEList->nExpr; i++){
  114805. if( pEList->a[i].u.x.iOrderByCol>0
  114806. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  114807. || pEList->a[i].bSorterRef
  114808. #endif
  114809. ){
  114810. nResultCol--;
  114811. regOrig = 0;
  114812. }
  114813. }
  114814. testcase( regOrig );
  114815. testcase( eDest==SRT_Set );
  114816. testcase( eDest==SRT_Mem );
  114817. testcase( eDest==SRT_Coroutine );
  114818. testcase( eDest==SRT_Output );
  114819. assert( eDest==SRT_Set || eDest==SRT_Mem
  114820. || eDest==SRT_Coroutine || eDest==SRT_Output );
  114821. }
  114822. sRowLoadInfo.regResult = regResult;
  114823. sRowLoadInfo.ecelFlags = ecelFlags;
  114824. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  114825. sRowLoadInfo.pExtra = pExtra;
  114826. sRowLoadInfo.regExtraResult = regResult + nResultCol;
  114827. if( pExtra ) nResultCol += pExtra->nExpr;
  114828. #endif
  114829. if( p->iLimit
  114830. && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
  114831. && nPrefixReg>0
  114832. ){
  114833. assert( pSort!=0 );
  114834. assert( hasDistinct==0 );
  114835. pSort->pDeferredRowLoad = &sRowLoadInfo;
  114836. regOrig = 0;
  114837. }else{
  114838. innerLoopLoadRow(pParse, p, &sRowLoadInfo);
  114839. }
  114840. }
  114841. /* If the DISTINCT keyword was present on the SELECT statement
  114842. ** and this row has been seen before, then do not make this row
  114843. ** part of the result.
  114844. */
  114845. if( hasDistinct ){
  114846. switch( pDistinct->eTnctType ){
  114847. case WHERE_DISTINCT_ORDERED: {
  114848. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  114849. int iJump; /* Jump destination */
  114850. int regPrev; /* Previous row content */
  114851. /* Allocate space for the previous row */
  114852. regPrev = pParse->nMem+1;
  114853. pParse->nMem += nResultCol;
  114854. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  114855. ** sets the MEM_Cleared bit on the first register of the
  114856. ** previous value. This will cause the OP_Ne below to always
  114857. ** fail on the first iteration of the loop even if the first
  114858. ** row is all NULLs.
  114859. */
  114860. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  114861. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  114862. pOp->opcode = OP_Null;
  114863. pOp->p1 = 1;
  114864. pOp->p2 = regPrev;
  114865. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  114866. for(i=0; i<nResultCol; i++){
  114867. CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
  114868. if( i<nResultCol-1 ){
  114869. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  114870. VdbeCoverage(v);
  114871. }else{
  114872. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  114873. VdbeCoverage(v);
  114874. }
  114875. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  114876. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  114877. }
  114878. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  114879. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  114880. break;
  114881. }
  114882. case WHERE_DISTINCT_UNIQUE: {
  114883. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  114884. break;
  114885. }
  114886. default: {
  114887. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  114888. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  114889. regResult);
  114890. break;
  114891. }
  114892. }
  114893. if( pSort==0 ){
  114894. codeOffset(v, p->iOffset, iContinue);
  114895. }
  114896. }
  114897. switch( eDest ){
  114898. /* In this mode, write each query result to the key of the temporary
  114899. ** table iParm.
  114900. */
  114901. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  114902. case SRT_Union: {
  114903. int r1;
  114904. r1 = sqlite3GetTempReg(pParse);
  114905. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  114906. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  114907. sqlite3ReleaseTempReg(pParse, r1);
  114908. break;
  114909. }
  114910. /* Construct a record from the query result, but instead of
  114911. ** saving that record, use it as a key to delete elements from
  114912. ** the temporary table iParm.
  114913. */
  114914. case SRT_Except: {
  114915. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  114916. break;
  114917. }
  114918. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  114919. /* Store the result as data using a unique key.
  114920. */
  114921. case SRT_Fifo:
  114922. case SRT_DistFifo:
  114923. case SRT_Table:
  114924. case SRT_EphemTab: {
  114925. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  114926. testcase( eDest==SRT_Table );
  114927. testcase( eDest==SRT_EphemTab );
  114928. testcase( eDest==SRT_Fifo );
  114929. testcase( eDest==SRT_DistFifo );
  114930. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  114931. #ifndef SQLITE_OMIT_CTE
  114932. if( eDest==SRT_DistFifo ){
  114933. /* If the destination is DistFifo, then cursor (iParm+1) is open
  114934. ** on an ephemeral index. If the current row is already present
  114935. ** in the index, do not write it to the output. If not, add the
  114936. ** current row to the index and proceed with writing it to the
  114937. ** output table as well. */
  114938. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  114939. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  114940. VdbeCoverage(v);
  114941. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  114942. assert( pSort==0 );
  114943. }
  114944. #endif
  114945. if( pSort ){
  114946. assert( regResult==regOrig );
  114947. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
  114948. }else{
  114949. int r2 = sqlite3GetTempReg(pParse);
  114950. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  114951. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  114952. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  114953. sqlite3ReleaseTempReg(pParse, r2);
  114954. }
  114955. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  114956. break;
  114957. }
  114958. #ifndef SQLITE_OMIT_SUBQUERY
  114959. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  114960. ** then there should be a single item on the stack. Write this
  114961. ** item into the set table with bogus data.
  114962. */
  114963. case SRT_Set: {
  114964. if( pSort ){
  114965. /* At first glance you would think we could optimize out the
  114966. ** ORDER BY in this case since the order of entries in the set
  114967. ** does not matter. But there might be a LIMIT clause, in which
  114968. ** case the order does matter */
  114969. pushOntoSorter(
  114970. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  114971. }else{
  114972. int r1 = sqlite3GetTempReg(pParse);
  114973. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  114974. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  114975. r1, pDest->zAffSdst, nResultCol);
  114976. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  114977. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  114978. sqlite3ReleaseTempReg(pParse, r1);
  114979. }
  114980. break;
  114981. }
  114982. /* If any row exist in the result set, record that fact and abort.
  114983. */
  114984. case SRT_Exists: {
  114985. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  114986. /* The LIMIT clause will terminate the loop for us */
  114987. break;
  114988. }
  114989. /* If this is a scalar select that is part of an expression, then
  114990. ** store the results in the appropriate memory cell or array of
  114991. ** memory cells and break out of the scan loop.
  114992. */
  114993. case SRT_Mem: {
  114994. if( pSort ){
  114995. assert( nResultCol<=pDest->nSdst );
  114996. pushOntoSorter(
  114997. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  114998. }else{
  114999. assert( nResultCol==pDest->nSdst );
  115000. assert( regResult==iParm );
  115001. /* The LIMIT clause will jump out of the loop for us */
  115002. }
  115003. break;
  115004. }
  115005. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  115006. case SRT_Coroutine: /* Send data to a co-routine */
  115007. case SRT_Output: { /* Return the results */
  115008. testcase( eDest==SRT_Coroutine );
  115009. testcase( eDest==SRT_Output );
  115010. if( pSort ){
  115011. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  115012. nPrefixReg);
  115013. }else if( eDest==SRT_Coroutine ){
  115014. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  115015. }else{
  115016. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  115017. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  115018. }
  115019. break;
  115020. }
  115021. #ifndef SQLITE_OMIT_CTE
  115022. /* Write the results into a priority queue that is order according to
  115023. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  115024. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  115025. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  115026. ** final OP_Sequence column. The last column is the record as a blob.
  115027. */
  115028. case SRT_DistQueue:
  115029. case SRT_Queue: {
  115030. int nKey;
  115031. int r1, r2, r3;
  115032. int addrTest = 0;
  115033. ExprList *pSO;
  115034. pSO = pDest->pOrderBy;
  115035. assert( pSO );
  115036. nKey = pSO->nExpr;
  115037. r1 = sqlite3GetTempReg(pParse);
  115038. r2 = sqlite3GetTempRange(pParse, nKey+2);
  115039. r3 = r2+nKey+1;
  115040. if( eDest==SRT_DistQueue ){
  115041. /* If the destination is DistQueue, then cursor (iParm+1) is open
  115042. ** on a second ephemeral index that holds all values every previously
  115043. ** added to the queue. */
  115044. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  115045. regResult, nResultCol);
  115046. VdbeCoverage(v);
  115047. }
  115048. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  115049. if( eDest==SRT_DistQueue ){
  115050. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  115051. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  115052. }
  115053. for(i=0; i<nKey; i++){
  115054. sqlite3VdbeAddOp2(v, OP_SCopy,
  115055. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  115056. r2+i);
  115057. }
  115058. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  115059. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  115060. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  115061. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  115062. sqlite3ReleaseTempReg(pParse, r1);
  115063. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  115064. break;
  115065. }
  115066. #endif /* SQLITE_OMIT_CTE */
  115067. #if !defined(SQLITE_OMIT_TRIGGER)
  115068. /* Discard the results. This is used for SELECT statements inside
  115069. ** the body of a TRIGGER. The purpose of such selects is to call
  115070. ** user-defined functions that have side effects. We do not care
  115071. ** about the actual results of the select.
  115072. */
  115073. default: {
  115074. assert( eDest==SRT_Discard );
  115075. break;
  115076. }
  115077. #endif
  115078. }
  115079. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  115080. ** there is a sorter, in which case the sorter has already limited
  115081. ** the output for us.
  115082. */
  115083. if( pSort==0 && p->iLimit ){
  115084. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  115085. }
  115086. }
  115087. /*
  115088. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  115089. ** X extra columns.
  115090. */
  115091. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  115092. int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
  115093. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  115094. if( p ){
  115095. p->aSortOrder = (u8*)&p->aColl[N+X];
  115096. p->nKeyField = (u16)N;
  115097. p->nAllField = (u16)(N+X);
  115098. p->enc = ENC(db);
  115099. p->db = db;
  115100. p->nRef = 1;
  115101. memset(&p[1], 0, nExtra);
  115102. }else{
  115103. sqlite3OomFault(db);
  115104. }
  115105. return p;
  115106. }
  115107. /*
  115108. ** Deallocate a KeyInfo object
  115109. */
  115110. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  115111. if( p ){
  115112. assert( p->nRef>0 );
  115113. p->nRef--;
  115114. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  115115. }
  115116. }
  115117. /*
  115118. ** Make a new pointer to a KeyInfo object
  115119. */
  115120. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  115121. if( p ){
  115122. assert( p->nRef>0 );
  115123. p->nRef++;
  115124. }
  115125. return p;
  115126. }
  115127. #ifdef SQLITE_DEBUG
  115128. /*
  115129. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  115130. ** can only be changed if this is just a single reference to the object.
  115131. **
  115132. ** This routine is used only inside of assert() statements.
  115133. */
  115134. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  115135. #endif /* SQLITE_DEBUG */
  115136. /*
  115137. ** Given an expression list, generate a KeyInfo structure that records
  115138. ** the collating sequence for each expression in that expression list.
  115139. **
  115140. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  115141. ** KeyInfo structure is appropriate for initializing a virtual index to
  115142. ** implement that clause. If the ExprList is the result set of a SELECT
  115143. ** then the KeyInfo structure is appropriate for initializing a virtual
  115144. ** index to implement a DISTINCT test.
  115145. **
  115146. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  115147. ** function is responsible for seeing that this structure is eventually
  115148. ** freed.
  115149. */
  115150. static KeyInfo *keyInfoFromExprList(
  115151. Parse *pParse, /* Parsing context */
  115152. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  115153. int iStart, /* Begin with this column of pList */
  115154. int nExtra /* Add this many extra columns to the end */
  115155. ){
  115156. int nExpr;
  115157. KeyInfo *pInfo;
  115158. struct ExprList_item *pItem;
  115159. sqlite3 *db = pParse->db;
  115160. int i;
  115161. nExpr = pList->nExpr;
  115162. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  115163. if( pInfo ){
  115164. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  115165. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  115166. pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
  115167. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  115168. }
  115169. }
  115170. return pInfo;
  115171. }
  115172. /*
  115173. ** Name of the connection operator, used for error messages.
  115174. */
  115175. static const char *selectOpName(int id){
  115176. char *z;
  115177. switch( id ){
  115178. case TK_ALL: z = "UNION ALL"; break;
  115179. case TK_INTERSECT: z = "INTERSECT"; break;
  115180. case TK_EXCEPT: z = "EXCEPT"; break;
  115181. default: z = "UNION"; break;
  115182. }
  115183. return z;
  115184. }
  115185. #ifndef SQLITE_OMIT_EXPLAIN
  115186. /*
  115187. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  115188. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  115189. ** where the caption is of the form:
  115190. **
  115191. ** "USE TEMP B-TREE FOR xxx"
  115192. **
  115193. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  115194. ** is determined by the zUsage argument.
  115195. */
  115196. static void explainTempTable(Parse *pParse, const char *zUsage){
  115197. ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
  115198. }
  115199. /*
  115200. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  115201. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  115202. ** in sqlite3Select() to assign values to structure member variables that
  115203. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  115204. ** code with #ifndef directives.
  115205. */
  115206. # define explainSetInteger(a, b) a = b
  115207. #else
  115208. /* No-op versions of the explainXXX() functions and macros. */
  115209. # define explainTempTable(y,z)
  115210. # define explainSetInteger(y,z)
  115211. #endif
  115212. /*
  115213. ** If the inner loop was generated using a non-null pOrderBy argument,
  115214. ** then the results were placed in a sorter. After the loop is terminated
  115215. ** we need to run the sorter and output the results. The following
  115216. ** routine generates the code needed to do that.
  115217. */
  115218. static void generateSortTail(
  115219. Parse *pParse, /* Parsing context */
  115220. Select *p, /* The SELECT statement */
  115221. SortCtx *pSort, /* Information on the ORDER BY clause */
  115222. int nColumn, /* Number of columns of data */
  115223. SelectDest *pDest /* Write the sorted results here */
  115224. ){
  115225. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  115226. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  115227. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  115228. int addr; /* Top of output loop. Jump for Next. */
  115229. int addrOnce = 0;
  115230. int iTab;
  115231. ExprList *pOrderBy = pSort->pOrderBy;
  115232. int eDest = pDest->eDest;
  115233. int iParm = pDest->iSDParm;
  115234. int regRow;
  115235. int regRowid;
  115236. int iCol;
  115237. int nKey; /* Number of key columns in sorter record */
  115238. int iSortTab; /* Sorter cursor to read from */
  115239. int i;
  115240. int bSeq; /* True if sorter record includes seq. no. */
  115241. int nRefKey = 0;
  115242. struct ExprList_item *aOutEx = p->pEList->a;
  115243. assert( addrBreak<0 );
  115244. if( pSort->labelBkOut ){
  115245. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  115246. sqlite3VdbeGoto(v, addrBreak);
  115247. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  115248. }
  115249. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  115250. /* Open any cursors needed for sorter-reference expressions */
  115251. for(i=0; i<pSort->nDefer; i++){
  115252. Table *pTab = pSort->aDefer[i].pTab;
  115253. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  115254. sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
  115255. nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
  115256. }
  115257. #endif
  115258. iTab = pSort->iECursor;
  115259. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  115260. regRowid = 0;
  115261. regRow = pDest->iSdst;
  115262. }else{
  115263. regRowid = sqlite3GetTempReg(pParse);
  115264. regRow = sqlite3GetTempRange(pParse, nColumn);
  115265. }
  115266. nKey = pOrderBy->nExpr - pSort->nOBSat;
  115267. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  115268. int regSortOut = ++pParse->nMem;
  115269. iSortTab = pParse->nTab++;
  115270. if( pSort->labelBkOut ){
  115271. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  115272. }
  115273. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
  115274. nKey+1+nColumn+nRefKey);
  115275. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  115276. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  115277. VdbeCoverage(v);
  115278. codeOffset(v, p->iOffset, addrContinue);
  115279. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  115280. bSeq = 0;
  115281. }else{
  115282. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  115283. codeOffset(v, p->iOffset, addrContinue);
  115284. iSortTab = iTab;
  115285. bSeq = 1;
  115286. }
  115287. for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
  115288. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  115289. if( aOutEx[i].bSorterRef ) continue;
  115290. #endif
  115291. if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
  115292. }
  115293. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  115294. if( pSort->nDefer ){
  115295. int iKey = iCol+1;
  115296. int regKey = sqlite3GetTempRange(pParse, nRefKey);
  115297. for(i=0; i<pSort->nDefer; i++){
  115298. int iCsr = pSort->aDefer[i].iCsr;
  115299. Table *pTab = pSort->aDefer[i].pTab;
  115300. int nKey = pSort->aDefer[i].nKey;
  115301. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  115302. if( HasRowid(pTab) ){
  115303. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
  115304. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
  115305. sqlite3VdbeCurrentAddr(v)+1, regKey);
  115306. }else{
  115307. int k;
  115308. int iJmp;
  115309. assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
  115310. for(k=0; k<nKey; k++){
  115311. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
  115312. }
  115313. iJmp = sqlite3VdbeCurrentAddr(v);
  115314. sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
  115315. sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
  115316. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  115317. }
  115318. }
  115319. sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
  115320. }
  115321. #endif
  115322. for(i=nColumn-1; i>=0; i--){
  115323. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  115324. if( aOutEx[i].bSorterRef ){
  115325. sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
  115326. }else
  115327. #endif
  115328. {
  115329. int iRead;
  115330. if( aOutEx[i].u.x.iOrderByCol ){
  115331. iRead = aOutEx[i].u.x.iOrderByCol-1;
  115332. }else{
  115333. iRead = iCol--;
  115334. }
  115335. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  115336. VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
  115337. }
  115338. }
  115339. switch( eDest ){
  115340. case SRT_Table:
  115341. case SRT_EphemTab: {
  115342. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  115343. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  115344. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  115345. break;
  115346. }
  115347. #ifndef SQLITE_OMIT_SUBQUERY
  115348. case SRT_Set: {
  115349. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  115350. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  115351. pDest->zAffSdst, nColumn);
  115352. sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
  115353. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  115354. break;
  115355. }
  115356. case SRT_Mem: {
  115357. /* The LIMIT clause will terminate the loop for us */
  115358. break;
  115359. }
  115360. #endif
  115361. default: {
  115362. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  115363. testcase( eDest==SRT_Output );
  115364. testcase( eDest==SRT_Coroutine );
  115365. if( eDest==SRT_Output ){
  115366. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  115367. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  115368. }else{
  115369. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  115370. }
  115371. break;
  115372. }
  115373. }
  115374. if( regRowid ){
  115375. if( eDest==SRT_Set ){
  115376. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  115377. }else{
  115378. sqlite3ReleaseTempReg(pParse, regRow);
  115379. }
  115380. sqlite3ReleaseTempReg(pParse, regRowid);
  115381. }
  115382. /* The bottom of the loop
  115383. */
  115384. sqlite3VdbeResolveLabel(v, addrContinue);
  115385. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  115386. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  115387. }else{
  115388. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  115389. }
  115390. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  115391. sqlite3VdbeResolveLabel(v, addrBreak);
  115392. }
  115393. /*
  115394. ** Return a pointer to a string containing the 'declaration type' of the
  115395. ** expression pExpr. The string may be treated as static by the caller.
  115396. **
  115397. ** Also try to estimate the size of the returned value and return that
  115398. ** result in *pEstWidth.
  115399. **
  115400. ** The declaration type is the exact datatype definition extracted from the
  115401. ** original CREATE TABLE statement if the expression is a column. The
  115402. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  115403. ** is considered a column can be complex in the presence of subqueries. The
  115404. ** result-set expression in all of the following SELECT statements is
  115405. ** considered a column by this function.
  115406. **
  115407. ** SELECT col FROM tbl;
  115408. ** SELECT (SELECT col FROM tbl;
  115409. ** SELECT (SELECT col FROM tbl);
  115410. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  115411. **
  115412. ** The declaration type for any expression other than a column is NULL.
  115413. **
  115414. ** This routine has either 3 or 6 parameters depending on whether or not
  115415. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  115416. */
  115417. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  115418. # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
  115419. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  115420. # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
  115421. #endif
  115422. static const char *columnTypeImpl(
  115423. NameContext *pNC,
  115424. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  115425. Expr *pExpr
  115426. #else
  115427. Expr *pExpr,
  115428. const char **pzOrigDb,
  115429. const char **pzOrigTab,
  115430. const char **pzOrigCol
  115431. #endif
  115432. ){
  115433. char const *zType = 0;
  115434. int j;
  115435. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  115436. char const *zOrigDb = 0;
  115437. char const *zOrigTab = 0;
  115438. char const *zOrigCol = 0;
  115439. #endif
  115440. assert( pExpr!=0 );
  115441. assert( pNC->pSrcList!=0 );
  115442. assert( pExpr->op!=TK_AGG_COLUMN ); /* This routine runes before aggregates
  115443. ** are processed */
  115444. switch( pExpr->op ){
  115445. case TK_COLUMN: {
  115446. /* The expression is a column. Locate the table the column is being
  115447. ** extracted from in NameContext.pSrcList. This table may be real
  115448. ** database table or a subquery.
  115449. */
  115450. Table *pTab = 0; /* Table structure column is extracted from */
  115451. Select *pS = 0; /* Select the column is extracted from */
  115452. int iCol = pExpr->iColumn; /* Index of column in pTab */
  115453. while( pNC && !pTab ){
  115454. SrcList *pTabList = pNC->pSrcList;
  115455. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  115456. if( j<pTabList->nSrc ){
  115457. pTab = pTabList->a[j].pTab;
  115458. pS = pTabList->a[j].pSelect;
  115459. }else{
  115460. pNC = pNC->pNext;
  115461. }
  115462. }
  115463. if( pTab==0 ){
  115464. /* At one time, code such as "SELECT new.x" within a trigger would
  115465. ** cause this condition to run. Since then, we have restructured how
  115466. ** trigger code is generated and so this condition is no longer
  115467. ** possible. However, it can still be true for statements like
  115468. ** the following:
  115469. **
  115470. ** CREATE TABLE t1(col INTEGER);
  115471. ** SELECT (SELECT t1.col) FROM FROM t1;
  115472. **
  115473. ** when columnType() is called on the expression "t1.col" in the
  115474. ** sub-select. In this case, set the column type to NULL, even
  115475. ** though it should really be "INTEGER".
  115476. **
  115477. ** This is not a problem, as the column type of "t1.col" is never
  115478. ** used. When columnType() is called on the expression
  115479. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  115480. ** branch below. */
  115481. break;
  115482. }
  115483. assert( pTab && pExpr->pTab==pTab );
  115484. if( pS ){
  115485. /* The "table" is actually a sub-select or a view in the FROM clause
  115486. ** of the SELECT statement. Return the declaration type and origin
  115487. ** data for the result-set column of the sub-select.
  115488. */
  115489. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  115490. /* If iCol is less than zero, then the expression requests the
  115491. ** rowid of the sub-select or view. This expression is legal (see
  115492. ** test case misc2.2.2) - it always evaluates to NULL.
  115493. */
  115494. NameContext sNC;
  115495. Expr *p = pS->pEList->a[iCol].pExpr;
  115496. sNC.pSrcList = pS->pSrc;
  115497. sNC.pNext = pNC;
  115498. sNC.pParse = pNC->pParse;
  115499. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
  115500. }
  115501. }else{
  115502. /* A real table or a CTE table */
  115503. assert( !pS );
  115504. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  115505. if( iCol<0 ) iCol = pTab->iPKey;
  115506. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  115507. if( iCol<0 ){
  115508. zType = "INTEGER";
  115509. zOrigCol = "rowid";
  115510. }else{
  115511. zOrigCol = pTab->aCol[iCol].zName;
  115512. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  115513. }
  115514. zOrigTab = pTab->zName;
  115515. if( pNC->pParse && pTab->pSchema ){
  115516. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  115517. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  115518. }
  115519. #else
  115520. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  115521. if( iCol<0 ){
  115522. zType = "INTEGER";
  115523. }else{
  115524. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  115525. }
  115526. #endif
  115527. }
  115528. break;
  115529. }
  115530. #ifndef SQLITE_OMIT_SUBQUERY
  115531. case TK_SELECT: {
  115532. /* The expression is a sub-select. Return the declaration type and
  115533. ** origin info for the single column in the result set of the SELECT
  115534. ** statement.
  115535. */
  115536. NameContext sNC;
  115537. Select *pS = pExpr->x.pSelect;
  115538. Expr *p = pS->pEList->a[0].pExpr;
  115539. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  115540. sNC.pSrcList = pS->pSrc;
  115541. sNC.pNext = pNC;
  115542. sNC.pParse = pNC->pParse;
  115543. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  115544. break;
  115545. }
  115546. #endif
  115547. }
  115548. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  115549. if( pzOrigDb ){
  115550. assert( pzOrigTab && pzOrigCol );
  115551. *pzOrigDb = zOrigDb;
  115552. *pzOrigTab = zOrigTab;
  115553. *pzOrigCol = zOrigCol;
  115554. }
  115555. #endif
  115556. return zType;
  115557. }
  115558. /*
  115559. ** Generate code that will tell the VDBE the declaration types of columns
  115560. ** in the result set.
  115561. */
  115562. static void generateColumnTypes(
  115563. Parse *pParse, /* Parser context */
  115564. SrcList *pTabList, /* List of tables */
  115565. ExprList *pEList /* Expressions defining the result set */
  115566. ){
  115567. #ifndef SQLITE_OMIT_DECLTYPE
  115568. Vdbe *v = pParse->pVdbe;
  115569. int i;
  115570. NameContext sNC;
  115571. sNC.pSrcList = pTabList;
  115572. sNC.pParse = pParse;
  115573. sNC.pNext = 0;
  115574. for(i=0; i<pEList->nExpr; i++){
  115575. Expr *p = pEList->a[i].pExpr;
  115576. const char *zType;
  115577. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  115578. const char *zOrigDb = 0;
  115579. const char *zOrigTab = 0;
  115580. const char *zOrigCol = 0;
  115581. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  115582. /* The vdbe must make its own copy of the column-type and other
  115583. ** column specific strings, in case the schema is reset before this
  115584. ** virtual machine is deleted.
  115585. */
  115586. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  115587. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  115588. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  115589. #else
  115590. zType = columnType(&sNC, p, 0, 0, 0);
  115591. #endif
  115592. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  115593. }
  115594. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  115595. }
  115596. /*
  115597. ** Compute the column names for a SELECT statement.
  115598. **
  115599. ** The only guarantee that SQLite makes about column names is that if the
  115600. ** column has an AS clause assigning it a name, that will be the name used.
  115601. ** That is the only documented guarantee. However, countless applications
  115602. ** developed over the years have made baseless assumptions about column names
  115603. ** and will break if those assumptions changes. Hence, use extreme caution
  115604. ** when modifying this routine to avoid breaking legacy.
  115605. **
  115606. ** See Also: sqlite3ColumnsFromExprList()
  115607. **
  115608. ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
  115609. ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
  115610. ** applications should operate this way. Nevertheless, we need to support the
  115611. ** other modes for legacy:
  115612. **
  115613. ** short=OFF, full=OFF: Column name is the text of the expression has it
  115614. ** originally appears in the SELECT statement. In
  115615. ** other words, the zSpan of the result expression.
  115616. **
  115617. ** short=ON, full=OFF: (This is the default setting). If the result
  115618. ** refers directly to a table column, then the
  115619. ** result column name is just the table column
  115620. ** name: COLUMN. Otherwise use zSpan.
  115621. **
  115622. ** full=ON, short=ANY: If the result refers directly to a table column,
  115623. ** then the result column name with the table name
  115624. ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
  115625. */
  115626. static void generateColumnNames(
  115627. Parse *pParse, /* Parser context */
  115628. Select *pSelect /* Generate column names for this SELECT statement */
  115629. ){
  115630. Vdbe *v = pParse->pVdbe;
  115631. int i;
  115632. Table *pTab;
  115633. SrcList *pTabList;
  115634. ExprList *pEList;
  115635. sqlite3 *db = pParse->db;
  115636. int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
  115637. int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
  115638. #ifndef SQLITE_OMIT_EXPLAIN
  115639. /* If this is an EXPLAIN, skip this step */
  115640. if( pParse->explain ){
  115641. return;
  115642. }
  115643. #endif
  115644. if( pParse->colNamesSet ) return;
  115645. /* Column names are determined by the left-most term of a compound select */
  115646. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  115647. SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
  115648. pTabList = pSelect->pSrc;
  115649. pEList = pSelect->pEList;
  115650. assert( v!=0 );
  115651. assert( pTabList!=0 );
  115652. pParse->colNamesSet = 1;
  115653. fullName = (db->flags & SQLITE_FullColNames)!=0;
  115654. srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
  115655. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  115656. for(i=0; i<pEList->nExpr; i++){
  115657. Expr *p = pEList->a[i].pExpr;
  115658. assert( p!=0 );
  115659. assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
  115660. assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
  115661. if( pEList->a[i].zName ){
  115662. /* An AS clause always takes first priority */
  115663. char *zName = pEList->a[i].zName;
  115664. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  115665. }else if( srcName && p->op==TK_COLUMN ){
  115666. char *zCol;
  115667. int iCol = p->iColumn;
  115668. pTab = p->pTab;
  115669. assert( pTab!=0 );
  115670. if( iCol<0 ) iCol = pTab->iPKey;
  115671. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  115672. if( iCol<0 ){
  115673. zCol = "rowid";
  115674. }else{
  115675. zCol = pTab->aCol[iCol].zName;
  115676. }
  115677. if( fullName ){
  115678. char *zName = 0;
  115679. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  115680. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  115681. }else{
  115682. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  115683. }
  115684. }else{
  115685. const char *z = pEList->a[i].zSpan;
  115686. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  115687. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  115688. }
  115689. }
  115690. generateColumnTypes(pParse, pTabList, pEList);
  115691. }
  115692. /*
  115693. ** Given an expression list (which is really the list of expressions
  115694. ** that form the result set of a SELECT statement) compute appropriate
  115695. ** column names for a table that would hold the expression list.
  115696. **
  115697. ** All column names will be unique.
  115698. **
  115699. ** Only the column names are computed. Column.zType, Column.zColl,
  115700. ** and other fields of Column are zeroed.
  115701. **
  115702. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  115703. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  115704. **
  115705. ** The only guarantee that SQLite makes about column names is that if the
  115706. ** column has an AS clause assigning it a name, that will be the name used.
  115707. ** That is the only documented guarantee. However, countless applications
  115708. ** developed over the years have made baseless assumptions about column names
  115709. ** and will break if those assumptions changes. Hence, use extreme caution
  115710. ** when modifying this routine to avoid breaking legacy.
  115711. **
  115712. ** See Also: generateColumnNames()
  115713. */
  115714. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  115715. Parse *pParse, /* Parsing context */
  115716. ExprList *pEList, /* Expr list from which to derive column names */
  115717. i16 *pnCol, /* Write the number of columns here */
  115718. Column **paCol /* Write the new column list here */
  115719. ){
  115720. sqlite3 *db = pParse->db; /* Database connection */
  115721. int i, j; /* Loop counters */
  115722. u32 cnt; /* Index added to make the name unique */
  115723. Column *aCol, *pCol; /* For looping over result columns */
  115724. int nCol; /* Number of columns in the result set */
  115725. char *zName; /* Column name */
  115726. int nName; /* Size of name in zName[] */
  115727. Hash ht; /* Hash table of column names */
  115728. sqlite3HashInit(&ht);
  115729. if( pEList ){
  115730. nCol = pEList->nExpr;
  115731. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  115732. testcase( aCol==0 );
  115733. if( nCol>32767 ) nCol = 32767;
  115734. }else{
  115735. nCol = 0;
  115736. aCol = 0;
  115737. }
  115738. assert( nCol==(i16)nCol );
  115739. *pnCol = nCol;
  115740. *paCol = aCol;
  115741. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  115742. /* Get an appropriate name for the column
  115743. */
  115744. if( (zName = pEList->a[i].zName)!=0 ){
  115745. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  115746. }else{
  115747. Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  115748. while( pColExpr->op==TK_DOT ){
  115749. pColExpr = pColExpr->pRight;
  115750. assert( pColExpr!=0 );
  115751. }
  115752. assert( pColExpr->op!=TK_AGG_COLUMN );
  115753. if( pColExpr->op==TK_COLUMN ){
  115754. /* For columns use the column name name */
  115755. int iCol = pColExpr->iColumn;
  115756. Table *pTab = pColExpr->pTab;
  115757. assert( pTab!=0 );
  115758. if( iCol<0 ) iCol = pTab->iPKey;
  115759. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  115760. }else if( pColExpr->op==TK_ID ){
  115761. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  115762. zName = pColExpr->u.zToken;
  115763. }else{
  115764. /* Use the original text of the column expression as its name */
  115765. zName = pEList->a[i].zSpan;
  115766. }
  115767. }
  115768. if( zName ){
  115769. zName = sqlite3DbStrDup(db, zName);
  115770. }else{
  115771. zName = sqlite3MPrintf(db,"column%d",i+1);
  115772. }
  115773. /* Make sure the column name is unique. If the name is not unique,
  115774. ** append an integer to the name so that it becomes unique.
  115775. */
  115776. cnt = 0;
  115777. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  115778. nName = sqlite3Strlen30(zName);
  115779. if( nName>0 ){
  115780. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  115781. if( zName[j]==':' ) nName = j;
  115782. }
  115783. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  115784. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  115785. }
  115786. pCol->zName = zName;
  115787. sqlite3ColumnPropertiesFromName(0, pCol);
  115788. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  115789. sqlite3OomFault(db);
  115790. }
  115791. }
  115792. sqlite3HashClear(&ht);
  115793. if( db->mallocFailed ){
  115794. for(j=0; j<i; j++){
  115795. sqlite3DbFree(db, aCol[j].zName);
  115796. }
  115797. sqlite3DbFree(db, aCol);
  115798. *paCol = 0;
  115799. *pnCol = 0;
  115800. return SQLITE_NOMEM_BKPT;
  115801. }
  115802. return SQLITE_OK;
  115803. }
  115804. /*
  115805. ** Add type and collation information to a column list based on
  115806. ** a SELECT statement.
  115807. **
  115808. ** The column list presumably came from selectColumnNamesFromExprList().
  115809. ** The column list has only names, not types or collations. This
  115810. ** routine goes through and adds the types and collations.
  115811. **
  115812. ** This routine requires that all identifiers in the SELECT
  115813. ** statement be resolved.
  115814. */
  115815. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  115816. Parse *pParse, /* Parsing contexts */
  115817. Table *pTab, /* Add column type information to this table */
  115818. Select *pSelect /* SELECT used to determine types and collations */
  115819. ){
  115820. sqlite3 *db = pParse->db;
  115821. NameContext sNC;
  115822. Column *pCol;
  115823. CollSeq *pColl;
  115824. int i;
  115825. Expr *p;
  115826. struct ExprList_item *a;
  115827. assert( pSelect!=0 );
  115828. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  115829. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  115830. if( db->mallocFailed ) return;
  115831. memset(&sNC, 0, sizeof(sNC));
  115832. sNC.pSrcList = pSelect->pSrc;
  115833. a = pSelect->pEList->a;
  115834. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  115835. const char *zType;
  115836. int n, m;
  115837. p = a[i].pExpr;
  115838. zType = columnType(&sNC, p, 0, 0, 0);
  115839. /* pCol->szEst = ... // Column size est for SELECT tables never used */
  115840. pCol->affinity = sqlite3ExprAffinity(p);
  115841. if( zType ){
  115842. m = sqlite3Strlen30(zType);
  115843. n = sqlite3Strlen30(pCol->zName);
  115844. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  115845. if( pCol->zName ){
  115846. memcpy(&pCol->zName[n+1], zType, m+1);
  115847. pCol->colFlags |= COLFLAG_HASTYPE;
  115848. }
  115849. }
  115850. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  115851. pColl = sqlite3ExprCollSeq(pParse, p);
  115852. if( pColl && pCol->zColl==0 ){
  115853. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  115854. }
  115855. }
  115856. pTab->szTabRow = 1; /* Any non-zero value works */
  115857. }
  115858. /*
  115859. ** Given a SELECT statement, generate a Table structure that describes
  115860. ** the result set of that SELECT.
  115861. */
  115862. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  115863. Table *pTab;
  115864. sqlite3 *db = pParse->db;
  115865. int savedFlags;
  115866. savedFlags = db->flags;
  115867. db->flags &= ~SQLITE_FullColNames;
  115868. db->flags |= SQLITE_ShortColNames;
  115869. sqlite3SelectPrep(pParse, pSelect, 0);
  115870. if( pParse->nErr ) return 0;
  115871. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  115872. db->flags = savedFlags;
  115873. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  115874. if( pTab==0 ){
  115875. return 0;
  115876. }
  115877. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  115878. ** is disabled */
  115879. assert( db->lookaside.bDisable );
  115880. pTab->nTabRef = 1;
  115881. pTab->zName = 0;
  115882. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  115883. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  115884. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  115885. pTab->iPKey = -1;
  115886. if( db->mallocFailed ){
  115887. sqlite3DeleteTable(db, pTab);
  115888. return 0;
  115889. }
  115890. return pTab;
  115891. }
  115892. /*
  115893. ** Get a VDBE for the given parser context. Create a new one if necessary.
  115894. ** If an error occurs, return NULL and leave a message in pParse.
  115895. */
  115896. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  115897. if( pParse->pVdbe ){
  115898. return pParse->pVdbe;
  115899. }
  115900. if( pParse->pToplevel==0
  115901. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  115902. ){
  115903. pParse->okConstFactor = 1;
  115904. }
  115905. return sqlite3VdbeCreate(pParse);
  115906. }
  115907. /*
  115908. ** Compute the iLimit and iOffset fields of the SELECT based on the
  115909. ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
  115910. ** that appear in the original SQL statement after the LIMIT and OFFSET
  115911. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  115912. ** are the integer memory register numbers for counters used to compute
  115913. ** the limit and offset. If there is no limit and/or offset, then
  115914. ** iLimit and iOffset are negative.
  115915. **
  115916. ** This routine changes the values of iLimit and iOffset only if
  115917. ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
  115918. ** and iOffset should have been preset to appropriate default values (zero)
  115919. ** prior to calling this routine.
  115920. **
  115921. ** The iOffset register (if it exists) is initialized to the value
  115922. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  115923. ** iOffset+1 is initialized to LIMIT+OFFSET.
  115924. **
  115925. ** Only if pLimit->pLeft!=0 do the limit registers get
  115926. ** redefined. The UNION ALL operator uses this property to force
  115927. ** the reuse of the same limit and offset registers across multiple
  115928. ** SELECT statements.
  115929. */
  115930. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  115931. Vdbe *v = 0;
  115932. int iLimit = 0;
  115933. int iOffset;
  115934. int n;
  115935. Expr *pLimit = p->pLimit;
  115936. if( p->iLimit ) return;
  115937. /*
  115938. ** "LIMIT -1" always shows all rows. There is some
  115939. ** controversy about what the correct behavior should be.
  115940. ** The current implementation interprets "LIMIT 0" to mean
  115941. ** no rows.
  115942. */
  115943. sqlite3ExprCacheClear(pParse);
  115944. if( pLimit ){
  115945. assert( pLimit->op==TK_LIMIT );
  115946. assert( pLimit->pLeft!=0 );
  115947. p->iLimit = iLimit = ++pParse->nMem;
  115948. v = sqlite3GetVdbe(pParse);
  115949. assert( v!=0 );
  115950. if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
  115951. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  115952. VdbeComment((v, "LIMIT counter"));
  115953. if( n==0 ){
  115954. sqlite3VdbeGoto(v, iBreak);
  115955. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  115956. p->nSelectRow = sqlite3LogEst((u64)n);
  115957. p->selFlags |= SF_FixedLimit;
  115958. }
  115959. }else{
  115960. sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
  115961. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  115962. VdbeComment((v, "LIMIT counter"));
  115963. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  115964. }
  115965. if( pLimit->pRight ){
  115966. p->iOffset = iOffset = ++pParse->nMem;
  115967. pParse->nMem++; /* Allocate an extra register for limit+offset */
  115968. sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
  115969. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  115970. VdbeComment((v, "OFFSET counter"));
  115971. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  115972. VdbeComment((v, "LIMIT+OFFSET"));
  115973. }
  115974. }
  115975. }
  115976. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  115977. /*
  115978. ** Return the appropriate collating sequence for the iCol-th column of
  115979. ** the result set for the compound-select statement "p". Return NULL if
  115980. ** the column has no default collating sequence.
  115981. **
  115982. ** The collating sequence for the compound select is taken from the
  115983. ** left-most term of the select that has a collating sequence.
  115984. */
  115985. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  115986. CollSeq *pRet;
  115987. if( p->pPrior ){
  115988. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  115989. }else{
  115990. pRet = 0;
  115991. }
  115992. assert( iCol>=0 );
  115993. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  115994. ** have been thrown during name resolution and we would not have gotten
  115995. ** this far */
  115996. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  115997. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  115998. }
  115999. return pRet;
  116000. }
  116001. /*
  116002. ** The select statement passed as the second parameter is a compound SELECT
  116003. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  116004. ** structure suitable for implementing the ORDER BY.
  116005. **
  116006. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  116007. ** function is responsible for ensuring that this structure is eventually
  116008. ** freed.
  116009. */
  116010. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  116011. ExprList *pOrderBy = p->pOrderBy;
  116012. int nOrderBy = p->pOrderBy->nExpr;
  116013. sqlite3 *db = pParse->db;
  116014. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  116015. if( pRet ){
  116016. int i;
  116017. for(i=0; i<nOrderBy; i++){
  116018. struct ExprList_item *pItem = &pOrderBy->a[i];
  116019. Expr *pTerm = pItem->pExpr;
  116020. CollSeq *pColl;
  116021. if( pTerm->flags & EP_Collate ){
  116022. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  116023. }else{
  116024. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  116025. if( pColl==0 ) pColl = db->pDfltColl;
  116026. pOrderBy->a[i].pExpr =
  116027. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  116028. }
  116029. assert( sqlite3KeyInfoIsWriteable(pRet) );
  116030. pRet->aColl[i] = pColl;
  116031. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  116032. }
  116033. }
  116034. return pRet;
  116035. }
  116036. #ifndef SQLITE_OMIT_CTE
  116037. /*
  116038. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  116039. ** query of the form:
  116040. **
  116041. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  116042. ** \___________/ \_______________/
  116043. ** p->pPrior p
  116044. **
  116045. **
  116046. ** There is exactly one reference to the recursive-table in the FROM clause
  116047. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  116048. **
  116049. ** The setup-query runs once to generate an initial set of rows that go
  116050. ** into a Queue table. Rows are extracted from the Queue table one by
  116051. ** one. Each row extracted from Queue is output to pDest. Then the single
  116052. ** extracted row (now in the iCurrent table) becomes the content of the
  116053. ** recursive-table for a recursive-query run. The output of the recursive-query
  116054. ** is added back into the Queue table. Then another row is extracted from Queue
  116055. ** and the iteration continues until the Queue table is empty.
  116056. **
  116057. ** If the compound query operator is UNION then no duplicate rows are ever
  116058. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  116059. ** that have ever been inserted into Queue and causes duplicates to be
  116060. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  116061. **
  116062. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  116063. ** ORDER BY order and the first entry is extracted for each cycle. Without
  116064. ** an ORDER BY, the Queue table is just a FIFO.
  116065. **
  116066. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  116067. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  116068. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  116069. ** with a positive value, then the first OFFSET outputs are discarded rather
  116070. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  116071. ** rows have been skipped.
  116072. */
  116073. static void generateWithRecursiveQuery(
  116074. Parse *pParse, /* Parsing context */
  116075. Select *p, /* The recursive SELECT to be coded */
  116076. SelectDest *pDest /* What to do with query results */
  116077. ){
  116078. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  116079. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  116080. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  116081. Select *pSetup = p->pPrior; /* The setup query */
  116082. int addrTop; /* Top of the loop */
  116083. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  116084. int iCurrent = 0; /* The Current table */
  116085. int regCurrent; /* Register holding Current table */
  116086. int iQueue; /* The Queue table */
  116087. int iDistinct = 0; /* To ensure unique results if UNION */
  116088. int eDest = SRT_Fifo; /* How to write to Queue */
  116089. SelectDest destQueue; /* SelectDest targetting the Queue table */
  116090. int i; /* Loop counter */
  116091. int rc; /* Result code */
  116092. ExprList *pOrderBy; /* The ORDER BY clause */
  116093. Expr *pLimit; /* Saved LIMIT and OFFSET */
  116094. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  116095. /* Obtain authorization to do a recursive query */
  116096. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  116097. /* Process the LIMIT and OFFSET clauses, if they exist */
  116098. addrBreak = sqlite3VdbeMakeLabel(v);
  116099. p->nSelectRow = 320; /* 4 billion rows */
  116100. computeLimitRegisters(pParse, p, addrBreak);
  116101. pLimit = p->pLimit;
  116102. regLimit = p->iLimit;
  116103. regOffset = p->iOffset;
  116104. p->pLimit = 0;
  116105. p->iLimit = p->iOffset = 0;
  116106. pOrderBy = p->pOrderBy;
  116107. /* Locate the cursor number of the Current table */
  116108. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  116109. if( pSrc->a[i].fg.isRecursive ){
  116110. iCurrent = pSrc->a[i].iCursor;
  116111. break;
  116112. }
  116113. }
  116114. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  116115. ** the Distinct table must be exactly one greater than Queue in order
  116116. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  116117. iQueue = pParse->nTab++;
  116118. if( p->op==TK_UNION ){
  116119. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  116120. iDistinct = pParse->nTab++;
  116121. }else{
  116122. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  116123. }
  116124. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  116125. /* Allocate cursors for Current, Queue, and Distinct. */
  116126. regCurrent = ++pParse->nMem;
  116127. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  116128. if( pOrderBy ){
  116129. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  116130. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  116131. (char*)pKeyInfo, P4_KEYINFO);
  116132. destQueue.pOrderBy = pOrderBy;
  116133. }else{
  116134. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  116135. }
  116136. VdbeComment((v, "Queue table"));
  116137. if( iDistinct ){
  116138. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  116139. p->selFlags |= SF_UsesEphemeral;
  116140. }
  116141. /* Detach the ORDER BY clause from the compound SELECT */
  116142. p->pOrderBy = 0;
  116143. /* Store the results of the setup-query in Queue. */
  116144. pSetup->pNext = 0;
  116145. ExplainQueryPlan((pParse, 1, "SETUP"));
  116146. rc = sqlite3Select(pParse, pSetup, &destQueue);
  116147. pSetup->pNext = p;
  116148. if( rc ) goto end_of_recursive_query;
  116149. /* Find the next row in the Queue and output that row */
  116150. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  116151. /* Transfer the next row in Queue over to Current */
  116152. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  116153. if( pOrderBy ){
  116154. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  116155. }else{
  116156. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  116157. }
  116158. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  116159. /* Output the single row in Current */
  116160. addrCont = sqlite3VdbeMakeLabel(v);
  116161. codeOffset(v, regOffset, addrCont);
  116162. selectInnerLoop(pParse, p, iCurrent,
  116163. 0, 0, pDest, addrCont, addrBreak);
  116164. if( regLimit ){
  116165. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  116166. VdbeCoverage(v);
  116167. }
  116168. sqlite3VdbeResolveLabel(v, addrCont);
  116169. /* Execute the recursive SELECT taking the single row in Current as
  116170. ** the value for the recursive-table. Store the results in the Queue.
  116171. */
  116172. if( p->selFlags & SF_Aggregate ){
  116173. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  116174. }else{
  116175. p->pPrior = 0;
  116176. ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
  116177. sqlite3Select(pParse, p, &destQueue);
  116178. assert( p->pPrior==0 );
  116179. p->pPrior = pSetup;
  116180. }
  116181. /* Keep running the loop until the Queue is empty */
  116182. sqlite3VdbeGoto(v, addrTop);
  116183. sqlite3VdbeResolveLabel(v, addrBreak);
  116184. end_of_recursive_query:
  116185. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  116186. p->pOrderBy = pOrderBy;
  116187. p->pLimit = pLimit;
  116188. return;
  116189. }
  116190. #endif /* SQLITE_OMIT_CTE */
  116191. /* Forward references */
  116192. static int multiSelectOrderBy(
  116193. Parse *pParse, /* Parsing context */
  116194. Select *p, /* The right-most of SELECTs to be coded */
  116195. SelectDest *pDest /* What to do with query results */
  116196. );
  116197. /*
  116198. ** Handle the special case of a compound-select that originates from a
  116199. ** VALUES clause. By handling this as a special case, we avoid deep
  116200. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  116201. ** on a VALUES clause.
  116202. **
  116203. ** Because the Select object originates from a VALUES clause:
  116204. ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
  116205. ** (2) All terms are UNION ALL
  116206. ** (3) There is no ORDER BY clause
  116207. **
  116208. ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
  116209. ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
  116210. ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
  116211. ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
  116212. */
  116213. static int multiSelectValues(
  116214. Parse *pParse, /* Parsing context */
  116215. Select *p, /* The right-most of SELECTs to be coded */
  116216. SelectDest *pDest /* What to do with query results */
  116217. ){
  116218. int nRow = 1;
  116219. int rc = 0;
  116220. int bShowAll = p->pLimit==0;
  116221. assert( p->selFlags & SF_MultiValue );
  116222. do{
  116223. assert( p->selFlags & SF_Values );
  116224. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  116225. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  116226. if( p->pPrior==0 ) break;
  116227. assert( p->pPrior->pNext==p );
  116228. p = p->pPrior;
  116229. nRow += bShowAll;
  116230. }while(1);
  116231. ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
  116232. nRow==1 ? "" : "S"));
  116233. while( p ){
  116234. selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
  116235. if( !bShowAll ) break;
  116236. p->nSelectRow = nRow;
  116237. p = p->pNext;
  116238. }
  116239. return rc;
  116240. }
  116241. /*
  116242. ** This routine is called to process a compound query form from
  116243. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  116244. ** INTERSECT
  116245. **
  116246. ** "p" points to the right-most of the two queries. the query on the
  116247. ** left is p->pPrior. The left query could also be a compound query
  116248. ** in which case this routine will be called recursively.
  116249. **
  116250. ** The results of the total query are to be written into a destination
  116251. ** of type eDest with parameter iParm.
  116252. **
  116253. ** Example 1: Consider a three-way compound SQL statement.
  116254. **
  116255. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  116256. **
  116257. ** This statement is parsed up as follows:
  116258. **
  116259. ** SELECT c FROM t3
  116260. ** |
  116261. ** `-----> SELECT b FROM t2
  116262. ** |
  116263. ** `------> SELECT a FROM t1
  116264. **
  116265. ** The arrows in the diagram above represent the Select.pPrior pointer.
  116266. ** So if this routine is called with p equal to the t3 query, then
  116267. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  116268. **
  116269. ** Notice that because of the way SQLite parses compound SELECTs, the
  116270. ** individual selects always group from left to right.
  116271. */
  116272. static int multiSelect(
  116273. Parse *pParse, /* Parsing context */
  116274. Select *p, /* The right-most of SELECTs to be coded */
  116275. SelectDest *pDest /* What to do with query results */
  116276. ){
  116277. int rc = SQLITE_OK; /* Success code from a subroutine */
  116278. Select *pPrior; /* Another SELECT immediately to our left */
  116279. Vdbe *v; /* Generate code to this VDBE */
  116280. SelectDest dest; /* Alternative data destination */
  116281. Select *pDelete = 0; /* Chain of simple selects to delete */
  116282. sqlite3 *db; /* Database connection */
  116283. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  116284. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  116285. */
  116286. assert( p && p->pPrior ); /* Calling function guarantees this much */
  116287. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  116288. db = pParse->db;
  116289. pPrior = p->pPrior;
  116290. dest = *pDest;
  116291. if( pPrior->pOrderBy || pPrior->pLimit ){
  116292. sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
  116293. pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
  116294. rc = 1;
  116295. goto multi_select_end;
  116296. }
  116297. v = sqlite3GetVdbe(pParse);
  116298. assert( v!=0 ); /* The VDBE already created by calling function */
  116299. /* Create the destination temporary table if necessary
  116300. */
  116301. if( dest.eDest==SRT_EphemTab ){
  116302. assert( p->pEList );
  116303. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  116304. dest.eDest = SRT_Table;
  116305. }
  116306. /* Special handling for a compound-select that originates as a VALUES clause.
  116307. */
  116308. if( p->selFlags & SF_MultiValue ){
  116309. rc = multiSelectValues(pParse, p, &dest);
  116310. goto multi_select_end;
  116311. }
  116312. /* Make sure all SELECTs in the statement have the same number of elements
  116313. ** in their result sets.
  116314. */
  116315. assert( p->pEList && pPrior->pEList );
  116316. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  116317. #ifndef SQLITE_OMIT_CTE
  116318. if( p->selFlags & SF_Recursive ){
  116319. generateWithRecursiveQuery(pParse, p, &dest);
  116320. }else
  116321. #endif
  116322. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  116323. */
  116324. if( p->pOrderBy ){
  116325. return multiSelectOrderBy(pParse, p, pDest);
  116326. }else{
  116327. #ifndef SQLITE_OMIT_EXPLAIN
  116328. if( pPrior->pPrior==0 ){
  116329. ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
  116330. ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
  116331. }
  116332. #endif
  116333. /* Generate code for the left and right SELECT statements.
  116334. */
  116335. switch( p->op ){
  116336. case TK_ALL: {
  116337. int addr = 0;
  116338. int nLimit;
  116339. assert( !pPrior->pLimit );
  116340. pPrior->iLimit = p->iLimit;
  116341. pPrior->iOffset = p->iOffset;
  116342. pPrior->pLimit = p->pLimit;
  116343. rc = sqlite3Select(pParse, pPrior, &dest);
  116344. p->pLimit = 0;
  116345. if( rc ){
  116346. goto multi_select_end;
  116347. }
  116348. p->pPrior = 0;
  116349. p->iLimit = pPrior->iLimit;
  116350. p->iOffset = pPrior->iOffset;
  116351. if( p->iLimit ){
  116352. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  116353. VdbeComment((v, "Jump ahead if LIMIT reached"));
  116354. if( p->iOffset ){
  116355. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  116356. p->iLimit, p->iOffset+1, p->iOffset);
  116357. }
  116358. }
  116359. ExplainQueryPlan((pParse, 1, "UNION ALL"));
  116360. rc = sqlite3Select(pParse, p, &dest);
  116361. testcase( rc!=SQLITE_OK );
  116362. pDelete = p->pPrior;
  116363. p->pPrior = pPrior;
  116364. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  116365. if( pPrior->pLimit
  116366. && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
  116367. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  116368. ){
  116369. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  116370. }
  116371. if( addr ){
  116372. sqlite3VdbeJumpHere(v, addr);
  116373. }
  116374. break;
  116375. }
  116376. case TK_EXCEPT:
  116377. case TK_UNION: {
  116378. int unionTab; /* Cursor number of the temp table holding result */
  116379. u8 op = 0; /* One of the SRT_ operations to apply to self */
  116380. int priorOp; /* The SRT_ operation to apply to prior selects */
  116381. Expr *pLimit; /* Saved values of p->nLimit */
  116382. int addr;
  116383. SelectDest uniondest;
  116384. testcase( p->op==TK_EXCEPT );
  116385. testcase( p->op==TK_UNION );
  116386. priorOp = SRT_Union;
  116387. if( dest.eDest==priorOp ){
  116388. /* We can reuse a temporary table generated by a SELECT to our
  116389. ** right.
  116390. */
  116391. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  116392. unionTab = dest.iSDParm;
  116393. }else{
  116394. /* We will need to create our own temporary table to hold the
  116395. ** intermediate results.
  116396. */
  116397. unionTab = pParse->nTab++;
  116398. assert( p->pOrderBy==0 );
  116399. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  116400. assert( p->addrOpenEphm[0] == -1 );
  116401. p->addrOpenEphm[0] = addr;
  116402. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  116403. assert( p->pEList );
  116404. }
  116405. /* Code the SELECT statements to our left
  116406. */
  116407. assert( !pPrior->pOrderBy );
  116408. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  116409. rc = sqlite3Select(pParse, pPrior, &uniondest);
  116410. if( rc ){
  116411. goto multi_select_end;
  116412. }
  116413. /* Code the current SELECT statement
  116414. */
  116415. if( p->op==TK_EXCEPT ){
  116416. op = SRT_Except;
  116417. }else{
  116418. assert( p->op==TK_UNION );
  116419. op = SRT_Union;
  116420. }
  116421. p->pPrior = 0;
  116422. pLimit = p->pLimit;
  116423. p->pLimit = 0;
  116424. uniondest.eDest = op;
  116425. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  116426. selectOpName(p->op)));
  116427. rc = sqlite3Select(pParse, p, &uniondest);
  116428. testcase( rc!=SQLITE_OK );
  116429. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  116430. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  116431. sqlite3ExprListDelete(db, p->pOrderBy);
  116432. pDelete = p->pPrior;
  116433. p->pPrior = pPrior;
  116434. p->pOrderBy = 0;
  116435. if( p->op==TK_UNION ){
  116436. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  116437. }
  116438. sqlite3ExprDelete(db, p->pLimit);
  116439. p->pLimit = pLimit;
  116440. p->iLimit = 0;
  116441. p->iOffset = 0;
  116442. /* Convert the data in the temporary table into whatever form
  116443. ** it is that we currently need.
  116444. */
  116445. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  116446. if( dest.eDest!=priorOp ){
  116447. int iCont, iBreak, iStart;
  116448. assert( p->pEList );
  116449. iBreak = sqlite3VdbeMakeLabel(v);
  116450. iCont = sqlite3VdbeMakeLabel(v);
  116451. computeLimitRegisters(pParse, p, iBreak);
  116452. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  116453. iStart = sqlite3VdbeCurrentAddr(v);
  116454. selectInnerLoop(pParse, p, unionTab,
  116455. 0, 0, &dest, iCont, iBreak);
  116456. sqlite3VdbeResolveLabel(v, iCont);
  116457. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  116458. sqlite3VdbeResolveLabel(v, iBreak);
  116459. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  116460. }
  116461. break;
  116462. }
  116463. default: assert( p->op==TK_INTERSECT ); {
  116464. int tab1, tab2;
  116465. int iCont, iBreak, iStart;
  116466. Expr *pLimit;
  116467. int addr;
  116468. SelectDest intersectdest;
  116469. int r1;
  116470. /* INTERSECT is different from the others since it requires
  116471. ** two temporary tables. Hence it has its own case. Begin
  116472. ** by allocating the tables we will need.
  116473. */
  116474. tab1 = pParse->nTab++;
  116475. tab2 = pParse->nTab++;
  116476. assert( p->pOrderBy==0 );
  116477. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  116478. assert( p->addrOpenEphm[0] == -1 );
  116479. p->addrOpenEphm[0] = addr;
  116480. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  116481. assert( p->pEList );
  116482. /* Code the SELECTs to our left into temporary table "tab1".
  116483. */
  116484. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  116485. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  116486. if( rc ){
  116487. goto multi_select_end;
  116488. }
  116489. /* Code the current SELECT into temporary table "tab2"
  116490. */
  116491. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  116492. assert( p->addrOpenEphm[1] == -1 );
  116493. p->addrOpenEphm[1] = addr;
  116494. p->pPrior = 0;
  116495. pLimit = p->pLimit;
  116496. p->pLimit = 0;
  116497. intersectdest.iSDParm = tab2;
  116498. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  116499. selectOpName(p->op)));
  116500. rc = sqlite3Select(pParse, p, &intersectdest);
  116501. testcase( rc!=SQLITE_OK );
  116502. pDelete = p->pPrior;
  116503. p->pPrior = pPrior;
  116504. if( p->nSelectRow>pPrior->nSelectRow ){
  116505. p->nSelectRow = pPrior->nSelectRow;
  116506. }
  116507. sqlite3ExprDelete(db, p->pLimit);
  116508. p->pLimit = pLimit;
  116509. /* Generate code to take the intersection of the two temporary
  116510. ** tables.
  116511. */
  116512. assert( p->pEList );
  116513. iBreak = sqlite3VdbeMakeLabel(v);
  116514. iCont = sqlite3VdbeMakeLabel(v);
  116515. computeLimitRegisters(pParse, p, iBreak);
  116516. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  116517. r1 = sqlite3GetTempReg(pParse);
  116518. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  116519. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  116520. VdbeCoverage(v);
  116521. sqlite3ReleaseTempReg(pParse, r1);
  116522. selectInnerLoop(pParse, p, tab1,
  116523. 0, 0, &dest, iCont, iBreak);
  116524. sqlite3VdbeResolveLabel(v, iCont);
  116525. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  116526. sqlite3VdbeResolveLabel(v, iBreak);
  116527. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  116528. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  116529. break;
  116530. }
  116531. }
  116532. #ifndef SQLITE_OMIT_EXPLAIN
  116533. if( p->pNext==0 ){
  116534. ExplainQueryPlanPop(pParse);
  116535. }
  116536. #endif
  116537. }
  116538. /* Compute collating sequences used by
  116539. ** temporary tables needed to implement the compound select.
  116540. ** Attach the KeyInfo structure to all temporary tables.
  116541. **
  116542. ** This section is run by the right-most SELECT statement only.
  116543. ** SELECT statements to the left always skip this part. The right-most
  116544. ** SELECT might also skip this part if it has no ORDER BY clause and
  116545. ** no temp tables are required.
  116546. */
  116547. if( p->selFlags & SF_UsesEphemeral ){
  116548. int i; /* Loop counter */
  116549. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  116550. Select *pLoop; /* For looping through SELECT statements */
  116551. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  116552. int nCol; /* Number of columns in result set */
  116553. assert( p->pNext==0 );
  116554. nCol = p->pEList->nExpr;
  116555. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  116556. if( !pKeyInfo ){
  116557. rc = SQLITE_NOMEM_BKPT;
  116558. goto multi_select_end;
  116559. }
  116560. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  116561. *apColl = multiSelectCollSeq(pParse, p, i);
  116562. if( 0==*apColl ){
  116563. *apColl = db->pDfltColl;
  116564. }
  116565. }
  116566. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  116567. for(i=0; i<2; i++){
  116568. int addr = pLoop->addrOpenEphm[i];
  116569. if( addr<0 ){
  116570. /* If [0] is unused then [1] is also unused. So we can
  116571. ** always safely abort as soon as the first unused slot is found */
  116572. assert( pLoop->addrOpenEphm[1]<0 );
  116573. break;
  116574. }
  116575. sqlite3VdbeChangeP2(v, addr, nCol);
  116576. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  116577. P4_KEYINFO);
  116578. pLoop->addrOpenEphm[i] = -1;
  116579. }
  116580. }
  116581. sqlite3KeyInfoUnref(pKeyInfo);
  116582. }
  116583. multi_select_end:
  116584. pDest->iSdst = dest.iSdst;
  116585. pDest->nSdst = dest.nSdst;
  116586. sqlite3SelectDelete(db, pDelete);
  116587. return rc;
  116588. }
  116589. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  116590. /*
  116591. ** Error message for when two or more terms of a compound select have different
  116592. ** size result sets.
  116593. */
  116594. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  116595. if( p->selFlags & SF_Values ){
  116596. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  116597. }else{
  116598. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  116599. " do not have the same number of result columns", selectOpName(p->op));
  116600. }
  116601. }
  116602. /*
  116603. ** Code an output subroutine for a coroutine implementation of a
  116604. ** SELECT statment.
  116605. **
  116606. ** The data to be output is contained in pIn->iSdst. There are
  116607. ** pIn->nSdst columns to be output. pDest is where the output should
  116608. ** be sent.
  116609. **
  116610. ** regReturn is the number of the register holding the subroutine
  116611. ** return address.
  116612. **
  116613. ** If regPrev>0 then it is the first register in a vector that
  116614. ** records the previous output. mem[regPrev] is a flag that is false
  116615. ** if there has been no previous output. If regPrev>0 then code is
  116616. ** generated to suppress duplicates. pKeyInfo is used for comparing
  116617. ** keys.
  116618. **
  116619. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  116620. ** iBreak.
  116621. */
  116622. static int generateOutputSubroutine(
  116623. Parse *pParse, /* Parsing context */
  116624. Select *p, /* The SELECT statement */
  116625. SelectDest *pIn, /* Coroutine supplying data */
  116626. SelectDest *pDest, /* Where to send the data */
  116627. int regReturn, /* The return address register */
  116628. int regPrev, /* Previous result register. No uniqueness if 0 */
  116629. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  116630. int iBreak /* Jump here if we hit the LIMIT */
  116631. ){
  116632. Vdbe *v = pParse->pVdbe;
  116633. int iContinue;
  116634. int addr;
  116635. addr = sqlite3VdbeCurrentAddr(v);
  116636. iContinue = sqlite3VdbeMakeLabel(v);
  116637. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  116638. */
  116639. if( regPrev ){
  116640. int addr1, addr2;
  116641. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  116642. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  116643. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  116644. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  116645. sqlite3VdbeJumpHere(v, addr1);
  116646. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  116647. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  116648. }
  116649. if( pParse->db->mallocFailed ) return 0;
  116650. /* Suppress the first OFFSET entries if there is an OFFSET clause
  116651. */
  116652. codeOffset(v, p->iOffset, iContinue);
  116653. assert( pDest->eDest!=SRT_Exists );
  116654. assert( pDest->eDest!=SRT_Table );
  116655. switch( pDest->eDest ){
  116656. /* Store the result as data using a unique key.
  116657. */
  116658. case SRT_EphemTab: {
  116659. int r1 = sqlite3GetTempReg(pParse);
  116660. int r2 = sqlite3GetTempReg(pParse);
  116661. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  116662. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  116663. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  116664. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  116665. sqlite3ReleaseTempReg(pParse, r2);
  116666. sqlite3ReleaseTempReg(pParse, r1);
  116667. break;
  116668. }
  116669. #ifndef SQLITE_OMIT_SUBQUERY
  116670. /* If we are creating a set for an "expr IN (SELECT ...)".
  116671. */
  116672. case SRT_Set: {
  116673. int r1;
  116674. testcase( pIn->nSdst>1 );
  116675. r1 = sqlite3GetTempReg(pParse);
  116676. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  116677. r1, pDest->zAffSdst, pIn->nSdst);
  116678. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  116679. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  116680. pIn->iSdst, pIn->nSdst);
  116681. sqlite3ReleaseTempReg(pParse, r1);
  116682. break;
  116683. }
  116684. /* If this is a scalar select that is part of an expression, then
  116685. ** store the results in the appropriate memory cell and break out
  116686. ** of the scan loop.
  116687. */
  116688. case SRT_Mem: {
  116689. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  116690. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  116691. /* The LIMIT clause will jump out of the loop for us */
  116692. break;
  116693. }
  116694. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  116695. /* The results are stored in a sequence of registers
  116696. ** starting at pDest->iSdst. Then the co-routine yields.
  116697. */
  116698. case SRT_Coroutine: {
  116699. if( pDest->iSdst==0 ){
  116700. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  116701. pDest->nSdst = pIn->nSdst;
  116702. }
  116703. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  116704. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  116705. break;
  116706. }
  116707. /* If none of the above, then the result destination must be
  116708. ** SRT_Output. This routine is never called with any other
  116709. ** destination other than the ones handled above or SRT_Output.
  116710. **
  116711. ** For SRT_Output, results are stored in a sequence of registers.
  116712. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  116713. ** return the next row of result.
  116714. */
  116715. default: {
  116716. assert( pDest->eDest==SRT_Output );
  116717. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  116718. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  116719. break;
  116720. }
  116721. }
  116722. /* Jump to the end of the loop if the LIMIT is reached.
  116723. */
  116724. if( p->iLimit ){
  116725. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  116726. }
  116727. /* Generate the subroutine return
  116728. */
  116729. sqlite3VdbeResolveLabel(v, iContinue);
  116730. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  116731. return addr;
  116732. }
  116733. /*
  116734. ** Alternative compound select code generator for cases when there
  116735. ** is an ORDER BY clause.
  116736. **
  116737. ** We assume a query of the following form:
  116738. **
  116739. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  116740. **
  116741. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  116742. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  116743. ** co-routines. Then run the co-routines in parallel and merge the results
  116744. ** into the output. In addition to the two coroutines (called selectA and
  116745. ** selectB) there are 7 subroutines:
  116746. **
  116747. ** outA: Move the output of the selectA coroutine into the output
  116748. ** of the compound query.
  116749. **
  116750. ** outB: Move the output of the selectB coroutine into the output
  116751. ** of the compound query. (Only generated for UNION and
  116752. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  116753. ** appears only in B.)
  116754. **
  116755. ** AltB: Called when there is data from both coroutines and A<B.
  116756. **
  116757. ** AeqB: Called when there is data from both coroutines and A==B.
  116758. **
  116759. ** AgtB: Called when there is data from both coroutines and A>B.
  116760. **
  116761. ** EofA: Called when data is exhausted from selectA.
  116762. **
  116763. ** EofB: Called when data is exhausted from selectB.
  116764. **
  116765. ** The implementation of the latter five subroutines depend on which
  116766. ** <operator> is used:
  116767. **
  116768. **
  116769. ** UNION ALL UNION EXCEPT INTERSECT
  116770. ** ------------- ----------------- -------------- -----------------
  116771. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  116772. **
  116773. ** AeqB: outA, nextA nextA nextA outA, nextA
  116774. **
  116775. ** AgtB: outB, nextB outB, nextB nextB nextB
  116776. **
  116777. ** EofA: outB, nextB outB, nextB halt halt
  116778. **
  116779. ** EofB: outA, nextA outA, nextA outA, nextA halt
  116780. **
  116781. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  116782. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  116783. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  116784. ** following nextX causes a jump to the end of the select processing.
  116785. **
  116786. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  116787. ** within the output subroutine. The regPrev register set holds the previously
  116788. ** output value. A comparison is made against this value and the output
  116789. ** is skipped if the next results would be the same as the previous.
  116790. **
  116791. ** The implementation plan is to implement the two coroutines and seven
  116792. ** subroutines first, then put the control logic at the bottom. Like this:
  116793. **
  116794. ** goto Init
  116795. ** coA: coroutine for left query (A)
  116796. ** coB: coroutine for right query (B)
  116797. ** outA: output one row of A
  116798. ** outB: output one row of B (UNION and UNION ALL only)
  116799. ** EofA: ...
  116800. ** EofB: ...
  116801. ** AltB: ...
  116802. ** AeqB: ...
  116803. ** AgtB: ...
  116804. ** Init: initialize coroutine registers
  116805. ** yield coA
  116806. ** if eof(A) goto EofA
  116807. ** yield coB
  116808. ** if eof(B) goto EofB
  116809. ** Cmpr: Compare A, B
  116810. ** Jump AltB, AeqB, AgtB
  116811. ** End: ...
  116812. **
  116813. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  116814. ** actually called using Gosub and they do not Return. EofA and EofB loop
  116815. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  116816. ** and AgtB jump to either L2 or to one of EofA or EofB.
  116817. */
  116818. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  116819. static int multiSelectOrderBy(
  116820. Parse *pParse, /* Parsing context */
  116821. Select *p, /* The right-most of SELECTs to be coded */
  116822. SelectDest *pDest /* What to do with query results */
  116823. ){
  116824. int i, j; /* Loop counters */
  116825. Select *pPrior; /* Another SELECT immediately to our left */
  116826. Vdbe *v; /* Generate code to this VDBE */
  116827. SelectDest destA; /* Destination for coroutine A */
  116828. SelectDest destB; /* Destination for coroutine B */
  116829. int regAddrA; /* Address register for select-A coroutine */
  116830. int regAddrB; /* Address register for select-B coroutine */
  116831. int addrSelectA; /* Address of the select-A coroutine */
  116832. int addrSelectB; /* Address of the select-B coroutine */
  116833. int regOutA; /* Address register for the output-A subroutine */
  116834. int regOutB; /* Address register for the output-B subroutine */
  116835. int addrOutA; /* Address of the output-A subroutine */
  116836. int addrOutB = 0; /* Address of the output-B subroutine */
  116837. int addrEofA; /* Address of the select-A-exhausted subroutine */
  116838. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  116839. int addrEofB; /* Address of the select-B-exhausted subroutine */
  116840. int addrAltB; /* Address of the A<B subroutine */
  116841. int addrAeqB; /* Address of the A==B subroutine */
  116842. int addrAgtB; /* Address of the A>B subroutine */
  116843. int regLimitA; /* Limit register for select-A */
  116844. int regLimitB; /* Limit register for select-A */
  116845. int regPrev; /* A range of registers to hold previous output */
  116846. int savedLimit; /* Saved value of p->iLimit */
  116847. int savedOffset; /* Saved value of p->iOffset */
  116848. int labelCmpr; /* Label for the start of the merge algorithm */
  116849. int labelEnd; /* Label for the end of the overall SELECT stmt */
  116850. int addr1; /* Jump instructions that get retargetted */
  116851. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  116852. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  116853. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  116854. sqlite3 *db; /* Database connection */
  116855. ExprList *pOrderBy; /* The ORDER BY clause */
  116856. int nOrderBy; /* Number of terms in the ORDER BY clause */
  116857. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  116858. assert( p->pOrderBy!=0 );
  116859. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  116860. db = pParse->db;
  116861. v = pParse->pVdbe;
  116862. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  116863. labelEnd = sqlite3VdbeMakeLabel(v);
  116864. labelCmpr = sqlite3VdbeMakeLabel(v);
  116865. /* Patch up the ORDER BY clause
  116866. */
  116867. op = p->op;
  116868. pPrior = p->pPrior;
  116869. assert( pPrior->pOrderBy==0 );
  116870. pOrderBy = p->pOrderBy;
  116871. assert( pOrderBy );
  116872. nOrderBy = pOrderBy->nExpr;
  116873. /* For operators other than UNION ALL we have to make sure that
  116874. ** the ORDER BY clause covers every term of the result set. Add
  116875. ** terms to the ORDER BY clause as necessary.
  116876. */
  116877. if( op!=TK_ALL ){
  116878. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  116879. struct ExprList_item *pItem;
  116880. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  116881. assert( pItem->u.x.iOrderByCol>0 );
  116882. if( pItem->u.x.iOrderByCol==i ) break;
  116883. }
  116884. if( j==nOrderBy ){
  116885. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  116886. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  116887. pNew->flags |= EP_IntValue;
  116888. pNew->u.iValue = i;
  116889. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  116890. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  116891. }
  116892. }
  116893. }
  116894. /* Compute the comparison permutation and keyinfo that is used with
  116895. ** the permutation used to determine if the next
  116896. ** row of results comes from selectA or selectB. Also add explicit
  116897. ** collations to the ORDER BY clause terms so that when the subqueries
  116898. ** to the right and the left are evaluated, they use the correct
  116899. ** collation.
  116900. */
  116901. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  116902. if( aPermute ){
  116903. struct ExprList_item *pItem;
  116904. aPermute[0] = nOrderBy;
  116905. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  116906. assert( pItem->u.x.iOrderByCol>0 );
  116907. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  116908. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  116909. }
  116910. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  116911. }else{
  116912. pKeyMerge = 0;
  116913. }
  116914. /* Reattach the ORDER BY clause to the query.
  116915. */
  116916. p->pOrderBy = pOrderBy;
  116917. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  116918. /* Allocate a range of temporary registers and the KeyInfo needed
  116919. ** for the logic that removes duplicate result rows when the
  116920. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  116921. */
  116922. if( op==TK_ALL ){
  116923. regPrev = 0;
  116924. }else{
  116925. int nExpr = p->pEList->nExpr;
  116926. assert( nOrderBy>=nExpr || db->mallocFailed );
  116927. regPrev = pParse->nMem+1;
  116928. pParse->nMem += nExpr+1;
  116929. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  116930. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  116931. if( pKeyDup ){
  116932. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  116933. for(i=0; i<nExpr; i++){
  116934. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  116935. pKeyDup->aSortOrder[i] = 0;
  116936. }
  116937. }
  116938. }
  116939. /* Separate the left and the right query from one another
  116940. */
  116941. p->pPrior = 0;
  116942. pPrior->pNext = 0;
  116943. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  116944. if( pPrior->pPrior==0 ){
  116945. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  116946. }
  116947. /* Compute the limit registers */
  116948. computeLimitRegisters(pParse, p, labelEnd);
  116949. if( p->iLimit && op==TK_ALL ){
  116950. regLimitA = ++pParse->nMem;
  116951. regLimitB = ++pParse->nMem;
  116952. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  116953. regLimitA);
  116954. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  116955. }else{
  116956. regLimitA = regLimitB = 0;
  116957. }
  116958. sqlite3ExprDelete(db, p->pLimit);
  116959. p->pLimit = 0;
  116960. regAddrA = ++pParse->nMem;
  116961. regAddrB = ++pParse->nMem;
  116962. regOutA = ++pParse->nMem;
  116963. regOutB = ++pParse->nMem;
  116964. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  116965. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  116966. ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
  116967. /* Generate a coroutine to evaluate the SELECT statement to the
  116968. ** left of the compound operator - the "A" select.
  116969. */
  116970. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  116971. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  116972. VdbeComment((v, "left SELECT"));
  116973. pPrior->iLimit = regLimitA;
  116974. ExplainQueryPlan((pParse, 1, "LEFT"));
  116975. sqlite3Select(pParse, pPrior, &destA);
  116976. sqlite3VdbeEndCoroutine(v, regAddrA);
  116977. sqlite3VdbeJumpHere(v, addr1);
  116978. /* Generate a coroutine to evaluate the SELECT statement on
  116979. ** the right - the "B" select
  116980. */
  116981. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  116982. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  116983. VdbeComment((v, "right SELECT"));
  116984. savedLimit = p->iLimit;
  116985. savedOffset = p->iOffset;
  116986. p->iLimit = regLimitB;
  116987. p->iOffset = 0;
  116988. ExplainQueryPlan((pParse, 1, "RIGHT"));
  116989. sqlite3Select(pParse, p, &destB);
  116990. p->iLimit = savedLimit;
  116991. p->iOffset = savedOffset;
  116992. sqlite3VdbeEndCoroutine(v, regAddrB);
  116993. /* Generate a subroutine that outputs the current row of the A
  116994. ** select as the next output row of the compound select.
  116995. */
  116996. VdbeNoopComment((v, "Output routine for A"));
  116997. addrOutA = generateOutputSubroutine(pParse,
  116998. p, &destA, pDest, regOutA,
  116999. regPrev, pKeyDup, labelEnd);
  117000. /* Generate a subroutine that outputs the current row of the B
  117001. ** select as the next output row of the compound select.
  117002. */
  117003. if( op==TK_ALL || op==TK_UNION ){
  117004. VdbeNoopComment((v, "Output routine for B"));
  117005. addrOutB = generateOutputSubroutine(pParse,
  117006. p, &destB, pDest, regOutB,
  117007. regPrev, pKeyDup, labelEnd);
  117008. }
  117009. sqlite3KeyInfoUnref(pKeyDup);
  117010. /* Generate a subroutine to run when the results from select A
  117011. ** are exhausted and only data in select B remains.
  117012. */
  117013. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  117014. addrEofA_noB = addrEofA = labelEnd;
  117015. }else{
  117016. VdbeNoopComment((v, "eof-A subroutine"));
  117017. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  117018. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  117019. VdbeCoverage(v);
  117020. sqlite3VdbeGoto(v, addrEofA);
  117021. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  117022. }
  117023. /* Generate a subroutine to run when the results from select B
  117024. ** are exhausted and only data in select A remains.
  117025. */
  117026. if( op==TK_INTERSECT ){
  117027. addrEofB = addrEofA;
  117028. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  117029. }else{
  117030. VdbeNoopComment((v, "eof-B subroutine"));
  117031. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  117032. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  117033. sqlite3VdbeGoto(v, addrEofB);
  117034. }
  117035. /* Generate code to handle the case of A<B
  117036. */
  117037. VdbeNoopComment((v, "A-lt-B subroutine"));
  117038. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  117039. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  117040. sqlite3VdbeGoto(v, labelCmpr);
  117041. /* Generate code to handle the case of A==B
  117042. */
  117043. if( op==TK_ALL ){
  117044. addrAeqB = addrAltB;
  117045. }else if( op==TK_INTERSECT ){
  117046. addrAeqB = addrAltB;
  117047. addrAltB++;
  117048. }else{
  117049. VdbeNoopComment((v, "A-eq-B subroutine"));
  117050. addrAeqB =
  117051. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  117052. sqlite3VdbeGoto(v, labelCmpr);
  117053. }
  117054. /* Generate code to handle the case of A>B
  117055. */
  117056. VdbeNoopComment((v, "A-gt-B subroutine"));
  117057. addrAgtB = sqlite3VdbeCurrentAddr(v);
  117058. if( op==TK_ALL || op==TK_UNION ){
  117059. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  117060. }
  117061. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  117062. sqlite3VdbeGoto(v, labelCmpr);
  117063. /* This code runs once to initialize everything.
  117064. */
  117065. sqlite3VdbeJumpHere(v, addr1);
  117066. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  117067. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  117068. /* Implement the main merge loop
  117069. */
  117070. sqlite3VdbeResolveLabel(v, labelCmpr);
  117071. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  117072. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  117073. (char*)pKeyMerge, P4_KEYINFO);
  117074. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  117075. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  117076. /* Jump to the this point in order to terminate the query.
  117077. */
  117078. sqlite3VdbeResolveLabel(v, labelEnd);
  117079. /* Reassembly the compound query so that it will be freed correctly
  117080. ** by the calling function */
  117081. if( p->pPrior ){
  117082. sqlite3SelectDelete(db, p->pPrior);
  117083. }
  117084. p->pPrior = pPrior;
  117085. pPrior->pNext = p;
  117086. /*** TBD: Insert subroutine calls to close cursors on incomplete
  117087. **** subqueries ****/
  117088. ExplainQueryPlanPop(pParse);
  117089. return pParse->nErr!=0;
  117090. }
  117091. #endif
  117092. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  117093. /* An instance of the SubstContext object describes an substitution edit
  117094. ** to be performed on a parse tree.
  117095. **
  117096. ** All references to columns in table iTable are to be replaced by corresponding
  117097. ** expressions in pEList.
  117098. */
  117099. typedef struct SubstContext {
  117100. Parse *pParse; /* The parsing context */
  117101. int iTable; /* Replace references to this table */
  117102. int iNewTable; /* New table number */
  117103. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  117104. ExprList *pEList; /* Replacement expressions */
  117105. } SubstContext;
  117106. /* Forward Declarations */
  117107. static void substExprList(SubstContext*, ExprList*);
  117108. static void substSelect(SubstContext*, Select*, int);
  117109. /*
  117110. ** Scan through the expression pExpr. Replace every reference to
  117111. ** a column in table number iTable with a copy of the iColumn-th
  117112. ** entry in pEList. (But leave references to the ROWID column
  117113. ** unchanged.)
  117114. **
  117115. ** This routine is part of the flattening procedure. A subquery
  117116. ** whose result set is defined by pEList appears as entry in the
  117117. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  117118. ** FORM clause entry is iTable. This routine makes the necessary
  117119. ** changes to pExpr so that it refers directly to the source table
  117120. ** of the subquery rather the result set of the subquery.
  117121. */
  117122. static Expr *substExpr(
  117123. SubstContext *pSubst, /* Description of the substitution */
  117124. Expr *pExpr /* Expr in which substitution occurs */
  117125. ){
  117126. if( pExpr==0 ) return 0;
  117127. if( ExprHasProperty(pExpr, EP_FromJoin)
  117128. && pExpr->iRightJoinTable==pSubst->iTable
  117129. ){
  117130. pExpr->iRightJoinTable = pSubst->iNewTable;
  117131. }
  117132. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  117133. if( pExpr->iColumn<0 ){
  117134. pExpr->op = TK_NULL;
  117135. }else{
  117136. Expr *pNew;
  117137. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  117138. Expr ifNullRow;
  117139. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  117140. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  117141. if( sqlite3ExprIsVector(pCopy) ){
  117142. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  117143. }else{
  117144. sqlite3 *db = pSubst->pParse->db;
  117145. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  117146. memset(&ifNullRow, 0, sizeof(ifNullRow));
  117147. ifNullRow.op = TK_IF_NULL_ROW;
  117148. ifNullRow.pLeft = pCopy;
  117149. ifNullRow.iTable = pSubst->iNewTable;
  117150. pCopy = &ifNullRow;
  117151. }
  117152. pNew = sqlite3ExprDup(db, pCopy, 0);
  117153. if( pNew && pSubst->isLeftJoin ){
  117154. ExprSetProperty(pNew, EP_CanBeNull);
  117155. }
  117156. if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
  117157. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  117158. ExprSetProperty(pNew, EP_FromJoin);
  117159. }
  117160. sqlite3ExprDelete(db, pExpr);
  117161. pExpr = pNew;
  117162. }
  117163. }
  117164. }else{
  117165. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  117166. pExpr->iTable = pSubst->iNewTable;
  117167. }
  117168. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  117169. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  117170. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  117171. substSelect(pSubst, pExpr->x.pSelect, 1);
  117172. }else{
  117173. substExprList(pSubst, pExpr->x.pList);
  117174. }
  117175. }
  117176. return pExpr;
  117177. }
  117178. static void substExprList(
  117179. SubstContext *pSubst, /* Description of the substitution */
  117180. ExprList *pList /* List to scan and in which to make substitutes */
  117181. ){
  117182. int i;
  117183. if( pList==0 ) return;
  117184. for(i=0; i<pList->nExpr; i++){
  117185. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  117186. }
  117187. }
  117188. static void substSelect(
  117189. SubstContext *pSubst, /* Description of the substitution */
  117190. Select *p, /* SELECT statement in which to make substitutions */
  117191. int doPrior /* Do substitutes on p->pPrior too */
  117192. ){
  117193. SrcList *pSrc;
  117194. struct SrcList_item *pItem;
  117195. int i;
  117196. if( !p ) return;
  117197. do{
  117198. substExprList(pSubst, p->pEList);
  117199. substExprList(pSubst, p->pGroupBy);
  117200. substExprList(pSubst, p->pOrderBy);
  117201. p->pHaving = substExpr(pSubst, p->pHaving);
  117202. p->pWhere = substExpr(pSubst, p->pWhere);
  117203. pSrc = p->pSrc;
  117204. assert( pSrc!=0 );
  117205. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  117206. substSelect(pSubst, pItem->pSelect, 1);
  117207. if( pItem->fg.isTabFunc ){
  117208. substExprList(pSubst, pItem->u1.pFuncArg);
  117209. }
  117210. }
  117211. }while( doPrior && (p = p->pPrior)!=0 );
  117212. }
  117213. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  117214. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  117215. /*
  117216. ** This routine attempts to flatten subqueries as a performance optimization.
  117217. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  117218. **
  117219. ** To understand the concept of flattening, consider the following
  117220. ** query:
  117221. **
  117222. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  117223. **
  117224. ** The default way of implementing this query is to execute the
  117225. ** subquery first and store the results in a temporary table, then
  117226. ** run the outer query on that temporary table. This requires two
  117227. ** passes over the data. Furthermore, because the temporary table
  117228. ** has no indices, the WHERE clause on the outer query cannot be
  117229. ** optimized.
  117230. **
  117231. ** This routine attempts to rewrite queries such as the above into
  117232. ** a single flat select, like this:
  117233. **
  117234. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  117235. **
  117236. ** The code generated for this simplification gives the same result
  117237. ** but only has to scan the data once. And because indices might
  117238. ** exist on the table t1, a complete scan of the data might be
  117239. ** avoided.
  117240. **
  117241. ** Flattening is subject to the following constraints:
  117242. **
  117243. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  117244. ** The subquery and the outer query cannot both be aggregates.
  117245. **
  117246. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  117247. ** (2) If the subquery is an aggregate then
  117248. ** (2a) the outer query must not be a join and
  117249. ** (2b) the outer query must not use subqueries
  117250. ** other than the one FROM-clause subquery that is a candidate
  117251. ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
  117252. ** from 2015-02-09.)
  117253. **
  117254. ** (3) If the subquery is the right operand of a LEFT JOIN then
  117255. ** (3a) the subquery may not be a join and
  117256. ** (3b) the FROM clause of the subquery may not contain a virtual
  117257. ** table and
  117258. ** (3c) the outer query may not be an aggregate.
  117259. **
  117260. ** (4) The subquery can not be DISTINCT.
  117261. **
  117262. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  117263. ** sub-queries that were excluded from this optimization. Restriction
  117264. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  117265. **
  117266. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  117267. ** If the subquery is aggregate, the outer query may not be DISTINCT.
  117268. **
  117269. ** (7) The subquery must have a FROM clause. TODO: For subqueries without
  117270. ** A FROM clause, consider adding a FROM clause with the special
  117271. ** table sqlite_once that consists of a single row containing a
  117272. ** single NULL.
  117273. **
  117274. ** (8) If the subquery uses LIMIT then the outer query may not be a join.
  117275. **
  117276. ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
  117277. **
  117278. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  117279. ** accidently carried the comment forward until 2014-09-15. Original
  117280. ** constraint: "If the subquery is aggregate then the outer query
  117281. ** may not use LIMIT."
  117282. **
  117283. ** (11) The subquery and the outer query may not both have ORDER BY clauses.
  117284. **
  117285. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  117286. ** a separate restriction deriving from ticket #350.
  117287. **
  117288. ** (13) The subquery and outer query may not both use LIMIT.
  117289. **
  117290. ** (14) The subquery may not use OFFSET.
  117291. **
  117292. ** (15) If the outer query is part of a compound select, then the
  117293. ** subquery may not use LIMIT.
  117294. ** (See ticket #2339 and ticket [02a8e81d44]).
  117295. **
  117296. ** (16) If the outer query is aggregate, then the subquery may not
  117297. ** use ORDER BY. (Ticket #2942) This used to not matter
  117298. ** until we introduced the group_concat() function.
  117299. **
  117300. ** (17) If the subquery is a compound select, then
  117301. ** (17a) all compound operators must be a UNION ALL, and
  117302. ** (17b) no terms within the subquery compound may be aggregate
  117303. ** or DISTINCT, and
  117304. ** (17c) every term within the subquery compound must have a FROM clause
  117305. ** (17d) the outer query may not be
  117306. ** (17d1) aggregate, or
  117307. ** (17d2) DISTINCT, or
  117308. ** (17d3) a join.
  117309. **
  117310. ** The parent and sub-query may contain WHERE clauses. Subject to
  117311. ** rules (11), (13) and (14), they may also contain ORDER BY,
  117312. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  117313. ** operator other than UNION ALL because all the other compound
  117314. ** operators have an implied DISTINCT which is disallowed by
  117315. ** restriction (4).
  117316. **
  117317. ** Also, each component of the sub-query must return the same number
  117318. ** of result columns. This is actually a requirement for any compound
  117319. ** SELECT statement, but all the code here does is make sure that no
  117320. ** such (illegal) sub-query is flattened. The caller will detect the
  117321. ** syntax error and return a detailed message.
  117322. **
  117323. ** (18) If the sub-query is a compound select, then all terms of the
  117324. ** ORDER BY clause of the parent must be simple references to
  117325. ** columns of the sub-query.
  117326. **
  117327. ** (19) If the subquery uses LIMIT then the outer query may not
  117328. ** have a WHERE clause.
  117329. **
  117330. ** (20) If the sub-query is a compound select, then it must not use
  117331. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  117332. ** somewhat by saying that the terms of the ORDER BY clause must
  117333. ** appear as unmodified result columns in the outer query. But we
  117334. ** have other optimizations in mind to deal with that case.
  117335. **
  117336. ** (21) If the subquery uses LIMIT then the outer query may not be
  117337. ** DISTINCT. (See ticket [752e1646fc]).
  117338. **
  117339. ** (22) The subquery may not be a recursive CTE.
  117340. **
  117341. ** (**) Subsumed into restriction (17d3). Was: If the outer query is
  117342. ** a recursive CTE, then the sub-query may not be a compound query.
  117343. ** This restriction is because transforming the
  117344. ** parent to a compound query confuses the code that handles
  117345. ** recursive queries in multiSelect().
  117346. **
  117347. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  117348. ** The subquery may not be an aggregate that uses the built-in min() or
  117349. ** or max() functions. (Without this restriction, a query like:
  117350. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  117351. ** return the value X for which Y was maximal.)
  117352. **
  117353. **
  117354. ** In this routine, the "p" parameter is a pointer to the outer query.
  117355. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  117356. ** uses aggregates.
  117357. **
  117358. ** If flattening is not attempted, this routine is a no-op and returns 0.
  117359. ** If flattening is attempted this routine returns 1.
  117360. **
  117361. ** All of the expression analysis must occur on both the outer query and
  117362. ** the subquery before this routine runs.
  117363. */
  117364. static int flattenSubquery(
  117365. Parse *pParse, /* Parsing context */
  117366. Select *p, /* The parent or outer SELECT statement */
  117367. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  117368. int isAgg /* True if outer SELECT uses aggregate functions */
  117369. ){
  117370. const char *zSavedAuthContext = pParse->zAuthContext;
  117371. Select *pParent; /* Current UNION ALL term of the other query */
  117372. Select *pSub; /* The inner query or "subquery" */
  117373. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  117374. SrcList *pSrc; /* The FROM clause of the outer query */
  117375. SrcList *pSubSrc; /* The FROM clause of the subquery */
  117376. int iParent; /* VDBE cursor number of the pSub result set temp table */
  117377. int iNewParent = -1;/* Replacement table for iParent */
  117378. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  117379. int i; /* Loop counter */
  117380. Expr *pWhere; /* The WHERE clause */
  117381. struct SrcList_item *pSubitem; /* The subquery */
  117382. sqlite3 *db = pParse->db;
  117383. /* Check to see if flattening is permitted. Return 0 if not.
  117384. */
  117385. assert( p!=0 );
  117386. assert( p->pPrior==0 );
  117387. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  117388. pSrc = p->pSrc;
  117389. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  117390. pSubitem = &pSrc->a[iFrom];
  117391. iParent = pSubitem->iCursor;
  117392. pSub = pSubitem->pSelect;
  117393. assert( pSub!=0 );
  117394. pSubSrc = pSub->pSrc;
  117395. assert( pSubSrc );
  117396. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  117397. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  117398. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  117399. ** became arbitrary expressions, we were forced to add restrictions (13)
  117400. ** and (14). */
  117401. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  117402. if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
  117403. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  117404. return 0; /* Restriction (15) */
  117405. }
  117406. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  117407. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
  117408. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  117409. return 0; /* Restrictions (8)(9) */
  117410. }
  117411. if( p->pOrderBy && pSub->pOrderBy ){
  117412. return 0; /* Restriction (11) */
  117413. }
  117414. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  117415. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  117416. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  117417. return 0; /* Restriction (21) */
  117418. }
  117419. if( pSub->selFlags & (SF_Recursive) ){
  117420. return 0; /* Restrictions (22) */
  117421. }
  117422. /*
  117423. ** If the subquery is the right operand of a LEFT JOIN, then the
  117424. ** subquery may not be a join itself (3a). Example of why this is not
  117425. ** allowed:
  117426. **
  117427. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  117428. **
  117429. ** If we flatten the above, we would get
  117430. **
  117431. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  117432. **
  117433. ** which is not at all the same thing.
  117434. **
  117435. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  117436. ** query cannot be an aggregate. (3c) This is an artifact of the way
  117437. ** aggregates are processed - there is no mechanism to determine if
  117438. ** the LEFT JOIN table should be all-NULL.
  117439. **
  117440. ** See also tickets #306, #350, and #3300.
  117441. */
  117442. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  117443. isLeftJoin = 1;
  117444. if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
  117445. /* (3a) (3c) (3b) */
  117446. return 0;
  117447. }
  117448. }
  117449. #ifdef SQLITE_EXTRA_IFNULLROW
  117450. else if( iFrom>0 && !isAgg ){
  117451. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  117452. ** every reference to any result column from subquery in a join, even
  117453. ** though they are not necessary. This will stress-test the OP_IfNullRow
  117454. ** opcode. */
  117455. isLeftJoin = -1;
  117456. }
  117457. #endif
  117458. /* Restriction (17): If the sub-query is a compound SELECT, then it must
  117459. ** use only the UNION ALL operator. And none of the simple select queries
  117460. ** that make up the compound SELECT are allowed to be aggregate or distinct
  117461. ** queries.
  117462. */
  117463. if( pSub->pPrior ){
  117464. if( pSub->pOrderBy ){
  117465. return 0; /* Restriction (20) */
  117466. }
  117467. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  117468. return 0; /* (17d1), (17d2), or (17d3) */
  117469. }
  117470. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  117471. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  117472. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  117473. assert( pSub->pSrc!=0 );
  117474. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  117475. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
  117476. || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
  117477. || pSub1->pSrc->nSrc<1 /* (17c) */
  117478. ){
  117479. return 0;
  117480. }
  117481. testcase( pSub1->pSrc->nSrc>1 );
  117482. }
  117483. /* Restriction (18). */
  117484. if( p->pOrderBy ){
  117485. int ii;
  117486. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  117487. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  117488. }
  117489. }
  117490. }
  117491. /* Ex-restriction (23):
  117492. ** The only way that the recursive part of a CTE can contain a compound
  117493. ** subquery is for the subquery to be one term of a join. But if the
  117494. ** subquery is a join, then the flattening has already been stopped by
  117495. ** restriction (17d3)
  117496. */
  117497. assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
  117498. /***** If we reach this point, flattening is permitted. *****/
  117499. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  117500. pSub->zSelName, pSub, iFrom));
  117501. /* Authorize the subquery */
  117502. pParse->zAuthContext = pSubitem->zName;
  117503. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  117504. testcase( i==SQLITE_DENY );
  117505. pParse->zAuthContext = zSavedAuthContext;
  117506. /* If the sub-query is a compound SELECT statement, then (by restrictions
  117507. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  117508. ** be of the form:
  117509. **
  117510. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  117511. **
  117512. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  117513. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  117514. ** OFFSET clauses and joins them to the left-hand-side of the original
  117515. ** using UNION ALL operators. In this case N is the number of simple
  117516. ** select statements in the compound sub-query.
  117517. **
  117518. ** Example:
  117519. **
  117520. ** SELECT a+1 FROM (
  117521. ** SELECT x FROM tab
  117522. ** UNION ALL
  117523. ** SELECT y FROM tab
  117524. ** UNION ALL
  117525. ** SELECT abs(z*2) FROM tab2
  117526. ** ) WHERE a!=5 ORDER BY 1
  117527. **
  117528. ** Transformed into:
  117529. **
  117530. ** SELECT x+1 FROM tab WHERE x+1!=5
  117531. ** UNION ALL
  117532. ** SELECT y+1 FROM tab WHERE y+1!=5
  117533. ** UNION ALL
  117534. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  117535. ** ORDER BY 1
  117536. **
  117537. ** We call this the "compound-subquery flattening".
  117538. */
  117539. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  117540. Select *pNew;
  117541. ExprList *pOrderBy = p->pOrderBy;
  117542. Expr *pLimit = p->pLimit;
  117543. Select *pPrior = p->pPrior;
  117544. p->pOrderBy = 0;
  117545. p->pSrc = 0;
  117546. p->pPrior = 0;
  117547. p->pLimit = 0;
  117548. pNew = sqlite3SelectDup(db, p, 0);
  117549. sqlite3SelectSetName(pNew, pSub->zSelName);
  117550. p->pLimit = pLimit;
  117551. p->pOrderBy = pOrderBy;
  117552. p->pSrc = pSrc;
  117553. p->op = TK_ALL;
  117554. if( pNew==0 ){
  117555. p->pPrior = pPrior;
  117556. }else{
  117557. pNew->pPrior = pPrior;
  117558. if( pPrior ) pPrior->pNext = pNew;
  117559. pNew->pNext = p;
  117560. p->pPrior = pNew;
  117561. SELECTTRACE(2,pParse,p,("compound-subquery flattener"
  117562. " creates %s.%p as peer\n",pNew->zSelName, pNew));
  117563. }
  117564. if( db->mallocFailed ) return 1;
  117565. }
  117566. /* Begin flattening the iFrom-th entry of the FROM clause
  117567. ** in the outer query.
  117568. */
  117569. pSub = pSub1 = pSubitem->pSelect;
  117570. /* Delete the transient table structure associated with the
  117571. ** subquery
  117572. */
  117573. sqlite3DbFree(db, pSubitem->zDatabase);
  117574. sqlite3DbFree(db, pSubitem->zName);
  117575. sqlite3DbFree(db, pSubitem->zAlias);
  117576. pSubitem->zDatabase = 0;
  117577. pSubitem->zName = 0;
  117578. pSubitem->zAlias = 0;
  117579. pSubitem->pSelect = 0;
  117580. /* Defer deleting the Table object associated with the
  117581. ** subquery until code generation is
  117582. ** complete, since there may still exist Expr.pTab entries that
  117583. ** refer to the subquery even after flattening. Ticket #3346.
  117584. **
  117585. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  117586. */
  117587. if( ALWAYS(pSubitem->pTab!=0) ){
  117588. Table *pTabToDel = pSubitem->pTab;
  117589. if( pTabToDel->nTabRef==1 ){
  117590. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  117591. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  117592. pToplevel->pZombieTab = pTabToDel;
  117593. }else{
  117594. pTabToDel->nTabRef--;
  117595. }
  117596. pSubitem->pTab = 0;
  117597. }
  117598. /* The following loop runs once for each term in a compound-subquery
  117599. ** flattening (as described above). If we are doing a different kind
  117600. ** of flattening - a flattening other than a compound-subquery flattening -
  117601. ** then this loop only runs once.
  117602. **
  117603. ** This loop moves all of the FROM elements of the subquery into the
  117604. ** the FROM clause of the outer query. Before doing this, remember
  117605. ** the cursor number for the original outer query FROM element in
  117606. ** iParent. The iParent cursor will never be used. Subsequent code
  117607. ** will scan expressions looking for iParent references and replace
  117608. ** those references with expressions that resolve to the subquery FROM
  117609. ** elements we are now copying in.
  117610. */
  117611. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  117612. int nSubSrc;
  117613. u8 jointype = 0;
  117614. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  117615. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  117616. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  117617. if( pSrc ){
  117618. assert( pParent==p ); /* First time through the loop */
  117619. jointype = pSubitem->fg.jointype;
  117620. }else{
  117621. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  117622. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  117623. if( pSrc==0 ){
  117624. assert( db->mallocFailed );
  117625. break;
  117626. }
  117627. }
  117628. /* The subquery uses a single slot of the FROM clause of the outer
  117629. ** query. If the subquery has more than one element in its FROM clause,
  117630. ** then expand the outer query to make space for it to hold all elements
  117631. ** of the subquery.
  117632. **
  117633. ** Example:
  117634. **
  117635. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  117636. **
  117637. ** The outer query has 3 slots in its FROM clause. One slot of the
  117638. ** outer query (the middle slot) is used by the subquery. The next
  117639. ** block of code will expand the outer query FROM clause to 4 slots.
  117640. ** The middle slot is expanded to two slots in order to make space
  117641. ** for the two elements in the FROM clause of the subquery.
  117642. */
  117643. if( nSubSrc>1 ){
  117644. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  117645. if( db->mallocFailed ){
  117646. break;
  117647. }
  117648. }
  117649. /* Transfer the FROM clause terms from the subquery into the
  117650. ** outer query.
  117651. */
  117652. for(i=0; i<nSubSrc; i++){
  117653. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  117654. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  117655. pSrc->a[i+iFrom] = pSubSrc->a[i];
  117656. iNewParent = pSubSrc->a[i].iCursor;
  117657. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  117658. }
  117659. pSrc->a[iFrom].fg.jointype = jointype;
  117660. /* Now begin substituting subquery result set expressions for
  117661. ** references to the iParent in the outer query.
  117662. **
  117663. ** Example:
  117664. **
  117665. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  117666. ** \ \_____________ subquery __________/ /
  117667. ** \_____________________ outer query ______________________________/
  117668. **
  117669. ** We look at every expression in the outer query and every place we see
  117670. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  117671. */
  117672. if( pSub->pOrderBy ){
  117673. /* At this point, any non-zero iOrderByCol values indicate that the
  117674. ** ORDER BY column expression is identical to the iOrderByCol'th
  117675. ** expression returned by SELECT statement pSub. Since these values
  117676. ** do not necessarily correspond to columns in SELECT statement pParent,
  117677. ** zero them before transfering the ORDER BY clause.
  117678. **
  117679. ** Not doing this may cause an error if a subsequent call to this
  117680. ** function attempts to flatten a compound sub-query into pParent
  117681. ** (the only way this can happen is if the compound sub-query is
  117682. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  117683. ExprList *pOrderBy = pSub->pOrderBy;
  117684. for(i=0; i<pOrderBy->nExpr; i++){
  117685. pOrderBy->a[i].u.x.iOrderByCol = 0;
  117686. }
  117687. assert( pParent->pOrderBy==0 );
  117688. pParent->pOrderBy = pOrderBy;
  117689. pSub->pOrderBy = 0;
  117690. }
  117691. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  117692. if( isLeftJoin>0 ){
  117693. setJoinExpr(pWhere, iNewParent);
  117694. }
  117695. pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
  117696. if( db->mallocFailed==0 ){
  117697. SubstContext x;
  117698. x.pParse = pParse;
  117699. x.iTable = iParent;
  117700. x.iNewTable = iNewParent;
  117701. x.isLeftJoin = isLeftJoin;
  117702. x.pEList = pSub->pEList;
  117703. substSelect(&x, pParent, 0);
  117704. }
  117705. /* The flattened query is distinct if either the inner or the
  117706. ** outer query is distinct.
  117707. */
  117708. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  117709. /*
  117710. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  117711. **
  117712. ** One is tempted to try to add a and b to combine the limits. But this
  117713. ** does not work if either limit is negative.
  117714. */
  117715. if( pSub->pLimit ){
  117716. pParent->pLimit = pSub->pLimit;
  117717. pSub->pLimit = 0;
  117718. }
  117719. }
  117720. /* Finially, delete what is left of the subquery and return
  117721. ** success.
  117722. */
  117723. sqlite3SelectDelete(db, pSub1);
  117724. #if SELECTTRACE_ENABLED
  117725. if( sqlite3SelectTrace & 0x100 ){
  117726. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  117727. sqlite3TreeViewSelect(0, p, 0);
  117728. }
  117729. #endif
  117730. return 1;
  117731. }
  117732. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  117733. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  117734. /*
  117735. ** Make copies of relevant WHERE clause terms of the outer query into
  117736. ** the WHERE clause of subquery. Example:
  117737. **
  117738. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  117739. **
  117740. ** Transformed into:
  117741. **
  117742. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  117743. ** WHERE x=5 AND y=10;
  117744. **
  117745. ** The hope is that the terms added to the inner query will make it more
  117746. ** efficient.
  117747. **
  117748. ** Do not attempt this optimization if:
  117749. **
  117750. ** (1) (** This restriction was removed on 2017-09-29. We used to
  117751. ** disallow this optimization for aggregate subqueries, but now
  117752. ** it is allowed by putting the extra terms on the HAVING clause.
  117753. ** The added HAVING clause is pointless if the subquery lacks
  117754. ** a GROUP BY clause. But such a HAVING clause is also harmless
  117755. ** so there does not appear to be any reason to add extra logic
  117756. ** to suppress it. **)
  117757. **
  117758. ** (2) The inner query is the recursive part of a common table expression.
  117759. **
  117760. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  117761. ** close would change the meaning of the LIMIT).
  117762. **
  117763. ** (4) The inner query is the right operand of a LEFT JOIN and the
  117764. ** expression to be pushed down does not come from the ON clause
  117765. ** on that LEFT JOIN.
  117766. **
  117767. ** (5) The WHERE clause expression originates in the ON or USING clause
  117768. ** of a LEFT JOIN where iCursor is not the right-hand table of that
  117769. ** left join. An example:
  117770. **
  117771. ** SELECT *
  117772. ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
  117773. ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
  117774. ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
  117775. **
  117776. ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
  117777. ** But if the (b2=2) term were to be pushed down into the bb subquery,
  117778. ** then the (1,1,NULL) row would be suppressed.
  117779. **
  117780. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  117781. ** terms are duplicated into the subquery.
  117782. */
  117783. static int pushDownWhereTerms(
  117784. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  117785. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  117786. Expr *pWhere, /* The WHERE clause of the outer query */
  117787. int iCursor, /* Cursor number of the subquery */
  117788. int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
  117789. ){
  117790. Expr *pNew;
  117791. int nChng = 0;
  117792. if( pWhere==0 ) return 0;
  117793. if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
  117794. #ifdef SQLITE_DEBUG
  117795. /* Only the first term of a compound can have a WITH clause. But make
  117796. ** sure no other terms are marked SF_Recursive in case something changes
  117797. ** in the future.
  117798. */
  117799. {
  117800. Select *pX;
  117801. for(pX=pSubq; pX; pX=pX->pPrior){
  117802. assert( (pX->selFlags & (SF_Recursive))==0 );
  117803. }
  117804. }
  117805. #endif
  117806. if( pSubq->pLimit!=0 ){
  117807. return 0; /* restriction (3) */
  117808. }
  117809. while( pWhere->op==TK_AND ){
  117810. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
  117811. iCursor, isLeftJoin);
  117812. pWhere = pWhere->pLeft;
  117813. }
  117814. if( isLeftJoin
  117815. && (ExprHasProperty(pWhere,EP_FromJoin)==0
  117816. || pWhere->iRightJoinTable!=iCursor)
  117817. ){
  117818. return 0; /* restriction (4) */
  117819. }
  117820. if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
  117821. return 0; /* restriction (5) */
  117822. }
  117823. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  117824. nChng++;
  117825. while( pSubq ){
  117826. SubstContext x;
  117827. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  117828. unsetJoinExpr(pNew, -1);
  117829. x.pParse = pParse;
  117830. x.iTable = iCursor;
  117831. x.iNewTable = iCursor;
  117832. x.isLeftJoin = 0;
  117833. x.pEList = pSubq->pEList;
  117834. pNew = substExpr(&x, pNew);
  117835. if( pSubq->selFlags & SF_Aggregate ){
  117836. pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
  117837. }else{
  117838. pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
  117839. }
  117840. pSubq = pSubq->pPrior;
  117841. }
  117842. }
  117843. return nChng;
  117844. }
  117845. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  117846. /*
  117847. ** The pFunc is the only aggregate function in the query. Check to see
  117848. ** if the query is a candidate for the min/max optimization.
  117849. **
  117850. ** If the query is a candidate for the min/max optimization, then set
  117851. ** *ppMinMax to be an ORDER BY clause to be used for the optimization
  117852. ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
  117853. ** whether pFunc is a min() or max() function.
  117854. **
  117855. ** If the query is not a candidate for the min/max optimization, return
  117856. ** WHERE_ORDERBY_NORMAL (which must be zero).
  117857. **
  117858. ** This routine must be called after aggregate functions have been
  117859. ** located but before their arguments have been subjected to aggregate
  117860. ** analysis.
  117861. */
  117862. static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
  117863. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  117864. ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
  117865. const char *zFunc; /* Name of aggregate function pFunc */
  117866. ExprList *pOrderBy;
  117867. u8 sortOrder;
  117868. assert( *ppMinMax==0 );
  117869. assert( pFunc->op==TK_AGG_FUNCTION );
  117870. if( pEList==0 || pEList->nExpr!=1 ) return eRet;
  117871. zFunc = pFunc->u.zToken;
  117872. if( sqlite3StrICmp(zFunc, "min")==0 ){
  117873. eRet = WHERE_ORDERBY_MIN;
  117874. sortOrder = SQLITE_SO_ASC;
  117875. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  117876. eRet = WHERE_ORDERBY_MAX;
  117877. sortOrder = SQLITE_SO_DESC;
  117878. }else{
  117879. return eRet;
  117880. }
  117881. *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
  117882. assert( pOrderBy!=0 || db->mallocFailed );
  117883. if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder;
  117884. return eRet;
  117885. }
  117886. /*
  117887. ** The select statement passed as the first argument is an aggregate query.
  117888. ** The second argument is the associated aggregate-info object. This
  117889. ** function tests if the SELECT is of the form:
  117890. **
  117891. ** SELECT count(*) FROM <tbl>
  117892. **
  117893. ** where table is a database table, not a sub-select or view. If the query
  117894. ** does match this pattern, then a pointer to the Table object representing
  117895. ** <tbl> is returned. Otherwise, 0 is returned.
  117896. */
  117897. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  117898. Table *pTab;
  117899. Expr *pExpr;
  117900. assert( !p->pGroupBy );
  117901. if( p->pWhere || p->pEList->nExpr!=1
  117902. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  117903. ){
  117904. return 0;
  117905. }
  117906. pTab = p->pSrc->a[0].pTab;
  117907. pExpr = p->pEList->a[0].pExpr;
  117908. assert( pTab && !pTab->pSelect && pExpr );
  117909. if( IsVirtual(pTab) ) return 0;
  117910. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  117911. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  117912. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  117913. if( pExpr->flags&EP_Distinct ) return 0;
  117914. return pTab;
  117915. }
  117916. /*
  117917. ** If the source-list item passed as an argument was augmented with an
  117918. ** INDEXED BY clause, then try to locate the specified index. If there
  117919. ** was such a clause and the named index cannot be found, return
  117920. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  117921. ** pFrom->pIndex and return SQLITE_OK.
  117922. */
  117923. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  117924. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  117925. Table *pTab = pFrom->pTab;
  117926. char *zIndexedBy = pFrom->u1.zIndexedBy;
  117927. Index *pIdx;
  117928. for(pIdx=pTab->pIndex;
  117929. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  117930. pIdx=pIdx->pNext
  117931. );
  117932. if( !pIdx ){
  117933. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  117934. pParse->checkSchema = 1;
  117935. return SQLITE_ERROR;
  117936. }
  117937. pFrom->pIBIndex = pIdx;
  117938. }
  117939. return SQLITE_OK;
  117940. }
  117941. /*
  117942. ** Detect compound SELECT statements that use an ORDER BY clause with
  117943. ** an alternative collating sequence.
  117944. **
  117945. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  117946. **
  117947. ** These are rewritten as a subquery:
  117948. **
  117949. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  117950. ** ORDER BY ... COLLATE ...
  117951. **
  117952. ** This transformation is necessary because the multiSelectOrderBy() routine
  117953. ** above that generates the code for a compound SELECT with an ORDER BY clause
  117954. ** uses a merge algorithm that requires the same collating sequence on the
  117955. ** result columns as on the ORDER BY clause. See ticket
  117956. ** http://www.sqlite.org/src/info/6709574d2a
  117957. **
  117958. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  117959. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  117960. ** there are COLLATE terms in the ORDER BY.
  117961. */
  117962. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  117963. int i;
  117964. Select *pNew;
  117965. Select *pX;
  117966. sqlite3 *db;
  117967. struct ExprList_item *a;
  117968. SrcList *pNewSrc;
  117969. Parse *pParse;
  117970. Token dummy;
  117971. if( p->pPrior==0 ) return WRC_Continue;
  117972. if( p->pOrderBy==0 ) return WRC_Continue;
  117973. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  117974. if( pX==0 ) return WRC_Continue;
  117975. a = p->pOrderBy->a;
  117976. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  117977. if( a[i].pExpr->flags & EP_Collate ) break;
  117978. }
  117979. if( i<0 ) return WRC_Continue;
  117980. /* If we reach this point, that means the transformation is required. */
  117981. pParse = pWalker->pParse;
  117982. db = pParse->db;
  117983. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  117984. if( pNew==0 ) return WRC_Abort;
  117985. memset(&dummy, 0, sizeof(dummy));
  117986. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  117987. if( pNewSrc==0 ) return WRC_Abort;
  117988. *pNew = *p;
  117989. p->pSrc = pNewSrc;
  117990. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  117991. p->op = TK_SELECT;
  117992. p->pWhere = 0;
  117993. pNew->pGroupBy = 0;
  117994. pNew->pHaving = 0;
  117995. pNew->pOrderBy = 0;
  117996. p->pPrior = 0;
  117997. p->pNext = 0;
  117998. p->pWith = 0;
  117999. p->selFlags &= ~SF_Compound;
  118000. assert( (p->selFlags & SF_Converted)==0 );
  118001. p->selFlags |= SF_Converted;
  118002. assert( pNew->pPrior!=0 );
  118003. pNew->pPrior->pNext = pNew;
  118004. pNew->pLimit = 0;
  118005. return WRC_Continue;
  118006. }
  118007. /*
  118008. ** Check to see if the FROM clause term pFrom has table-valued function
  118009. ** arguments. If it does, leave an error message in pParse and return
  118010. ** non-zero, since pFrom is not allowed to be a table-valued function.
  118011. */
  118012. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  118013. if( pFrom->fg.isTabFunc ){
  118014. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  118015. return 1;
  118016. }
  118017. return 0;
  118018. }
  118019. #ifndef SQLITE_OMIT_CTE
  118020. /*
  118021. ** Argument pWith (which may be NULL) points to a linked list of nested
  118022. ** WITH contexts, from inner to outermost. If the table identified by
  118023. ** FROM clause element pItem is really a common-table-expression (CTE)
  118024. ** then return a pointer to the CTE definition for that table. Otherwise
  118025. ** return NULL.
  118026. **
  118027. ** If a non-NULL value is returned, set *ppContext to point to the With
  118028. ** object that the returned CTE belongs to.
  118029. */
  118030. static struct Cte *searchWith(
  118031. With *pWith, /* Current innermost WITH clause */
  118032. struct SrcList_item *pItem, /* FROM clause element to resolve */
  118033. With **ppContext /* OUT: WITH clause return value belongs to */
  118034. ){
  118035. const char *zName;
  118036. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  118037. With *p;
  118038. for(p=pWith; p; p=p->pOuter){
  118039. int i;
  118040. for(i=0; i<p->nCte; i++){
  118041. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  118042. *ppContext = p;
  118043. return &p->a[i];
  118044. }
  118045. }
  118046. }
  118047. }
  118048. return 0;
  118049. }
  118050. /* The code generator maintains a stack of active WITH clauses
  118051. ** with the inner-most WITH clause being at the top of the stack.
  118052. **
  118053. ** This routine pushes the WITH clause passed as the second argument
  118054. ** onto the top of the stack. If argument bFree is true, then this
  118055. ** WITH clause will never be popped from the stack. In this case it
  118056. ** should be freed along with the Parse object. In other cases, when
  118057. ** bFree==0, the With object will be freed along with the SELECT
  118058. ** statement with which it is associated.
  118059. */
  118060. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  118061. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  118062. if( pWith ){
  118063. assert( pParse->pWith!=pWith );
  118064. pWith->pOuter = pParse->pWith;
  118065. pParse->pWith = pWith;
  118066. if( bFree ) pParse->pWithToFree = pWith;
  118067. }
  118068. }
  118069. /*
  118070. ** This function checks if argument pFrom refers to a CTE declared by
  118071. ** a WITH clause on the stack currently maintained by the parser. And,
  118072. ** if currently processing a CTE expression, if it is a recursive
  118073. ** reference to the current CTE.
  118074. **
  118075. ** If pFrom falls into either of the two categories above, pFrom->pTab
  118076. ** and other fields are populated accordingly. The caller should check
  118077. ** (pFrom->pTab!=0) to determine whether or not a successful match
  118078. ** was found.
  118079. **
  118080. ** Whether or not a match is found, SQLITE_OK is returned if no error
  118081. ** occurs. If an error does occur, an error message is stored in the
  118082. ** parser and some error code other than SQLITE_OK returned.
  118083. */
  118084. static int withExpand(
  118085. Walker *pWalker,
  118086. struct SrcList_item *pFrom
  118087. ){
  118088. Parse *pParse = pWalker->pParse;
  118089. sqlite3 *db = pParse->db;
  118090. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  118091. With *pWith; /* WITH clause that pCte belongs to */
  118092. assert( pFrom->pTab==0 );
  118093. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  118094. if( pCte ){
  118095. Table *pTab;
  118096. ExprList *pEList;
  118097. Select *pSel;
  118098. Select *pLeft; /* Left-most SELECT statement */
  118099. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  118100. With *pSavedWith; /* Initial value of pParse->pWith */
  118101. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  118102. ** recursive reference to CTE pCte. Leave an error in pParse and return
  118103. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  118104. ** In this case, proceed. */
  118105. if( pCte->zCteErr ){
  118106. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  118107. return SQLITE_ERROR;
  118108. }
  118109. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  118110. assert( pFrom->pTab==0 );
  118111. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  118112. if( pTab==0 ) return WRC_Abort;
  118113. pTab->nTabRef = 1;
  118114. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  118115. pTab->iPKey = -1;
  118116. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  118117. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  118118. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  118119. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  118120. assert( pFrom->pSelect );
  118121. /* Check if this is a recursive CTE. */
  118122. pSel = pFrom->pSelect;
  118123. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  118124. if( bMayRecursive ){
  118125. int i;
  118126. SrcList *pSrc = pFrom->pSelect->pSrc;
  118127. for(i=0; i<pSrc->nSrc; i++){
  118128. struct SrcList_item *pItem = &pSrc->a[i];
  118129. if( pItem->zDatabase==0
  118130. && pItem->zName!=0
  118131. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  118132. ){
  118133. pItem->pTab = pTab;
  118134. pItem->fg.isRecursive = 1;
  118135. pTab->nTabRef++;
  118136. pSel->selFlags |= SF_Recursive;
  118137. }
  118138. }
  118139. }
  118140. /* Only one recursive reference is permitted. */
  118141. if( pTab->nTabRef>2 ){
  118142. sqlite3ErrorMsg(
  118143. pParse, "multiple references to recursive table: %s", pCte->zName
  118144. );
  118145. return SQLITE_ERROR;
  118146. }
  118147. assert( pTab->nTabRef==1 ||
  118148. ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  118149. pCte->zCteErr = "circular reference: %s";
  118150. pSavedWith = pParse->pWith;
  118151. pParse->pWith = pWith;
  118152. if( bMayRecursive ){
  118153. Select *pPrior = pSel->pPrior;
  118154. assert( pPrior->pWith==0 );
  118155. pPrior->pWith = pSel->pWith;
  118156. sqlite3WalkSelect(pWalker, pPrior);
  118157. pPrior->pWith = 0;
  118158. }else{
  118159. sqlite3WalkSelect(pWalker, pSel);
  118160. }
  118161. pParse->pWith = pWith;
  118162. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  118163. pEList = pLeft->pEList;
  118164. if( pCte->pCols ){
  118165. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  118166. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  118167. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  118168. );
  118169. pParse->pWith = pSavedWith;
  118170. return SQLITE_ERROR;
  118171. }
  118172. pEList = pCte->pCols;
  118173. }
  118174. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  118175. if( bMayRecursive ){
  118176. if( pSel->selFlags & SF_Recursive ){
  118177. pCte->zCteErr = "multiple recursive references: %s";
  118178. }else{
  118179. pCte->zCteErr = "recursive reference in a subquery: %s";
  118180. }
  118181. sqlite3WalkSelect(pWalker, pSel);
  118182. }
  118183. pCte->zCteErr = 0;
  118184. pParse->pWith = pSavedWith;
  118185. }
  118186. return SQLITE_OK;
  118187. }
  118188. #endif
  118189. #ifndef SQLITE_OMIT_CTE
  118190. /*
  118191. ** If the SELECT passed as the second argument has an associated WITH
  118192. ** clause, pop it from the stack stored as part of the Parse object.
  118193. **
  118194. ** This function is used as the xSelectCallback2() callback by
  118195. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  118196. ** names and other FROM clause elements.
  118197. */
  118198. static void selectPopWith(Walker *pWalker, Select *p){
  118199. Parse *pParse = pWalker->pParse;
  118200. if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
  118201. With *pWith = findRightmost(p)->pWith;
  118202. if( pWith!=0 ){
  118203. assert( pParse->pWith==pWith );
  118204. pParse->pWith = pWith->pOuter;
  118205. }
  118206. }
  118207. }
  118208. #else
  118209. #define selectPopWith 0
  118210. #endif
  118211. /*
  118212. ** This routine is a Walker callback for "expanding" a SELECT statement.
  118213. ** "Expanding" means to do the following:
  118214. **
  118215. ** (1) Make sure VDBE cursor numbers have been assigned to every
  118216. ** element of the FROM clause.
  118217. **
  118218. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  118219. ** defines FROM clause. When views appear in the FROM clause,
  118220. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  118221. ** that implements the view. A copy is made of the view's SELECT
  118222. ** statement so that we can freely modify or delete that statement
  118223. ** without worrying about messing up the persistent representation
  118224. ** of the view.
  118225. **
  118226. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  118227. ** on joins and the ON and USING clause of joins.
  118228. **
  118229. ** (4) Scan the list of columns in the result set (pEList) looking
  118230. ** for instances of the "*" operator or the TABLE.* operator.
  118231. ** If found, expand each "*" to be every column in every table
  118232. ** and TABLE.* to be every column in TABLE.
  118233. **
  118234. */
  118235. static int selectExpander(Walker *pWalker, Select *p){
  118236. Parse *pParse = pWalker->pParse;
  118237. int i, j, k;
  118238. SrcList *pTabList;
  118239. ExprList *pEList;
  118240. struct SrcList_item *pFrom;
  118241. sqlite3 *db = pParse->db;
  118242. Expr *pE, *pRight, *pExpr;
  118243. u16 selFlags = p->selFlags;
  118244. u32 elistFlags = 0;
  118245. p->selFlags |= SF_Expanded;
  118246. if( db->mallocFailed ){
  118247. return WRC_Abort;
  118248. }
  118249. assert( p->pSrc!=0 );
  118250. if( (selFlags & SF_Expanded)!=0 ){
  118251. return WRC_Prune;
  118252. }
  118253. pTabList = p->pSrc;
  118254. pEList = p->pEList;
  118255. sqlite3WithPush(pParse, p->pWith, 0);
  118256. /* Make sure cursor numbers have been assigned to all entries in
  118257. ** the FROM clause of the SELECT statement.
  118258. */
  118259. sqlite3SrcListAssignCursors(pParse, pTabList);
  118260. /* Look up every table named in the FROM clause of the select. If
  118261. ** an entry of the FROM clause is a subquery instead of a table or view,
  118262. ** then create a transient table structure to describe the subquery.
  118263. */
  118264. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  118265. Table *pTab;
  118266. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  118267. if( pFrom->fg.isRecursive ) continue;
  118268. assert( pFrom->pTab==0 );
  118269. #ifndef SQLITE_OMIT_CTE
  118270. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  118271. if( pFrom->pTab ) {} else
  118272. #endif
  118273. if( pFrom->zName==0 ){
  118274. #ifndef SQLITE_OMIT_SUBQUERY
  118275. Select *pSel = pFrom->pSelect;
  118276. /* A sub-query in the FROM clause of a SELECT */
  118277. assert( pSel!=0 );
  118278. assert( pFrom->pTab==0 );
  118279. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  118280. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  118281. if( pTab==0 ) return WRC_Abort;
  118282. pTab->nTabRef = 1;
  118283. if( pFrom->zAlias ){
  118284. pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias);
  118285. }else{
  118286. pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab);
  118287. }
  118288. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  118289. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  118290. pTab->iPKey = -1;
  118291. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  118292. pTab->tabFlags |= TF_Ephemeral;
  118293. #endif
  118294. }else{
  118295. /* An ordinary table or view name in the FROM clause */
  118296. assert( pFrom->pTab==0 );
  118297. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  118298. if( pTab==0 ) return WRC_Abort;
  118299. if( pTab->nTabRef>=0xffff ){
  118300. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  118301. pTab->zName);
  118302. pFrom->pTab = 0;
  118303. return WRC_Abort;
  118304. }
  118305. pTab->nTabRef++;
  118306. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  118307. return WRC_Abort;
  118308. }
  118309. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  118310. if( IsVirtual(pTab) || pTab->pSelect ){
  118311. i16 nCol;
  118312. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  118313. assert( pFrom->pSelect==0 );
  118314. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  118315. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  118316. nCol = pTab->nCol;
  118317. pTab->nCol = -1;
  118318. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  118319. pTab->nCol = nCol;
  118320. }
  118321. #endif
  118322. }
  118323. /* Locate the index named by the INDEXED BY clause, if any. */
  118324. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  118325. return WRC_Abort;
  118326. }
  118327. }
  118328. /* Process NATURAL keywords, and ON and USING clauses of joins.
  118329. */
  118330. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  118331. return WRC_Abort;
  118332. }
  118333. /* For every "*" that occurs in the column list, insert the names of
  118334. ** all columns in all tables. And for every TABLE.* insert the names
  118335. ** of all columns in TABLE. The parser inserted a special expression
  118336. ** with the TK_ASTERISK operator for each "*" that it found in the column
  118337. ** list. The following code just has to locate the TK_ASTERISK
  118338. ** expressions and expand each one to the list of all columns in
  118339. ** all tables.
  118340. **
  118341. ** The first loop just checks to see if there are any "*" operators
  118342. ** that need expanding.
  118343. */
  118344. for(k=0; k<pEList->nExpr; k++){
  118345. pE = pEList->a[k].pExpr;
  118346. if( pE->op==TK_ASTERISK ) break;
  118347. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  118348. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  118349. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  118350. elistFlags |= pE->flags;
  118351. }
  118352. if( k<pEList->nExpr ){
  118353. /*
  118354. ** If we get here it means the result set contains one or more "*"
  118355. ** operators that need to be expanded. Loop through each expression
  118356. ** in the result set and expand them one by one.
  118357. */
  118358. struct ExprList_item *a = pEList->a;
  118359. ExprList *pNew = 0;
  118360. int flags = pParse->db->flags;
  118361. int longNames = (flags & SQLITE_FullColNames)!=0
  118362. && (flags & SQLITE_ShortColNames)==0;
  118363. for(k=0; k<pEList->nExpr; k++){
  118364. pE = a[k].pExpr;
  118365. elistFlags |= pE->flags;
  118366. pRight = pE->pRight;
  118367. assert( pE->op!=TK_DOT || pRight!=0 );
  118368. if( pE->op!=TK_ASTERISK
  118369. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  118370. ){
  118371. /* This particular expression does not need to be expanded.
  118372. */
  118373. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  118374. if( pNew ){
  118375. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  118376. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  118377. a[k].zName = 0;
  118378. a[k].zSpan = 0;
  118379. }
  118380. a[k].pExpr = 0;
  118381. }else{
  118382. /* This expression is a "*" or a "TABLE.*" and needs to be
  118383. ** expanded. */
  118384. int tableSeen = 0; /* Set to 1 when TABLE matches */
  118385. char *zTName = 0; /* text of name of TABLE */
  118386. if( pE->op==TK_DOT ){
  118387. assert( pE->pLeft!=0 );
  118388. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  118389. zTName = pE->pLeft->u.zToken;
  118390. }
  118391. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  118392. Table *pTab = pFrom->pTab;
  118393. Select *pSub = pFrom->pSelect;
  118394. char *zTabName = pFrom->zAlias;
  118395. const char *zSchemaName = 0;
  118396. int iDb;
  118397. if( zTabName==0 ){
  118398. zTabName = pTab->zName;
  118399. }
  118400. if( db->mallocFailed ) break;
  118401. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  118402. pSub = 0;
  118403. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  118404. continue;
  118405. }
  118406. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  118407. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  118408. }
  118409. for(j=0; j<pTab->nCol; j++){
  118410. char *zName = pTab->aCol[j].zName;
  118411. char *zColname; /* The computed column name */
  118412. char *zToFree; /* Malloced string that needs to be freed */
  118413. Token sColname; /* Computed column name as a token */
  118414. assert( zName );
  118415. if( zTName && pSub
  118416. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  118417. ){
  118418. continue;
  118419. }
  118420. /* If a column is marked as 'hidden', omit it from the expanded
  118421. ** result-set list unless the SELECT has the SF_IncludeHidden
  118422. ** bit set.
  118423. */
  118424. if( (p->selFlags & SF_IncludeHidden)==0
  118425. && IsHiddenColumn(&pTab->aCol[j])
  118426. ){
  118427. continue;
  118428. }
  118429. tableSeen = 1;
  118430. if( i>0 && zTName==0 ){
  118431. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  118432. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  118433. ){
  118434. /* In a NATURAL join, omit the join columns from the
  118435. ** table to the right of the join */
  118436. continue;
  118437. }
  118438. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  118439. /* In a join with a USING clause, omit columns in the
  118440. ** using clause from the table on the right. */
  118441. continue;
  118442. }
  118443. }
  118444. pRight = sqlite3Expr(db, TK_ID, zName);
  118445. zColname = zName;
  118446. zToFree = 0;
  118447. if( longNames || pTabList->nSrc>1 ){
  118448. Expr *pLeft;
  118449. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  118450. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  118451. if( zSchemaName ){
  118452. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  118453. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  118454. }
  118455. if( longNames ){
  118456. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  118457. zToFree = zColname;
  118458. }
  118459. }else{
  118460. pExpr = pRight;
  118461. }
  118462. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  118463. sqlite3TokenInit(&sColname, zColname);
  118464. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  118465. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  118466. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  118467. if( pSub ){
  118468. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  118469. testcase( pX->zSpan==0 );
  118470. }else{
  118471. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  118472. zSchemaName, zTabName, zColname);
  118473. testcase( pX->zSpan==0 );
  118474. }
  118475. pX->bSpanIsTab = 1;
  118476. }
  118477. sqlite3DbFree(db, zToFree);
  118478. }
  118479. }
  118480. if( !tableSeen ){
  118481. if( zTName ){
  118482. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  118483. }else{
  118484. sqlite3ErrorMsg(pParse, "no tables specified");
  118485. }
  118486. }
  118487. }
  118488. }
  118489. sqlite3ExprListDelete(db, pEList);
  118490. p->pEList = pNew;
  118491. }
  118492. if( p->pEList ){
  118493. if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  118494. sqlite3ErrorMsg(pParse, "too many columns in result set");
  118495. return WRC_Abort;
  118496. }
  118497. if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
  118498. p->selFlags |= SF_ComplexResult;
  118499. }
  118500. }
  118501. return WRC_Continue;
  118502. }
  118503. /*
  118504. ** No-op routine for the parse-tree walker.
  118505. **
  118506. ** When this routine is the Walker.xExprCallback then expression trees
  118507. ** are walked without any actions being taken at each node. Presumably,
  118508. ** when this routine is used for Walker.xExprCallback then
  118509. ** Walker.xSelectCallback is set to do something useful for every
  118510. ** subquery in the parser tree.
  118511. */
  118512. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  118513. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  118514. return WRC_Continue;
  118515. }
  118516. /*
  118517. ** No-op routine for the parse-tree walker for SELECT statements.
  118518. ** subquery in the parser tree.
  118519. */
  118520. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
  118521. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  118522. return WRC_Continue;
  118523. }
  118524. #if SQLITE_DEBUG
  118525. /*
  118526. ** Always assert. This xSelectCallback2 implementation proves that the
  118527. ** xSelectCallback2 is never invoked.
  118528. */
  118529. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
  118530. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  118531. assert( 0 );
  118532. }
  118533. #endif
  118534. /*
  118535. ** This routine "expands" a SELECT statement and all of its subqueries.
  118536. ** For additional information on what it means to "expand" a SELECT
  118537. ** statement, see the comment on the selectExpand worker callback above.
  118538. **
  118539. ** Expanding a SELECT statement is the first step in processing a
  118540. ** SELECT statement. The SELECT statement must be expanded before
  118541. ** name resolution is performed.
  118542. **
  118543. ** If anything goes wrong, an error message is written into pParse.
  118544. ** The calling function can detect the problem by looking at pParse->nErr
  118545. ** and/or pParse->db->mallocFailed.
  118546. */
  118547. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  118548. Walker w;
  118549. w.xExprCallback = sqlite3ExprWalkNoop;
  118550. w.pParse = pParse;
  118551. if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
  118552. w.xSelectCallback = convertCompoundSelectToSubquery;
  118553. w.xSelectCallback2 = 0;
  118554. sqlite3WalkSelect(&w, pSelect);
  118555. }
  118556. w.xSelectCallback = selectExpander;
  118557. w.xSelectCallback2 = selectPopWith;
  118558. sqlite3WalkSelect(&w, pSelect);
  118559. }
  118560. #ifndef SQLITE_OMIT_SUBQUERY
  118561. /*
  118562. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  118563. ** interface.
  118564. **
  118565. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  118566. ** information to the Table structure that represents the result set
  118567. ** of that subquery.
  118568. **
  118569. ** The Table structure that represents the result set was constructed
  118570. ** by selectExpander() but the type and collation information was omitted
  118571. ** at that point because identifiers had not yet been resolved. This
  118572. ** routine is called after identifier resolution.
  118573. */
  118574. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  118575. Parse *pParse;
  118576. int i;
  118577. SrcList *pTabList;
  118578. struct SrcList_item *pFrom;
  118579. assert( p->selFlags & SF_Resolved );
  118580. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  118581. p->selFlags |= SF_HasTypeInfo;
  118582. pParse = pWalker->pParse;
  118583. pTabList = p->pSrc;
  118584. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  118585. Table *pTab = pFrom->pTab;
  118586. assert( pTab!=0 );
  118587. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  118588. /* A sub-query in the FROM clause of a SELECT */
  118589. Select *pSel = pFrom->pSelect;
  118590. if( pSel ){
  118591. while( pSel->pPrior ) pSel = pSel->pPrior;
  118592. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  118593. }
  118594. }
  118595. }
  118596. }
  118597. #endif
  118598. /*
  118599. ** This routine adds datatype and collating sequence information to
  118600. ** the Table structures of all FROM-clause subqueries in a
  118601. ** SELECT statement.
  118602. **
  118603. ** Use this routine after name resolution.
  118604. */
  118605. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  118606. #ifndef SQLITE_OMIT_SUBQUERY
  118607. Walker w;
  118608. w.xSelectCallback = sqlite3SelectWalkNoop;
  118609. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  118610. w.xExprCallback = sqlite3ExprWalkNoop;
  118611. w.pParse = pParse;
  118612. sqlite3WalkSelect(&w, pSelect);
  118613. #endif
  118614. }
  118615. /*
  118616. ** This routine sets up a SELECT statement for processing. The
  118617. ** following is accomplished:
  118618. **
  118619. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  118620. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  118621. ** * ON and USING clauses are shifted into WHERE statements
  118622. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  118623. ** * Identifiers in expression are matched to tables.
  118624. **
  118625. ** This routine acts recursively on all subqueries within the SELECT.
  118626. */
  118627. SQLITE_PRIVATE void sqlite3SelectPrep(
  118628. Parse *pParse, /* The parser context */
  118629. Select *p, /* The SELECT statement being coded. */
  118630. NameContext *pOuterNC /* Name context for container */
  118631. ){
  118632. assert( p!=0 || pParse->db->mallocFailed );
  118633. if( pParse->db->mallocFailed ) return;
  118634. if( p->selFlags & SF_HasTypeInfo ) return;
  118635. sqlite3SelectExpand(pParse, p);
  118636. if( pParse->nErr || pParse->db->mallocFailed ) return;
  118637. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  118638. if( pParse->nErr || pParse->db->mallocFailed ) return;
  118639. sqlite3SelectAddTypeInfo(pParse, p);
  118640. }
  118641. /*
  118642. ** Reset the aggregate accumulator.
  118643. **
  118644. ** The aggregate accumulator is a set of memory cells that hold
  118645. ** intermediate results while calculating an aggregate. This
  118646. ** routine generates code that stores NULLs in all of those memory
  118647. ** cells.
  118648. */
  118649. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  118650. Vdbe *v = pParse->pVdbe;
  118651. int i;
  118652. struct AggInfo_func *pFunc;
  118653. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  118654. if( nReg==0 ) return;
  118655. #ifdef SQLITE_DEBUG
  118656. /* Verify that all AggInfo registers are within the range specified by
  118657. ** AggInfo.mnReg..AggInfo.mxReg */
  118658. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  118659. for(i=0; i<pAggInfo->nColumn; i++){
  118660. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  118661. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  118662. }
  118663. for(i=0; i<pAggInfo->nFunc; i++){
  118664. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  118665. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  118666. }
  118667. #endif
  118668. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  118669. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  118670. if( pFunc->iDistinct>=0 ){
  118671. Expr *pE = pFunc->pExpr;
  118672. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  118673. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  118674. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  118675. "argument");
  118676. pFunc->iDistinct = -1;
  118677. }else{
  118678. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  118679. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  118680. (char*)pKeyInfo, P4_KEYINFO);
  118681. }
  118682. }
  118683. }
  118684. }
  118685. /*
  118686. ** Invoke the OP_AggFinalize opcode for every aggregate function
  118687. ** in the AggInfo structure.
  118688. */
  118689. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  118690. Vdbe *v = pParse->pVdbe;
  118691. int i;
  118692. struct AggInfo_func *pF;
  118693. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  118694. ExprList *pList = pF->pExpr->x.pList;
  118695. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  118696. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  118697. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  118698. }
  118699. }
  118700. /*
  118701. ** Update the accumulator memory cells for an aggregate based on
  118702. ** the current cursor position.
  118703. */
  118704. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  118705. Vdbe *v = pParse->pVdbe;
  118706. int i;
  118707. int regHit = 0;
  118708. int addrHitTest = 0;
  118709. struct AggInfo_func *pF;
  118710. struct AggInfo_col *pC;
  118711. pAggInfo->directMode = 1;
  118712. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  118713. int nArg;
  118714. int addrNext = 0;
  118715. int regAgg;
  118716. ExprList *pList = pF->pExpr->x.pList;
  118717. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  118718. if( pList ){
  118719. nArg = pList->nExpr;
  118720. regAgg = sqlite3GetTempRange(pParse, nArg);
  118721. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  118722. }else{
  118723. nArg = 0;
  118724. regAgg = 0;
  118725. }
  118726. if( pF->iDistinct>=0 ){
  118727. addrNext = sqlite3VdbeMakeLabel(v);
  118728. testcase( nArg==0 ); /* Error condition */
  118729. testcase( nArg>1 ); /* Also an error */
  118730. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  118731. }
  118732. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  118733. CollSeq *pColl = 0;
  118734. struct ExprList_item *pItem;
  118735. int j;
  118736. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  118737. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  118738. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  118739. }
  118740. if( !pColl ){
  118741. pColl = pParse->db->pDfltColl;
  118742. }
  118743. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  118744. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  118745. }
  118746. sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
  118747. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  118748. sqlite3VdbeChangeP5(v, (u8)nArg);
  118749. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  118750. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  118751. if( addrNext ){
  118752. sqlite3VdbeResolveLabel(v, addrNext);
  118753. sqlite3ExprCacheClear(pParse);
  118754. }
  118755. }
  118756. /* Before populating the accumulator registers, clear the column cache.
  118757. ** Otherwise, if any of the required column values are already present
  118758. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  118759. ** to pC->iMem. But by the time the value is used, the original register
  118760. ** may have been used, invalidating the underlying buffer holding the
  118761. ** text or blob value. See ticket [883034dcb5].
  118762. **
  118763. ** Another solution would be to change the OP_SCopy used to copy cached
  118764. ** values to an OP_Copy.
  118765. */
  118766. if( regHit ){
  118767. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  118768. }
  118769. sqlite3ExprCacheClear(pParse);
  118770. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  118771. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  118772. }
  118773. pAggInfo->directMode = 0;
  118774. sqlite3ExprCacheClear(pParse);
  118775. if( addrHitTest ){
  118776. sqlite3VdbeJumpHere(v, addrHitTest);
  118777. }
  118778. }
  118779. /*
  118780. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  118781. ** count(*) query ("SELECT count(*) FROM pTab").
  118782. */
  118783. #ifndef SQLITE_OMIT_EXPLAIN
  118784. static void explainSimpleCount(
  118785. Parse *pParse, /* Parse context */
  118786. Table *pTab, /* Table being queried */
  118787. Index *pIdx /* Index used to optimize scan, or NULL */
  118788. ){
  118789. if( pParse->explain==2 ){
  118790. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  118791. sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
  118792. pTab->zName,
  118793. bCover ? " USING COVERING INDEX " : "",
  118794. bCover ? pIdx->zName : ""
  118795. );
  118796. }
  118797. }
  118798. #else
  118799. # define explainSimpleCount(a,b,c)
  118800. #endif
  118801. /*
  118802. ** sqlite3WalkExpr() callback used by havingToWhere().
  118803. **
  118804. ** If the node passed to the callback is a TK_AND node, return
  118805. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  118806. **
  118807. ** Otherwise, return WRC_Prune. In this case, also check if the
  118808. ** sub-expression matches the criteria for being moved to the WHERE
  118809. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  118810. ** within the HAVING expression with a constant "1".
  118811. */
  118812. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  118813. if( pExpr->op!=TK_AND ){
  118814. Select *pS = pWalker->u.pSelect;
  118815. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
  118816. sqlite3 *db = pWalker->pParse->db;
  118817. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  118818. if( pNew ){
  118819. Expr *pWhere = pS->pWhere;
  118820. SWAP(Expr, *pNew, *pExpr);
  118821. pNew = sqlite3ExprAnd(db, pWhere, pNew);
  118822. pS->pWhere = pNew;
  118823. pWalker->eCode = 1;
  118824. }
  118825. }
  118826. return WRC_Prune;
  118827. }
  118828. return WRC_Continue;
  118829. }
  118830. /*
  118831. ** Transfer eligible terms from the HAVING clause of a query, which is
  118832. ** processed after grouping, to the WHERE clause, which is processed before
  118833. ** grouping. For example, the query:
  118834. **
  118835. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  118836. **
  118837. ** can be rewritten as:
  118838. **
  118839. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  118840. **
  118841. ** A term of the HAVING expression is eligible for transfer if it consists
  118842. ** entirely of constants and expressions that are also GROUP BY terms that
  118843. ** use the "BINARY" collation sequence.
  118844. */
  118845. static void havingToWhere(Parse *pParse, Select *p){
  118846. Walker sWalker;
  118847. memset(&sWalker, 0, sizeof(sWalker));
  118848. sWalker.pParse = pParse;
  118849. sWalker.xExprCallback = havingToWhereExprCb;
  118850. sWalker.u.pSelect = p;
  118851. sqlite3WalkExpr(&sWalker, p->pHaving);
  118852. #if SELECTTRACE_ENABLED
  118853. if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
  118854. SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
  118855. sqlite3TreeViewSelect(0, p, 0);
  118856. }
  118857. #endif
  118858. }
  118859. /*
  118860. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  118861. ** If it is, then return the SrcList_item for the prior view. If it is not,
  118862. ** then return 0.
  118863. */
  118864. static struct SrcList_item *isSelfJoinView(
  118865. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  118866. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  118867. ){
  118868. struct SrcList_item *pItem;
  118869. for(pItem = pTabList->a; pItem<pThis; pItem++){
  118870. if( pItem->pSelect==0 ) continue;
  118871. if( pItem->fg.viaCoroutine ) continue;
  118872. if( pItem->zName==0 ) continue;
  118873. if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
  118874. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  118875. if( sqlite3ExprCompare(0,
  118876. pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
  118877. ){
  118878. /* The view was modified by some other optimization such as
  118879. ** pushDownWhereTerms() */
  118880. continue;
  118881. }
  118882. return pItem;
  118883. }
  118884. return 0;
  118885. }
  118886. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  118887. /*
  118888. ** Attempt to transform a query of the form
  118889. **
  118890. ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
  118891. **
  118892. ** Into this:
  118893. **
  118894. ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
  118895. **
  118896. ** The transformation only works if all of the following are true:
  118897. **
  118898. ** * The subquery is a UNION ALL of two or more terms
  118899. ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
  118900. ** * The outer query is a simple count(*)
  118901. **
  118902. ** Return TRUE if the optimization is undertaken.
  118903. */
  118904. static int countOfViewOptimization(Parse *pParse, Select *p){
  118905. Select *pSub, *pPrior;
  118906. Expr *pExpr;
  118907. Expr *pCount;
  118908. sqlite3 *db;
  118909. if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
  118910. if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
  118911. pExpr = p->pEList->a[0].pExpr;
  118912. if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
  118913. if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
  118914. if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
  118915. if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
  118916. pSub = p->pSrc->a[0].pSelect;
  118917. if( pSub==0 ) return 0; /* The FROM is a subquery */
  118918. if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
  118919. do{
  118920. if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
  118921. if( pSub->pWhere ) return 0; /* No WHERE clause */
  118922. if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
  118923. pSub = pSub->pPrior; /* Repeat over compound */
  118924. }while( pSub );
  118925. /* If we reach this point then it is OK to perform the transformation */
  118926. db = pParse->db;
  118927. pCount = pExpr;
  118928. pExpr = 0;
  118929. pSub = p->pSrc->a[0].pSelect;
  118930. p->pSrc->a[0].pSelect = 0;
  118931. sqlite3SrcListDelete(db, p->pSrc);
  118932. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
  118933. while( pSub ){
  118934. Expr *pTerm;
  118935. pPrior = pSub->pPrior;
  118936. pSub->pPrior = 0;
  118937. pSub->pNext = 0;
  118938. pSub->selFlags |= SF_Aggregate;
  118939. pSub->selFlags &= ~SF_Compound;
  118940. pSub->nSelectRow = 0;
  118941. sqlite3ExprListDelete(db, pSub->pEList);
  118942. pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
  118943. pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
  118944. pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  118945. sqlite3PExprAddSelect(pParse, pTerm, pSub);
  118946. if( pExpr==0 ){
  118947. pExpr = pTerm;
  118948. }else{
  118949. pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
  118950. }
  118951. pSub = pPrior;
  118952. }
  118953. p->pEList->a[0].pExpr = pExpr;
  118954. p->selFlags &= ~SF_Aggregate;
  118955. #if SELECTTRACE_ENABLED
  118956. if( sqlite3SelectTrace & 0x400 ){
  118957. SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
  118958. sqlite3TreeViewSelect(0, p, 0);
  118959. }
  118960. #endif
  118961. return 1;
  118962. }
  118963. #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
  118964. /*
  118965. ** Generate code for the SELECT statement given in the p argument.
  118966. **
  118967. ** The results are returned according to the SelectDest structure.
  118968. ** See comments in sqliteInt.h for further information.
  118969. **
  118970. ** This routine returns the number of errors. If any errors are
  118971. ** encountered, then an appropriate error message is left in
  118972. ** pParse->zErrMsg.
  118973. **
  118974. ** This routine does NOT free the Select structure passed in. The
  118975. ** calling function needs to do that.
  118976. */
  118977. SQLITE_PRIVATE int sqlite3Select(
  118978. Parse *pParse, /* The parser context */
  118979. Select *p, /* The SELECT statement being coded. */
  118980. SelectDest *pDest /* What to do with the query results */
  118981. ){
  118982. int i, j; /* Loop counters */
  118983. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  118984. Vdbe *v; /* The virtual machine under construction */
  118985. int isAgg; /* True for select lists like "count(*)" */
  118986. ExprList *pEList = 0; /* List of columns to extract. */
  118987. SrcList *pTabList; /* List of tables to select from */
  118988. Expr *pWhere; /* The WHERE clause. May be NULL */
  118989. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  118990. Expr *pHaving; /* The HAVING clause. May be NULL */
  118991. int rc = 1; /* Value to return from this function */
  118992. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  118993. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  118994. AggInfo sAggInfo; /* Information used by aggregate queries */
  118995. int iEnd; /* Address of the end of the query */
  118996. sqlite3 *db; /* The database connection */
  118997. ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
  118998. u8 minMaxFlag; /* Flag for min/max queries */
  118999. db = pParse->db;
  119000. v = sqlite3GetVdbe(pParse);
  119001. if( p==0 || db->mallocFailed || pParse->nErr ){
  119002. return 1;
  119003. }
  119004. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  119005. memset(&sAggInfo, 0, sizeof(sAggInfo));
  119006. #if SELECTTRACE_ENABLED
  119007. SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
  119008. if( sqlite3SelectTrace & 0x100 ){
  119009. sqlite3TreeViewSelect(0, p, 0);
  119010. }
  119011. #endif
  119012. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  119013. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  119014. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  119015. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  119016. if( IgnorableOrderby(pDest) ){
  119017. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  119018. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  119019. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  119020. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  119021. /* If ORDER BY makes no difference in the output then neither does
  119022. ** DISTINCT so it can be removed too. */
  119023. sqlite3ExprListDelete(db, p->pOrderBy);
  119024. p->pOrderBy = 0;
  119025. p->selFlags &= ~SF_Distinct;
  119026. }
  119027. sqlite3SelectPrep(pParse, p, 0);
  119028. memset(&sSort, 0, sizeof(sSort));
  119029. sSort.pOrderBy = p->pOrderBy;
  119030. pTabList = p->pSrc;
  119031. if( pParse->nErr || db->mallocFailed ){
  119032. goto select_end;
  119033. }
  119034. assert( p->pEList!=0 );
  119035. isAgg = (p->selFlags & SF_Aggregate)!=0;
  119036. #if SELECTTRACE_ENABLED
  119037. if( sqlite3SelectTrace & 0x104 ){
  119038. SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
  119039. sqlite3TreeViewSelect(0, p, 0);
  119040. }
  119041. #endif
  119042. if( pDest->eDest==SRT_Output ){
  119043. generateColumnNames(pParse, p);
  119044. }
  119045. /* Try to various optimizations (flattening subqueries, and strength
  119046. ** reduction of join operators) in the FROM clause up into the main query
  119047. */
  119048. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  119049. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  119050. struct SrcList_item *pItem = &pTabList->a[i];
  119051. Select *pSub = pItem->pSelect;
  119052. Table *pTab = pItem->pTab;
  119053. /* Convert LEFT JOIN into JOIN if there are terms of the right table
  119054. ** of the LEFT JOIN used in the WHERE clause.
  119055. */
  119056. if( (pItem->fg.jointype & JT_LEFT)!=0
  119057. && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
  119058. && OptimizationEnabled(db, SQLITE_SimplifyJoin)
  119059. ){
  119060. SELECTTRACE(0x100,pParse,p,
  119061. ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
  119062. pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
  119063. unsetJoinExpr(p->pWhere, pItem->iCursor);
  119064. }
  119065. /* No futher action if this term of the FROM clause is no a subquery */
  119066. if( pSub==0 ) continue;
  119067. /* Catch mismatch in the declared columns of a view and the number of
  119068. ** columns in the SELECT on the RHS */
  119069. if( pTab->nCol!=pSub->pEList->nExpr ){
  119070. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  119071. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  119072. goto select_end;
  119073. }
  119074. /* Do not try to flatten an aggregate subquery.
  119075. **
  119076. ** Flattening an aggregate subquery is only possible if the outer query
  119077. ** is not a join. But if the outer query is not a join, then the subquery
  119078. ** will be implemented as a co-routine and there is no advantage to
  119079. ** flattening in that case.
  119080. */
  119081. if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
  119082. assert( pSub->pGroupBy==0 );
  119083. /* If the outer query contains a "complex" result set (that is,
  119084. ** if the result set of the outer query uses functions or subqueries)
  119085. ** and if the subquery contains an ORDER BY clause and if
  119086. ** it will be implemented as a co-routine, then do not flatten. This
  119087. ** restriction allows SQL constructs like this:
  119088. **
  119089. ** SELECT expensive_function(x)
  119090. ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  119091. **
  119092. ** The expensive_function() is only computed on the 10 rows that
  119093. ** are output, rather than every row of the table.
  119094. **
  119095. ** The requirement that the outer query have a complex result set
  119096. ** means that flattening does occur on simpler SQL constraints without
  119097. ** the expensive_function() like:
  119098. **
  119099. ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  119100. */
  119101. if( pSub->pOrderBy!=0
  119102. && i==0
  119103. && (p->selFlags & SF_ComplexResult)!=0
  119104. && (pTabList->nSrc==1
  119105. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
  119106. ){
  119107. continue;
  119108. }
  119109. if( flattenSubquery(pParse, p, i, isAgg) ){
  119110. /* This subquery can be absorbed into its parent. */
  119111. i = -1;
  119112. }
  119113. pTabList = p->pSrc;
  119114. if( db->mallocFailed ) goto select_end;
  119115. if( !IgnorableOrderby(pDest) ){
  119116. sSort.pOrderBy = p->pOrderBy;
  119117. }
  119118. }
  119119. #endif
  119120. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  119121. /* Handle compound SELECT statements using the separate multiSelect()
  119122. ** procedure.
  119123. */
  119124. if( p->pPrior ){
  119125. rc = multiSelect(pParse, p, pDest);
  119126. #if SELECTTRACE_ENABLED
  119127. SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
  119128. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  119129. sqlite3TreeViewSelect(0, p, 0);
  119130. }
  119131. #endif
  119132. if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
  119133. return rc;
  119134. }
  119135. #endif
  119136. /* For each term in the FROM clause, do two things:
  119137. ** (1) Authorized unreferenced tables
  119138. ** (2) Generate code for all sub-queries
  119139. */
  119140. for(i=0; i<pTabList->nSrc; i++){
  119141. struct SrcList_item *pItem = &pTabList->a[i];
  119142. SelectDest dest;
  119143. Select *pSub;
  119144. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  119145. const char *zSavedAuthContext;
  119146. #endif
  119147. /* Issue SQLITE_READ authorizations with a fake column name for any
  119148. ** tables that are referenced but from which no values are extracted.
  119149. ** Examples of where these kinds of null SQLITE_READ authorizations
  119150. ** would occur:
  119151. **
  119152. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  119153. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  119154. **
  119155. ** The fake column name is an empty string. It is possible for a table to
  119156. ** have a column named by the empty string, in which case there is no way to
  119157. ** distinguish between an unreferenced table and an actual reference to the
  119158. ** "" column. The original design was for the fake column name to be a NULL,
  119159. ** which would be unambiguous. But legacy authorization callbacks might
  119160. ** assume the column name is non-NULL and segfault. The use of an empty
  119161. ** string for the fake column name seems safer.
  119162. */
  119163. if( pItem->colUsed==0 ){
  119164. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  119165. }
  119166. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  119167. /* Generate code for all sub-queries in the FROM clause
  119168. */
  119169. pSub = pItem->pSelect;
  119170. if( pSub==0 ) continue;
  119171. /* Sometimes the code for a subquery will be generated more than
  119172. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  119173. ** for example. In that case, do not regenerate the code to manifest
  119174. ** a view or the co-routine to implement a view. The first instance
  119175. ** is sufficient, though the subroutine to manifest the view does need
  119176. ** to be invoked again. */
  119177. if( pItem->addrFillSub ){
  119178. if( pItem->fg.viaCoroutine==0 ){
  119179. /* The subroutine that manifests the view might be a one-time routine,
  119180. ** or it might need to be rerun on each iteration because it
  119181. ** encodes a correlated subquery. */
  119182. testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
  119183. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  119184. }
  119185. continue;
  119186. }
  119187. /* Increment Parse.nHeight by the height of the largest expression
  119188. ** tree referred to by this, the parent select. The child select
  119189. ** may contain expression trees of at most
  119190. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  119191. ** more conservative than necessary, but much easier than enforcing
  119192. ** an exact limit.
  119193. */
  119194. pParse->nHeight += sqlite3SelectExprHeight(p);
  119195. /* Make copies of constant WHERE-clause terms in the outer query down
  119196. ** inside the subquery. This can help the subquery to run more efficiently.
  119197. */
  119198. if( OptimizationEnabled(db, SQLITE_PushDown)
  119199. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
  119200. (pItem->fg.jointype & JT_OUTER)!=0)
  119201. ){
  119202. #if SELECTTRACE_ENABLED
  119203. if( sqlite3SelectTrace & 0x100 ){
  119204. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  119205. sqlite3TreeViewSelect(0, p, 0);
  119206. }
  119207. #endif
  119208. }else{
  119209. SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
  119210. }
  119211. zSavedAuthContext = pParse->zAuthContext;
  119212. pParse->zAuthContext = pItem->zName;
  119213. /* Generate code to implement the subquery
  119214. **
  119215. ** The subquery is implemented as a co-routine if the subquery is
  119216. ** guaranteed to be the outer loop (so that it does not need to be
  119217. ** computed more than once)
  119218. **
  119219. ** TODO: Are there other reasons beside (1) to use a co-routine
  119220. ** implementation?
  119221. */
  119222. if( i==0
  119223. && (pTabList->nSrc==1
  119224. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  119225. ){
  119226. /* Implement a co-routine that will return a single row of the result
  119227. ** set on each invocation.
  119228. */
  119229. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  119230. pItem->regReturn = ++pParse->nMem;
  119231. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  119232. VdbeComment((v, "%s", pItem->pTab->zName));
  119233. pItem->addrFillSub = addrTop;
  119234. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  119235. ExplainQueryPlan((pParse, 1, "CO-ROUTINE 0x%p", pSub));
  119236. sqlite3Select(pParse, pSub, &dest);
  119237. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  119238. pItem->fg.viaCoroutine = 1;
  119239. pItem->regResult = dest.iSdst;
  119240. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  119241. sqlite3VdbeJumpHere(v, addrTop-1);
  119242. sqlite3ClearTempRegCache(pParse);
  119243. }else{
  119244. /* Generate a subroutine that will fill an ephemeral table with
  119245. ** the content of this subquery. pItem->addrFillSub will point
  119246. ** to the address of the generated subroutine. pItem->regReturn
  119247. ** is a register allocated to hold the subroutine return address
  119248. */
  119249. int topAddr;
  119250. int onceAddr = 0;
  119251. int retAddr;
  119252. struct SrcList_item *pPrior;
  119253. assert( pItem->addrFillSub==0 );
  119254. pItem->regReturn = ++pParse->nMem;
  119255. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  119256. pItem->addrFillSub = topAddr+1;
  119257. if( pItem->fg.isCorrelated==0 ){
  119258. /* If the subquery is not correlated and if we are not inside of
  119259. ** a trigger, then we only need to compute the value of the subquery
  119260. ** once. */
  119261. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  119262. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  119263. }else{
  119264. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  119265. }
  119266. pPrior = isSelfJoinView(pTabList, pItem);
  119267. if( pPrior ){
  119268. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  119269. assert( pPrior->pSelect!=0 );
  119270. pSub->nSelectRow = pPrior->pSelect->nSelectRow;
  119271. }else{
  119272. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  119273. ExplainQueryPlan((pParse, 1, "MATERIALIZE 0x%p", pSub));
  119274. sqlite3Select(pParse, pSub, &dest);
  119275. }
  119276. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  119277. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  119278. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  119279. VdbeComment((v, "end %s", pItem->pTab->zName));
  119280. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  119281. sqlite3ClearTempRegCache(pParse);
  119282. }
  119283. if( db->mallocFailed ) goto select_end;
  119284. pParse->nHeight -= sqlite3SelectExprHeight(p);
  119285. pParse->zAuthContext = zSavedAuthContext;
  119286. #endif
  119287. }
  119288. /* Various elements of the SELECT copied into local variables for
  119289. ** convenience */
  119290. pEList = p->pEList;
  119291. pWhere = p->pWhere;
  119292. pGroupBy = p->pGroupBy;
  119293. pHaving = p->pHaving;
  119294. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  119295. #if SELECTTRACE_ENABLED
  119296. if( sqlite3SelectTrace & 0x400 ){
  119297. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  119298. sqlite3TreeViewSelect(0, p, 0);
  119299. }
  119300. #endif
  119301. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  119302. if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
  119303. && countOfViewOptimization(pParse, p)
  119304. ){
  119305. if( db->mallocFailed ) goto select_end;
  119306. pEList = p->pEList;
  119307. pTabList = p->pSrc;
  119308. }
  119309. #endif
  119310. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  119311. ** if the select-list is the same as the ORDER BY list, then this query
  119312. ** can be rewritten as a GROUP BY. In other words, this:
  119313. **
  119314. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  119315. **
  119316. ** is transformed to:
  119317. **
  119318. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  119319. **
  119320. ** The second form is preferred as a single index (or temp-table) may be
  119321. ** used for both the ORDER BY and DISTINCT processing. As originally
  119322. ** written the query must use a temp-table for at least one of the ORDER
  119323. ** BY and DISTINCT, and an index or separate temp-table for the other.
  119324. */
  119325. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  119326. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  119327. ){
  119328. p->selFlags &= ~SF_Distinct;
  119329. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  119330. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  119331. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  119332. ** original setting of the SF_Distinct flag, not the current setting */
  119333. assert( sDistinct.isTnct );
  119334. #if SELECTTRACE_ENABLED
  119335. if( sqlite3SelectTrace & 0x400 ){
  119336. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  119337. sqlite3TreeViewSelect(0, p, 0);
  119338. }
  119339. #endif
  119340. }
  119341. /* If there is an ORDER BY clause, then create an ephemeral index to
  119342. ** do the sorting. But this sorting ephemeral index might end up
  119343. ** being unused if the data can be extracted in pre-sorted order.
  119344. ** If that is the case, then the OP_OpenEphemeral instruction will be
  119345. ** changed to an OP_Noop once we figure out that the sorting index is
  119346. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  119347. ** that change.
  119348. */
  119349. if( sSort.pOrderBy ){
  119350. KeyInfo *pKeyInfo;
  119351. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  119352. sSort.iECursor = pParse->nTab++;
  119353. sSort.addrSortIndex =
  119354. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  119355. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  119356. (char*)pKeyInfo, P4_KEYINFO
  119357. );
  119358. }else{
  119359. sSort.addrSortIndex = -1;
  119360. }
  119361. /* If the output is destined for a temporary table, open that table.
  119362. */
  119363. if( pDest->eDest==SRT_EphemTab ){
  119364. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  119365. }
  119366. /* Set the limiter.
  119367. */
  119368. iEnd = sqlite3VdbeMakeLabel(v);
  119369. if( (p->selFlags & SF_FixedLimit)==0 ){
  119370. p->nSelectRow = 320; /* 4 billion rows */
  119371. }
  119372. computeLimitRegisters(pParse, p, iEnd);
  119373. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  119374. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  119375. sSort.sortFlags |= SORTFLAG_UseSorter;
  119376. }
  119377. /* Open an ephemeral index to use for the distinct set.
  119378. */
  119379. if( p->selFlags & SF_Distinct ){
  119380. sDistinct.tabTnct = pParse->nTab++;
  119381. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  119382. sDistinct.tabTnct, 0, 0,
  119383. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  119384. P4_KEYINFO);
  119385. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  119386. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  119387. }else{
  119388. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  119389. }
  119390. if( !isAgg && pGroupBy==0 ){
  119391. /* No aggregate functions and no GROUP BY clause */
  119392. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  119393. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  119394. wctrlFlags |= p->selFlags & SF_FixedLimit;
  119395. /* Begin the database scan. */
  119396. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  119397. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  119398. p->pEList, wctrlFlags, p->nSelectRow);
  119399. if( pWInfo==0 ) goto select_end;
  119400. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  119401. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  119402. }
  119403. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  119404. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  119405. }
  119406. if( sSort.pOrderBy ){
  119407. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  119408. sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
  119409. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  119410. sSort.pOrderBy = 0;
  119411. }
  119412. }
  119413. /* If sorting index that was created by a prior OP_OpenEphemeral
  119414. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  119415. ** into an OP_Noop.
  119416. */
  119417. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  119418. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  119419. }
  119420. /* Use the standard inner loop. */
  119421. assert( p->pEList==pEList );
  119422. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
  119423. sqlite3WhereContinueLabel(pWInfo),
  119424. sqlite3WhereBreakLabel(pWInfo));
  119425. /* End the database scan loop.
  119426. */
  119427. sqlite3WhereEnd(pWInfo);
  119428. }else{
  119429. /* This case when there exist aggregate functions or a GROUP BY clause
  119430. ** or both */
  119431. NameContext sNC; /* Name context for processing aggregate information */
  119432. int iAMem; /* First Mem address for storing current GROUP BY */
  119433. int iBMem; /* First Mem address for previous GROUP BY */
  119434. int iUseFlag; /* Mem address holding flag indicating that at least
  119435. ** one row of the input to the aggregator has been
  119436. ** processed */
  119437. int iAbortFlag; /* Mem address which causes query abort if positive */
  119438. int groupBySort; /* Rows come from source in GROUP BY order */
  119439. int addrEnd; /* End of processing for this SELECT */
  119440. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  119441. int sortOut = 0; /* Output register from the sorter */
  119442. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  119443. /* Remove any and all aliases between the result set and the
  119444. ** GROUP BY clause.
  119445. */
  119446. if( pGroupBy ){
  119447. int k; /* Loop counter */
  119448. struct ExprList_item *pItem; /* For looping over expression in a list */
  119449. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  119450. pItem->u.x.iAlias = 0;
  119451. }
  119452. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  119453. pItem->u.x.iAlias = 0;
  119454. }
  119455. assert( 66==sqlite3LogEst(100) );
  119456. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  119457. }else{
  119458. assert( 0==sqlite3LogEst(1) );
  119459. p->nSelectRow = 0;
  119460. }
  119461. /* If there is both a GROUP BY and an ORDER BY clause and they are
  119462. ** identical, then it may be possible to disable the ORDER BY clause
  119463. ** on the grounds that the GROUP BY will cause elements to come out
  119464. ** in the correct order. It also may not - the GROUP BY might use a
  119465. ** database index that causes rows to be grouped together as required
  119466. ** but not actually sorted. Either way, record the fact that the
  119467. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  119468. ** variable. */
  119469. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  119470. orderByGrp = 1;
  119471. }
  119472. /* Create a label to jump to when we want to abort the query */
  119473. addrEnd = sqlite3VdbeMakeLabel(v);
  119474. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  119475. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  119476. ** SELECT statement.
  119477. */
  119478. memset(&sNC, 0, sizeof(sNC));
  119479. sNC.pParse = pParse;
  119480. sNC.pSrcList = pTabList;
  119481. sNC.uNC.pAggInfo = &sAggInfo;
  119482. VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
  119483. sAggInfo.mnReg = pParse->nMem+1;
  119484. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  119485. sAggInfo.pGroupBy = pGroupBy;
  119486. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  119487. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  119488. if( pHaving ){
  119489. if( pGroupBy ){
  119490. assert( pWhere==p->pWhere );
  119491. assert( pHaving==p->pHaving );
  119492. assert( pGroupBy==p->pGroupBy );
  119493. havingToWhere(pParse, p);
  119494. pWhere = p->pWhere;
  119495. }
  119496. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  119497. }
  119498. sAggInfo.nAccumulator = sAggInfo.nColumn;
  119499. if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
  119500. minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
  119501. }else{
  119502. minMaxFlag = WHERE_ORDERBY_NORMAL;
  119503. }
  119504. for(i=0; i<sAggInfo.nFunc; i++){
  119505. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  119506. sNC.ncFlags |= NC_InAggFunc;
  119507. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  119508. sNC.ncFlags &= ~NC_InAggFunc;
  119509. }
  119510. sAggInfo.mxReg = pParse->nMem;
  119511. if( db->mallocFailed ) goto select_end;
  119512. #if SELECTTRACE_ENABLED
  119513. if( sqlite3SelectTrace & 0x400 ){
  119514. int ii;
  119515. SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
  119516. sqlite3TreeViewSelect(0, p, 0);
  119517. for(ii=0; ii<sAggInfo.nColumn; ii++){
  119518. sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
  119519. ii, sAggInfo.aCol[ii].iMem);
  119520. sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
  119521. }
  119522. for(ii=0; ii<sAggInfo.nFunc; ii++){
  119523. sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
  119524. ii, sAggInfo.aFunc[ii].iMem);
  119525. sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
  119526. }
  119527. }
  119528. #endif
  119529. /* Processing for aggregates with GROUP BY is very different and
  119530. ** much more complex than aggregates without a GROUP BY.
  119531. */
  119532. if( pGroupBy ){
  119533. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  119534. int addr1; /* A-vs-B comparision jump */
  119535. int addrOutputRow; /* Start of subroutine that outputs a result row */
  119536. int regOutputRow; /* Return address register for output subroutine */
  119537. int addrSetAbort; /* Set the abort flag and return */
  119538. int addrTopOfLoop; /* Top of the input loop */
  119539. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  119540. int addrReset; /* Subroutine for resetting the accumulator */
  119541. int regReset; /* Return address register for reset subroutine */
  119542. /* If there is a GROUP BY clause we might need a sorting index to
  119543. ** implement it. Allocate that sorting index now. If it turns out
  119544. ** that we do not need it after all, the OP_SorterOpen instruction
  119545. ** will be converted into a Noop.
  119546. */
  119547. sAggInfo.sortingIdx = pParse->nTab++;
  119548. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  119549. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  119550. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  119551. 0, (char*)pKeyInfo, P4_KEYINFO);
  119552. /* Initialize memory locations used by GROUP BY aggregate processing
  119553. */
  119554. iUseFlag = ++pParse->nMem;
  119555. iAbortFlag = ++pParse->nMem;
  119556. regOutputRow = ++pParse->nMem;
  119557. addrOutputRow = sqlite3VdbeMakeLabel(v);
  119558. regReset = ++pParse->nMem;
  119559. addrReset = sqlite3VdbeMakeLabel(v);
  119560. iAMem = pParse->nMem + 1;
  119561. pParse->nMem += pGroupBy->nExpr;
  119562. iBMem = pParse->nMem + 1;
  119563. pParse->nMem += pGroupBy->nExpr;
  119564. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  119565. VdbeComment((v, "clear abort flag"));
  119566. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  119567. VdbeComment((v, "indicate accumulator empty"));
  119568. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  119569. /* Begin a loop that will extract all source rows in GROUP BY order.
  119570. ** This might involve two separate loops with an OP_Sort in between, or
  119571. ** it might be a single loop that uses an index to extract information
  119572. ** in the right order to begin with.
  119573. */
  119574. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  119575. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  119576. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  119577. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  119578. );
  119579. if( pWInfo==0 ) goto select_end;
  119580. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  119581. /* The optimizer is able to deliver rows in group by order so
  119582. ** we do not have to sort. The OP_OpenEphemeral table will be
  119583. ** cancelled later because we still need to use the pKeyInfo
  119584. */
  119585. groupBySort = 0;
  119586. }else{
  119587. /* Rows are coming out in undetermined order. We have to push
  119588. ** each row into a sorting index, terminate the first loop,
  119589. ** then loop over the sorting index in order to get the output
  119590. ** in sorted order
  119591. */
  119592. int regBase;
  119593. int regRecord;
  119594. int nCol;
  119595. int nGroupBy;
  119596. explainTempTable(pParse,
  119597. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  119598. "DISTINCT" : "GROUP BY");
  119599. groupBySort = 1;
  119600. nGroupBy = pGroupBy->nExpr;
  119601. nCol = nGroupBy;
  119602. j = nGroupBy;
  119603. for(i=0; i<sAggInfo.nColumn; i++){
  119604. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  119605. nCol++;
  119606. j++;
  119607. }
  119608. }
  119609. regBase = sqlite3GetTempRange(pParse, nCol);
  119610. sqlite3ExprCacheClear(pParse);
  119611. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  119612. j = nGroupBy;
  119613. for(i=0; i<sAggInfo.nColumn; i++){
  119614. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  119615. if( pCol->iSorterColumn>=j ){
  119616. int r1 = j + regBase;
  119617. sqlite3ExprCodeGetColumnToReg(pParse,
  119618. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  119619. j++;
  119620. }
  119621. }
  119622. regRecord = sqlite3GetTempReg(pParse);
  119623. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  119624. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  119625. sqlite3ReleaseTempReg(pParse, regRecord);
  119626. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  119627. sqlite3WhereEnd(pWInfo);
  119628. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  119629. sortOut = sqlite3GetTempReg(pParse);
  119630. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  119631. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  119632. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  119633. sAggInfo.useSortingIdx = 1;
  119634. sqlite3ExprCacheClear(pParse);
  119635. }
  119636. /* If the index or temporary table used by the GROUP BY sort
  119637. ** will naturally deliver rows in the order required by the ORDER BY
  119638. ** clause, cancel the ephemeral table open coded earlier.
  119639. **
  119640. ** This is an optimization - the correct answer should result regardless.
  119641. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  119642. ** disable this optimization for testing purposes. */
  119643. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  119644. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  119645. ){
  119646. sSort.pOrderBy = 0;
  119647. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  119648. }
  119649. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  119650. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  119651. ** Then compare the current GROUP BY terms against the GROUP BY terms
  119652. ** from the previous row currently stored in a0, a1, a2...
  119653. */
  119654. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  119655. sqlite3ExprCacheClear(pParse);
  119656. if( groupBySort ){
  119657. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  119658. sortOut, sortPTab);
  119659. }
  119660. for(j=0; j<pGroupBy->nExpr; j++){
  119661. if( groupBySort ){
  119662. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  119663. }else{
  119664. sAggInfo.directMode = 1;
  119665. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  119666. }
  119667. }
  119668. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  119669. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  119670. addr1 = sqlite3VdbeCurrentAddr(v);
  119671. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  119672. /* Generate code that runs whenever the GROUP BY changes.
  119673. ** Changes in the GROUP BY are detected by the previous code
  119674. ** block. If there were no changes, this block is skipped.
  119675. **
  119676. ** This code copies current group by terms in b0,b1,b2,...
  119677. ** over to a0,a1,a2. It then calls the output subroutine
  119678. ** and resets the aggregate accumulator registers in preparation
  119679. ** for the next GROUP BY batch.
  119680. */
  119681. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  119682. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  119683. VdbeComment((v, "output one row"));
  119684. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  119685. VdbeComment((v, "check abort flag"));
  119686. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  119687. VdbeComment((v, "reset accumulator"));
  119688. /* Update the aggregate accumulators based on the content of
  119689. ** the current row
  119690. */
  119691. sqlite3VdbeJumpHere(v, addr1);
  119692. updateAccumulator(pParse, &sAggInfo);
  119693. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  119694. VdbeComment((v, "indicate data in accumulator"));
  119695. /* End of the loop
  119696. */
  119697. if( groupBySort ){
  119698. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  119699. VdbeCoverage(v);
  119700. }else{
  119701. sqlite3WhereEnd(pWInfo);
  119702. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  119703. }
  119704. /* Output the final row of result
  119705. */
  119706. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  119707. VdbeComment((v, "output final row"));
  119708. /* Jump over the subroutines
  119709. */
  119710. sqlite3VdbeGoto(v, addrEnd);
  119711. /* Generate a subroutine that outputs a single row of the result
  119712. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  119713. ** is less than or equal to zero, the subroutine is a no-op. If
  119714. ** the processing calls for the query to abort, this subroutine
  119715. ** increments the iAbortFlag memory location before returning in
  119716. ** order to signal the caller to abort.
  119717. */
  119718. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  119719. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  119720. VdbeComment((v, "set abort flag"));
  119721. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  119722. sqlite3VdbeResolveLabel(v, addrOutputRow);
  119723. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  119724. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  119725. VdbeCoverage(v);
  119726. VdbeComment((v, "Groupby result generator entry point"));
  119727. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  119728. finalizeAggFunctions(pParse, &sAggInfo);
  119729. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  119730. selectInnerLoop(pParse, p, -1, &sSort,
  119731. &sDistinct, pDest,
  119732. addrOutputRow+1, addrSetAbort);
  119733. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  119734. VdbeComment((v, "end groupby result generator"));
  119735. /* Generate a subroutine that will reset the group-by accumulator
  119736. */
  119737. sqlite3VdbeResolveLabel(v, addrReset);
  119738. resetAccumulator(pParse, &sAggInfo);
  119739. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  119740. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  119741. else {
  119742. #ifndef SQLITE_OMIT_BTREECOUNT
  119743. Table *pTab;
  119744. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  119745. /* If isSimpleCount() returns a pointer to a Table structure, then
  119746. ** the SQL statement is of the form:
  119747. **
  119748. ** SELECT count(*) FROM <tbl>
  119749. **
  119750. ** where the Table structure returned represents table <tbl>.
  119751. **
  119752. ** This statement is so common that it is optimized specially. The
  119753. ** OP_Count instruction is executed either on the intkey table that
  119754. ** contains the data for table <tbl> or on one of its indexes. It
  119755. ** is better to execute the op on an index, as indexes are almost
  119756. ** always spread across less pages than their corresponding tables.
  119757. */
  119758. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  119759. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  119760. Index *pIdx; /* Iterator variable */
  119761. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  119762. Index *pBest = 0; /* Best index found so far */
  119763. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  119764. sqlite3CodeVerifySchema(pParse, iDb);
  119765. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  119766. /* Search for the index that has the lowest scan cost.
  119767. **
  119768. ** (2011-04-15) Do not do a full scan of an unordered index.
  119769. **
  119770. ** (2013-10-03) Do not count the entries in a partial index.
  119771. **
  119772. ** In practice the KeyInfo structure will not be used. It is only
  119773. ** passed to keep OP_OpenRead happy.
  119774. */
  119775. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  119776. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  119777. if( pIdx->bUnordered==0
  119778. && pIdx->szIdxRow<pTab->szTabRow
  119779. && pIdx->pPartIdxWhere==0
  119780. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  119781. ){
  119782. pBest = pIdx;
  119783. }
  119784. }
  119785. if( pBest ){
  119786. iRoot = pBest->tnum;
  119787. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  119788. }
  119789. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  119790. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  119791. if( pKeyInfo ){
  119792. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  119793. }
  119794. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  119795. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  119796. explainSimpleCount(pParse, pTab, pBest);
  119797. }else
  119798. #endif /* SQLITE_OMIT_BTREECOUNT */
  119799. {
  119800. /* This case runs if the aggregate has no GROUP BY clause. The
  119801. ** processing is much simpler since there is only a single row
  119802. ** of output.
  119803. */
  119804. assert( p->pGroupBy==0 );
  119805. resetAccumulator(pParse, &sAggInfo);
  119806. /* If this query is a candidate for the min/max optimization, then
  119807. ** minMaxFlag will have been previously set to either
  119808. ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
  119809. ** be an appropriate ORDER BY expression for the optimization.
  119810. */
  119811. assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
  119812. assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
  119813. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  119814. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
  119815. 0, minMaxFlag, 0);
  119816. if( pWInfo==0 ){
  119817. goto select_end;
  119818. }
  119819. updateAccumulator(pParse, &sAggInfo);
  119820. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  119821. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  119822. VdbeComment((v, "%s() by index",
  119823. (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
  119824. }
  119825. sqlite3WhereEnd(pWInfo);
  119826. finalizeAggFunctions(pParse, &sAggInfo);
  119827. }
  119828. sSort.pOrderBy = 0;
  119829. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  119830. selectInnerLoop(pParse, p, -1, 0, 0,
  119831. pDest, addrEnd, addrEnd);
  119832. }
  119833. sqlite3VdbeResolveLabel(v, addrEnd);
  119834. } /* endif aggregate query */
  119835. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  119836. explainTempTable(pParse, "DISTINCT");
  119837. }
  119838. /* If there is an ORDER BY clause, then we need to sort the results
  119839. ** and send them to the callback one by one.
  119840. */
  119841. if( sSort.pOrderBy ){
  119842. explainTempTable(pParse,
  119843. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  119844. assert( p->pEList==pEList );
  119845. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  119846. }
  119847. /* Jump here to skip this query
  119848. */
  119849. sqlite3VdbeResolveLabel(v, iEnd);
  119850. /* The SELECT has been coded. If there is an error in the Parse structure,
  119851. ** set the return code to 1. Otherwise 0. */
  119852. rc = (pParse->nErr>0);
  119853. /* Control jumps to here if an error is encountered above, or upon
  119854. ** successful coding of the SELECT.
  119855. */
  119856. select_end:
  119857. sqlite3ExprListDelete(db, pMinMaxOrderBy);
  119858. sqlite3DbFree(db, sAggInfo.aCol);
  119859. sqlite3DbFree(db, sAggInfo.aFunc);
  119860. #if SELECTTRACE_ENABLED
  119861. SELECTTRACE(0x1,pParse,p,("end processing\n"));
  119862. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  119863. sqlite3TreeViewSelect(0, p, 0);
  119864. }
  119865. #endif
  119866. ExplainQueryPlanPop(pParse);
  119867. return rc;
  119868. }
  119869. /************** End of select.c **********************************************/
  119870. /************** Begin file table.c *******************************************/
  119871. /*
  119872. ** 2001 September 15
  119873. **
  119874. ** The author disclaims copyright to this source code. In place of
  119875. ** a legal notice, here is a blessing:
  119876. **
  119877. ** May you do good and not evil.
  119878. ** May you find forgiveness for yourself and forgive others.
  119879. ** May you share freely, never taking more than you give.
  119880. **
  119881. *************************************************************************
  119882. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  119883. ** interface routines. These are just wrappers around the main
  119884. ** interface routine of sqlite3_exec().
  119885. **
  119886. ** These routines are in a separate files so that they will not be linked
  119887. ** if they are not used.
  119888. */
  119889. /* #include "sqliteInt.h" */
  119890. #ifndef SQLITE_OMIT_GET_TABLE
  119891. /*
  119892. ** This structure is used to pass data from sqlite3_get_table() through
  119893. ** to the callback function is uses to build the result.
  119894. */
  119895. typedef struct TabResult {
  119896. char **azResult; /* Accumulated output */
  119897. char *zErrMsg; /* Error message text, if an error occurs */
  119898. u32 nAlloc; /* Slots allocated for azResult[] */
  119899. u32 nRow; /* Number of rows in the result */
  119900. u32 nColumn; /* Number of columns in the result */
  119901. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  119902. int rc; /* Return code from sqlite3_exec() */
  119903. } TabResult;
  119904. /*
  119905. ** This routine is called once for each row in the result table. Its job
  119906. ** is to fill in the TabResult structure appropriately, allocating new
  119907. ** memory as necessary.
  119908. */
  119909. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  119910. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  119911. int need; /* Slots needed in p->azResult[] */
  119912. int i; /* Loop counter */
  119913. char *z; /* A single column of result */
  119914. /* Make sure there is enough space in p->azResult to hold everything
  119915. ** we need to remember from this invocation of the callback.
  119916. */
  119917. if( p->nRow==0 && argv!=0 ){
  119918. need = nCol*2;
  119919. }else{
  119920. need = nCol;
  119921. }
  119922. if( p->nData + need > p->nAlloc ){
  119923. char **azNew;
  119924. p->nAlloc = p->nAlloc*2 + need;
  119925. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  119926. if( azNew==0 ) goto malloc_failed;
  119927. p->azResult = azNew;
  119928. }
  119929. /* If this is the first row, then generate an extra row containing
  119930. ** the names of all columns.
  119931. */
  119932. if( p->nRow==0 ){
  119933. p->nColumn = nCol;
  119934. for(i=0; i<nCol; i++){
  119935. z = sqlite3_mprintf("%s", colv[i]);
  119936. if( z==0 ) goto malloc_failed;
  119937. p->azResult[p->nData++] = z;
  119938. }
  119939. }else if( (int)p->nColumn!=nCol ){
  119940. sqlite3_free(p->zErrMsg);
  119941. p->zErrMsg = sqlite3_mprintf(
  119942. "sqlite3_get_table() called with two or more incompatible queries"
  119943. );
  119944. p->rc = SQLITE_ERROR;
  119945. return 1;
  119946. }
  119947. /* Copy over the row data
  119948. */
  119949. if( argv!=0 ){
  119950. for(i=0; i<nCol; i++){
  119951. if( argv[i]==0 ){
  119952. z = 0;
  119953. }else{
  119954. int n = sqlite3Strlen30(argv[i])+1;
  119955. z = sqlite3_malloc64( n );
  119956. if( z==0 ) goto malloc_failed;
  119957. memcpy(z, argv[i], n);
  119958. }
  119959. p->azResult[p->nData++] = z;
  119960. }
  119961. p->nRow++;
  119962. }
  119963. return 0;
  119964. malloc_failed:
  119965. p->rc = SQLITE_NOMEM_BKPT;
  119966. return 1;
  119967. }
  119968. /*
  119969. ** Query the database. But instead of invoking a callback for each row,
  119970. ** malloc() for space to hold the result and return the entire results
  119971. ** at the conclusion of the call.
  119972. **
  119973. ** The result that is written to ***pazResult is held in memory obtained
  119974. ** from malloc(). But the caller cannot free this memory directly.
  119975. ** Instead, the entire table should be passed to sqlite3_free_table() when
  119976. ** the calling procedure is finished using it.
  119977. */
  119978. SQLITE_API int sqlite3_get_table(
  119979. sqlite3 *db, /* The database on which the SQL executes */
  119980. const char *zSql, /* The SQL to be executed */
  119981. char ***pazResult, /* Write the result table here */
  119982. int *pnRow, /* Write the number of rows in the result here */
  119983. int *pnColumn, /* Write the number of columns of result here */
  119984. char **pzErrMsg /* Write error messages here */
  119985. ){
  119986. int rc;
  119987. TabResult res;
  119988. #ifdef SQLITE_ENABLE_API_ARMOR
  119989. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  119990. #endif
  119991. *pazResult = 0;
  119992. if( pnColumn ) *pnColumn = 0;
  119993. if( pnRow ) *pnRow = 0;
  119994. if( pzErrMsg ) *pzErrMsg = 0;
  119995. res.zErrMsg = 0;
  119996. res.nRow = 0;
  119997. res.nColumn = 0;
  119998. res.nData = 1;
  119999. res.nAlloc = 20;
  120000. res.rc = SQLITE_OK;
  120001. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  120002. if( res.azResult==0 ){
  120003. db->errCode = SQLITE_NOMEM;
  120004. return SQLITE_NOMEM_BKPT;
  120005. }
  120006. res.azResult[0] = 0;
  120007. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  120008. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  120009. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  120010. if( (rc&0xff)==SQLITE_ABORT ){
  120011. sqlite3_free_table(&res.azResult[1]);
  120012. if( res.zErrMsg ){
  120013. if( pzErrMsg ){
  120014. sqlite3_free(*pzErrMsg);
  120015. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  120016. }
  120017. sqlite3_free(res.zErrMsg);
  120018. }
  120019. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  120020. return res.rc;
  120021. }
  120022. sqlite3_free(res.zErrMsg);
  120023. if( rc!=SQLITE_OK ){
  120024. sqlite3_free_table(&res.azResult[1]);
  120025. return rc;
  120026. }
  120027. if( res.nAlloc>res.nData ){
  120028. char **azNew;
  120029. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  120030. if( azNew==0 ){
  120031. sqlite3_free_table(&res.azResult[1]);
  120032. db->errCode = SQLITE_NOMEM;
  120033. return SQLITE_NOMEM_BKPT;
  120034. }
  120035. res.azResult = azNew;
  120036. }
  120037. *pazResult = &res.azResult[1];
  120038. if( pnColumn ) *pnColumn = res.nColumn;
  120039. if( pnRow ) *pnRow = res.nRow;
  120040. return rc;
  120041. }
  120042. /*
  120043. ** This routine frees the space the sqlite3_get_table() malloced.
  120044. */
  120045. SQLITE_API void sqlite3_free_table(
  120046. char **azResult /* Result returned from sqlite3_get_table() */
  120047. ){
  120048. if( azResult ){
  120049. int i, n;
  120050. azResult--;
  120051. assert( azResult!=0 );
  120052. n = SQLITE_PTR_TO_INT(azResult[0]);
  120053. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  120054. sqlite3_free(azResult);
  120055. }
  120056. }
  120057. #endif /* SQLITE_OMIT_GET_TABLE */
  120058. /************** End of table.c ***********************************************/
  120059. /************** Begin file trigger.c *****************************************/
  120060. /*
  120061. **
  120062. ** The author disclaims copyright to this source code. In place of
  120063. ** a legal notice, here is a blessing:
  120064. **
  120065. ** May you do good and not evil.
  120066. ** May you find forgiveness for yourself and forgive others.
  120067. ** May you share freely, never taking more than you give.
  120068. **
  120069. *************************************************************************
  120070. ** This file contains the implementation for TRIGGERs
  120071. */
  120072. /* #include "sqliteInt.h" */
  120073. #ifndef SQLITE_OMIT_TRIGGER
  120074. /*
  120075. ** Delete a linked list of TriggerStep structures.
  120076. */
  120077. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  120078. while( pTriggerStep ){
  120079. TriggerStep * pTmp = pTriggerStep;
  120080. pTriggerStep = pTriggerStep->pNext;
  120081. sqlite3ExprDelete(db, pTmp->pWhere);
  120082. sqlite3ExprListDelete(db, pTmp->pExprList);
  120083. sqlite3SelectDelete(db, pTmp->pSelect);
  120084. sqlite3IdListDelete(db, pTmp->pIdList);
  120085. sqlite3UpsertDelete(db, pTmp->pUpsert);
  120086. sqlite3DbFree(db, pTmp->zSpan);
  120087. sqlite3DbFree(db, pTmp);
  120088. }
  120089. }
  120090. /*
  120091. ** Given table pTab, return a list of all the triggers attached to
  120092. ** the table. The list is connected by Trigger.pNext pointers.
  120093. **
  120094. ** All of the triggers on pTab that are in the same database as pTab
  120095. ** are already attached to pTab->pTrigger. But there might be additional
  120096. ** triggers on pTab in the TEMP schema. This routine prepends all
  120097. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  120098. ** and returns the combined list.
  120099. **
  120100. ** To state it another way: This routine returns a list of all triggers
  120101. ** that fire off of pTab. The list will include any TEMP triggers on
  120102. ** pTab as well as the triggers lised in pTab->pTrigger.
  120103. */
  120104. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  120105. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  120106. Trigger *pList = 0; /* List of triggers to return */
  120107. if( pParse->disableTriggers ){
  120108. return 0;
  120109. }
  120110. if( pTmpSchema!=pTab->pSchema ){
  120111. HashElem *p;
  120112. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  120113. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  120114. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  120115. if( pTrig->pTabSchema==pTab->pSchema
  120116. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  120117. ){
  120118. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  120119. pList = pTrig;
  120120. }
  120121. }
  120122. }
  120123. return (pList ? pList : pTab->pTrigger);
  120124. }
  120125. /*
  120126. ** This is called by the parser when it sees a CREATE TRIGGER statement
  120127. ** up to the point of the BEGIN before the trigger actions. A Trigger
  120128. ** structure is generated based on the information available and stored
  120129. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  120130. ** sqlite3FinishTrigger() function is called to complete the trigger
  120131. ** construction process.
  120132. */
  120133. SQLITE_PRIVATE void sqlite3BeginTrigger(
  120134. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  120135. Token *pName1, /* The name of the trigger */
  120136. Token *pName2, /* The name of the trigger */
  120137. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  120138. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  120139. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  120140. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  120141. Expr *pWhen, /* WHEN clause */
  120142. int isTemp, /* True if the TEMPORARY keyword is present */
  120143. int noErr /* Suppress errors if the trigger already exists */
  120144. ){
  120145. Trigger *pTrigger = 0; /* The new trigger */
  120146. Table *pTab; /* Table that the trigger fires off of */
  120147. char *zName = 0; /* Name of the trigger */
  120148. sqlite3 *db = pParse->db; /* The database connection */
  120149. int iDb; /* The database to store the trigger in */
  120150. Token *pName; /* The unqualified db name */
  120151. DbFixer sFix; /* State vector for the DB fixer */
  120152. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  120153. assert( pName2!=0 );
  120154. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  120155. assert( op>0 && op<0xff );
  120156. if( isTemp ){
  120157. /* If TEMP was specified, then the trigger name may not be qualified. */
  120158. if( pName2->n>0 ){
  120159. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  120160. goto trigger_cleanup;
  120161. }
  120162. iDb = 1;
  120163. pName = pName1;
  120164. }else{
  120165. /* Figure out the db that the trigger will be created in */
  120166. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  120167. if( iDb<0 ){
  120168. goto trigger_cleanup;
  120169. }
  120170. }
  120171. if( !pTableName || db->mallocFailed ){
  120172. goto trigger_cleanup;
  120173. }
  120174. /* A long-standing parser bug is that this syntax was allowed:
  120175. **
  120176. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  120177. ** ^^^^^^^^
  120178. **
  120179. ** To maintain backwards compatibility, ignore the database
  120180. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  120181. */
  120182. if( db->init.busy && iDb!=1 ){
  120183. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  120184. pTableName->a[0].zDatabase = 0;
  120185. }
  120186. /* If the trigger name was unqualified, and the table is a temp table,
  120187. ** then set iDb to 1 to create the trigger in the temporary database.
  120188. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  120189. ** exist, the error is caught by the block below.
  120190. */
  120191. pTab = sqlite3SrcListLookup(pParse, pTableName);
  120192. if( db->init.busy==0 && pName2->n==0 && pTab
  120193. && pTab->pSchema==db->aDb[1].pSchema ){
  120194. iDb = 1;
  120195. }
  120196. /* Ensure the table name matches database name and that the table exists */
  120197. if( db->mallocFailed ) goto trigger_cleanup;
  120198. assert( pTableName->nSrc==1 );
  120199. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  120200. if( sqlite3FixSrcList(&sFix, pTableName) ){
  120201. goto trigger_cleanup;
  120202. }
  120203. pTab = sqlite3SrcListLookup(pParse, pTableName);
  120204. if( !pTab ){
  120205. /* The table does not exist. */
  120206. if( db->init.iDb==1 ){
  120207. /* Ticket #3810.
  120208. ** Normally, whenever a table is dropped, all associated triggers are
  120209. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  120210. ** and the table is dropped by a different database connection, the
  120211. ** trigger is not visible to the database connection that does the
  120212. ** drop so the trigger cannot be dropped. This results in an
  120213. ** "orphaned trigger" - a trigger whose associated table is missing.
  120214. */
  120215. db->init.orphanTrigger = 1;
  120216. }
  120217. goto trigger_cleanup;
  120218. }
  120219. if( IsVirtual(pTab) ){
  120220. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  120221. goto trigger_cleanup;
  120222. }
  120223. /* Check that the trigger name is not reserved and that no trigger of the
  120224. ** specified name exists */
  120225. zName = sqlite3NameFromToken(db, pName);
  120226. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  120227. goto trigger_cleanup;
  120228. }
  120229. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  120230. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  120231. if( !noErr ){
  120232. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  120233. }else{
  120234. assert( !db->init.busy );
  120235. sqlite3CodeVerifySchema(pParse, iDb);
  120236. }
  120237. goto trigger_cleanup;
  120238. }
  120239. /* Do not create a trigger on a system table */
  120240. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  120241. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  120242. goto trigger_cleanup;
  120243. }
  120244. /* INSTEAD of triggers are only for views and views only support INSTEAD
  120245. ** of triggers.
  120246. */
  120247. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  120248. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  120249. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  120250. goto trigger_cleanup;
  120251. }
  120252. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  120253. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  120254. " trigger on table: %S", pTableName, 0);
  120255. goto trigger_cleanup;
  120256. }
  120257. #ifndef SQLITE_OMIT_AUTHORIZATION
  120258. {
  120259. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  120260. int code = SQLITE_CREATE_TRIGGER;
  120261. const char *zDb = db->aDb[iTabDb].zDbSName;
  120262. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  120263. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  120264. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  120265. goto trigger_cleanup;
  120266. }
  120267. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  120268. goto trigger_cleanup;
  120269. }
  120270. }
  120271. #endif
  120272. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  120273. ** cannot appear on views. So we might as well translate every
  120274. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  120275. ** elsewhere.
  120276. */
  120277. if (tr_tm == TK_INSTEAD){
  120278. tr_tm = TK_BEFORE;
  120279. }
  120280. /* Build the Trigger object */
  120281. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  120282. if( pTrigger==0 ) goto trigger_cleanup;
  120283. pTrigger->zName = zName;
  120284. zName = 0;
  120285. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  120286. pTrigger->pSchema = db->aDb[iDb].pSchema;
  120287. pTrigger->pTabSchema = pTab->pSchema;
  120288. pTrigger->op = (u8)op;
  120289. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  120290. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  120291. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  120292. assert( pParse->pNewTrigger==0 );
  120293. pParse->pNewTrigger = pTrigger;
  120294. trigger_cleanup:
  120295. sqlite3DbFree(db, zName);
  120296. sqlite3SrcListDelete(db, pTableName);
  120297. sqlite3IdListDelete(db, pColumns);
  120298. sqlite3ExprDelete(db, pWhen);
  120299. if( !pParse->pNewTrigger ){
  120300. sqlite3DeleteTrigger(db, pTrigger);
  120301. }else{
  120302. assert( pParse->pNewTrigger==pTrigger );
  120303. }
  120304. }
  120305. /*
  120306. ** This routine is called after all of the trigger actions have been parsed
  120307. ** in order to complete the process of building the trigger.
  120308. */
  120309. SQLITE_PRIVATE void sqlite3FinishTrigger(
  120310. Parse *pParse, /* Parser context */
  120311. TriggerStep *pStepList, /* The triggered program */
  120312. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  120313. ){
  120314. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  120315. char *zName; /* Name of trigger */
  120316. sqlite3 *db = pParse->db; /* The database */
  120317. DbFixer sFix; /* Fixer object */
  120318. int iDb; /* Database containing the trigger */
  120319. Token nameToken; /* Trigger name for error reporting */
  120320. pParse->pNewTrigger = 0;
  120321. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  120322. zName = pTrig->zName;
  120323. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  120324. pTrig->step_list = pStepList;
  120325. while( pStepList ){
  120326. pStepList->pTrig = pTrig;
  120327. pStepList = pStepList->pNext;
  120328. }
  120329. sqlite3TokenInit(&nameToken, pTrig->zName);
  120330. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  120331. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  120332. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  120333. ){
  120334. goto triggerfinish_cleanup;
  120335. }
  120336. /* if we are not initializing,
  120337. ** build the sqlite_master entry
  120338. */
  120339. if( !db->init.busy ){
  120340. Vdbe *v;
  120341. char *z;
  120342. /* Make an entry in the sqlite_master table */
  120343. v = sqlite3GetVdbe(pParse);
  120344. if( v==0 ) goto triggerfinish_cleanup;
  120345. sqlite3BeginWriteOperation(pParse, 0, iDb);
  120346. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  120347. testcase( z==0 );
  120348. sqlite3NestedParse(pParse,
  120349. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  120350. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  120351. pTrig->table, z);
  120352. sqlite3DbFree(db, z);
  120353. sqlite3ChangeCookie(pParse, iDb);
  120354. sqlite3VdbeAddParseSchemaOp(v, iDb,
  120355. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  120356. }
  120357. if( db->init.busy ){
  120358. Trigger *pLink = pTrig;
  120359. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  120360. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  120361. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  120362. if( pTrig ){
  120363. sqlite3OomFault(db);
  120364. }else if( pLink->pSchema==pLink->pTabSchema ){
  120365. Table *pTab;
  120366. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  120367. assert( pTab!=0 );
  120368. pLink->pNext = pTab->pTrigger;
  120369. pTab->pTrigger = pLink;
  120370. }
  120371. }
  120372. triggerfinish_cleanup:
  120373. sqlite3DeleteTrigger(db, pTrig);
  120374. assert( !pParse->pNewTrigger );
  120375. sqlite3DeleteTriggerStep(db, pStepList);
  120376. }
  120377. /*
  120378. ** Duplicate a range of text from an SQL statement, then convert all
  120379. ** whitespace characters into ordinary space characters.
  120380. */
  120381. static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  120382. char *z = sqlite3DbSpanDup(db, zStart, zEnd);
  120383. int i;
  120384. if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
  120385. return z;
  120386. }
  120387. /*
  120388. ** Turn a SELECT statement (that the pSelect parameter points to) into
  120389. ** a trigger step. Return a pointer to a TriggerStep structure.
  120390. **
  120391. ** The parser calls this routine when it finds a SELECT statement in
  120392. ** body of a TRIGGER.
  120393. */
  120394. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
  120395. sqlite3 *db, /* Database connection */
  120396. Select *pSelect, /* The SELECT statement */
  120397. const char *zStart, /* Start of SQL text */
  120398. const char *zEnd /* End of SQL text */
  120399. ){
  120400. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  120401. if( pTriggerStep==0 ) {
  120402. sqlite3SelectDelete(db, pSelect);
  120403. return 0;
  120404. }
  120405. pTriggerStep->op = TK_SELECT;
  120406. pTriggerStep->pSelect = pSelect;
  120407. pTriggerStep->orconf = OE_Default;
  120408. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  120409. return pTriggerStep;
  120410. }
  120411. /*
  120412. ** Allocate space to hold a new trigger step. The allocated space
  120413. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  120414. **
  120415. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  120416. */
  120417. static TriggerStep *triggerStepAllocate(
  120418. sqlite3 *db, /* Database connection */
  120419. u8 op, /* Trigger opcode */
  120420. Token *pName, /* The target name */
  120421. const char *zStart, /* Start of SQL text */
  120422. const char *zEnd /* End of SQL text */
  120423. ){
  120424. TriggerStep *pTriggerStep;
  120425. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  120426. if( pTriggerStep ){
  120427. char *z = (char*)&pTriggerStep[1];
  120428. memcpy(z, pName->z, pName->n);
  120429. sqlite3Dequote(z);
  120430. pTriggerStep->zTarget = z;
  120431. pTriggerStep->op = op;
  120432. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  120433. }
  120434. return pTriggerStep;
  120435. }
  120436. /*
  120437. ** Build a trigger step out of an INSERT statement. Return a pointer
  120438. ** to the new trigger step.
  120439. **
  120440. ** The parser calls this routine when it sees an INSERT inside the
  120441. ** body of a trigger.
  120442. */
  120443. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  120444. sqlite3 *db, /* The database connection */
  120445. Token *pTableName, /* Name of the table into which we insert */
  120446. IdList *pColumn, /* List of columns in pTableName to insert into */
  120447. Select *pSelect, /* A SELECT statement that supplies values */
  120448. u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  120449. Upsert *pUpsert, /* ON CONFLICT clauses for upsert */
  120450. const char *zStart, /* Start of SQL text */
  120451. const char *zEnd /* End of SQL text */
  120452. ){
  120453. TriggerStep *pTriggerStep;
  120454. assert(pSelect != 0 || db->mallocFailed);
  120455. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName, zStart, zEnd);
  120456. if( pTriggerStep ){
  120457. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  120458. pTriggerStep->pIdList = pColumn;
  120459. pTriggerStep->pUpsert = pUpsert;
  120460. pTriggerStep->orconf = orconf;
  120461. }else{
  120462. testcase( pColumn );
  120463. sqlite3IdListDelete(db, pColumn);
  120464. testcase( pUpsert );
  120465. sqlite3UpsertDelete(db, pUpsert);
  120466. }
  120467. sqlite3SelectDelete(db, pSelect);
  120468. return pTriggerStep;
  120469. }
  120470. /*
  120471. ** Construct a trigger step that implements an UPDATE statement and return
  120472. ** a pointer to that trigger step. The parser calls this routine when it
  120473. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  120474. */
  120475. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  120476. sqlite3 *db, /* The database connection */
  120477. Token *pTableName, /* Name of the table to be updated */
  120478. ExprList *pEList, /* The SET clause: list of column and new values */
  120479. Expr *pWhere, /* The WHERE clause */
  120480. u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  120481. const char *zStart, /* Start of SQL text */
  120482. const char *zEnd /* End of SQL text */
  120483. ){
  120484. TriggerStep *pTriggerStep;
  120485. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName, zStart, zEnd);
  120486. if( pTriggerStep ){
  120487. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  120488. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  120489. pTriggerStep->orconf = orconf;
  120490. }
  120491. sqlite3ExprListDelete(db, pEList);
  120492. sqlite3ExprDelete(db, pWhere);
  120493. return pTriggerStep;
  120494. }
  120495. /*
  120496. ** Construct a trigger step that implements a DELETE statement and return
  120497. ** a pointer to that trigger step. The parser calls this routine when it
  120498. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  120499. */
  120500. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  120501. sqlite3 *db, /* Database connection */
  120502. Token *pTableName, /* The table from which rows are deleted */
  120503. Expr *pWhere, /* The WHERE clause */
  120504. const char *zStart, /* Start of SQL text */
  120505. const char *zEnd /* End of SQL text */
  120506. ){
  120507. TriggerStep *pTriggerStep;
  120508. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName, zStart, zEnd);
  120509. if( pTriggerStep ){
  120510. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  120511. pTriggerStep->orconf = OE_Default;
  120512. }
  120513. sqlite3ExprDelete(db, pWhere);
  120514. return pTriggerStep;
  120515. }
  120516. /*
  120517. ** Recursively delete a Trigger structure
  120518. */
  120519. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  120520. if( pTrigger==0 ) return;
  120521. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  120522. sqlite3DbFree(db, pTrigger->zName);
  120523. sqlite3DbFree(db, pTrigger->table);
  120524. sqlite3ExprDelete(db, pTrigger->pWhen);
  120525. sqlite3IdListDelete(db, pTrigger->pColumns);
  120526. sqlite3DbFree(db, pTrigger);
  120527. }
  120528. /*
  120529. ** This function is called to drop a trigger from the database schema.
  120530. **
  120531. ** This may be called directly from the parser and therefore identifies
  120532. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  120533. ** same job as this routine except it takes a pointer to the trigger
  120534. ** instead of the trigger name.
  120535. **/
  120536. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  120537. Trigger *pTrigger = 0;
  120538. int i;
  120539. const char *zDb;
  120540. const char *zName;
  120541. sqlite3 *db = pParse->db;
  120542. if( db->mallocFailed ) goto drop_trigger_cleanup;
  120543. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  120544. goto drop_trigger_cleanup;
  120545. }
  120546. assert( pName->nSrc==1 );
  120547. zDb = pName->a[0].zDatabase;
  120548. zName = pName->a[0].zName;
  120549. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  120550. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  120551. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  120552. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  120553. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  120554. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  120555. if( pTrigger ) break;
  120556. }
  120557. if( !pTrigger ){
  120558. if( !noErr ){
  120559. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  120560. }else{
  120561. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  120562. }
  120563. pParse->checkSchema = 1;
  120564. goto drop_trigger_cleanup;
  120565. }
  120566. sqlite3DropTriggerPtr(pParse, pTrigger);
  120567. drop_trigger_cleanup:
  120568. sqlite3SrcListDelete(db, pName);
  120569. }
  120570. /*
  120571. ** Return a pointer to the Table structure for the table that a trigger
  120572. ** is set on.
  120573. */
  120574. static Table *tableOfTrigger(Trigger *pTrigger){
  120575. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  120576. }
  120577. /*
  120578. ** Drop a trigger given a pointer to that trigger.
  120579. */
  120580. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  120581. Table *pTable;
  120582. Vdbe *v;
  120583. sqlite3 *db = pParse->db;
  120584. int iDb;
  120585. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  120586. assert( iDb>=0 && iDb<db->nDb );
  120587. pTable = tableOfTrigger(pTrigger);
  120588. assert( pTable );
  120589. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  120590. #ifndef SQLITE_OMIT_AUTHORIZATION
  120591. {
  120592. int code = SQLITE_DROP_TRIGGER;
  120593. const char *zDb = db->aDb[iDb].zDbSName;
  120594. const char *zTab = SCHEMA_TABLE(iDb);
  120595. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  120596. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  120597. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  120598. return;
  120599. }
  120600. }
  120601. #endif
  120602. /* Generate code to destroy the database record of the trigger.
  120603. */
  120604. assert( pTable!=0 );
  120605. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  120606. sqlite3NestedParse(pParse,
  120607. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  120608. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  120609. );
  120610. sqlite3ChangeCookie(pParse, iDb);
  120611. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  120612. }
  120613. }
  120614. /*
  120615. ** Remove a trigger from the hash tables of the sqlite* pointer.
  120616. */
  120617. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  120618. Trigger *pTrigger;
  120619. Hash *pHash;
  120620. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  120621. pHash = &(db->aDb[iDb].pSchema->trigHash);
  120622. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  120623. if( ALWAYS(pTrigger) ){
  120624. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  120625. Table *pTab = tableOfTrigger(pTrigger);
  120626. Trigger **pp;
  120627. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  120628. *pp = (*pp)->pNext;
  120629. }
  120630. sqlite3DeleteTrigger(db, pTrigger);
  120631. db->mDbFlags |= DBFLAG_SchemaChange;
  120632. }
  120633. }
  120634. /*
  120635. ** pEList is the SET clause of an UPDATE statement. Each entry
  120636. ** in pEList is of the format <id>=<expr>. If any of the entries
  120637. ** in pEList have an <id> which matches an identifier in pIdList,
  120638. ** then return TRUE. If pIdList==NULL, then it is considered a
  120639. ** wildcard that matches anything. Likewise if pEList==NULL then
  120640. ** it matches anything so always return true. Return false only
  120641. ** if there is no match.
  120642. */
  120643. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  120644. int e;
  120645. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  120646. for(e=0; e<pEList->nExpr; e++){
  120647. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  120648. }
  120649. return 0;
  120650. }
  120651. /*
  120652. ** Return a list of all triggers on table pTab if there exists at least
  120653. ** one trigger that must be fired when an operation of type 'op' is
  120654. ** performed on the table, and, if that operation is an UPDATE, if at
  120655. ** least one of the columns in pChanges is being modified.
  120656. */
  120657. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  120658. Parse *pParse, /* Parse context */
  120659. Table *pTab, /* The table the contains the triggers */
  120660. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  120661. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  120662. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  120663. ){
  120664. int mask = 0;
  120665. Trigger *pList = 0;
  120666. Trigger *p;
  120667. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  120668. pList = sqlite3TriggerList(pParse, pTab);
  120669. }
  120670. assert( pList==0 || IsVirtual(pTab)==0 );
  120671. for(p=pList; p; p=p->pNext){
  120672. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  120673. mask |= p->tr_tm;
  120674. }
  120675. }
  120676. if( pMask ){
  120677. *pMask = mask;
  120678. }
  120679. return (mask ? pList : 0);
  120680. }
  120681. /*
  120682. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  120683. ** to that SrcList.
  120684. **
  120685. ** This routine adds a specific database name, if needed, to the target when
  120686. ** forming the SrcList. This prevents a trigger in one database from
  120687. ** referring to a target in another database. An exception is when the
  120688. ** trigger is in TEMP in which case it can refer to any other database it
  120689. ** wants.
  120690. */
  120691. static SrcList *targetSrcList(
  120692. Parse *pParse, /* The parsing context */
  120693. TriggerStep *pStep /* The trigger containing the target token */
  120694. ){
  120695. sqlite3 *db = pParse->db;
  120696. int iDb; /* Index of the database to use */
  120697. SrcList *pSrc; /* SrcList to be returned */
  120698. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  120699. if( pSrc ){
  120700. assert( pSrc->nSrc>0 );
  120701. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  120702. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  120703. if( iDb==0 || iDb>=2 ){
  120704. const char *zDb;
  120705. assert( iDb<db->nDb );
  120706. zDb = db->aDb[iDb].zDbSName;
  120707. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  120708. }
  120709. }
  120710. return pSrc;
  120711. }
  120712. /*
  120713. ** Generate VDBE code for the statements inside the body of a single
  120714. ** trigger.
  120715. */
  120716. static int codeTriggerProgram(
  120717. Parse *pParse, /* The parser context */
  120718. TriggerStep *pStepList, /* List of statements inside the trigger body */
  120719. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  120720. ){
  120721. TriggerStep *pStep;
  120722. Vdbe *v = pParse->pVdbe;
  120723. sqlite3 *db = pParse->db;
  120724. assert( pParse->pTriggerTab && pParse->pToplevel );
  120725. assert( pStepList );
  120726. assert( v!=0 );
  120727. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  120728. /* Figure out the ON CONFLICT policy that will be used for this step
  120729. ** of the trigger program. If the statement that caused this trigger
  120730. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  120731. ** the ON CONFLICT policy that was specified as part of the trigger
  120732. ** step statement. Example:
  120733. **
  120734. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  120735. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  120736. ** END;
  120737. **
  120738. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  120739. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  120740. */
  120741. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  120742. assert( pParse->okConstFactor==0 );
  120743. #ifndef SQLITE_OMIT_TRACE
  120744. if( pStep->zSpan ){
  120745. sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
  120746. sqlite3MPrintf(db, "-- %s", pStep->zSpan),
  120747. P4_DYNAMIC);
  120748. }
  120749. #endif
  120750. switch( pStep->op ){
  120751. case TK_UPDATE: {
  120752. sqlite3Update(pParse,
  120753. targetSrcList(pParse, pStep),
  120754. sqlite3ExprListDup(db, pStep->pExprList, 0),
  120755. sqlite3ExprDup(db, pStep->pWhere, 0),
  120756. pParse->eOrconf, 0, 0, 0
  120757. );
  120758. break;
  120759. }
  120760. case TK_INSERT: {
  120761. sqlite3Insert(pParse,
  120762. targetSrcList(pParse, pStep),
  120763. sqlite3SelectDup(db, pStep->pSelect, 0),
  120764. sqlite3IdListDup(db, pStep->pIdList),
  120765. pParse->eOrconf,
  120766. sqlite3UpsertDup(db, pStep->pUpsert)
  120767. );
  120768. break;
  120769. }
  120770. case TK_DELETE: {
  120771. sqlite3DeleteFrom(pParse,
  120772. targetSrcList(pParse, pStep),
  120773. sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
  120774. );
  120775. break;
  120776. }
  120777. default: assert( pStep->op==TK_SELECT ); {
  120778. SelectDest sDest;
  120779. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  120780. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  120781. sqlite3Select(pParse, pSelect, &sDest);
  120782. sqlite3SelectDelete(db, pSelect);
  120783. break;
  120784. }
  120785. }
  120786. if( pStep->op!=TK_SELECT ){
  120787. sqlite3VdbeAddOp0(v, OP_ResetCount);
  120788. }
  120789. }
  120790. return 0;
  120791. }
  120792. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  120793. /*
  120794. ** This function is used to add VdbeComment() annotations to a VDBE
  120795. ** program. It is not used in production code, only for debugging.
  120796. */
  120797. static const char *onErrorText(int onError){
  120798. switch( onError ){
  120799. case OE_Abort: return "abort";
  120800. case OE_Rollback: return "rollback";
  120801. case OE_Fail: return "fail";
  120802. case OE_Replace: return "replace";
  120803. case OE_Ignore: return "ignore";
  120804. case OE_Default: return "default";
  120805. }
  120806. return "n/a";
  120807. }
  120808. #endif
  120809. /*
  120810. ** Parse context structure pFrom has just been used to create a sub-vdbe
  120811. ** (trigger program). If an error has occurred, transfer error information
  120812. ** from pFrom to pTo.
  120813. */
  120814. static void transferParseError(Parse *pTo, Parse *pFrom){
  120815. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  120816. assert( pTo->zErrMsg==0 || pTo->nErr );
  120817. if( pTo->nErr==0 ){
  120818. pTo->zErrMsg = pFrom->zErrMsg;
  120819. pTo->nErr = pFrom->nErr;
  120820. pTo->rc = pFrom->rc;
  120821. }else{
  120822. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  120823. }
  120824. }
  120825. /*
  120826. ** Create and populate a new TriggerPrg object with a sub-program
  120827. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  120828. */
  120829. static TriggerPrg *codeRowTrigger(
  120830. Parse *pParse, /* Current parse context */
  120831. Trigger *pTrigger, /* Trigger to code */
  120832. Table *pTab, /* The table pTrigger is attached to */
  120833. int orconf /* ON CONFLICT policy to code trigger program with */
  120834. ){
  120835. Parse *pTop = sqlite3ParseToplevel(pParse);
  120836. sqlite3 *db = pParse->db; /* Database handle */
  120837. TriggerPrg *pPrg; /* Value to return */
  120838. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  120839. Vdbe *v; /* Temporary VM */
  120840. NameContext sNC; /* Name context for sub-vdbe */
  120841. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  120842. Parse *pSubParse; /* Parse context for sub-vdbe */
  120843. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  120844. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  120845. assert( pTop->pVdbe );
  120846. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  120847. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  120848. ** list of the top-level Parse object sooner rather than later. */
  120849. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  120850. if( !pPrg ) return 0;
  120851. pPrg->pNext = pTop->pTriggerPrg;
  120852. pTop->pTriggerPrg = pPrg;
  120853. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  120854. if( !pProgram ) return 0;
  120855. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  120856. pPrg->pTrigger = pTrigger;
  120857. pPrg->orconf = orconf;
  120858. pPrg->aColmask[0] = 0xffffffff;
  120859. pPrg->aColmask[1] = 0xffffffff;
  120860. /* Allocate and populate a new Parse context to use for coding the
  120861. ** trigger sub-program. */
  120862. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  120863. if( !pSubParse ) return 0;
  120864. memset(&sNC, 0, sizeof(sNC));
  120865. sNC.pParse = pSubParse;
  120866. pSubParse->db = db;
  120867. pSubParse->pTriggerTab = pTab;
  120868. pSubParse->pToplevel = pTop;
  120869. pSubParse->zAuthContext = pTrigger->zName;
  120870. pSubParse->eTriggerOp = pTrigger->op;
  120871. pSubParse->nQueryLoop = pParse->nQueryLoop;
  120872. v = sqlite3GetVdbe(pSubParse);
  120873. if( v ){
  120874. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  120875. pTrigger->zName, onErrorText(orconf),
  120876. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  120877. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  120878. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  120879. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  120880. pTab->zName
  120881. ));
  120882. #ifndef SQLITE_OMIT_TRACE
  120883. if( pTrigger->zName ){
  120884. sqlite3VdbeChangeP4(v, -1,
  120885. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  120886. );
  120887. }
  120888. #endif
  120889. /* If one was specified, code the WHEN clause. If it evaluates to false
  120890. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  120891. ** OP_Halt inserted at the end of the program. */
  120892. if( pTrigger->pWhen ){
  120893. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  120894. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  120895. && db->mallocFailed==0
  120896. ){
  120897. iEndTrigger = sqlite3VdbeMakeLabel(v);
  120898. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  120899. }
  120900. sqlite3ExprDelete(db, pWhen);
  120901. }
  120902. /* Code the trigger program into the sub-vdbe. */
  120903. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  120904. /* Insert an OP_Halt at the end of the sub-program. */
  120905. if( iEndTrigger ){
  120906. sqlite3VdbeResolveLabel(v, iEndTrigger);
  120907. }
  120908. sqlite3VdbeAddOp0(v, OP_Halt);
  120909. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  120910. transferParseError(pParse, pSubParse);
  120911. if( db->mallocFailed==0 && pParse->nErr==0 ){
  120912. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  120913. }
  120914. pProgram->nMem = pSubParse->nMem;
  120915. pProgram->nCsr = pSubParse->nTab;
  120916. pProgram->token = (void *)pTrigger;
  120917. pPrg->aColmask[0] = pSubParse->oldmask;
  120918. pPrg->aColmask[1] = pSubParse->newmask;
  120919. sqlite3VdbeDelete(v);
  120920. }
  120921. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  120922. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  120923. sqlite3ParserReset(pSubParse);
  120924. sqlite3StackFree(db, pSubParse);
  120925. return pPrg;
  120926. }
  120927. /*
  120928. ** Return a pointer to a TriggerPrg object containing the sub-program for
  120929. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  120930. ** TriggerPrg object exists, a new object is allocated and populated before
  120931. ** being returned.
  120932. */
  120933. static TriggerPrg *getRowTrigger(
  120934. Parse *pParse, /* Current parse context */
  120935. Trigger *pTrigger, /* Trigger to code */
  120936. Table *pTab, /* The table trigger pTrigger is attached to */
  120937. int orconf /* ON CONFLICT algorithm. */
  120938. ){
  120939. Parse *pRoot = sqlite3ParseToplevel(pParse);
  120940. TriggerPrg *pPrg;
  120941. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  120942. /* It may be that this trigger has already been coded (or is in the
  120943. ** process of being coded). If this is the case, then an entry with
  120944. ** a matching TriggerPrg.pTrigger field will be present somewhere
  120945. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  120946. for(pPrg=pRoot->pTriggerPrg;
  120947. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  120948. pPrg=pPrg->pNext
  120949. );
  120950. /* If an existing TriggerPrg could not be located, create a new one. */
  120951. if( !pPrg ){
  120952. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  120953. }
  120954. return pPrg;
  120955. }
  120956. /*
  120957. ** Generate code for the trigger program associated with trigger p on
  120958. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  120959. ** function are the same as those described in the header function for
  120960. ** sqlite3CodeRowTrigger()
  120961. */
  120962. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  120963. Parse *pParse, /* Parse context */
  120964. Trigger *p, /* Trigger to code */
  120965. Table *pTab, /* The table to code triggers from */
  120966. int reg, /* Reg array containing OLD.* and NEW.* values */
  120967. int orconf, /* ON CONFLICT policy */
  120968. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  120969. ){
  120970. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  120971. TriggerPrg *pPrg;
  120972. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  120973. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  120974. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  120975. ** is a pointer to the sub-vdbe containing the trigger program. */
  120976. if( pPrg ){
  120977. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  120978. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  120979. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  120980. VdbeComment(
  120981. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  120982. /* Set the P5 operand of the OP_Program instruction to non-zero if
  120983. ** recursive invocation of this trigger program is disallowed. Recursive
  120984. ** invocation is disallowed if (a) the sub-program is really a trigger,
  120985. ** not a foreign key action, and (b) the flag to enable recursive triggers
  120986. ** is clear. */
  120987. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  120988. }
  120989. }
  120990. /*
  120991. ** This is called to code the required FOR EACH ROW triggers for an operation
  120992. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  120993. ** is given by the op parameter. The tr_tm parameter determines whether the
  120994. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  120995. ** parameter pChanges is passed the list of columns being modified.
  120996. **
  120997. ** If there are no triggers that fire at the specified time for the specified
  120998. ** operation on pTab, this function is a no-op.
  120999. **
  121000. ** The reg argument is the address of the first in an array of registers
  121001. ** that contain the values substituted for the new.* and old.* references
  121002. ** in the trigger program. If N is the number of columns in table pTab
  121003. ** (a copy of pTab->nCol), then registers are populated as follows:
  121004. **
  121005. ** Register Contains
  121006. ** ------------------------------------------------------
  121007. ** reg+0 OLD.rowid
  121008. ** reg+1 OLD.* value of left-most column of pTab
  121009. ** ... ...
  121010. ** reg+N OLD.* value of right-most column of pTab
  121011. ** reg+N+1 NEW.rowid
  121012. ** reg+N+2 OLD.* value of left-most column of pTab
  121013. ** ... ...
  121014. ** reg+N+N+1 NEW.* value of right-most column of pTab
  121015. **
  121016. ** For ON DELETE triggers, the registers containing the NEW.* values will
  121017. ** never be accessed by the trigger program, so they are not allocated or
  121018. ** populated by the caller (there is no data to populate them with anyway).
  121019. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  121020. ** are never accessed, and so are not allocated by the caller. So, for an
  121021. ** ON INSERT trigger, the value passed to this function as parameter reg
  121022. ** is not a readable register, although registers (reg+N) through
  121023. ** (reg+N+N+1) are.
  121024. **
  121025. ** Parameter orconf is the default conflict resolution algorithm for the
  121026. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  121027. ** is the instruction that control should jump to if a trigger program
  121028. ** raises an IGNORE exception.
  121029. */
  121030. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  121031. Parse *pParse, /* Parse context */
  121032. Trigger *pTrigger, /* List of triggers on table pTab */
  121033. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  121034. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  121035. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  121036. Table *pTab, /* The table to code triggers from */
  121037. int reg, /* The first in an array of registers (see above) */
  121038. int orconf, /* ON CONFLICT policy */
  121039. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  121040. ){
  121041. Trigger *p; /* Used to iterate through pTrigger list */
  121042. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  121043. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  121044. assert( (op==TK_UPDATE)==(pChanges!=0) );
  121045. for(p=pTrigger; p; p=p->pNext){
  121046. /* Sanity checking: The schema for the trigger and for the table are
  121047. ** always defined. The trigger must be in the same schema as the table
  121048. ** or else it must be a TEMP trigger. */
  121049. assert( p->pSchema!=0 );
  121050. assert( p->pTabSchema!=0 );
  121051. assert( p->pSchema==p->pTabSchema
  121052. || p->pSchema==pParse->db->aDb[1].pSchema );
  121053. /* Determine whether we should code this trigger */
  121054. if( p->op==op
  121055. && p->tr_tm==tr_tm
  121056. && checkColumnOverlap(p->pColumns, pChanges)
  121057. ){
  121058. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  121059. }
  121060. }
  121061. }
  121062. /*
  121063. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  121064. ** This function returns a 32-bit bitmask indicating which columns of the
  121065. ** old.* or new.* tables actually are used by triggers. This information
  121066. ** may be used by the caller, for example, to avoid having to load the entire
  121067. ** old.* record into memory when executing an UPDATE or DELETE command.
  121068. **
  121069. ** Bit 0 of the returned mask is set if the left-most column of the
  121070. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  121071. ** the second leftmost column value is required, and so on. If there
  121072. ** are more than 32 columns in the table, and at least one of the columns
  121073. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  121074. **
  121075. ** It is not possible to determine if the old.rowid or new.rowid column is
  121076. ** accessed by triggers. The caller must always assume that it is.
  121077. **
  121078. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  121079. ** applies to the old.* table. If 1, the new.* table.
  121080. **
  121081. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  121082. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  121083. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  121084. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  121085. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  121086. */
  121087. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  121088. Parse *pParse, /* Parse context */
  121089. Trigger *pTrigger, /* List of triggers on table pTab */
  121090. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  121091. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  121092. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  121093. Table *pTab, /* The table to code triggers from */
  121094. int orconf /* Default ON CONFLICT policy for trigger steps */
  121095. ){
  121096. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  121097. u32 mask = 0;
  121098. Trigger *p;
  121099. assert( isNew==1 || isNew==0 );
  121100. for(p=pTrigger; p; p=p->pNext){
  121101. if( p->op==op && (tr_tm&p->tr_tm)
  121102. && checkColumnOverlap(p->pColumns,pChanges)
  121103. ){
  121104. TriggerPrg *pPrg;
  121105. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  121106. if( pPrg ){
  121107. mask |= pPrg->aColmask[isNew];
  121108. }
  121109. }
  121110. }
  121111. return mask;
  121112. }
  121113. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  121114. /************** End of trigger.c *********************************************/
  121115. /************** Begin file update.c ******************************************/
  121116. /*
  121117. ** 2001 September 15
  121118. **
  121119. ** The author disclaims copyright to this source code. In place of
  121120. ** a legal notice, here is a blessing:
  121121. **
  121122. ** May you do good and not evil.
  121123. ** May you find forgiveness for yourself and forgive others.
  121124. ** May you share freely, never taking more than you give.
  121125. **
  121126. *************************************************************************
  121127. ** This file contains C code routines that are called by the parser
  121128. ** to handle UPDATE statements.
  121129. */
  121130. /* #include "sqliteInt.h" */
  121131. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121132. /* Forward declaration */
  121133. static void updateVirtualTable(
  121134. Parse *pParse, /* The parsing context */
  121135. SrcList *pSrc, /* The virtual table to be modified */
  121136. Table *pTab, /* The virtual table */
  121137. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  121138. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  121139. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  121140. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  121141. int onError /* ON CONFLICT strategy */
  121142. );
  121143. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  121144. /*
  121145. ** The most recently coded instruction was an OP_Column to retrieve the
  121146. ** i-th column of table pTab. This routine sets the P4 parameter of the
  121147. ** OP_Column to the default value, if any.
  121148. **
  121149. ** The default value of a column is specified by a DEFAULT clause in the
  121150. ** column definition. This was either supplied by the user when the table
  121151. ** was created, or added later to the table definition by an ALTER TABLE
  121152. ** command. If the latter, then the row-records in the table btree on disk
  121153. ** may not contain a value for the column and the default value, taken
  121154. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  121155. ** If the former, then all row-records are guaranteed to include a value
  121156. ** for the column and the P4 value is not required.
  121157. **
  121158. ** Column definitions created by an ALTER TABLE command may only have
  121159. ** literal default values specified: a number, null or a string. (If a more
  121160. ** complicated default expression value was provided, it is evaluated
  121161. ** when the ALTER TABLE is executed and one of the literal values written
  121162. ** into the sqlite_master table.)
  121163. **
  121164. ** Therefore, the P4 parameter is only required if the default value for
  121165. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  121166. ** function is capable of transforming these types of expressions into
  121167. ** sqlite3_value objects.
  121168. **
  121169. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  121170. ** on register iReg. This is used when an equivalent integer value is
  121171. ** stored in place of an 8-byte floating point value in order to save
  121172. ** space.
  121173. */
  121174. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  121175. assert( pTab!=0 );
  121176. if( !pTab->pSelect ){
  121177. sqlite3_value *pValue = 0;
  121178. u8 enc = ENC(sqlite3VdbeDb(v));
  121179. Column *pCol = &pTab->aCol[i];
  121180. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  121181. assert( i<pTab->nCol );
  121182. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  121183. pCol->affinity, &pValue);
  121184. if( pValue ){
  121185. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  121186. }
  121187. }
  121188. #ifndef SQLITE_OMIT_FLOATING_POINT
  121189. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  121190. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  121191. }
  121192. #endif
  121193. }
  121194. /*
  121195. ** Process an UPDATE statement.
  121196. **
  121197. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  121198. ** \_______/ \________/ \______/ \________________/
  121199. * onError pTabList pChanges pWhere
  121200. */
  121201. SQLITE_PRIVATE void sqlite3Update(
  121202. Parse *pParse, /* The parser context */
  121203. SrcList *pTabList, /* The table in which we should change things */
  121204. ExprList *pChanges, /* Things to be changed */
  121205. Expr *pWhere, /* The WHERE clause. May be null */
  121206. int onError, /* How to handle constraint errors */
  121207. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  121208. Expr *pLimit, /* LIMIT clause. May be null */
  121209. Upsert *pUpsert /* ON CONFLICT clause, or null */
  121210. ){
  121211. int i, j; /* Loop counters */
  121212. Table *pTab; /* The table to be updated */
  121213. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  121214. WhereInfo *pWInfo; /* Information about the WHERE clause */
  121215. Vdbe *v; /* The virtual database engine */
  121216. Index *pIdx; /* For looping over indices */
  121217. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  121218. int nIdx; /* Number of indices that need updating */
  121219. int iBaseCur; /* Base cursor number */
  121220. int iDataCur; /* Cursor for the canonical data btree */
  121221. int iIdxCur; /* Cursor for the first index */
  121222. sqlite3 *db; /* The database structure */
  121223. int *aRegIdx = 0; /* First register in array assigned to each index */
  121224. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  121225. ** an expression for the i-th column of the table.
  121226. ** aXRef[i]==-1 if the i-th column is not changed. */
  121227. u8 *aToOpen; /* 1 for tables and indices to be opened */
  121228. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  121229. u8 chngRowid; /* Rowid changed in a normal table */
  121230. u8 chngKey; /* Either chngPk or chngRowid */
  121231. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  121232. AuthContext sContext; /* The authorization context */
  121233. NameContext sNC; /* The name-context to resolve expressions in */
  121234. int iDb; /* Database containing the table being updated */
  121235. int eOnePass; /* ONEPASS_XXX value from where.c */
  121236. int hasFK; /* True if foreign key processing is required */
  121237. int labelBreak; /* Jump here to break out of UPDATE loop */
  121238. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  121239. int flags; /* Flags for sqlite3WhereBegin() */
  121240. #ifndef SQLITE_OMIT_TRIGGER
  121241. int isView; /* True when updating a view (INSTEAD OF trigger) */
  121242. Trigger *pTrigger; /* List of triggers on pTab, if required */
  121243. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  121244. #endif
  121245. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  121246. int iEph = 0; /* Ephemeral table holding all primary key values */
  121247. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  121248. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  121249. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  121250. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  121251. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  121252. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  121253. /* Register Allocations */
  121254. int regRowCount = 0; /* A count of rows changed */
  121255. int regOldRowid = 0; /* The old rowid */
  121256. int regNewRowid = 0; /* The new rowid */
  121257. int regNew = 0; /* Content of the NEW.* table in triggers */
  121258. int regOld = 0; /* Content of OLD.* table in triggers */
  121259. int regRowSet = 0; /* Rowset of rows to be updated */
  121260. int regKey = 0; /* composite PRIMARY KEY value */
  121261. memset(&sContext, 0, sizeof(sContext));
  121262. db = pParse->db;
  121263. if( pParse->nErr || db->mallocFailed ){
  121264. goto update_cleanup;
  121265. }
  121266. assert( pTabList->nSrc==1 );
  121267. /* Locate the table which we want to update.
  121268. */
  121269. pTab = sqlite3SrcListLookup(pParse, pTabList);
  121270. if( pTab==0 ) goto update_cleanup;
  121271. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  121272. /* Figure out if we have any triggers and if the table being
  121273. ** updated is a view.
  121274. */
  121275. #ifndef SQLITE_OMIT_TRIGGER
  121276. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  121277. isView = pTab->pSelect!=0;
  121278. assert( pTrigger || tmask==0 );
  121279. #else
  121280. # define pTrigger 0
  121281. # define isView 0
  121282. # define tmask 0
  121283. #endif
  121284. #ifdef SQLITE_OMIT_VIEW
  121285. # undef isView
  121286. # define isView 0
  121287. #endif
  121288. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  121289. if( !isView ){
  121290. pWhere = sqlite3LimitWhere(
  121291. pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
  121292. );
  121293. pOrderBy = 0;
  121294. pLimit = 0;
  121295. }
  121296. #endif
  121297. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  121298. goto update_cleanup;
  121299. }
  121300. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  121301. goto update_cleanup;
  121302. }
  121303. /* Allocate a cursors for the main database table and for all indices.
  121304. ** The index cursors might not be used, but if they are used they
  121305. ** need to occur right after the database cursor. So go ahead and
  121306. ** allocate enough space, just in case.
  121307. */
  121308. iBaseCur = iDataCur = pParse->nTab++;
  121309. iIdxCur = iDataCur+1;
  121310. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  121311. testcase( pPk!=0 && pPk!=pTab->pIndex );
  121312. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  121313. if( pPk==pIdx ){
  121314. iDataCur = pParse->nTab;
  121315. }
  121316. pParse->nTab++;
  121317. }
  121318. if( pUpsert ){
  121319. /* On an UPSERT, reuse the same cursors already opened by INSERT */
  121320. iDataCur = pUpsert->iDataCur;
  121321. iIdxCur = pUpsert->iIdxCur;
  121322. pParse->nTab = iBaseCur;
  121323. }
  121324. pTabList->a[0].iCursor = iDataCur;
  121325. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  121326. ** Initialize aXRef[] and aToOpen[] to their default values.
  121327. */
  121328. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  121329. if( aXRef==0 ) goto update_cleanup;
  121330. aRegIdx = aXRef+pTab->nCol;
  121331. aToOpen = (u8*)(aRegIdx+nIdx);
  121332. memset(aToOpen, 1, nIdx+1);
  121333. aToOpen[nIdx+1] = 0;
  121334. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  121335. /* Initialize the name-context */
  121336. memset(&sNC, 0, sizeof(sNC));
  121337. sNC.pParse = pParse;
  121338. sNC.pSrcList = pTabList;
  121339. sNC.uNC.pUpsert = pUpsert;
  121340. sNC.ncFlags = NC_UUpsert;
  121341. /* Resolve the column names in all the expressions of the
  121342. ** of the UPDATE statement. Also find the column index
  121343. ** for each column to be updated in the pChanges array. For each
  121344. ** column to be updated, make sure we have authorization to change
  121345. ** that column.
  121346. */
  121347. chngRowid = chngPk = 0;
  121348. for(i=0; i<pChanges->nExpr; i++){
  121349. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  121350. goto update_cleanup;
  121351. }
  121352. for(j=0; j<pTab->nCol; j++){
  121353. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  121354. if( j==pTab->iPKey ){
  121355. chngRowid = 1;
  121356. pRowidExpr = pChanges->a[i].pExpr;
  121357. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  121358. chngPk = 1;
  121359. }
  121360. aXRef[j] = i;
  121361. break;
  121362. }
  121363. }
  121364. if( j>=pTab->nCol ){
  121365. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  121366. j = -1;
  121367. chngRowid = 1;
  121368. pRowidExpr = pChanges->a[i].pExpr;
  121369. }else{
  121370. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  121371. pParse->checkSchema = 1;
  121372. goto update_cleanup;
  121373. }
  121374. }
  121375. #ifndef SQLITE_OMIT_AUTHORIZATION
  121376. {
  121377. int rc;
  121378. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  121379. j<0 ? "ROWID" : pTab->aCol[j].zName,
  121380. db->aDb[iDb].zDbSName);
  121381. if( rc==SQLITE_DENY ){
  121382. goto update_cleanup;
  121383. }else if( rc==SQLITE_IGNORE ){
  121384. aXRef[j] = -1;
  121385. }
  121386. }
  121387. #endif
  121388. }
  121389. assert( (chngRowid & chngPk)==0 );
  121390. assert( chngRowid==0 || chngRowid==1 );
  121391. assert( chngPk==0 || chngPk==1 );
  121392. chngKey = chngRowid + chngPk;
  121393. /* The SET expressions are not actually used inside the WHERE loop.
  121394. ** So reset the colUsed mask. Unless this is a virtual table. In that
  121395. ** case, set all bits of the colUsed mask (to ensure that the virtual
  121396. ** table implementation makes all columns available).
  121397. */
  121398. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  121399. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  121400. /* There is one entry in the aRegIdx[] array for each index on the table
  121401. ** being updated. Fill in aRegIdx[] with a register number that will hold
  121402. ** the key for accessing each index.
  121403. **
  121404. ** FIXME: Be smarter about omitting indexes that use expressions.
  121405. */
  121406. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  121407. int reg;
  121408. if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
  121409. reg = ++pParse->nMem;
  121410. pParse->nMem += pIdx->nColumn;
  121411. }else{
  121412. reg = 0;
  121413. for(i=0; i<pIdx->nKeyCol; i++){
  121414. i16 iIdxCol = pIdx->aiColumn[i];
  121415. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  121416. reg = ++pParse->nMem;
  121417. pParse->nMem += pIdx->nColumn;
  121418. if( (onError==OE_Replace)
  121419. || (onError==OE_Default && pIdx->onError==OE_Replace)
  121420. ){
  121421. bReplace = 1;
  121422. }
  121423. break;
  121424. }
  121425. }
  121426. }
  121427. if( reg==0 ) aToOpen[j+1] = 0;
  121428. aRegIdx[j] = reg;
  121429. }
  121430. if( bReplace ){
  121431. /* If REPLACE conflict resolution might be invoked, open cursors on all
  121432. ** indexes in case they are needed to delete records. */
  121433. memset(aToOpen, 1, nIdx+1);
  121434. }
  121435. /* Begin generating code. */
  121436. v = sqlite3GetVdbe(pParse);
  121437. if( v==0 ) goto update_cleanup;
  121438. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  121439. sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
  121440. /* Allocate required registers. */
  121441. if( !IsVirtual(pTab) ){
  121442. regRowSet = ++pParse->nMem;
  121443. regOldRowid = regNewRowid = ++pParse->nMem;
  121444. if( chngPk || pTrigger || hasFK ){
  121445. regOld = pParse->nMem + 1;
  121446. pParse->nMem += pTab->nCol;
  121447. }
  121448. if( chngKey || pTrigger || hasFK ){
  121449. regNewRowid = ++pParse->nMem;
  121450. }
  121451. regNew = pParse->nMem + 1;
  121452. pParse->nMem += pTab->nCol;
  121453. }
  121454. /* Start the view context. */
  121455. if( isView ){
  121456. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  121457. }
  121458. /* If we are trying to update a view, realize that view into
  121459. ** an ephemeral table.
  121460. */
  121461. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  121462. if( isView ){
  121463. sqlite3MaterializeView(pParse, pTab,
  121464. pWhere, pOrderBy, pLimit, iDataCur
  121465. );
  121466. pOrderBy = 0;
  121467. pLimit = 0;
  121468. }
  121469. #endif
  121470. /* Resolve the column names in all the expressions in the
  121471. ** WHERE clause.
  121472. */
  121473. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  121474. goto update_cleanup;
  121475. }
  121476. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121477. /* Virtual tables must be handled separately */
  121478. if( IsVirtual(pTab) ){
  121479. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  121480. pWhere, onError);
  121481. goto update_cleanup;
  121482. }
  121483. #endif
  121484. /* Jump to labelBreak to abandon further processing of this UPDATE */
  121485. labelContinue = labelBreak = sqlite3VdbeMakeLabel(v);
  121486. /* Not an UPSERT. Normal processing. Begin by
  121487. ** initialize the count of updated rows */
  121488. if( (db->flags&SQLITE_CountRows)!=0
  121489. && !pParse->pTriggerTab
  121490. && !pParse->nested
  121491. && pUpsert==0
  121492. ){
  121493. regRowCount = ++pParse->nMem;
  121494. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  121495. }
  121496. if( HasRowid(pTab) ){
  121497. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  121498. }else{
  121499. assert( pPk!=0 );
  121500. nPk = pPk->nKeyCol;
  121501. iPk = pParse->nMem+1;
  121502. pParse->nMem += nPk;
  121503. regKey = ++pParse->nMem;
  121504. if( pUpsert==0 ){
  121505. iEph = pParse->nTab++;
  121506. sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
  121507. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  121508. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  121509. }
  121510. }
  121511. if( pUpsert ){
  121512. /* If this is an UPSERT, then all cursors have already been opened by
  121513. ** the outer INSERT and the data cursor should be pointing at the row
  121514. ** that is to be updated. So bypass the code that searches for the
  121515. ** row(s) to be updated.
  121516. */
  121517. pWInfo = 0;
  121518. eOnePass = ONEPASS_SINGLE;
  121519. sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
  121520. }else{
  121521. /* Begin the database scan.
  121522. **
  121523. ** Do not consider a single-pass strategy for a multi-row update if
  121524. ** there are any triggers or foreign keys to process, or rows may
  121525. ** be deleted as a result of REPLACE conflict handling. Any of these
  121526. ** things might disturb a cursor being used to scan through the table
  121527. ** or index, causing a single-pass approach to malfunction. */
  121528. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  121529. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  121530. flags |= WHERE_ONEPASS_MULTIROW;
  121531. }
  121532. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  121533. if( pWInfo==0 ) goto update_cleanup;
  121534. /* A one-pass strategy that might update more than one row may not
  121535. ** be used if any column of the index used for the scan is being
  121536. ** updated. Otherwise, if there is an index on "b", statements like
  121537. ** the following could create an infinite loop:
  121538. **
  121539. ** UPDATE t1 SET b=b+1 WHERE b>?
  121540. **
  121541. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  121542. ** strategy that uses an index for which one or more columns are being
  121543. ** updated. */
  121544. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  121545. if( eOnePass!=ONEPASS_SINGLE ){
  121546. sqlite3MultiWrite(pParse);
  121547. if( eOnePass==ONEPASS_MULTI ){
  121548. int iCur = aiCurOnePass[1];
  121549. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  121550. eOnePass = ONEPASS_OFF;
  121551. }
  121552. assert( iCur!=iDataCur || !HasRowid(pTab) );
  121553. }
  121554. }
  121555. }
  121556. if( HasRowid(pTab) ){
  121557. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  121558. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  121559. ** leave it in register regOldRowid. */
  121560. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  121561. if( eOnePass==ONEPASS_OFF ){
  121562. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  121563. }
  121564. }else{
  121565. /* Read the PK of the current row into an array of registers. In
  121566. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  121567. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  121568. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  121569. ** is not required) and leave the PK fields in the array of registers. */
  121570. for(i=0; i<nPk; i++){
  121571. assert( pPk->aiColumn[i]>=0 );
  121572. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  121573. }
  121574. if( eOnePass ){
  121575. if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
  121576. nKey = nPk;
  121577. regKey = iPk;
  121578. }else{
  121579. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  121580. sqlite3IndexAffinityStr(db, pPk), nPk);
  121581. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  121582. }
  121583. }
  121584. if( pUpsert==0 ){
  121585. if( eOnePass!=ONEPASS_MULTI ){
  121586. sqlite3WhereEnd(pWInfo);
  121587. }
  121588. if( !isView ){
  121589. int addrOnce = 0;
  121590. /* Open every index that needs updating. */
  121591. if( eOnePass!=ONEPASS_OFF ){
  121592. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  121593. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  121594. }
  121595. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  121596. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  121597. }
  121598. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
  121599. aToOpen, 0, 0);
  121600. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  121601. }
  121602. /* Top of the update loop */
  121603. if( eOnePass!=ONEPASS_OFF ){
  121604. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  121605. assert( pPk );
  121606. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
  121607. VdbeCoverageNeverTaken(v);
  121608. }
  121609. if( eOnePass!=ONEPASS_SINGLE ){
  121610. labelContinue = sqlite3VdbeMakeLabel(v);
  121611. }
  121612. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  121613. VdbeCoverageIf(v, pPk==0);
  121614. VdbeCoverageIf(v, pPk!=0);
  121615. }else if( pPk ){
  121616. labelContinue = sqlite3VdbeMakeLabel(v);
  121617. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  121618. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  121619. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  121620. VdbeCoverage(v);
  121621. }else{
  121622. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
  121623. regOldRowid);
  121624. VdbeCoverage(v);
  121625. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  121626. VdbeCoverage(v);
  121627. }
  121628. }
  121629. /* If the rowid value will change, set register regNewRowid to
  121630. ** contain the new value. If the rowid is not being modified,
  121631. ** then regNewRowid is the same register as regOldRowid, which is
  121632. ** already populated. */
  121633. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  121634. if( chngRowid ){
  121635. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  121636. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  121637. }
  121638. /* Compute the old pre-UPDATE content of the row being changed, if that
  121639. ** information is needed */
  121640. if( chngPk || hasFK || pTrigger ){
  121641. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  121642. oldmask |= sqlite3TriggerColmask(pParse,
  121643. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  121644. );
  121645. for(i=0; i<pTab->nCol; i++){
  121646. if( oldmask==0xffffffff
  121647. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  121648. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  121649. ){
  121650. testcase( oldmask!=0xffffffff && i==31 );
  121651. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  121652. }else{
  121653. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  121654. }
  121655. }
  121656. if( chngRowid==0 && pPk==0 ){
  121657. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  121658. }
  121659. }
  121660. /* Populate the array of registers beginning at regNew with the new
  121661. ** row data. This array is used to check constants, create the new
  121662. ** table and index records, and as the values for any new.* references
  121663. ** made by triggers.
  121664. **
  121665. ** If there are one or more BEFORE triggers, then do not populate the
  121666. ** registers associated with columns that are (a) not modified by
  121667. ** this UPDATE statement and (b) not accessed by new.* references. The
  121668. ** values for registers not modified by the UPDATE must be reloaded from
  121669. ** the database after the BEFORE triggers are fired anyway (as the trigger
  121670. ** may have modified them). So not loading those that are not going to
  121671. ** be used eliminates some redundant opcodes.
  121672. */
  121673. newmask = sqlite3TriggerColmask(
  121674. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  121675. );
  121676. for(i=0; i<pTab->nCol; i++){
  121677. if( i==pTab->iPKey ){
  121678. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  121679. }else{
  121680. j = aXRef[i];
  121681. if( j>=0 ){
  121682. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  121683. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  121684. /* This branch loads the value of a column that will not be changed
  121685. ** into a register. This is done if there are no BEFORE triggers, or
  121686. ** if there are one or more BEFORE triggers that use this value via
  121687. ** a new.* reference in a trigger program.
  121688. */
  121689. testcase( i==31 );
  121690. testcase( i==32 );
  121691. sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
  121692. if( tmask & TRIGGER_BEFORE ){
  121693. /* This value will be recomputed in After-BEFORE-trigger-reload-loop
  121694. ** below, so make sure that it is not cached and reused.
  121695. ** Ticket d85fffd6ffe856092ed8daefa811b1e399706b28. */
  121696. sqlite3ExprCacheRemove(pParse, regNew+i, 1);
  121697. }
  121698. }else{
  121699. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  121700. }
  121701. }
  121702. }
  121703. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  121704. ** verified. One could argue that this is wrong.
  121705. */
  121706. if( tmask&TRIGGER_BEFORE ){
  121707. sqlite3TableAffinity(v, pTab, regNew);
  121708. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  121709. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  121710. /* The row-trigger may have deleted the row being updated. In this
  121711. ** case, jump to the next row. No updates or AFTER triggers are
  121712. ** required. This behavior - what happens when the row being updated
  121713. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  121714. ** documentation.
  121715. */
  121716. if( pPk ){
  121717. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  121718. VdbeCoverage(v);
  121719. }else{
  121720. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  121721. VdbeCoverage(v);
  121722. }
  121723. /* After-BEFORE-trigger-reload-loop:
  121724. ** If it did not delete it, the BEFORE trigger may still have modified
  121725. ** some of the columns of the row being updated. Load the values for
  121726. ** all columns not modified by the update statement into their registers
  121727. ** in case this has happened. Only unmodified columns are reloaded.
  121728. ** The values computed for modified columns use the values before the
  121729. ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
  121730. ** for an example.
  121731. */
  121732. for(i=0; i<pTab->nCol; i++){
  121733. if( aXRef[i]<0 && i!=pTab->iPKey ){
  121734. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  121735. }
  121736. }
  121737. }
  121738. if( !isView ){
  121739. int addr1 = 0; /* Address of jump instruction */
  121740. /* Do constraint checks. */
  121741. assert( regOldRowid>0 );
  121742. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  121743. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  121744. aXRef, 0);
  121745. /* Do FK constraint checks. */
  121746. if( hasFK ){
  121747. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  121748. }
  121749. /* Delete the index entries associated with the current record. */
  121750. if( bReplace || chngKey ){
  121751. if( pPk ){
  121752. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  121753. }else{
  121754. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  121755. }
  121756. VdbeCoverageNeverTaken(v);
  121757. }
  121758. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  121759. /* If changing the rowid value, or if there are foreign key constraints
  121760. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  121761. ** to invoke the pre-update hook.
  121762. **
  121763. ** That (regNew==regnewRowid+1) is true is also important for the
  121764. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  121765. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  121766. ** is the column index supplied by the user.
  121767. */
  121768. assert( regNew==regNewRowid+1 );
  121769. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  121770. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  121771. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  121772. regNewRowid
  121773. );
  121774. if( eOnePass==ONEPASS_MULTI ){
  121775. assert( hasFK==0 && chngKey==0 );
  121776. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  121777. }
  121778. if( !pParse->nested ){
  121779. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  121780. }
  121781. #else
  121782. if( hasFK>1 || chngKey ){
  121783. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  121784. }
  121785. #endif
  121786. if( bReplace || chngKey ){
  121787. sqlite3VdbeJumpHere(v, addr1);
  121788. }
  121789. if( hasFK ){
  121790. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  121791. }
  121792. /* Insert the new index entries and the new record. */
  121793. sqlite3CompleteInsertion(
  121794. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  121795. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  121796. 0, 0
  121797. );
  121798. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  121799. ** handle rows (possibly in other tables) that refer via a foreign key
  121800. ** to the row just updated. */
  121801. if( hasFK ){
  121802. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  121803. }
  121804. }
  121805. /* Increment the row counter
  121806. */
  121807. if( regRowCount ){
  121808. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  121809. }
  121810. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  121811. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  121812. /* Repeat the above with the next record to be updated, until
  121813. ** all record selected by the WHERE clause have been updated.
  121814. */
  121815. if( eOnePass==ONEPASS_SINGLE ){
  121816. /* Nothing to do at end-of-loop for a single-pass */
  121817. }else if( eOnePass==ONEPASS_MULTI ){
  121818. sqlite3VdbeResolveLabel(v, labelContinue);
  121819. sqlite3WhereEnd(pWInfo);
  121820. }else if( pPk ){
  121821. sqlite3VdbeResolveLabel(v, labelContinue);
  121822. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  121823. }else{
  121824. sqlite3VdbeGoto(v, labelContinue);
  121825. }
  121826. sqlite3VdbeResolveLabel(v, labelBreak);
  121827. /* Update the sqlite_sequence table by storing the content of the
  121828. ** maximum rowid counter values recorded while inserting into
  121829. ** autoincrement tables.
  121830. */
  121831. if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
  121832. sqlite3AutoincrementEnd(pParse);
  121833. }
  121834. /*
  121835. ** Return the number of rows that were changed, if we are tracking
  121836. ** that information.
  121837. */
  121838. if( regRowCount ){
  121839. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  121840. sqlite3VdbeSetNumCols(v, 1);
  121841. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  121842. }
  121843. update_cleanup:
  121844. sqlite3AuthContextPop(&sContext);
  121845. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  121846. sqlite3SrcListDelete(db, pTabList);
  121847. sqlite3ExprListDelete(db, pChanges);
  121848. sqlite3ExprDelete(db, pWhere);
  121849. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  121850. sqlite3ExprListDelete(db, pOrderBy);
  121851. sqlite3ExprDelete(db, pLimit);
  121852. #endif
  121853. return;
  121854. }
  121855. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  121856. ** they may interfere with compilation of other functions in this file
  121857. ** (or in another file, if this file becomes part of the amalgamation). */
  121858. #ifdef isView
  121859. #undef isView
  121860. #endif
  121861. #ifdef pTrigger
  121862. #undef pTrigger
  121863. #endif
  121864. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121865. /*
  121866. ** Generate code for an UPDATE of a virtual table.
  121867. **
  121868. ** There are two possible strategies - the default and the special
  121869. ** "onepass" strategy. Onepass is only used if the virtual table
  121870. ** implementation indicates that pWhere may match at most one row.
  121871. **
  121872. ** The default strategy is to create an ephemeral table that contains
  121873. ** for each row to be changed:
  121874. **
  121875. ** (A) The original rowid of that row.
  121876. ** (B) The revised rowid for the row.
  121877. ** (C) The content of every column in the row.
  121878. **
  121879. ** Then loop through the contents of this ephemeral table executing a
  121880. ** VUpdate for each row. When finished, drop the ephemeral table.
  121881. **
  121882. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  121883. ** stores the same values (A, B and C above) in a register array and
  121884. ** makes a single invocation of VUpdate.
  121885. */
  121886. static void updateVirtualTable(
  121887. Parse *pParse, /* The parsing context */
  121888. SrcList *pSrc, /* The virtual table to be modified */
  121889. Table *pTab, /* The virtual table */
  121890. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  121891. Expr *pRowid, /* Expression used to recompute the rowid */
  121892. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  121893. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  121894. int onError /* ON CONFLICT strategy */
  121895. ){
  121896. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  121897. int ephemTab; /* Table holding the result of the SELECT */
  121898. int i; /* Loop counter */
  121899. sqlite3 *db = pParse->db; /* Database connection */
  121900. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  121901. WhereInfo *pWInfo;
  121902. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  121903. int regArg; /* First register in VUpdate arg array */
  121904. int regRec; /* Register in which to assemble record */
  121905. int regRowid; /* Register for ephem table rowid */
  121906. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  121907. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  121908. int eOnePass; /* True to use onepass strategy */
  121909. int addr; /* Address of OP_OpenEphemeral */
  121910. /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
  121911. ** create and open the ephemeral table in which the records created from
  121912. ** these arguments will be temporarily stored. */
  121913. assert( v );
  121914. ephemTab = pParse->nTab++;
  121915. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  121916. regArg = pParse->nMem + 1;
  121917. pParse->nMem += nArg;
  121918. regRec = ++pParse->nMem;
  121919. regRowid = ++pParse->nMem;
  121920. /* Start scanning the virtual table */
  121921. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  121922. if( pWInfo==0 ) return;
  121923. /* Populate the argument registers. */
  121924. for(i=0; i<pTab->nCol; i++){
  121925. if( aXRef[i]>=0 ){
  121926. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  121927. }else{
  121928. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  121929. sqlite3VdbeChangeP5(v, 1); /* Enable sqlite3_vtab_nochange() */
  121930. }
  121931. }
  121932. if( HasRowid(pTab) ){
  121933. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  121934. if( pRowid ){
  121935. sqlite3ExprCode(pParse, pRowid, regArg+1);
  121936. }else{
  121937. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  121938. }
  121939. }else{
  121940. Index *pPk; /* PRIMARY KEY index */
  121941. i16 iPk; /* PRIMARY KEY column */
  121942. pPk = sqlite3PrimaryKeyIndex(pTab);
  121943. assert( pPk!=0 );
  121944. assert( pPk->nKeyCol==1 );
  121945. iPk = pPk->aiColumn[0];
  121946. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
  121947. sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
  121948. }
  121949. eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  121950. /* There is no ONEPASS_MULTI on virtual tables */
  121951. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  121952. if( eOnePass ){
  121953. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  121954. ** above. */
  121955. sqlite3VdbeChangeToNoop(v, addr);
  121956. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  121957. }else{
  121958. /* Create a record from the argument register contents and insert it into
  121959. ** the ephemeral table. */
  121960. sqlite3MultiWrite(pParse);
  121961. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  121962. #ifdef SQLITE_DEBUG
  121963. /* Signal an assert() within OP_MakeRecord that it is allowed to
  121964. ** accept no-change records with serial_type 10 */
  121965. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
  121966. #endif
  121967. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  121968. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  121969. }
  121970. if( eOnePass==ONEPASS_OFF ){
  121971. /* End the virtual table scan */
  121972. sqlite3WhereEnd(pWInfo);
  121973. /* Begin scannning through the ephemeral table. */
  121974. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  121975. /* Extract arguments from the current row of the ephemeral table and
  121976. ** invoke the VUpdate method. */
  121977. for(i=0; i<nArg; i++){
  121978. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  121979. }
  121980. }
  121981. sqlite3VtabMakeWritable(pParse, pTab);
  121982. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  121983. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  121984. sqlite3MayAbort(pParse);
  121985. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  121986. ** jump to here if the scan visited zero rows. */
  121987. if( eOnePass==ONEPASS_OFF ){
  121988. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  121989. sqlite3VdbeJumpHere(v, addr);
  121990. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  121991. }else{
  121992. sqlite3WhereEnd(pWInfo);
  121993. }
  121994. }
  121995. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  121996. /************** End of update.c **********************************************/
  121997. /************** Begin file upsert.c ******************************************/
  121998. /*
  121999. ** 2018-04-12
  122000. **
  122001. ** The author disclaims copyright to this source code. In place of
  122002. ** a legal notice, here is a blessing:
  122003. **
  122004. ** May you do good and not evil.
  122005. ** May you find forgiveness for yourself and forgive others.
  122006. ** May you share freely, never taking more than you give.
  122007. **
  122008. *************************************************************************
  122009. ** This file contains code to implement various aspects of UPSERT
  122010. ** processing and handling of the Upsert object.
  122011. */
  122012. /* #include "sqliteInt.h" */
  122013. #ifndef SQLITE_OMIT_UPSERT
  122014. /*
  122015. ** Free a list of Upsert objects
  122016. */
  122017. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
  122018. if( p ){
  122019. sqlite3ExprListDelete(db, p->pUpsertTarget);
  122020. sqlite3ExprDelete(db, p->pUpsertTargetWhere);
  122021. sqlite3ExprListDelete(db, p->pUpsertSet);
  122022. sqlite3ExprDelete(db, p->pUpsertWhere);
  122023. sqlite3DbFree(db, p);
  122024. }
  122025. }
  122026. /*
  122027. ** Duplicate an Upsert object.
  122028. */
  122029. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
  122030. if( p==0 ) return 0;
  122031. return sqlite3UpsertNew(db,
  122032. sqlite3ExprListDup(db, p->pUpsertTarget, 0),
  122033. sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
  122034. sqlite3ExprListDup(db, p->pUpsertSet, 0),
  122035. sqlite3ExprDup(db, p->pUpsertWhere, 0)
  122036. );
  122037. }
  122038. /*
  122039. ** Create a new Upsert object.
  122040. */
  122041. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
  122042. sqlite3 *db, /* Determines which memory allocator to use */
  122043. ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */
  122044. Expr *pTargetWhere, /* Optional WHERE clause on the target */
  122045. ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */
  122046. Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */
  122047. ){
  122048. Upsert *pNew;
  122049. pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
  122050. if( pNew==0 ){
  122051. sqlite3ExprListDelete(db, pTarget);
  122052. sqlite3ExprDelete(db, pTargetWhere);
  122053. sqlite3ExprListDelete(db, pSet);
  122054. sqlite3ExprDelete(db, pWhere);
  122055. return 0;
  122056. }else{
  122057. pNew->pUpsertTarget = pTarget;
  122058. pNew->pUpsertTargetWhere = pTargetWhere;
  122059. pNew->pUpsertSet = pSet;
  122060. pNew->pUpsertWhere = pWhere;
  122061. pNew->pUpsertIdx = 0;
  122062. }
  122063. return pNew;
  122064. }
  122065. /*
  122066. ** Analyze the ON CONFLICT clause described by pUpsert. Resolve all
  122067. ** symbols in the conflict-target.
  122068. **
  122069. ** Return SQLITE_OK if everything works, or an error code is something
  122070. ** is wrong.
  122071. */
  122072. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
  122073. Parse *pParse, /* The parsing context */
  122074. SrcList *pTabList, /* Table into which we are inserting */
  122075. Upsert *pUpsert /* The ON CONFLICT clauses */
  122076. ){
  122077. Table *pTab; /* That table into which we are inserting */
  122078. int rc; /* Result code */
  122079. int iCursor; /* Cursor used by pTab */
  122080. Index *pIdx; /* One of the indexes of pTab */
  122081. ExprList *pTarget; /* The conflict-target clause */
  122082. Expr *pTerm; /* One term of the conflict-target clause */
  122083. NameContext sNC; /* Context for resolving symbolic names */
  122084. Expr sCol[2]; /* Index column converted into an Expr */
  122085. assert( pTabList->nSrc==1 );
  122086. assert( pTabList->a[0].pTab!=0 );
  122087. assert( pUpsert!=0 );
  122088. assert( pUpsert->pUpsertTarget!=0 );
  122089. /* Resolve all symbolic names in the conflict-target clause, which
  122090. ** includes both the list of columns and the optional partial-index
  122091. ** WHERE clause.
  122092. */
  122093. memset(&sNC, 0, sizeof(sNC));
  122094. sNC.pParse = pParse;
  122095. sNC.pSrcList = pTabList;
  122096. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  122097. if( rc ) return rc;
  122098. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  122099. if( rc ) return rc;
  122100. /* Check to see if the conflict target matches the rowid. */
  122101. pTab = pTabList->a[0].pTab;
  122102. pTarget = pUpsert->pUpsertTarget;
  122103. iCursor = pTabList->a[0].iCursor;
  122104. if( HasRowid(pTab)
  122105. && pTarget->nExpr==1
  122106. && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
  122107. && pTerm->iColumn==XN_ROWID
  122108. ){
  122109. /* The conflict-target is the rowid of the primary table */
  122110. assert( pUpsert->pUpsertIdx==0 );
  122111. return SQLITE_OK;
  122112. }
  122113. /* Initialize sCol[0..1] to be an expression parse tree for a
  122114. ** single column of an index. The sCol[0] node will be the TK_COLLATE
  122115. ** operator and sCol[1] will be the TK_COLUMN operator. Code below
  122116. ** will populate the specific collation and column number values
  122117. ** prior to comparing against the conflict-target expression.
  122118. */
  122119. memset(sCol, 0, sizeof(sCol));
  122120. sCol[0].op = TK_COLLATE;
  122121. sCol[0].pLeft = &sCol[1];
  122122. sCol[1].op = TK_COLUMN;
  122123. sCol[1].iTable = pTabList->a[0].iCursor;
  122124. /* Check for matches against other indexes */
  122125. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  122126. int ii, jj, nn;
  122127. if( !IsUniqueIndex(pIdx) ) continue;
  122128. if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
  122129. if( pIdx->pPartIdxWhere ){
  122130. if( pUpsert->pUpsertTargetWhere==0 ) continue;
  122131. if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
  122132. pIdx->pPartIdxWhere, iCursor)!=0 ){
  122133. continue;
  122134. }
  122135. }
  122136. nn = pIdx->nKeyCol;
  122137. for(ii=0; ii<nn; ii++){
  122138. Expr *pExpr;
  122139. sCol[0].u.zToken = (char*)pIdx->azColl[ii];
  122140. if( pIdx->aiColumn[ii]==XN_EXPR ){
  122141. assert( pIdx->aColExpr!=0 );
  122142. assert( pIdx->aColExpr->nExpr>ii );
  122143. pExpr = pIdx->aColExpr->a[ii].pExpr;
  122144. if( pExpr->op!=TK_COLLATE ){
  122145. sCol[0].pLeft = pExpr;
  122146. pExpr = &sCol[0];
  122147. }
  122148. }else{
  122149. sCol[0].pLeft = &sCol[1];
  122150. sCol[1].iColumn = pIdx->aiColumn[ii];
  122151. pExpr = &sCol[0];
  122152. }
  122153. for(jj=0; jj<nn; jj++){
  122154. if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
  122155. break; /* Column ii of the index matches column jj of target */
  122156. }
  122157. }
  122158. if( jj>=nn ){
  122159. /* The target contains no match for column jj of the index */
  122160. break;
  122161. }
  122162. }
  122163. if( ii<nn ){
  122164. /* Column ii of the index did not match any term of the conflict target.
  122165. ** Continue the search with the next index. */
  122166. continue;
  122167. }
  122168. pUpsert->pUpsertIdx = pIdx;
  122169. return SQLITE_OK;
  122170. }
  122171. sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
  122172. "PRIMARY KEY or UNIQUE constraint");
  122173. return SQLITE_ERROR;
  122174. }
  122175. /*
  122176. ** Generate bytecode that does an UPDATE as part of an upsert.
  122177. **
  122178. ** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
  122179. ** In this case parameter iCur is a cursor open on the table b-tree that
  122180. ** currently points to the conflicting table row. Otherwise, if pIdx
  122181. ** is not NULL, then pIdx is the constraint that failed and iCur is a
  122182. ** cursor points to the conflicting row.
  122183. */
  122184. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
  122185. Parse *pParse, /* The parsing and code-generating context */
  122186. Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */
  122187. Table *pTab, /* The table being updated */
  122188. Index *pIdx, /* The UNIQUE constraint that failed */
  122189. int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */
  122190. ){
  122191. Vdbe *v = pParse->pVdbe;
  122192. sqlite3 *db = pParse->db;
  122193. SrcList *pSrc; /* FROM clause for the UPDATE */
  122194. int iDataCur = pUpsert->iDataCur;
  122195. assert( v!=0 );
  122196. VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
  122197. if( pIdx && iCur!=iDataCur ){
  122198. if( HasRowid(pTab) ){
  122199. int regRowid = sqlite3GetTempReg(pParse);
  122200. sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
  122201. sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
  122202. VdbeCoverage(v);
  122203. sqlite3ReleaseTempReg(pParse, regRowid);
  122204. }else{
  122205. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  122206. int nPk = pPk->nKeyCol;
  122207. int iPk = pParse->nMem+1;
  122208. int i;
  122209. pParse->nMem += nPk;
  122210. for(i=0; i<nPk; i++){
  122211. int k;
  122212. assert( pPk->aiColumn[i]>=0 );
  122213. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  122214. sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
  122215. VdbeComment((v, "%s.%s", pIdx->zName,
  122216. pTab->aCol[pPk->aiColumn[i]].zName));
  122217. }
  122218. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  122219. i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
  122220. VdbeCoverage(v);
  122221. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
  122222. "corrupt database", P4_STATIC);
  122223. sqlite3VdbeJumpHere(v, i);
  122224. }
  122225. }
  122226. /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So
  122227. ** we have to make a copy before passing it down into sqlite3Update() */
  122228. pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
  122229. sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
  122230. pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
  122231. pUpsert->pUpsertSet = 0; /* Will have been deleted by sqlite3Update() */
  122232. pUpsert->pUpsertWhere = 0; /* Will have been deleted by sqlite3Update() */
  122233. VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
  122234. }
  122235. #endif /* SQLITE_OMIT_UPSERT */
  122236. /************** End of upsert.c **********************************************/
  122237. /************** Begin file vacuum.c ******************************************/
  122238. /*
  122239. ** 2003 April 6
  122240. **
  122241. ** The author disclaims copyright to this source code. In place of
  122242. ** a legal notice, here is a blessing:
  122243. **
  122244. ** May you do good and not evil.
  122245. ** May you find forgiveness for yourself and forgive others.
  122246. ** May you share freely, never taking more than you give.
  122247. **
  122248. *************************************************************************
  122249. ** This file contains code used to implement the VACUUM command.
  122250. **
  122251. ** Most of the code in this file may be omitted by defining the
  122252. ** SQLITE_OMIT_VACUUM macro.
  122253. */
  122254. /* #include "sqliteInt.h" */
  122255. /* #include "vdbeInt.h" */
  122256. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  122257. /*
  122258. ** Execute zSql on database db.
  122259. **
  122260. ** If zSql returns rows, then each row will have exactly one
  122261. ** column. (This will only happen if zSql begins with "SELECT".)
  122262. ** Take each row of result and call execSql() again recursively.
  122263. **
  122264. ** The execSqlF() routine does the same thing, except it accepts
  122265. ** a format string as its third argument
  122266. */
  122267. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  122268. sqlite3_stmt *pStmt;
  122269. int rc;
  122270. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  122271. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  122272. if( rc!=SQLITE_OK ) return rc;
  122273. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  122274. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  122275. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  122276. /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
  122277. ** or INSERT. Historically there have been attacks that first
  122278. ** corrupt the sqlite_master.sql field with other kinds of statements
  122279. ** then run VACUUM to get those statements to execute at inappropriate
  122280. ** times. */
  122281. if( zSubSql
  122282. && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
  122283. ){
  122284. rc = execSql(db, pzErrMsg, zSubSql);
  122285. if( rc!=SQLITE_OK ) break;
  122286. }
  122287. }
  122288. assert( rc!=SQLITE_ROW );
  122289. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  122290. if( rc ){
  122291. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  122292. }
  122293. (void)sqlite3_finalize(pStmt);
  122294. return rc;
  122295. }
  122296. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  122297. char *z;
  122298. va_list ap;
  122299. int rc;
  122300. va_start(ap, zSql);
  122301. z = sqlite3VMPrintf(db, zSql, ap);
  122302. va_end(ap);
  122303. if( z==0 ) return SQLITE_NOMEM;
  122304. rc = execSql(db, pzErrMsg, z);
  122305. sqlite3DbFree(db, z);
  122306. return rc;
  122307. }
  122308. /*
  122309. ** The VACUUM command is used to clean up the database,
  122310. ** collapse free space, etc. It is modelled after the VACUUM command
  122311. ** in PostgreSQL. The VACUUM command works as follows:
  122312. **
  122313. ** (1) Create a new transient database file
  122314. ** (2) Copy all content from the database being vacuumed into
  122315. ** the new transient database file
  122316. ** (3) Copy content from the transient database back into the
  122317. ** original database.
  122318. **
  122319. ** The transient database requires temporary disk space approximately
  122320. ** equal to the size of the original database. The copy operation of
  122321. ** step (3) requires additional temporary disk space approximately equal
  122322. ** to the size of the original database for the rollback journal.
  122323. ** Hence, temporary disk space that is approximately 2x the size of the
  122324. ** original database is required. Every page of the database is written
  122325. ** approximately 3 times: Once for step (2) and twice for step (3).
  122326. ** Two writes per page are required in step (3) because the original
  122327. ** database content must be written into the rollback journal prior to
  122328. ** overwriting the database with the vacuumed content.
  122329. **
  122330. ** Only 1x temporary space and only 1x writes would be required if
  122331. ** the copy of step (3) were replaced by deleting the original database
  122332. ** and renaming the transient database as the original. But that will
  122333. ** not work if other processes are attached to the original database.
  122334. ** And a power loss in between deleting the original and renaming the
  122335. ** transient would cause the database file to appear to be deleted
  122336. ** following reboot.
  122337. */
  122338. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
  122339. Vdbe *v = sqlite3GetVdbe(pParse);
  122340. int iDb = 0;
  122341. if( v==0 ) return;
  122342. if( pNm ){
  122343. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  122344. /* Default behavior: Report an error if the argument to VACUUM is
  122345. ** not recognized */
  122346. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  122347. if( iDb<0 ) return;
  122348. #else
  122349. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  122350. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  122351. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  122352. ** The buggy behavior is required for binary compatibility with some
  122353. ** legacy applications. */
  122354. iDb = sqlite3FindDb(pParse->db, pNm);
  122355. if( iDb<0 ) iDb = 0;
  122356. #endif
  122357. }
  122358. if( iDb!=1 ){
  122359. sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
  122360. sqlite3VdbeUsesBtree(v, iDb);
  122361. }
  122362. return;
  122363. }
  122364. /*
  122365. ** This routine implements the OP_Vacuum opcode of the VDBE.
  122366. */
  122367. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
  122368. int rc = SQLITE_OK; /* Return code from service routines */
  122369. Btree *pMain; /* The database being vacuumed */
  122370. Btree *pTemp; /* The temporary database we vacuum into */
  122371. u16 saved_mDbFlags; /* Saved value of db->mDbFlags */
  122372. u32 saved_flags; /* Saved value of db->flags */
  122373. int saved_nChange; /* Saved value of db->nChange */
  122374. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  122375. u8 saved_mTrace; /* Saved trace settings */
  122376. Db *pDb = 0; /* Database to detach at end of vacuum */
  122377. int isMemDb; /* True if vacuuming a :memory: database */
  122378. int nRes; /* Bytes of reserved space at the end of each page */
  122379. int nDb; /* Number of attached databases */
  122380. const char *zDbMain; /* Schema name of database to vacuum */
  122381. if( !db->autoCommit ){
  122382. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  122383. return SQLITE_ERROR;
  122384. }
  122385. if( db->nVdbeActive>1 ){
  122386. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  122387. return SQLITE_ERROR;
  122388. }
  122389. /* Save the current value of the database flags so that it can be
  122390. ** restored before returning. Then set the writable-schema flag, and
  122391. ** disable CHECK and foreign key constraints. */
  122392. saved_flags = db->flags;
  122393. saved_mDbFlags = db->mDbFlags;
  122394. saved_nChange = db->nChange;
  122395. saved_nTotalChange = db->nTotalChange;
  122396. saved_mTrace = db->mTrace;
  122397. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  122398. db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
  122399. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
  122400. db->mTrace = 0;
  122401. zDbMain = db->aDb[iDb].zDbSName;
  122402. pMain = db->aDb[iDb].pBt;
  122403. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  122404. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  122405. ** can be set to 'off' for this file, as it is not recovered if a crash
  122406. ** occurs anyway. The integrity of the database is maintained by a
  122407. ** (possibly synchronous) transaction opened on the main database before
  122408. ** sqlite3BtreeCopyFile() is called.
  122409. **
  122410. ** An optimisation would be to use a non-journaled pager.
  122411. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  122412. ** that actually made the VACUUM run slower. Very little journalling
  122413. ** actually occurs when doing a vacuum since the vacuum_db is initially
  122414. ** empty. Only the journal header is written. Apparently it takes more
  122415. ** time to parse and run the PRAGMA to turn journalling off than it does
  122416. ** to write the journal header file.
  122417. */
  122418. nDb = db->nDb;
  122419. rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
  122420. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122421. assert( (db->nDb-1)==nDb );
  122422. pDb = &db->aDb[nDb];
  122423. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  122424. pTemp = pDb->pBt;
  122425. /* The call to execSql() to attach the temp database has left the file
  122426. ** locked (as there was more than one active statement when the transaction
  122427. ** to read the schema was concluded. Unlock it here so that this doesn't
  122428. ** cause problems for the call to BtreeSetPageSize() below. */
  122429. sqlite3BtreeCommit(pTemp);
  122430. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  122431. /* A VACUUM cannot change the pagesize of an encrypted database. */
  122432. #ifdef SQLITE_HAS_CODEC
  122433. if( db->nextPagesize ){
  122434. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  122435. int nKey;
  122436. char *zKey;
  122437. sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
  122438. if( nKey ) db->nextPagesize = 0;
  122439. }
  122440. #endif
  122441. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  122442. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  122443. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  122444. /* Begin a transaction and take an exclusive lock on the main database
  122445. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  122446. ** to ensure that we do not try to change the page-size on a WAL database.
  122447. */
  122448. rc = execSql(db, pzErrMsg, "BEGIN");
  122449. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122450. rc = sqlite3BtreeBeginTrans(pMain, 2);
  122451. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122452. /* Do not attempt to change the page size for a WAL database */
  122453. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  122454. ==PAGER_JOURNALMODE_WAL ){
  122455. db->nextPagesize = 0;
  122456. }
  122457. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  122458. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  122459. || NEVER(db->mallocFailed)
  122460. ){
  122461. rc = SQLITE_NOMEM_BKPT;
  122462. goto end_of_vacuum;
  122463. }
  122464. #ifndef SQLITE_OMIT_AUTOVACUUM
  122465. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  122466. sqlite3BtreeGetAutoVacuum(pMain));
  122467. #endif
  122468. /* Query the schema of the main database. Create a mirror schema
  122469. ** in the temporary database.
  122470. */
  122471. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  122472. rc = execSqlF(db, pzErrMsg,
  122473. "SELECT sql FROM \"%w\".sqlite_master"
  122474. " WHERE type='table'AND name<>'sqlite_sequence'"
  122475. " AND coalesce(rootpage,1)>0",
  122476. zDbMain
  122477. );
  122478. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122479. rc = execSqlF(db, pzErrMsg,
  122480. "SELECT sql FROM \"%w\".sqlite_master"
  122481. " WHERE type='index'",
  122482. zDbMain
  122483. );
  122484. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122485. db->init.iDb = 0;
  122486. /* Loop through the tables in the main database. For each, do
  122487. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  122488. ** the contents to the temporary database.
  122489. */
  122490. rc = execSqlF(db, pzErrMsg,
  122491. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  122492. "||' SELECT*FROM\"%w\".'||quote(name)"
  122493. "FROM vacuum_db.sqlite_master "
  122494. "WHERE type='table'AND coalesce(rootpage,1)>0",
  122495. zDbMain
  122496. );
  122497. assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  122498. db->mDbFlags &= ~DBFLAG_Vacuum;
  122499. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122500. /* Copy the triggers, views, and virtual tables from the main database
  122501. ** over to the temporary database. None of these objects has any
  122502. ** associated storage, so all we have to do is copy their entries
  122503. ** from the SQLITE_MASTER table.
  122504. */
  122505. rc = execSqlF(db, pzErrMsg,
  122506. "INSERT INTO vacuum_db.sqlite_master"
  122507. " SELECT*FROM \"%w\".sqlite_master"
  122508. " WHERE type IN('view','trigger')"
  122509. " OR(type='table'AND rootpage=0)",
  122510. zDbMain
  122511. );
  122512. if( rc ) goto end_of_vacuum;
  122513. /* At this point, there is a write transaction open on both the
  122514. ** vacuum database and the main database. Assuming no error occurs,
  122515. ** both transactions are closed by this block - the main database
  122516. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  122517. ** call to sqlite3BtreeCommit().
  122518. */
  122519. {
  122520. u32 meta;
  122521. int i;
  122522. /* This array determines which meta meta values are preserved in the
  122523. ** vacuum. Even entries are the meta value number and odd entries
  122524. ** are an increment to apply to the meta value after the vacuum.
  122525. ** The increment is used to increase the schema cookie so that other
  122526. ** connections to the same database will know to reread the schema.
  122527. */
  122528. static const unsigned char aCopy[] = {
  122529. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  122530. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  122531. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  122532. BTREE_USER_VERSION, 0, /* Preserve the user version */
  122533. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  122534. };
  122535. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  122536. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  122537. /* Copy Btree meta values */
  122538. for(i=0; i<ArraySize(aCopy); i+=2){
  122539. /* GetMeta() and UpdateMeta() cannot fail in this context because
  122540. ** we already have page 1 loaded into cache and marked dirty. */
  122541. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  122542. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  122543. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  122544. }
  122545. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  122546. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122547. rc = sqlite3BtreeCommit(pTemp);
  122548. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  122549. #ifndef SQLITE_OMIT_AUTOVACUUM
  122550. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  122551. #endif
  122552. }
  122553. assert( rc==SQLITE_OK );
  122554. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  122555. end_of_vacuum:
  122556. /* Restore the original value of db->flags */
  122557. db->init.iDb = 0;
  122558. db->mDbFlags = saved_mDbFlags;
  122559. db->flags = saved_flags;
  122560. db->nChange = saved_nChange;
  122561. db->nTotalChange = saved_nTotalChange;
  122562. db->mTrace = saved_mTrace;
  122563. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  122564. /* Currently there is an SQL level transaction open on the vacuum
  122565. ** database. No locks are held on any other files (since the main file
  122566. ** was committed at the btree level). So it safe to end the transaction
  122567. ** by manually setting the autoCommit flag to true and detaching the
  122568. ** vacuum database. The vacuum_db journal file is deleted when the pager
  122569. ** is closed by the DETACH.
  122570. */
  122571. db->autoCommit = 1;
  122572. if( pDb ){
  122573. sqlite3BtreeClose(pDb->pBt);
  122574. pDb->pBt = 0;
  122575. pDb->pSchema = 0;
  122576. }
  122577. /* This both clears the schemas and reduces the size of the db->aDb[]
  122578. ** array. */
  122579. sqlite3ResetAllSchemasOfConnection(db);
  122580. return rc;
  122581. }
  122582. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  122583. /************** End of vacuum.c **********************************************/
  122584. /************** Begin file vtab.c ********************************************/
  122585. /*
  122586. ** 2006 June 10
  122587. **
  122588. ** The author disclaims copyright to this source code. In place of
  122589. ** a legal notice, here is a blessing:
  122590. **
  122591. ** May you do good and not evil.
  122592. ** May you find forgiveness for yourself and forgive others.
  122593. ** May you share freely, never taking more than you give.
  122594. **
  122595. *************************************************************************
  122596. ** This file contains code used to help implement virtual tables.
  122597. */
  122598. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122599. /* #include "sqliteInt.h" */
  122600. /*
  122601. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  122602. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  122603. ** this struct allocated on the stack. It is used by the implementation of
  122604. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  122605. ** are invoked only from within xCreate and xConnect methods.
  122606. */
  122607. struct VtabCtx {
  122608. VTable *pVTable; /* The virtual table being constructed */
  122609. Table *pTab; /* The Table object to which the virtual table belongs */
  122610. VtabCtx *pPrior; /* Parent context (if any) */
  122611. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  122612. };
  122613. /*
  122614. ** Construct and install a Module object for a virtual table. When this
  122615. ** routine is called, it is guaranteed that all appropriate locks are held
  122616. ** and the module is not already part of the connection.
  122617. */
  122618. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  122619. sqlite3 *db, /* Database in which module is registered */
  122620. const char *zName, /* Name assigned to this module */
  122621. const sqlite3_module *pModule, /* The definition of the module */
  122622. void *pAux, /* Context pointer for xCreate/xConnect */
  122623. void (*xDestroy)(void *) /* Module destructor function */
  122624. ){
  122625. Module *pMod;
  122626. int nName = sqlite3Strlen30(zName);
  122627. pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
  122628. if( pMod==0 ){
  122629. sqlite3OomFault(db);
  122630. }else{
  122631. Module *pDel;
  122632. char *zCopy = (char *)(&pMod[1]);
  122633. memcpy(zCopy, zName, nName+1);
  122634. pMod->zName = zCopy;
  122635. pMod->pModule = pModule;
  122636. pMod->pAux = pAux;
  122637. pMod->xDestroy = xDestroy;
  122638. pMod->pEpoTab = 0;
  122639. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  122640. assert( pDel==0 || pDel==pMod );
  122641. if( pDel ){
  122642. sqlite3OomFault(db);
  122643. sqlite3DbFree(db, pDel);
  122644. pMod = 0;
  122645. }
  122646. }
  122647. return pMod;
  122648. }
  122649. /*
  122650. ** The actual function that does the work of creating a new module.
  122651. ** This function implements the sqlite3_create_module() and
  122652. ** sqlite3_create_module_v2() interfaces.
  122653. */
  122654. static int createModule(
  122655. sqlite3 *db, /* Database in which module is registered */
  122656. const char *zName, /* Name assigned to this module */
  122657. const sqlite3_module *pModule, /* The definition of the module */
  122658. void *pAux, /* Context pointer for xCreate/xConnect */
  122659. void (*xDestroy)(void *) /* Module destructor function */
  122660. ){
  122661. int rc = SQLITE_OK;
  122662. sqlite3_mutex_enter(db->mutex);
  122663. if( sqlite3HashFind(&db->aModule, zName) ){
  122664. rc = SQLITE_MISUSE_BKPT;
  122665. }else{
  122666. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  122667. }
  122668. rc = sqlite3ApiExit(db, rc);
  122669. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  122670. sqlite3_mutex_leave(db->mutex);
  122671. return rc;
  122672. }
  122673. /*
  122674. ** External API function used to create a new virtual-table module.
  122675. */
  122676. SQLITE_API int sqlite3_create_module(
  122677. sqlite3 *db, /* Database in which module is registered */
  122678. const char *zName, /* Name assigned to this module */
  122679. const sqlite3_module *pModule, /* The definition of the module */
  122680. void *pAux /* Context pointer for xCreate/xConnect */
  122681. ){
  122682. #ifdef SQLITE_ENABLE_API_ARMOR
  122683. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  122684. #endif
  122685. return createModule(db, zName, pModule, pAux, 0);
  122686. }
  122687. /*
  122688. ** External API function used to create a new virtual-table module.
  122689. */
  122690. SQLITE_API int sqlite3_create_module_v2(
  122691. sqlite3 *db, /* Database in which module is registered */
  122692. const char *zName, /* Name assigned to this module */
  122693. const sqlite3_module *pModule, /* The definition of the module */
  122694. void *pAux, /* Context pointer for xCreate/xConnect */
  122695. void (*xDestroy)(void *) /* Module destructor function */
  122696. ){
  122697. #ifdef SQLITE_ENABLE_API_ARMOR
  122698. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  122699. #endif
  122700. return createModule(db, zName, pModule, pAux, xDestroy);
  122701. }
  122702. /*
  122703. ** Lock the virtual table so that it cannot be disconnected.
  122704. ** Locks nest. Every lock should have a corresponding unlock.
  122705. ** If an unlock is omitted, resources leaks will occur.
  122706. **
  122707. ** If a disconnect is attempted while a virtual table is locked,
  122708. ** the disconnect is deferred until all locks have been removed.
  122709. */
  122710. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  122711. pVTab->nRef++;
  122712. }
  122713. /*
  122714. ** pTab is a pointer to a Table structure representing a virtual-table.
  122715. ** Return a pointer to the VTable object used by connection db to access
  122716. ** this virtual-table, if one has been created, or NULL otherwise.
  122717. */
  122718. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  122719. VTable *pVtab;
  122720. assert( IsVirtual(pTab) );
  122721. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  122722. return pVtab;
  122723. }
  122724. /*
  122725. ** Decrement the ref-count on a virtual table object. When the ref-count
  122726. ** reaches zero, call the xDisconnect() method to delete the object.
  122727. */
  122728. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  122729. sqlite3 *db = pVTab->db;
  122730. assert( db );
  122731. assert( pVTab->nRef>0 );
  122732. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  122733. pVTab->nRef--;
  122734. if( pVTab->nRef==0 ){
  122735. sqlite3_vtab *p = pVTab->pVtab;
  122736. if( p ){
  122737. p->pModule->xDisconnect(p);
  122738. }
  122739. sqlite3DbFree(db, pVTab);
  122740. }
  122741. }
  122742. /*
  122743. ** Table p is a virtual table. This function moves all elements in the
  122744. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  122745. ** database connections to be disconnected at the next opportunity.
  122746. ** Except, if argument db is not NULL, then the entry associated with
  122747. ** connection db is left in the p->pVTable list.
  122748. */
  122749. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  122750. VTable *pRet = 0;
  122751. VTable *pVTable = p->pVTable;
  122752. p->pVTable = 0;
  122753. /* Assert that the mutex (if any) associated with the BtShared database
  122754. ** that contains table p is held by the caller. See header comments
  122755. ** above function sqlite3VtabUnlockList() for an explanation of why
  122756. ** this makes it safe to access the sqlite3.pDisconnect list of any
  122757. ** database connection that may have an entry in the p->pVTable list.
  122758. */
  122759. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  122760. while( pVTable ){
  122761. sqlite3 *db2 = pVTable->db;
  122762. VTable *pNext = pVTable->pNext;
  122763. assert( db2 );
  122764. if( db2==db ){
  122765. pRet = pVTable;
  122766. p->pVTable = pRet;
  122767. pRet->pNext = 0;
  122768. }else{
  122769. pVTable->pNext = db2->pDisconnect;
  122770. db2->pDisconnect = pVTable;
  122771. }
  122772. pVTable = pNext;
  122773. }
  122774. assert( !db || pRet );
  122775. return pRet;
  122776. }
  122777. /*
  122778. ** Table *p is a virtual table. This function removes the VTable object
  122779. ** for table *p associated with database connection db from the linked
  122780. ** list in p->pVTab. It also decrements the VTable ref count. This is
  122781. ** used when closing database connection db to free all of its VTable
  122782. ** objects without disturbing the rest of the Schema object (which may
  122783. ** be being used by other shared-cache connections).
  122784. */
  122785. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  122786. VTable **ppVTab;
  122787. assert( IsVirtual(p) );
  122788. assert( sqlite3BtreeHoldsAllMutexes(db) );
  122789. assert( sqlite3_mutex_held(db->mutex) );
  122790. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  122791. if( (*ppVTab)->db==db ){
  122792. VTable *pVTab = *ppVTab;
  122793. *ppVTab = pVTab->pNext;
  122794. sqlite3VtabUnlock(pVTab);
  122795. break;
  122796. }
  122797. }
  122798. }
  122799. /*
  122800. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  122801. **
  122802. ** This function may only be called when the mutexes associated with all
  122803. ** shared b-tree databases opened using connection db are held by the
  122804. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  122805. ** sqlite3.pDisconnect list is accessed only as follows:
  122806. **
  122807. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  122808. ** associated with the database handle itself must be held.
  122809. **
  122810. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  122811. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  122812. ** associated with the database the virtual table is stored in is held
  122813. ** or, if the virtual table is stored in a non-sharable database, then
  122814. ** the database handle mutex is held.
  122815. **
  122816. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  122817. ** by multiple threads. It is thread-safe.
  122818. */
  122819. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  122820. VTable *p = db->pDisconnect;
  122821. db->pDisconnect = 0;
  122822. assert( sqlite3BtreeHoldsAllMutexes(db) );
  122823. assert( sqlite3_mutex_held(db->mutex) );
  122824. if( p ){
  122825. sqlite3ExpirePreparedStatements(db);
  122826. do {
  122827. VTable *pNext = p->pNext;
  122828. sqlite3VtabUnlock(p);
  122829. p = pNext;
  122830. }while( p );
  122831. }
  122832. }
  122833. /*
  122834. ** Clear any and all virtual-table information from the Table record.
  122835. ** This routine is called, for example, just before deleting the Table
  122836. ** record.
  122837. **
  122838. ** Since it is a virtual-table, the Table structure contains a pointer
  122839. ** to the head of a linked list of VTable structures. Each VTable
  122840. ** structure is associated with a single sqlite3* user of the schema.
  122841. ** The reference count of the VTable structure associated with database
  122842. ** connection db is decremented immediately (which may lead to the
  122843. ** structure being xDisconnected and free). Any other VTable structures
  122844. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  122845. ** database connection.
  122846. */
  122847. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  122848. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  122849. if( p->azModuleArg ){
  122850. int i;
  122851. for(i=0; i<p->nModuleArg; i++){
  122852. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  122853. }
  122854. sqlite3DbFree(db, p->azModuleArg);
  122855. }
  122856. }
  122857. /*
  122858. ** Add a new module argument to pTable->azModuleArg[].
  122859. ** The string is not copied - the pointer is stored. The
  122860. ** string will be freed automatically when the table is
  122861. ** deleted.
  122862. */
  122863. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  122864. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  122865. char **azModuleArg;
  122866. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  122867. if( azModuleArg==0 ){
  122868. sqlite3DbFree(db, zArg);
  122869. }else{
  122870. int i = pTable->nModuleArg++;
  122871. azModuleArg[i] = zArg;
  122872. azModuleArg[i+1] = 0;
  122873. pTable->azModuleArg = azModuleArg;
  122874. }
  122875. }
  122876. /*
  122877. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  122878. ** statement. The module name has been parsed, but the optional list
  122879. ** of parameters that follow the module name are still pending.
  122880. */
  122881. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  122882. Parse *pParse, /* Parsing context */
  122883. Token *pName1, /* Name of new table, or database name */
  122884. Token *pName2, /* Name of new table or NULL */
  122885. Token *pModuleName, /* Name of the module for the virtual table */
  122886. int ifNotExists /* No error if the table already exists */
  122887. ){
  122888. int iDb; /* The database the table is being created in */
  122889. Table *pTable; /* The new virtual table */
  122890. sqlite3 *db; /* Database connection */
  122891. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  122892. pTable = pParse->pNewTable;
  122893. if( pTable==0 ) return;
  122894. assert( 0==pTable->pIndex );
  122895. db = pParse->db;
  122896. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  122897. assert( iDb>=0 );
  122898. assert( pTable->nModuleArg==0 );
  122899. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  122900. addModuleArgument(db, pTable, 0);
  122901. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  122902. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  122903. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  122904. );
  122905. pParse->sNameToken.n = (int)(
  122906. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  122907. );
  122908. #ifndef SQLITE_OMIT_AUTHORIZATION
  122909. /* Creating a virtual table invokes the authorization callback twice.
  122910. ** The first invocation, to obtain permission to INSERT a row into the
  122911. ** sqlite_master table, has already been made by sqlite3StartTable().
  122912. ** The second call, to obtain permission to create the table, is made now.
  122913. */
  122914. if( pTable->azModuleArg ){
  122915. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  122916. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  122917. }
  122918. #endif
  122919. }
  122920. /*
  122921. ** This routine takes the module argument that has been accumulating
  122922. ** in pParse->zArg[] and appends it to the list of arguments on the
  122923. ** virtual table currently under construction in pParse->pTable.
  122924. */
  122925. static void addArgumentToVtab(Parse *pParse){
  122926. if( pParse->sArg.z && pParse->pNewTable ){
  122927. const char *z = (const char*)pParse->sArg.z;
  122928. int n = pParse->sArg.n;
  122929. sqlite3 *db = pParse->db;
  122930. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  122931. }
  122932. }
  122933. /*
  122934. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  122935. ** has been completely parsed.
  122936. */
  122937. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  122938. Table *pTab = pParse->pNewTable; /* The table being constructed */
  122939. sqlite3 *db = pParse->db; /* The database connection */
  122940. if( pTab==0 ) return;
  122941. addArgumentToVtab(pParse);
  122942. pParse->sArg.z = 0;
  122943. if( pTab->nModuleArg<1 ) return;
  122944. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  122945. ** first time (in other words if the virtual table is actually being
  122946. ** created now instead of just being read out of sqlite_master) then
  122947. ** do additional initialization work and store the statement text
  122948. ** in the sqlite_master table.
  122949. */
  122950. if( !db->init.busy ){
  122951. char *zStmt;
  122952. char *zWhere;
  122953. int iDb;
  122954. int iReg;
  122955. Vdbe *v;
  122956. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  122957. if( pEnd ){
  122958. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  122959. }
  122960. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  122961. /* A slot for the record has already been allocated in the
  122962. ** SQLITE_MASTER table. We just need to update that slot with all
  122963. ** the information we've collected.
  122964. **
  122965. ** The VM register number pParse->regRowid holds the rowid of an
  122966. ** entry in the sqlite_master table tht was created for this vtab
  122967. ** by sqlite3StartTable().
  122968. */
  122969. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  122970. sqlite3NestedParse(pParse,
  122971. "UPDATE %Q.%s "
  122972. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  122973. "WHERE rowid=#%d",
  122974. db->aDb[iDb].zDbSName, MASTER_NAME,
  122975. pTab->zName,
  122976. pTab->zName,
  122977. zStmt,
  122978. pParse->regRowid
  122979. );
  122980. sqlite3DbFree(db, zStmt);
  122981. v = sqlite3GetVdbe(pParse);
  122982. sqlite3ChangeCookie(pParse, iDb);
  122983. sqlite3VdbeAddOp0(v, OP_Expire);
  122984. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  122985. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  122986. iReg = ++pParse->nMem;
  122987. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  122988. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  122989. }
  122990. /* If we are rereading the sqlite_master table create the in-memory
  122991. ** record of the table. The xConnect() method is not called until
  122992. ** the first time the virtual table is used in an SQL statement. This
  122993. ** allows a schema that contains virtual tables to be loaded before
  122994. ** the required virtual table implementations are registered. */
  122995. else {
  122996. Table *pOld;
  122997. Schema *pSchema = pTab->pSchema;
  122998. const char *zName = pTab->zName;
  122999. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  123000. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  123001. if( pOld ){
  123002. sqlite3OomFault(db);
  123003. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  123004. return;
  123005. }
  123006. pParse->pNewTable = 0;
  123007. }
  123008. }
  123009. /*
  123010. ** The parser calls this routine when it sees the first token
  123011. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  123012. */
  123013. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  123014. addArgumentToVtab(pParse);
  123015. pParse->sArg.z = 0;
  123016. pParse->sArg.n = 0;
  123017. }
  123018. /*
  123019. ** The parser calls this routine for each token after the first token
  123020. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  123021. */
  123022. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  123023. Token *pArg = &pParse->sArg;
  123024. if( pArg->z==0 ){
  123025. pArg->z = p->z;
  123026. pArg->n = p->n;
  123027. }else{
  123028. assert(pArg->z <= p->z);
  123029. pArg->n = (int)(&p->z[p->n] - pArg->z);
  123030. }
  123031. }
  123032. /*
  123033. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  123034. ** pointer to the function to invoke is passed as the fourth parameter
  123035. ** to this procedure.
  123036. */
  123037. static int vtabCallConstructor(
  123038. sqlite3 *db,
  123039. Table *pTab,
  123040. Module *pMod,
  123041. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  123042. char **pzErr
  123043. ){
  123044. VtabCtx sCtx;
  123045. VTable *pVTable;
  123046. int rc;
  123047. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  123048. int nArg = pTab->nModuleArg;
  123049. char *zErr = 0;
  123050. char *zModuleName;
  123051. int iDb;
  123052. VtabCtx *pCtx;
  123053. /* Check that the virtual-table is not already being initialized */
  123054. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  123055. if( pCtx->pTab==pTab ){
  123056. *pzErr = sqlite3MPrintf(db,
  123057. "vtable constructor called recursively: %s", pTab->zName
  123058. );
  123059. return SQLITE_LOCKED;
  123060. }
  123061. }
  123062. zModuleName = sqlite3DbStrDup(db, pTab->zName);
  123063. if( !zModuleName ){
  123064. return SQLITE_NOMEM_BKPT;
  123065. }
  123066. pVTable = sqlite3MallocZero(sizeof(VTable));
  123067. if( !pVTable ){
  123068. sqlite3OomFault(db);
  123069. sqlite3DbFree(db, zModuleName);
  123070. return SQLITE_NOMEM_BKPT;
  123071. }
  123072. pVTable->db = db;
  123073. pVTable->pMod = pMod;
  123074. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  123075. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  123076. /* Invoke the virtual table constructor */
  123077. assert( &db->pVtabCtx );
  123078. assert( xConstruct );
  123079. sCtx.pTab = pTab;
  123080. sCtx.pVTable = pVTable;
  123081. sCtx.pPrior = db->pVtabCtx;
  123082. sCtx.bDeclared = 0;
  123083. db->pVtabCtx = &sCtx;
  123084. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  123085. db->pVtabCtx = sCtx.pPrior;
  123086. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  123087. assert( sCtx.pTab==pTab );
  123088. if( SQLITE_OK!=rc ){
  123089. if( zErr==0 ){
  123090. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  123091. }else {
  123092. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  123093. sqlite3_free(zErr);
  123094. }
  123095. sqlite3DbFree(db, pVTable);
  123096. }else if( ALWAYS(pVTable->pVtab) ){
  123097. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  123098. ** the sqlite3_vtab object if successful. */
  123099. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  123100. pVTable->pVtab->pModule = pMod->pModule;
  123101. pVTable->nRef = 1;
  123102. if( sCtx.bDeclared==0 ){
  123103. const char *zFormat = "vtable constructor did not declare schema: %s";
  123104. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  123105. sqlite3VtabUnlock(pVTable);
  123106. rc = SQLITE_ERROR;
  123107. }else{
  123108. int iCol;
  123109. u8 oooHidden = 0;
  123110. /* If everything went according to plan, link the new VTable structure
  123111. ** into the linked list headed by pTab->pVTable. Then loop through the
  123112. ** columns of the table to see if any of them contain the token "hidden".
  123113. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  123114. ** the type string. */
  123115. pVTable->pNext = pTab->pVTable;
  123116. pTab->pVTable = pVTable;
  123117. for(iCol=0; iCol<pTab->nCol; iCol++){
  123118. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  123119. int nType;
  123120. int i = 0;
  123121. nType = sqlite3Strlen30(zType);
  123122. for(i=0; i<nType; i++){
  123123. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  123124. && (i==0 || zType[i-1]==' ')
  123125. && (zType[i+6]=='\0' || zType[i+6]==' ')
  123126. ){
  123127. break;
  123128. }
  123129. }
  123130. if( i<nType ){
  123131. int j;
  123132. int nDel = 6 + (zType[i+6] ? 1 : 0);
  123133. for(j=i; (j+nDel)<=nType; j++){
  123134. zType[j] = zType[j+nDel];
  123135. }
  123136. if( zType[i]=='\0' && i>0 ){
  123137. assert(zType[i-1]==' ');
  123138. zType[i-1] = '\0';
  123139. }
  123140. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  123141. oooHidden = TF_OOOHidden;
  123142. }else{
  123143. pTab->tabFlags |= oooHidden;
  123144. }
  123145. }
  123146. }
  123147. }
  123148. sqlite3DbFree(db, zModuleName);
  123149. return rc;
  123150. }
  123151. /*
  123152. ** This function is invoked by the parser to call the xConnect() method
  123153. ** of the virtual table pTab. If an error occurs, an error code is returned
  123154. ** and an error left in pParse.
  123155. **
  123156. ** This call is a no-op if table pTab is not a virtual table.
  123157. */
  123158. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  123159. sqlite3 *db = pParse->db;
  123160. const char *zMod;
  123161. Module *pMod;
  123162. int rc;
  123163. assert( pTab );
  123164. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  123165. return SQLITE_OK;
  123166. }
  123167. /* Locate the required virtual table module */
  123168. zMod = pTab->azModuleArg[0];
  123169. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  123170. if( !pMod ){
  123171. const char *zModule = pTab->azModuleArg[0];
  123172. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  123173. rc = SQLITE_ERROR;
  123174. }else{
  123175. char *zErr = 0;
  123176. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  123177. if( rc!=SQLITE_OK ){
  123178. sqlite3ErrorMsg(pParse, "%s", zErr);
  123179. pParse->rc = rc;
  123180. }
  123181. sqlite3DbFree(db, zErr);
  123182. }
  123183. return rc;
  123184. }
  123185. /*
  123186. ** Grow the db->aVTrans[] array so that there is room for at least one
  123187. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  123188. */
  123189. static int growVTrans(sqlite3 *db){
  123190. const int ARRAY_INCR = 5;
  123191. /* Grow the sqlite3.aVTrans array if required */
  123192. if( (db->nVTrans%ARRAY_INCR)==0 ){
  123193. VTable **aVTrans;
  123194. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  123195. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  123196. if( !aVTrans ){
  123197. return SQLITE_NOMEM_BKPT;
  123198. }
  123199. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  123200. db->aVTrans = aVTrans;
  123201. }
  123202. return SQLITE_OK;
  123203. }
  123204. /*
  123205. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  123206. ** have already been reserved using growVTrans().
  123207. */
  123208. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  123209. /* Add pVtab to the end of sqlite3.aVTrans */
  123210. db->aVTrans[db->nVTrans++] = pVTab;
  123211. sqlite3VtabLock(pVTab);
  123212. }
  123213. /*
  123214. ** This function is invoked by the vdbe to call the xCreate method
  123215. ** of the virtual table named zTab in database iDb.
  123216. **
  123217. ** If an error occurs, *pzErr is set to point to an English language
  123218. ** description of the error and an SQLITE_XXX error code is returned.
  123219. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  123220. */
  123221. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  123222. int rc = SQLITE_OK;
  123223. Table *pTab;
  123224. Module *pMod;
  123225. const char *zMod;
  123226. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  123227. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  123228. /* Locate the required virtual table module */
  123229. zMod = pTab->azModuleArg[0];
  123230. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  123231. /* If the module has been registered and includes a Create method,
  123232. ** invoke it now. If the module has not been registered, return an
  123233. ** error. Otherwise, do nothing.
  123234. */
  123235. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  123236. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  123237. rc = SQLITE_ERROR;
  123238. }else{
  123239. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  123240. }
  123241. /* Justification of ALWAYS(): The xConstructor method is required to
  123242. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  123243. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  123244. rc = growVTrans(db);
  123245. if( rc==SQLITE_OK ){
  123246. addToVTrans(db, sqlite3GetVTable(db, pTab));
  123247. }
  123248. }
  123249. return rc;
  123250. }
  123251. /*
  123252. ** This function is used to set the schema of a virtual table. It is only
  123253. ** valid to call this function from within the xCreate() or xConnect() of a
  123254. ** virtual table module.
  123255. */
  123256. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  123257. VtabCtx *pCtx;
  123258. int rc = SQLITE_OK;
  123259. Table *pTab;
  123260. char *zErr = 0;
  123261. Parse sParse;
  123262. #ifdef SQLITE_ENABLE_API_ARMOR
  123263. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  123264. return SQLITE_MISUSE_BKPT;
  123265. }
  123266. #endif
  123267. sqlite3_mutex_enter(db->mutex);
  123268. pCtx = db->pVtabCtx;
  123269. if( !pCtx || pCtx->bDeclared ){
  123270. sqlite3Error(db, SQLITE_MISUSE);
  123271. sqlite3_mutex_leave(db->mutex);
  123272. return SQLITE_MISUSE_BKPT;
  123273. }
  123274. pTab = pCtx->pTab;
  123275. assert( IsVirtual(pTab) );
  123276. memset(&sParse, 0, sizeof(sParse));
  123277. sParse.declareVtab = 1;
  123278. sParse.db = db;
  123279. sParse.nQueryLoop = 1;
  123280. if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
  123281. && sParse.pNewTable
  123282. && !db->mallocFailed
  123283. && !sParse.pNewTable->pSelect
  123284. && !IsVirtual(sParse.pNewTable)
  123285. ){
  123286. if( !pTab->aCol ){
  123287. Table *pNew = sParse.pNewTable;
  123288. Index *pIdx;
  123289. pTab->aCol = pNew->aCol;
  123290. pTab->nCol = pNew->nCol;
  123291. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  123292. pNew->nCol = 0;
  123293. pNew->aCol = 0;
  123294. assert( pTab->pIndex==0 );
  123295. assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
  123296. if( !HasRowid(pNew)
  123297. && pCtx->pVTable->pMod->pModule->xUpdate!=0
  123298. && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
  123299. ){
  123300. /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
  123301. ** or else must have a single-column PRIMARY KEY */
  123302. rc = SQLITE_ERROR;
  123303. }
  123304. pIdx = pNew->pIndex;
  123305. if( pIdx ){
  123306. assert( pIdx->pNext==0 );
  123307. pTab->pIndex = pIdx;
  123308. pNew->pIndex = 0;
  123309. pIdx->pTable = pTab;
  123310. }
  123311. }
  123312. pCtx->bDeclared = 1;
  123313. }else{
  123314. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  123315. sqlite3DbFree(db, zErr);
  123316. rc = SQLITE_ERROR;
  123317. }
  123318. sParse.declareVtab = 0;
  123319. if( sParse.pVdbe ){
  123320. sqlite3VdbeFinalize(sParse.pVdbe);
  123321. }
  123322. sqlite3DeleteTable(db, sParse.pNewTable);
  123323. sqlite3ParserReset(&sParse);
  123324. assert( (rc&0xff)==rc );
  123325. rc = sqlite3ApiExit(db, rc);
  123326. sqlite3_mutex_leave(db->mutex);
  123327. return rc;
  123328. }
  123329. /*
  123330. ** This function is invoked by the vdbe to call the xDestroy method
  123331. ** of the virtual table named zTab in database iDb. This occurs
  123332. ** when a DROP TABLE is mentioned.
  123333. **
  123334. ** This call is a no-op if zTab is not a virtual table.
  123335. */
  123336. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  123337. int rc = SQLITE_OK;
  123338. Table *pTab;
  123339. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  123340. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  123341. VTable *p;
  123342. int (*xDestroy)(sqlite3_vtab *);
  123343. for(p=pTab->pVTable; p; p=p->pNext){
  123344. assert( p->pVtab );
  123345. if( p->pVtab->nRef>0 ){
  123346. return SQLITE_LOCKED;
  123347. }
  123348. }
  123349. p = vtabDisconnectAll(db, pTab);
  123350. xDestroy = p->pMod->pModule->xDestroy;
  123351. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  123352. rc = xDestroy(p->pVtab);
  123353. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  123354. if( rc==SQLITE_OK ){
  123355. assert( pTab->pVTable==p && p->pNext==0 );
  123356. p->pVtab = 0;
  123357. pTab->pVTable = 0;
  123358. sqlite3VtabUnlock(p);
  123359. }
  123360. }
  123361. return rc;
  123362. }
  123363. /*
  123364. ** This function invokes either the xRollback or xCommit method
  123365. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  123366. ** called is identified by the second argument, "offset", which is
  123367. ** the offset of the method to call in the sqlite3_module structure.
  123368. **
  123369. ** The array is cleared after invoking the callbacks.
  123370. */
  123371. static void callFinaliser(sqlite3 *db, int offset){
  123372. int i;
  123373. if( db->aVTrans ){
  123374. VTable **aVTrans = db->aVTrans;
  123375. db->aVTrans = 0;
  123376. for(i=0; i<db->nVTrans; i++){
  123377. VTable *pVTab = aVTrans[i];
  123378. sqlite3_vtab *p = pVTab->pVtab;
  123379. if( p ){
  123380. int (*x)(sqlite3_vtab *);
  123381. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  123382. if( x ) x(p);
  123383. }
  123384. pVTab->iSavepoint = 0;
  123385. sqlite3VtabUnlock(pVTab);
  123386. }
  123387. sqlite3DbFree(db, aVTrans);
  123388. db->nVTrans = 0;
  123389. }
  123390. }
  123391. /*
  123392. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  123393. ** array. Return the error code for the first error that occurs, or
  123394. ** SQLITE_OK if all xSync operations are successful.
  123395. **
  123396. ** If an error message is available, leave it in p->zErrMsg.
  123397. */
  123398. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  123399. int i;
  123400. int rc = SQLITE_OK;
  123401. VTable **aVTrans = db->aVTrans;
  123402. db->aVTrans = 0;
  123403. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  123404. int (*x)(sqlite3_vtab *);
  123405. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  123406. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  123407. rc = x(pVtab);
  123408. sqlite3VtabImportErrmsg(p, pVtab);
  123409. }
  123410. }
  123411. db->aVTrans = aVTrans;
  123412. return rc;
  123413. }
  123414. /*
  123415. ** Invoke the xRollback method of all virtual tables in the
  123416. ** sqlite3.aVTrans array. Then clear the array itself.
  123417. */
  123418. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  123419. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  123420. return SQLITE_OK;
  123421. }
  123422. /*
  123423. ** Invoke the xCommit method of all virtual tables in the
  123424. ** sqlite3.aVTrans array. Then clear the array itself.
  123425. */
  123426. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  123427. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  123428. return SQLITE_OK;
  123429. }
  123430. /*
  123431. ** If the virtual table pVtab supports the transaction interface
  123432. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  123433. ** not currently open, invoke the xBegin method now.
  123434. **
  123435. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  123436. ** in the sqlite3.aVTrans array.
  123437. */
  123438. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  123439. int rc = SQLITE_OK;
  123440. const sqlite3_module *pModule;
  123441. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  123442. ** than zero, then this function is being called from within a
  123443. ** virtual module xSync() callback. It is illegal to write to
  123444. ** virtual module tables in this case, so return SQLITE_LOCKED.
  123445. */
  123446. if( sqlite3VtabInSync(db) ){
  123447. return SQLITE_LOCKED;
  123448. }
  123449. if( !pVTab ){
  123450. return SQLITE_OK;
  123451. }
  123452. pModule = pVTab->pVtab->pModule;
  123453. if( pModule->xBegin ){
  123454. int i;
  123455. /* If pVtab is already in the aVTrans array, return early */
  123456. for(i=0; i<db->nVTrans; i++){
  123457. if( db->aVTrans[i]==pVTab ){
  123458. return SQLITE_OK;
  123459. }
  123460. }
  123461. /* Invoke the xBegin method. If successful, add the vtab to the
  123462. ** sqlite3.aVTrans[] array. */
  123463. rc = growVTrans(db);
  123464. if( rc==SQLITE_OK ){
  123465. rc = pModule->xBegin(pVTab->pVtab);
  123466. if( rc==SQLITE_OK ){
  123467. int iSvpt = db->nStatement + db->nSavepoint;
  123468. addToVTrans(db, pVTab);
  123469. if( iSvpt && pModule->xSavepoint ){
  123470. pVTab->iSavepoint = iSvpt;
  123471. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  123472. }
  123473. }
  123474. }
  123475. }
  123476. return rc;
  123477. }
  123478. /*
  123479. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  123480. ** virtual tables that currently have an open transaction. Pass iSavepoint
  123481. ** as the second argument to the virtual table method invoked.
  123482. **
  123483. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  123484. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  123485. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  123486. ** an open transaction is invoked.
  123487. **
  123488. ** If any virtual table method returns an error code other than SQLITE_OK,
  123489. ** processing is abandoned and the error returned to the caller of this
  123490. ** function immediately. If all calls to virtual table methods are successful,
  123491. ** SQLITE_OK is returned.
  123492. */
  123493. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  123494. int rc = SQLITE_OK;
  123495. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  123496. assert( iSavepoint>=-1 );
  123497. if( db->aVTrans ){
  123498. int i;
  123499. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  123500. VTable *pVTab = db->aVTrans[i];
  123501. const sqlite3_module *pMod = pVTab->pMod->pModule;
  123502. if( pVTab->pVtab && pMod->iVersion>=2 ){
  123503. int (*xMethod)(sqlite3_vtab *, int);
  123504. switch( op ){
  123505. case SAVEPOINT_BEGIN:
  123506. xMethod = pMod->xSavepoint;
  123507. pVTab->iSavepoint = iSavepoint+1;
  123508. break;
  123509. case SAVEPOINT_ROLLBACK:
  123510. xMethod = pMod->xRollbackTo;
  123511. break;
  123512. default:
  123513. xMethod = pMod->xRelease;
  123514. break;
  123515. }
  123516. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  123517. rc = xMethod(pVTab->pVtab, iSavepoint);
  123518. }
  123519. }
  123520. }
  123521. }
  123522. return rc;
  123523. }
  123524. /*
  123525. ** The first parameter (pDef) is a function implementation. The
  123526. ** second parameter (pExpr) is the first argument to this function.
  123527. ** If pExpr is a column in a virtual table, then let the virtual
  123528. ** table implementation have an opportunity to overload the function.
  123529. **
  123530. ** This routine is used to allow virtual table implementations to
  123531. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  123532. **
  123533. ** Return either the pDef argument (indicating no change) or a
  123534. ** new FuncDef structure that is marked as ephemeral using the
  123535. ** SQLITE_FUNC_EPHEM flag.
  123536. */
  123537. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  123538. sqlite3 *db, /* Database connection for reporting malloc problems */
  123539. FuncDef *pDef, /* Function to possibly overload */
  123540. int nArg, /* Number of arguments to the function */
  123541. Expr *pExpr /* First argument to the function */
  123542. ){
  123543. Table *pTab;
  123544. sqlite3_vtab *pVtab;
  123545. sqlite3_module *pMod;
  123546. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  123547. void *pArg = 0;
  123548. FuncDef *pNew;
  123549. int rc = 0;
  123550. /* Check to see the left operand is a column in a virtual table */
  123551. if( NEVER(pExpr==0) ) return pDef;
  123552. if( pExpr->op!=TK_COLUMN ) return pDef;
  123553. pTab = pExpr->pTab;
  123554. if( pTab==0 ) return pDef;
  123555. if( !IsVirtual(pTab) ) return pDef;
  123556. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  123557. assert( pVtab!=0 );
  123558. assert( pVtab->pModule!=0 );
  123559. pMod = (sqlite3_module *)pVtab->pModule;
  123560. if( pMod->xFindFunction==0 ) return pDef;
  123561. /* Call the xFindFunction method on the virtual table implementation
  123562. ** to see if the implementation wants to overload this function.
  123563. **
  123564. ** Though undocumented, we have historically always invoked xFindFunction
  123565. ** with an all lower-case function name. Continue in this tradition to
  123566. ** avoid any chance of an incompatibility.
  123567. */
  123568. #ifdef SQLITE_DEBUG
  123569. {
  123570. int i;
  123571. for(i=0; pDef->zName[i]; i++){
  123572. unsigned char x = (unsigned char)pDef->zName[i];
  123573. assert( x==sqlite3UpperToLower[x] );
  123574. }
  123575. }
  123576. #endif
  123577. rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
  123578. if( rc==0 ){
  123579. return pDef;
  123580. }
  123581. /* Create a new ephemeral function definition for the overloaded
  123582. ** function */
  123583. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  123584. + sqlite3Strlen30(pDef->zName) + 1);
  123585. if( pNew==0 ){
  123586. return pDef;
  123587. }
  123588. *pNew = *pDef;
  123589. pNew->zName = (const char*)&pNew[1];
  123590. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  123591. pNew->xSFunc = xSFunc;
  123592. pNew->pUserData = pArg;
  123593. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  123594. return pNew;
  123595. }
  123596. /*
  123597. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  123598. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  123599. ** array if it is missing. If pTab is already in the array, this routine
  123600. ** is a no-op.
  123601. */
  123602. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  123603. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  123604. int i, n;
  123605. Table **apVtabLock;
  123606. assert( IsVirtual(pTab) );
  123607. for(i=0; i<pToplevel->nVtabLock; i++){
  123608. if( pTab==pToplevel->apVtabLock[i] ) return;
  123609. }
  123610. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  123611. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  123612. if( apVtabLock ){
  123613. pToplevel->apVtabLock = apVtabLock;
  123614. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  123615. }else{
  123616. sqlite3OomFault(pToplevel->db);
  123617. }
  123618. }
  123619. /*
  123620. ** Check to see if virtual table module pMod can be have an eponymous
  123621. ** virtual table instance. If it can, create one if one does not already
  123622. ** exist. Return non-zero if the eponymous virtual table instance exists
  123623. ** when this routine returns, and return zero if it does not exist.
  123624. **
  123625. ** An eponymous virtual table instance is one that is named after its
  123626. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  123627. ** statement in order to come into existance. Eponymous virtual table
  123628. ** instances always exist. They cannot be DROP-ed.
  123629. **
  123630. ** Any virtual table module for which xConnect and xCreate are the same
  123631. ** method can have an eponymous virtual table instance.
  123632. */
  123633. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  123634. const sqlite3_module *pModule = pMod->pModule;
  123635. Table *pTab;
  123636. char *zErr = 0;
  123637. int rc;
  123638. sqlite3 *db = pParse->db;
  123639. if( pMod->pEpoTab ) return 1;
  123640. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  123641. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  123642. if( pTab==0 ) return 0;
  123643. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  123644. if( pTab->zName==0 ){
  123645. sqlite3DbFree(db, pTab);
  123646. return 0;
  123647. }
  123648. pMod->pEpoTab = pTab;
  123649. pTab->nTabRef = 1;
  123650. pTab->pSchema = db->aDb[0].pSchema;
  123651. assert( pTab->nModuleArg==0 );
  123652. pTab->iPKey = -1;
  123653. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  123654. addModuleArgument(db, pTab, 0);
  123655. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  123656. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  123657. if( rc ){
  123658. sqlite3ErrorMsg(pParse, "%s", zErr);
  123659. sqlite3DbFree(db, zErr);
  123660. sqlite3VtabEponymousTableClear(db, pMod);
  123661. return 0;
  123662. }
  123663. return 1;
  123664. }
  123665. /*
  123666. ** Erase the eponymous virtual table instance associated with
  123667. ** virtual table module pMod, if it exists.
  123668. */
  123669. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  123670. Table *pTab = pMod->pEpoTab;
  123671. if( pTab!=0 ){
  123672. /* Mark the table as Ephemeral prior to deleting it, so that the
  123673. ** sqlite3DeleteTable() routine will know that it is not stored in
  123674. ** the schema. */
  123675. pTab->tabFlags |= TF_Ephemeral;
  123676. sqlite3DeleteTable(db, pTab);
  123677. pMod->pEpoTab = 0;
  123678. }
  123679. }
  123680. /*
  123681. ** Return the ON CONFLICT resolution mode in effect for the virtual
  123682. ** table update operation currently in progress.
  123683. **
  123684. ** The results of this routine are undefined unless it is called from
  123685. ** within an xUpdate method.
  123686. */
  123687. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  123688. static const unsigned char aMap[] = {
  123689. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  123690. };
  123691. #ifdef SQLITE_ENABLE_API_ARMOR
  123692. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123693. #endif
  123694. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  123695. assert( OE_Ignore==4 && OE_Replace==5 );
  123696. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  123697. return (int)aMap[db->vtabOnConflict-1];
  123698. }
  123699. /*
  123700. ** Call from within the xCreate() or xConnect() methods to provide
  123701. ** the SQLite core with additional information about the behavior
  123702. ** of the virtual table being implemented.
  123703. */
  123704. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  123705. va_list ap;
  123706. int rc = SQLITE_OK;
  123707. #ifdef SQLITE_ENABLE_API_ARMOR
  123708. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123709. #endif
  123710. sqlite3_mutex_enter(db->mutex);
  123711. va_start(ap, op);
  123712. switch( op ){
  123713. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  123714. VtabCtx *p = db->pVtabCtx;
  123715. if( !p ){
  123716. rc = SQLITE_MISUSE_BKPT;
  123717. }else{
  123718. assert( p->pTab==0 || IsVirtual(p->pTab) );
  123719. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  123720. }
  123721. break;
  123722. }
  123723. default:
  123724. rc = SQLITE_MISUSE_BKPT;
  123725. break;
  123726. }
  123727. va_end(ap);
  123728. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  123729. sqlite3_mutex_leave(db->mutex);
  123730. return rc;
  123731. }
  123732. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  123733. /************** End of vtab.c ************************************************/
  123734. /************** Begin file wherecode.c ***************************************/
  123735. /*
  123736. ** 2015-06-06
  123737. **
  123738. ** The author disclaims copyright to this source code. In place of
  123739. ** a legal notice, here is a blessing:
  123740. **
  123741. ** May you do good and not evil.
  123742. ** May you find forgiveness for yourself and forgive others.
  123743. ** May you share freely, never taking more than you give.
  123744. **
  123745. *************************************************************************
  123746. ** This module contains C code that generates VDBE code used to process
  123747. ** the WHERE clause of SQL statements.
  123748. **
  123749. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  123750. ** size of where.c and make it easier to edit. This file contains the routines
  123751. ** that actually generate the bulk of the WHERE loop code. The original where.c
  123752. ** file retains the code that does query planning and analysis.
  123753. */
  123754. /* #include "sqliteInt.h" */
  123755. /************** Include whereInt.h in the middle of wherecode.c **************/
  123756. /************** Begin file whereInt.h ****************************************/
  123757. /*
  123758. ** 2013-11-12
  123759. **
  123760. ** The author disclaims copyright to this source code. In place of
  123761. ** a legal notice, here is a blessing:
  123762. **
  123763. ** May you do good and not evil.
  123764. ** May you find forgiveness for yourself and forgive others.
  123765. ** May you share freely, never taking more than you give.
  123766. **
  123767. *************************************************************************
  123768. **
  123769. ** This file contains structure and macro definitions for the query
  123770. ** planner logic in "where.c". These definitions are broken out into
  123771. ** a separate source file for easier editing.
  123772. */
  123773. /*
  123774. ** Trace output macros
  123775. */
  123776. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  123777. /***/ extern int sqlite3WhereTrace;
  123778. #endif
  123779. #if defined(SQLITE_DEBUG) \
  123780. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  123781. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  123782. # define WHERETRACE_ENABLED 1
  123783. #else
  123784. # define WHERETRACE(K,X)
  123785. #endif
  123786. /* Forward references
  123787. */
  123788. typedef struct WhereClause WhereClause;
  123789. typedef struct WhereMaskSet WhereMaskSet;
  123790. typedef struct WhereOrInfo WhereOrInfo;
  123791. typedef struct WhereAndInfo WhereAndInfo;
  123792. typedef struct WhereLevel WhereLevel;
  123793. typedef struct WhereLoop WhereLoop;
  123794. typedef struct WherePath WherePath;
  123795. typedef struct WhereTerm WhereTerm;
  123796. typedef struct WhereLoopBuilder WhereLoopBuilder;
  123797. typedef struct WhereScan WhereScan;
  123798. typedef struct WhereOrCost WhereOrCost;
  123799. typedef struct WhereOrSet WhereOrSet;
  123800. /*
  123801. ** This object contains information needed to implement a single nested
  123802. ** loop in WHERE clause.
  123803. **
  123804. ** Contrast this object with WhereLoop. This object describes the
  123805. ** implementation of the loop. WhereLoop describes the algorithm.
  123806. ** This object contains a pointer to the WhereLoop algorithm as one of
  123807. ** its elements.
  123808. **
  123809. ** The WhereInfo object contains a single instance of this object for
  123810. ** each term in the FROM clause (which is to say, for each of the
  123811. ** nested loops as implemented). The order of WhereLevel objects determines
  123812. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  123813. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  123814. */
  123815. struct WhereLevel {
  123816. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  123817. int iTabCur; /* The VDBE cursor used to access the table */
  123818. int iIdxCur; /* The VDBE cursor used to access pIdx */
  123819. int addrBrk; /* Jump here to break out of the loop */
  123820. int addrNxt; /* Jump here to start the next IN combination */
  123821. int addrSkip; /* Jump here for next iteration of skip-scan */
  123822. int addrCont; /* Jump here to continue with the next loop cycle */
  123823. int addrFirst; /* First instruction of interior of the loop */
  123824. int addrBody; /* Beginning of the body of this loop */
  123825. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  123826. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  123827. int addrLikeRep; /* LIKE range processing address */
  123828. #endif
  123829. u8 iFrom; /* Which entry in the FROM clause */
  123830. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  123831. int p1, p2; /* Operands of the opcode used to ends the loop */
  123832. union { /* Information that depends on pWLoop->wsFlags */
  123833. struct {
  123834. int nIn; /* Number of entries in aInLoop[] */
  123835. struct InLoop {
  123836. int iCur; /* The VDBE cursor used by this IN operator */
  123837. int addrInTop; /* Top of the IN loop */
  123838. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  123839. } *aInLoop; /* Information about each nested IN operator */
  123840. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  123841. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  123842. } u;
  123843. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  123844. Bitmask notReady; /* FROM entries not usable at this level */
  123845. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  123846. int addrVisit; /* Address at which row is visited */
  123847. #endif
  123848. };
  123849. /*
  123850. ** Each instance of this object represents an algorithm for evaluating one
  123851. ** term of a join. Every term of the FROM clause will have at least
  123852. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  123853. ** prevent a query solution - which is an error) and many terms of the
  123854. ** FROM clause will have multiple WhereLoop objects, each describing a
  123855. ** potential way of implementing that FROM-clause term, together with
  123856. ** dependencies and cost estimates for using the chosen algorithm.
  123857. **
  123858. ** Query planning consists of building up a collection of these WhereLoop
  123859. ** objects, then computing a particular sequence of WhereLoop objects, with
  123860. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  123861. ** and that minimize the overall cost.
  123862. */
  123863. struct WhereLoop {
  123864. Bitmask prereq; /* Bitmask of other loops that must run first */
  123865. Bitmask maskSelf; /* Bitmask identifying table iTab */
  123866. #ifdef SQLITE_DEBUG
  123867. char cId; /* Symbolic ID of this loop for debugging use */
  123868. #endif
  123869. u8 iTab; /* Position in FROM clause of table for this loop */
  123870. u8 iSortIdx; /* Sorting index number. 0==None */
  123871. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  123872. LogEst rRun; /* Cost of running each loop */
  123873. LogEst nOut; /* Estimated number of output rows */
  123874. union {
  123875. struct { /* Information for internal btree tables */
  123876. u16 nEq; /* Number of equality constraints */
  123877. u16 nBtm; /* Size of BTM vector */
  123878. u16 nTop; /* Size of TOP vector */
  123879. u16 nIdxCol; /* Index column used for ORDER BY */
  123880. Index *pIndex; /* Index used, or NULL */
  123881. } btree;
  123882. struct { /* Information for virtual tables */
  123883. int idxNum; /* Index number */
  123884. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  123885. i8 isOrdered; /* True if satisfies ORDER BY */
  123886. u16 omitMask; /* Terms that may be omitted */
  123887. char *idxStr; /* Index identifier string */
  123888. } vtab;
  123889. } u;
  123890. u32 wsFlags; /* WHERE_* flags describing the plan */
  123891. u16 nLTerm; /* Number of entries in aLTerm[] */
  123892. u16 nSkip; /* Number of NULL aLTerm[] entries */
  123893. /**** whereLoopXfer() copies fields above ***********************/
  123894. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  123895. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  123896. WhereTerm **aLTerm; /* WhereTerms used */
  123897. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  123898. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  123899. };
  123900. /* This object holds the prerequisites and the cost of running a
  123901. ** subquery on one operand of an OR operator in the WHERE clause.
  123902. ** See WhereOrSet for additional information
  123903. */
  123904. struct WhereOrCost {
  123905. Bitmask prereq; /* Prerequisites */
  123906. LogEst rRun; /* Cost of running this subquery */
  123907. LogEst nOut; /* Number of outputs for this subquery */
  123908. };
  123909. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  123910. ** correspond to the subquery(s) of OR-clause processing. Only the
  123911. ** best N_OR_COST elements are retained.
  123912. */
  123913. #define N_OR_COST 3
  123914. struct WhereOrSet {
  123915. u16 n; /* Number of valid a[] entries */
  123916. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  123917. };
  123918. /*
  123919. ** Each instance of this object holds a sequence of WhereLoop objects
  123920. ** that implement some or all of a query plan.
  123921. **
  123922. ** Think of each WhereLoop object as a node in a graph with arcs
  123923. ** showing dependencies and costs for travelling between nodes. (That is
  123924. ** not a completely accurate description because WhereLoop costs are a
  123925. ** vector, not a scalar, and because dependencies are many-to-one, not
  123926. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  123927. ** Then a WherePath object is a path through the graph that visits some
  123928. ** or all of the WhereLoop objects once.
  123929. **
  123930. ** The "solver" works by creating the N best WherePath objects of length
  123931. ** 1. Then using those as a basis to compute the N best WherePath objects
  123932. ** of length 2. And so forth until the length of WherePaths equals the
  123933. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  123934. ** at the end is the chosen query plan.
  123935. */
  123936. struct WherePath {
  123937. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  123938. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  123939. LogEst nRow; /* Estimated number of rows generated by this path */
  123940. LogEst rCost; /* Total cost of this path */
  123941. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  123942. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  123943. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  123944. };
  123945. /*
  123946. ** The query generator uses an array of instances of this structure to
  123947. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  123948. ** clause subexpression is separated from the others by AND operators,
  123949. ** usually, or sometimes subexpressions separated by OR.
  123950. **
  123951. ** All WhereTerms are collected into a single WhereClause structure.
  123952. ** The following identity holds:
  123953. **
  123954. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  123955. **
  123956. ** When a term is of the form:
  123957. **
  123958. ** X <op> <expr>
  123959. **
  123960. ** where X is a column name and <op> is one of certain operators,
  123961. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  123962. ** cursor number and column number for X. WhereTerm.eOperator records
  123963. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  123964. ** use of a bitmask encoding for the operator allows us to search
  123965. ** quickly for terms that match any of several different operators.
  123966. **
  123967. ** A WhereTerm might also be two or more subterms connected by OR:
  123968. **
  123969. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  123970. **
  123971. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  123972. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  123973. ** is collected about the OR clause.
  123974. **
  123975. ** If a term in the WHERE clause does not match either of the two previous
  123976. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  123977. ** to the original subexpression content and wtFlags is set up appropriately
  123978. ** but no other fields in the WhereTerm object are meaningful.
  123979. **
  123980. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  123981. ** but they do so indirectly. A single WhereMaskSet structure translates
  123982. ** cursor number into bits and the translated bit is stored in the prereq
  123983. ** fields. The translation is used in order to maximize the number of
  123984. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  123985. ** spread out over the non-negative integers. For example, the cursor
  123986. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  123987. ** translates these sparse cursor numbers into consecutive integers
  123988. ** beginning with 0 in order to make the best possible use of the available
  123989. ** bits in the Bitmask. So, in the example above, the cursor numbers
  123990. ** would be mapped into integers 0 through 7.
  123991. **
  123992. ** The number of terms in a join is limited by the number of bits
  123993. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  123994. ** is only able to process joins with 64 or fewer tables.
  123995. */
  123996. struct WhereTerm {
  123997. Expr *pExpr; /* Pointer to the subexpression that is this term */
  123998. WhereClause *pWC; /* The clause this term is part of */
  123999. LogEst truthProb; /* Probability of truth for this expression */
  124000. u16 wtFlags; /* TERM_xxx bit flags. See below */
  124001. u16 eOperator; /* A WO_xx value describing <op> */
  124002. u8 nChild; /* Number of children that must disable us */
  124003. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  124004. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  124005. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  124006. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  124007. union {
  124008. int leftColumn; /* Column number of X in "X <op> <expr>" */
  124009. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  124010. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  124011. } u;
  124012. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  124013. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  124014. };
  124015. /*
  124016. ** Allowed values of WhereTerm.wtFlags
  124017. */
  124018. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  124019. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  124020. #define TERM_CODED 0x04 /* This term is already coded */
  124021. #define TERM_COPIED 0x08 /* Has a child */
  124022. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  124023. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  124024. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  124025. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124026. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  124027. #else
  124028. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  124029. #endif
  124030. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  124031. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  124032. #define TERM_LIKE 0x400 /* The original LIKE operator */
  124033. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  124034. #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
  124035. /*
  124036. ** An instance of the WhereScan object is used as an iterator for locating
  124037. ** terms in the WHERE clause that are useful to the query planner.
  124038. */
  124039. struct WhereScan {
  124040. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  124041. WhereClause *pWC; /* WhereClause currently being scanned */
  124042. const char *zCollName; /* Required collating sequence, if not NULL */
  124043. Expr *pIdxExpr; /* Search for this index expression */
  124044. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  124045. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  124046. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  124047. u32 opMask; /* Acceptable operators */
  124048. int k; /* Resume scanning at this->pWC->a[this->k] */
  124049. int aiCur[11]; /* Cursors in the equivalence class */
  124050. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  124051. };
  124052. /*
  124053. ** An instance of the following structure holds all information about a
  124054. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  124055. **
  124056. ** Explanation of pOuter: For a WHERE clause of the form
  124057. **
  124058. ** a AND ((b AND c) OR (d AND e)) AND f
  124059. **
  124060. ** There are separate WhereClause objects for the whole clause and for
  124061. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  124062. ** subclauses points to the WhereClause object for the whole clause.
  124063. */
  124064. struct WhereClause {
  124065. WhereInfo *pWInfo; /* WHERE clause processing context */
  124066. WhereClause *pOuter; /* Outer conjunction */
  124067. u8 op; /* Split operator. TK_AND or TK_OR */
  124068. int nTerm; /* Number of terms */
  124069. int nSlot; /* Number of entries in a[] */
  124070. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  124071. #if defined(SQLITE_SMALL_STACK)
  124072. WhereTerm aStatic[1]; /* Initial static space for a[] */
  124073. #else
  124074. WhereTerm aStatic[8]; /* Initial static space for a[] */
  124075. #endif
  124076. };
  124077. /*
  124078. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  124079. ** a dynamically allocated instance of the following structure.
  124080. */
  124081. struct WhereOrInfo {
  124082. WhereClause wc; /* Decomposition into subterms */
  124083. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  124084. };
  124085. /*
  124086. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  124087. ** a dynamically allocated instance of the following structure.
  124088. */
  124089. struct WhereAndInfo {
  124090. WhereClause wc; /* The subexpression broken out */
  124091. };
  124092. /*
  124093. ** An instance of the following structure keeps track of a mapping
  124094. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  124095. **
  124096. ** The VDBE cursor numbers are small integers contained in
  124097. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  124098. ** clause, the cursor numbers might not begin with 0 and they might
  124099. ** contain gaps in the numbering sequence. But we want to make maximum
  124100. ** use of the bits in our bitmasks. This structure provides a mapping
  124101. ** from the sparse cursor numbers into consecutive integers beginning
  124102. ** with 0.
  124103. **
  124104. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  124105. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  124106. **
  124107. ** For example, if the WHERE clause expression used these VDBE
  124108. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  124109. ** would map those cursor numbers into bits 0 through 5.
  124110. **
  124111. ** Note that the mapping is not necessarily ordered. In the example
  124112. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  124113. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  124114. ** does not really matter. What is important is that sparse cursor
  124115. ** numbers all get mapped into bit numbers that begin with 0 and contain
  124116. ** no gaps.
  124117. */
  124118. struct WhereMaskSet {
  124119. int bVarSelect; /* Used by sqlite3WhereExprUsage() */
  124120. int n; /* Number of assigned cursor values */
  124121. int ix[BMS]; /* Cursor assigned to each bit */
  124122. };
  124123. /*
  124124. ** Initialize a WhereMaskSet object
  124125. */
  124126. #define initMaskSet(P) (P)->n=0
  124127. /*
  124128. ** This object is a convenience wrapper holding all information needed
  124129. ** to construct WhereLoop objects for a particular query.
  124130. */
  124131. struct WhereLoopBuilder {
  124132. WhereInfo *pWInfo; /* Information about this WHERE */
  124133. WhereClause *pWC; /* WHERE clause terms */
  124134. ExprList *pOrderBy; /* ORDER BY clause */
  124135. WhereLoop *pNew; /* Template WhereLoop */
  124136. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  124137. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124138. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  124139. int nRecValid; /* Number of valid fields currently in pRec */
  124140. #endif
  124141. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  124142. };
  124143. /* Allowed values for WhereLoopBuider.bldFlags */
  124144. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  124145. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  124146. /*
  124147. ** The WHERE clause processing routine has two halves. The
  124148. ** first part does the start of the WHERE loop and the second
  124149. ** half does the tail of the WHERE loop. An instance of
  124150. ** this structure is returned by the first half and passed
  124151. ** into the second half to give some continuity.
  124152. **
  124153. ** An instance of this object holds the complete state of the query
  124154. ** planner.
  124155. */
  124156. struct WhereInfo {
  124157. Parse *pParse; /* Parsing and code generating context */
  124158. SrcList *pTabList; /* List of tables in the join */
  124159. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  124160. ExprList *pResultSet; /* Result set of the query */
  124161. Expr *pWhere; /* The complete WHERE clause */
  124162. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  124163. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  124164. int iContinue; /* Jump here to continue with next record */
  124165. int iBreak; /* Jump here to break out of the loop */
  124166. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  124167. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  124168. u8 nLevel; /* Number of nested loop */
  124169. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  124170. u8 sorted; /* True if really sorted (not just grouped) */
  124171. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  124172. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  124173. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  124174. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  124175. int iTop; /* The very beginning of the WHERE loop */
  124176. WhereLoop *pLoops; /* List of all WhereLoop objects */
  124177. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  124178. LogEst nRowOut; /* Estimated number of output rows */
  124179. WhereClause sWC; /* Decomposition of the WHERE clause */
  124180. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  124181. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  124182. };
  124183. /*
  124184. ** Private interfaces - callable only by other where.c routines.
  124185. **
  124186. ** where.c:
  124187. */
  124188. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  124189. #ifdef WHERETRACE_ENABLED
  124190. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  124191. #endif
  124192. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  124193. WhereClause *pWC, /* The WHERE clause to be searched */
  124194. int iCur, /* Cursor number of LHS */
  124195. int iColumn, /* Column number of LHS */
  124196. Bitmask notReady, /* RHS must not overlap with this mask */
  124197. u32 op, /* Mask of WO_xx values describing operator */
  124198. Index *pIdx /* Must be compatible with this index, if not NULL */
  124199. );
  124200. /* wherecode.c: */
  124201. #ifndef SQLITE_OMIT_EXPLAIN
  124202. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  124203. Parse *pParse, /* Parse context */
  124204. SrcList *pTabList, /* Table list this loop refers to */
  124205. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  124206. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  124207. );
  124208. #else
  124209. # define sqlite3WhereExplainOneScan(u,v,w,x) 0
  124210. #endif /* SQLITE_OMIT_EXPLAIN */
  124211. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  124212. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  124213. Vdbe *v, /* Vdbe to add scanstatus entry to */
  124214. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  124215. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  124216. int addrExplain /* Address of OP_Explain (or 0) */
  124217. );
  124218. #else
  124219. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  124220. #endif
  124221. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  124222. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  124223. int iLevel, /* Which level of pWInfo->a[] should be coded */
  124224. Bitmask notReady /* Which tables are currently available */
  124225. );
  124226. /* whereexpr.c: */
  124227. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  124228. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  124229. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  124230. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  124231. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  124232. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  124233. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  124234. /*
  124235. ** Bitmasks for the operators on WhereTerm objects. These are all
  124236. ** operators that are of interest to the query planner. An
  124237. ** OR-ed combination of these values can be used when searching for
  124238. ** particular WhereTerms within a WhereClause.
  124239. **
  124240. ** Value constraints:
  124241. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  124242. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  124243. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  124244. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  124245. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  124246. */
  124247. #define WO_IN 0x0001
  124248. #define WO_EQ 0x0002
  124249. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  124250. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  124251. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  124252. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  124253. #define WO_AUX 0x0040 /* Op useful to virtual tables only */
  124254. #define WO_IS 0x0080
  124255. #define WO_ISNULL 0x0100
  124256. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  124257. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  124258. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  124259. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  124260. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  124261. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  124262. /*
  124263. ** These are definitions of bits in the WhereLoop.wsFlags field.
  124264. ** The particular combination of bits in each WhereLoop help to
  124265. ** determine the algorithm that WhereLoop represents.
  124266. */
  124267. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  124268. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  124269. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  124270. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  124271. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  124272. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  124273. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  124274. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  124275. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  124276. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  124277. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  124278. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  124279. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  124280. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  124281. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  124282. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  124283. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  124284. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  124285. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  124286. /************** End of whereInt.h ********************************************/
  124287. /************** Continuing where we left off in wherecode.c ******************/
  124288. #ifndef SQLITE_OMIT_EXPLAIN
  124289. /*
  124290. ** Return the name of the i-th column of the pIdx index.
  124291. */
  124292. static const char *explainIndexColumnName(Index *pIdx, int i){
  124293. i = pIdx->aiColumn[i];
  124294. if( i==XN_EXPR ) return "<expr>";
  124295. if( i==XN_ROWID ) return "rowid";
  124296. return pIdx->pTable->aCol[i].zName;
  124297. }
  124298. /*
  124299. ** This routine is a helper for explainIndexRange() below
  124300. **
  124301. ** pStr holds the text of an expression that we are building up one term
  124302. ** at a time. This routine adds a new term to the end of the expression.
  124303. ** Terms are separated by AND so add the "AND" text for second and subsequent
  124304. ** terms only.
  124305. */
  124306. static void explainAppendTerm(
  124307. StrAccum *pStr, /* The text expression being built */
  124308. Index *pIdx, /* Index to read column names from */
  124309. int nTerm, /* Number of terms */
  124310. int iTerm, /* Zero-based index of first term. */
  124311. int bAnd, /* Non-zero to append " AND " */
  124312. const char *zOp /* Name of the operator */
  124313. ){
  124314. int i;
  124315. assert( nTerm>=1 );
  124316. if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
  124317. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  124318. for(i=0; i<nTerm; i++){
  124319. if( i ) sqlite3_str_append(pStr, ",", 1);
  124320. sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
  124321. }
  124322. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  124323. sqlite3_str_append(pStr, zOp, 1);
  124324. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  124325. for(i=0; i<nTerm; i++){
  124326. if( i ) sqlite3_str_append(pStr, ",", 1);
  124327. sqlite3_str_append(pStr, "?", 1);
  124328. }
  124329. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  124330. }
  124331. /*
  124332. ** Argument pLevel describes a strategy for scanning table pTab. This
  124333. ** function appends text to pStr that describes the subset of table
  124334. ** rows scanned by the strategy in the form of an SQL expression.
  124335. **
  124336. ** For example, if the query:
  124337. **
  124338. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  124339. **
  124340. ** is run and there is an index on (a, b), then this function returns a
  124341. ** string similar to:
  124342. **
  124343. ** "a=? AND b>?"
  124344. */
  124345. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  124346. Index *pIndex = pLoop->u.btree.pIndex;
  124347. u16 nEq = pLoop->u.btree.nEq;
  124348. u16 nSkip = pLoop->nSkip;
  124349. int i, j;
  124350. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  124351. sqlite3_str_append(pStr, " (", 2);
  124352. for(i=0; i<nEq; i++){
  124353. const char *z = explainIndexColumnName(pIndex, i);
  124354. if( i ) sqlite3_str_append(pStr, " AND ", 5);
  124355. sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  124356. }
  124357. j = i;
  124358. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  124359. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  124360. i = 1;
  124361. }
  124362. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  124363. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  124364. }
  124365. sqlite3_str_append(pStr, ")", 1);
  124366. }
  124367. /*
  124368. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  124369. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  124370. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  124371. ** is added to the output to describe the table scan strategy in pLevel.
  124372. **
  124373. ** If an OP_Explain opcode is added to the VM, its address is returned.
  124374. ** Otherwise, if no OP_Explain is coded, zero is returned.
  124375. */
  124376. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  124377. Parse *pParse, /* Parse context */
  124378. SrcList *pTabList, /* Table list this loop refers to */
  124379. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  124380. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  124381. ){
  124382. int ret = 0;
  124383. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  124384. if( sqlite3ParseToplevel(pParse)->explain==2 )
  124385. #endif
  124386. {
  124387. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  124388. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  124389. sqlite3 *db = pParse->db; /* Database handle */
  124390. int isSearch; /* True for a SEARCH. False for SCAN. */
  124391. WhereLoop *pLoop; /* The controlling WhereLoop object */
  124392. u32 flags; /* Flags that describe this loop */
  124393. char *zMsg; /* Text to add to EQP output */
  124394. StrAccum str; /* EQP output string */
  124395. char zBuf[100]; /* Initial space for EQP output string */
  124396. pLoop = pLevel->pWLoop;
  124397. flags = pLoop->wsFlags;
  124398. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  124399. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  124400. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  124401. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  124402. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  124403. sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
  124404. if( pItem->pSelect ){
  124405. sqlite3_str_appendf(&str, " SUBQUERY 0x%p", pItem->pSelect);
  124406. }else{
  124407. sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
  124408. }
  124409. if( pItem->zAlias ){
  124410. sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
  124411. }
  124412. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  124413. const char *zFmt = 0;
  124414. Index *pIdx;
  124415. assert( pLoop->u.btree.pIndex!=0 );
  124416. pIdx = pLoop->u.btree.pIndex;
  124417. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  124418. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  124419. if( isSearch ){
  124420. zFmt = "PRIMARY KEY";
  124421. }
  124422. }else if( flags & WHERE_PARTIALIDX ){
  124423. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  124424. }else if( flags & WHERE_AUTO_INDEX ){
  124425. zFmt = "AUTOMATIC COVERING INDEX";
  124426. }else if( flags & WHERE_IDX_ONLY ){
  124427. zFmt = "COVERING INDEX %s";
  124428. }else{
  124429. zFmt = "INDEX %s";
  124430. }
  124431. if( zFmt ){
  124432. sqlite3_str_append(&str, " USING ", 7);
  124433. sqlite3_str_appendf(&str, zFmt, pIdx->zName);
  124434. explainIndexRange(&str, pLoop);
  124435. }
  124436. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  124437. const char *zRangeOp;
  124438. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  124439. zRangeOp = "=";
  124440. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  124441. zRangeOp = ">? AND rowid<";
  124442. }else if( flags&WHERE_BTM_LIMIT ){
  124443. zRangeOp = ">";
  124444. }else{
  124445. assert( flags&WHERE_TOP_LIMIT);
  124446. zRangeOp = "<";
  124447. }
  124448. sqlite3_str_appendf(&str,
  124449. " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  124450. }
  124451. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124452. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  124453. sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
  124454. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  124455. }
  124456. #endif
  124457. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  124458. if( pLoop->nOut>=10 ){
  124459. sqlite3_str_appendf(&str, " (~%llu rows)",
  124460. sqlite3LogEstToInt(pLoop->nOut));
  124461. }else{
  124462. sqlite3_str_append(&str, " (~1 row)", 9);
  124463. }
  124464. #endif
  124465. zMsg = sqlite3StrAccumFinish(&str);
  124466. ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
  124467. pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
  124468. }
  124469. return ret;
  124470. }
  124471. #endif /* SQLITE_OMIT_EXPLAIN */
  124472. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  124473. /*
  124474. ** Configure the VM passed as the first argument with an
  124475. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  124476. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  124477. ** clause that the scan reads data from.
  124478. **
  124479. ** If argument addrExplain is not 0, it must be the address of an
  124480. ** OP_Explain instruction that describes the same loop.
  124481. */
  124482. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  124483. Vdbe *v, /* Vdbe to add scanstatus entry to */
  124484. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  124485. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  124486. int addrExplain /* Address of OP_Explain (or 0) */
  124487. ){
  124488. const char *zObj = 0;
  124489. WhereLoop *pLoop = pLvl->pWLoop;
  124490. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  124491. zObj = pLoop->u.btree.pIndex->zName;
  124492. }else{
  124493. zObj = pSrclist->a[pLvl->iFrom].zName;
  124494. }
  124495. sqlite3VdbeScanStatus(
  124496. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  124497. );
  124498. }
  124499. #endif
  124500. /*
  124501. ** Disable a term in the WHERE clause. Except, do not disable the term
  124502. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  124503. ** or USING clause of that join.
  124504. **
  124505. ** Consider the term t2.z='ok' in the following queries:
  124506. **
  124507. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  124508. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  124509. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  124510. **
  124511. ** The t2.z='ok' is disabled in the in (2) because it originates
  124512. ** in the ON clause. The term is disabled in (3) because it is not part
  124513. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  124514. **
  124515. ** Disabling a term causes that term to not be tested in the inner loop
  124516. ** of the join. Disabling is an optimization. When terms are satisfied
  124517. ** by indices, we disable them to prevent redundant tests in the inner
  124518. ** loop. We would get the correct results if nothing were ever disabled,
  124519. ** but joins might run a little slower. The trick is to disable as much
  124520. ** as we can without disabling too much. If we disabled in (1), we'd get
  124521. ** the wrong answer. See ticket #813.
  124522. **
  124523. ** If all the children of a term are disabled, then that term is also
  124524. ** automatically disabled. In this way, terms get disabled if derived
  124525. ** virtual terms are tested first. For example:
  124526. **
  124527. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  124528. ** \___________/ \______/ \_____/
  124529. ** parent child1 child2
  124530. **
  124531. ** Only the parent term was in the original WHERE clause. The child1
  124532. ** and child2 terms were added by the LIKE optimization. If both of
  124533. ** the virtual child terms are valid, then testing of the parent can be
  124534. ** skipped.
  124535. **
  124536. ** Usually the parent term is marked as TERM_CODED. But if the parent
  124537. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  124538. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  124539. ** a conditional such that is only evaluated on the second pass of a
  124540. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  124541. */
  124542. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  124543. int nLoop = 0;
  124544. assert( pTerm!=0 );
  124545. while( (pTerm->wtFlags & TERM_CODED)==0
  124546. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  124547. && (pLevel->notReady & pTerm->prereqAll)==0
  124548. ){
  124549. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  124550. pTerm->wtFlags |= TERM_LIKECOND;
  124551. }else{
  124552. pTerm->wtFlags |= TERM_CODED;
  124553. }
  124554. if( pTerm->iParent<0 ) break;
  124555. pTerm = &pTerm->pWC->a[pTerm->iParent];
  124556. assert( pTerm!=0 );
  124557. pTerm->nChild--;
  124558. if( pTerm->nChild!=0 ) break;
  124559. nLoop++;
  124560. }
  124561. }
  124562. /*
  124563. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  124564. ** to the n registers starting at base.
  124565. **
  124566. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  124567. ** beginning and end of zAff are ignored. If all entries in zAff are
  124568. ** SQLITE_AFF_BLOB, then no code gets generated.
  124569. **
  124570. ** This routine makes its own copy of zAff so that the caller is free
  124571. ** to modify zAff after this routine returns.
  124572. */
  124573. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  124574. Vdbe *v = pParse->pVdbe;
  124575. if( zAff==0 ){
  124576. assert( pParse->db->mallocFailed );
  124577. return;
  124578. }
  124579. assert( v!=0 );
  124580. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  124581. ** and end of the affinity string.
  124582. */
  124583. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  124584. n--;
  124585. base++;
  124586. zAff++;
  124587. }
  124588. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  124589. n--;
  124590. }
  124591. /* Code the OP_Affinity opcode if there is anything left to do. */
  124592. if( n>0 ){
  124593. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  124594. sqlite3ExprCacheAffinityChange(pParse, base, n);
  124595. }
  124596. }
  124597. /*
  124598. ** Expression pRight, which is the RHS of a comparison operation, is
  124599. ** either a vector of n elements or, if n==1, a scalar expression.
  124600. ** Before the comparison operation, affinity zAff is to be applied
  124601. ** to the pRight values. This function modifies characters within the
  124602. ** affinity string to SQLITE_AFF_BLOB if either:
  124603. **
  124604. ** * the comparison will be performed with no affinity, or
  124605. ** * the affinity change in zAff is guaranteed not to change the value.
  124606. */
  124607. static void updateRangeAffinityStr(
  124608. Expr *pRight, /* RHS of comparison */
  124609. int n, /* Number of vector elements in comparison */
  124610. char *zAff /* Affinity string to modify */
  124611. ){
  124612. int i;
  124613. for(i=0; i<n; i++){
  124614. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  124615. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  124616. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  124617. ){
  124618. zAff[i] = SQLITE_AFF_BLOB;
  124619. }
  124620. }
  124621. }
  124622. /*
  124623. ** pX is an expression of the form: (vector) IN (SELECT ...)
  124624. ** In other words, it is a vector IN operator with a SELECT clause on the
  124625. ** LHS. But not all terms in the vector are indexable and the terms might
  124626. ** not be in the correct order for indexing.
  124627. **
  124628. ** This routine makes a copy of the input pX expression and then adjusts
  124629. ** the vector on the LHS with corresponding changes to the SELECT so that
  124630. ** the vector contains only index terms and those terms are in the correct
  124631. ** order. The modified IN expression is returned. The caller is responsible
  124632. ** for deleting the returned expression.
  124633. **
  124634. ** Example:
  124635. **
  124636. ** CREATE TABLE t1(a,b,c,d,e,f);
  124637. ** CREATE INDEX t1x1 ON t1(e,c);
  124638. ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
  124639. ** \_______________________________________/
  124640. ** The pX expression
  124641. **
  124642. ** Since only columns e and c can be used with the index, in that order,
  124643. ** the modified IN expression that is returned will be:
  124644. **
  124645. ** (e,c) IN (SELECT z,x FROM t2)
  124646. **
  124647. ** The reduced pX is different from the original (obviously) and thus is
  124648. ** only used for indexing, to improve performance. The original unaltered
  124649. ** IN expression must also be run on each output row for correctness.
  124650. */
  124651. static Expr *removeUnindexableInClauseTerms(
  124652. Parse *pParse, /* The parsing context */
  124653. int iEq, /* Look at loop terms starting here */
  124654. WhereLoop *pLoop, /* The current loop */
  124655. Expr *pX /* The IN expression to be reduced */
  124656. ){
  124657. sqlite3 *db = pParse->db;
  124658. Expr *pNew = sqlite3ExprDup(db, pX, 0);
  124659. if( db->mallocFailed==0 ){
  124660. ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */
  124661. ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */
  124662. ExprList *pRhs = 0; /* New RHS after modifications */
  124663. ExprList *pLhs = 0; /* New LHS after mods */
  124664. int i; /* Loop counter */
  124665. Select *pSelect; /* Pointer to the SELECT on the RHS */
  124666. for(i=iEq; i<pLoop->nLTerm; i++){
  124667. if( pLoop->aLTerm[i]->pExpr==pX ){
  124668. int iField = pLoop->aLTerm[i]->iField - 1;
  124669. assert( pOrigRhs->a[iField].pExpr!=0 );
  124670. pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
  124671. pOrigRhs->a[iField].pExpr = 0;
  124672. assert( pOrigLhs->a[iField].pExpr!=0 );
  124673. pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
  124674. pOrigLhs->a[iField].pExpr = 0;
  124675. }
  124676. }
  124677. sqlite3ExprListDelete(db, pOrigRhs);
  124678. sqlite3ExprListDelete(db, pOrigLhs);
  124679. pNew->pLeft->x.pList = pLhs;
  124680. pNew->x.pSelect->pEList = pRhs;
  124681. if( pLhs && pLhs->nExpr==1 ){
  124682. /* Take care here not to generate a TK_VECTOR containing only a
  124683. ** single value. Since the parser never creates such a vector, some
  124684. ** of the subroutines do not handle this case. */
  124685. Expr *p = pLhs->a[0].pExpr;
  124686. pLhs->a[0].pExpr = 0;
  124687. sqlite3ExprDelete(db, pNew->pLeft);
  124688. pNew->pLeft = p;
  124689. }
  124690. pSelect = pNew->x.pSelect;
  124691. if( pSelect->pOrderBy ){
  124692. /* If the SELECT statement has an ORDER BY clause, zero the
  124693. ** iOrderByCol variables. These are set to non-zero when an
  124694. ** ORDER BY term exactly matches one of the terms of the
  124695. ** result-set. Since the result-set of the SELECT statement may
  124696. ** have been modified or reordered, these variables are no longer
  124697. ** set correctly. Since setting them is just an optimization,
  124698. ** it's easiest just to zero them here. */
  124699. ExprList *pOrderBy = pSelect->pOrderBy;
  124700. for(i=0; i<pOrderBy->nExpr; i++){
  124701. pOrderBy->a[i].u.x.iOrderByCol = 0;
  124702. }
  124703. }
  124704. #if 0
  124705. printf("For indexing, change the IN expr:\n");
  124706. sqlite3TreeViewExpr(0, pX, 0);
  124707. printf("Into:\n");
  124708. sqlite3TreeViewExpr(0, pNew, 0);
  124709. #endif
  124710. }
  124711. return pNew;
  124712. }
  124713. /*
  124714. ** Generate code for a single equality term of the WHERE clause. An equality
  124715. ** term can be either X=expr or X IN (...). pTerm is the term to be
  124716. ** coded.
  124717. **
  124718. ** The current value for the constraint is left in a register, the index
  124719. ** of which is returned. An attempt is made store the result in iTarget but
  124720. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  124721. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  124722. ** some other register and it is the caller's responsibility to compensate.
  124723. **
  124724. ** For a constraint of the form X=expr, the expression is evaluated in
  124725. ** straight-line code. For constraints of the form X IN (...)
  124726. ** this routine sets up a loop that will iterate over all values of X.
  124727. */
  124728. static int codeEqualityTerm(
  124729. Parse *pParse, /* The parsing context */
  124730. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  124731. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  124732. int iEq, /* Index of the equality term within this level */
  124733. int bRev, /* True for reverse-order IN operations */
  124734. int iTarget /* Attempt to leave results in this register */
  124735. ){
  124736. Expr *pX = pTerm->pExpr;
  124737. Vdbe *v = pParse->pVdbe;
  124738. int iReg; /* Register holding results */
  124739. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  124740. assert( iTarget>0 );
  124741. if( pX->op==TK_EQ || pX->op==TK_IS ){
  124742. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  124743. }else if( pX->op==TK_ISNULL ){
  124744. iReg = iTarget;
  124745. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  124746. #ifndef SQLITE_OMIT_SUBQUERY
  124747. }else{
  124748. int eType = IN_INDEX_NOOP;
  124749. int iTab;
  124750. struct InLoop *pIn;
  124751. WhereLoop *pLoop = pLevel->pWLoop;
  124752. int i;
  124753. int nEq = 0;
  124754. int *aiMap = 0;
  124755. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  124756. && pLoop->u.btree.pIndex!=0
  124757. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  124758. ){
  124759. testcase( iEq==0 );
  124760. testcase( bRev );
  124761. bRev = !bRev;
  124762. }
  124763. assert( pX->op==TK_IN );
  124764. iReg = iTarget;
  124765. for(i=0; i<iEq; i++){
  124766. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  124767. disableTerm(pLevel, pTerm);
  124768. return iTarget;
  124769. }
  124770. }
  124771. for(i=iEq;i<pLoop->nLTerm; i++){
  124772. assert( pLoop->aLTerm[i]!=0 );
  124773. if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  124774. }
  124775. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  124776. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
  124777. }else{
  124778. sqlite3 *db = pParse->db;
  124779. pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
  124780. if( !db->mallocFailed ){
  124781. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
  124782. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
  124783. pTerm->pExpr->iTable = pX->iTable;
  124784. }
  124785. sqlite3ExprDelete(db, pX);
  124786. pX = pTerm->pExpr;
  124787. }
  124788. if( eType==IN_INDEX_INDEX_DESC ){
  124789. testcase( bRev );
  124790. bRev = !bRev;
  124791. }
  124792. iTab = pX->iTable;
  124793. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  124794. VdbeCoverageIf(v, bRev);
  124795. VdbeCoverageIf(v, !bRev);
  124796. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  124797. pLoop->wsFlags |= WHERE_IN_ABLE;
  124798. if( pLevel->u.in.nIn==0 ){
  124799. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  124800. }
  124801. i = pLevel->u.in.nIn;
  124802. pLevel->u.in.nIn += nEq;
  124803. pLevel->u.in.aInLoop =
  124804. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  124805. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  124806. pIn = pLevel->u.in.aInLoop;
  124807. if( pIn ){
  124808. int iMap = 0; /* Index in aiMap[] */
  124809. pIn += i;
  124810. for(i=iEq;i<pLoop->nLTerm; i++){
  124811. if( pLoop->aLTerm[i]->pExpr==pX ){
  124812. int iOut = iReg + i - iEq;
  124813. if( eType==IN_INDEX_ROWID ){
  124814. testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
  124815. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  124816. }else{
  124817. int iCol = aiMap ? aiMap[iMap++] : 0;
  124818. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  124819. }
  124820. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  124821. if( i==iEq ){
  124822. pIn->iCur = iTab;
  124823. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  124824. }else{
  124825. pIn->eEndLoopOp = OP_Noop;
  124826. }
  124827. pIn++;
  124828. }
  124829. }
  124830. }else{
  124831. pLevel->u.in.nIn = 0;
  124832. }
  124833. sqlite3DbFree(pParse->db, aiMap);
  124834. #endif
  124835. }
  124836. disableTerm(pLevel, pTerm);
  124837. return iReg;
  124838. }
  124839. /*
  124840. ** Generate code that will evaluate all == and IN constraints for an
  124841. ** index scan.
  124842. **
  124843. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  124844. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  124845. ** The index has as many as three equality constraints, but in this
  124846. ** example, the third "c" value is an inequality. So only two
  124847. ** constraints are coded. This routine will generate code to evaluate
  124848. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  124849. ** in consecutive registers and the index of the first register is returned.
  124850. **
  124851. ** In the example above nEq==2. But this subroutine works for any value
  124852. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  124853. ** The only thing it does is allocate the pLevel->iMem memory cell and
  124854. ** compute the affinity string.
  124855. **
  124856. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  124857. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  124858. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  124859. ** occurs after the nEq quality constraints.
  124860. **
  124861. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  124862. ** the index of the first memory cell in that range. The code that
  124863. ** calls this routine will use that memory range to store keys for
  124864. ** start and termination conditions of the loop.
  124865. ** key value of the loop. If one or more IN operators appear, then
  124866. ** this routine allocates an additional nEq memory cells for internal
  124867. ** use.
  124868. **
  124869. ** Before returning, *pzAff is set to point to a buffer containing a
  124870. ** copy of the column affinity string of the index allocated using
  124871. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  124872. ** with equality constraints that use BLOB or NONE affinity are set to
  124873. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  124874. **
  124875. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  124876. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  124877. **
  124878. ** In the example above, the index on t1(a) has TEXT affinity. But since
  124879. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  124880. ** no conversion should be attempted before using a t2.b value as part of
  124881. ** a key to search the index. Hence the first byte in the returned affinity
  124882. ** string in this example would be set to SQLITE_AFF_BLOB.
  124883. */
  124884. static int codeAllEqualityTerms(
  124885. Parse *pParse, /* Parsing context */
  124886. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  124887. int bRev, /* Reverse the order of IN operators */
  124888. int nExtraReg, /* Number of extra registers to allocate */
  124889. char **pzAff /* OUT: Set to point to affinity string */
  124890. ){
  124891. u16 nEq; /* The number of == or IN constraints to code */
  124892. u16 nSkip; /* Number of left-most columns to skip */
  124893. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  124894. Index *pIdx; /* The index being used for this loop */
  124895. WhereTerm *pTerm; /* A single constraint term */
  124896. WhereLoop *pLoop; /* The WhereLoop object */
  124897. int j; /* Loop counter */
  124898. int regBase; /* Base register */
  124899. int nReg; /* Number of registers to allocate */
  124900. char *zAff; /* Affinity string to return */
  124901. /* This module is only called on query plans that use an index. */
  124902. pLoop = pLevel->pWLoop;
  124903. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  124904. nEq = pLoop->u.btree.nEq;
  124905. nSkip = pLoop->nSkip;
  124906. pIdx = pLoop->u.btree.pIndex;
  124907. assert( pIdx!=0 );
  124908. /* Figure out how many memory cells we will need then allocate them.
  124909. */
  124910. regBase = pParse->nMem + 1;
  124911. nReg = pLoop->u.btree.nEq + nExtraReg;
  124912. pParse->nMem += nReg;
  124913. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  124914. assert( zAff!=0 || pParse->db->mallocFailed );
  124915. if( nSkip ){
  124916. int iIdxCur = pLevel->iIdxCur;
  124917. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  124918. VdbeCoverageIf(v, bRev==0);
  124919. VdbeCoverageIf(v, bRev!=0);
  124920. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  124921. j = sqlite3VdbeAddOp0(v, OP_Goto);
  124922. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  124923. iIdxCur, 0, regBase, nSkip);
  124924. VdbeCoverageIf(v, bRev==0);
  124925. VdbeCoverageIf(v, bRev!=0);
  124926. sqlite3VdbeJumpHere(v, j);
  124927. for(j=0; j<nSkip; j++){
  124928. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  124929. testcase( pIdx->aiColumn[j]==XN_EXPR );
  124930. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  124931. }
  124932. }
  124933. /* Evaluate the equality constraints
  124934. */
  124935. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  124936. for(j=nSkip; j<nEq; j++){
  124937. int r1;
  124938. pTerm = pLoop->aLTerm[j];
  124939. assert( pTerm!=0 );
  124940. /* The following testcase is true for indices with redundant columns.
  124941. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  124942. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  124943. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  124944. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  124945. if( r1!=regBase+j ){
  124946. if( nReg==1 ){
  124947. sqlite3ReleaseTempReg(pParse, regBase);
  124948. regBase = r1;
  124949. }else{
  124950. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  124951. }
  124952. }
  124953. if( pTerm->eOperator & WO_IN ){
  124954. if( pTerm->pExpr->flags & EP_xIsSelect ){
  124955. /* No affinity ever needs to be (or should be) applied to a value
  124956. ** from the RHS of an "? IN (SELECT ...)" expression. The
  124957. ** sqlite3FindInIndex() routine has already ensured that the
  124958. ** affinity of the comparison has been applied to the value. */
  124959. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  124960. }
  124961. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  124962. Expr *pRight = pTerm->pExpr->pRight;
  124963. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  124964. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  124965. VdbeCoverage(v);
  124966. }
  124967. if( zAff ){
  124968. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  124969. zAff[j] = SQLITE_AFF_BLOB;
  124970. }
  124971. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  124972. zAff[j] = SQLITE_AFF_BLOB;
  124973. }
  124974. }
  124975. }
  124976. }
  124977. *pzAff = zAff;
  124978. return regBase;
  124979. }
  124980. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  124981. /*
  124982. ** If the most recently coded instruction is a constant range constraint
  124983. ** (a string literal) that originated from the LIKE optimization, then
  124984. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  124985. ** to a BLOB at appropriate times.
  124986. **
  124987. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  124988. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  124989. ** scan loop run twice, once for strings and a second time for BLOBs.
  124990. ** The OP_String opcodes on the second pass convert the upper and lower
  124991. ** bound string constants to blobs. This routine makes the necessary changes
  124992. ** to the OP_String opcodes for that to happen.
  124993. **
  124994. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  124995. ** only the one pass through the string space is required, so this routine
  124996. ** becomes a no-op.
  124997. */
  124998. static void whereLikeOptimizationStringFixup(
  124999. Vdbe *v, /* prepared statement under construction */
  125000. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  125001. WhereTerm *pTerm /* The upper or lower bound just coded */
  125002. ){
  125003. if( pTerm->wtFlags & TERM_LIKEOPT ){
  125004. VdbeOp *pOp;
  125005. assert( pLevel->iLikeRepCntr>0 );
  125006. pOp = sqlite3VdbeGetOp(v, -1);
  125007. assert( pOp!=0 );
  125008. assert( pOp->opcode==OP_String8
  125009. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  125010. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  125011. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  125012. }
  125013. }
  125014. #else
  125015. # define whereLikeOptimizationStringFixup(A,B,C)
  125016. #endif
  125017. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  125018. /*
  125019. ** Information is passed from codeCursorHint() down to individual nodes of
  125020. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  125021. ** structure.
  125022. */
  125023. struct CCurHint {
  125024. int iTabCur; /* Cursor for the main table */
  125025. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  125026. Index *pIdx; /* The index used to access the table */
  125027. };
  125028. /*
  125029. ** This function is called for every node of an expression that is a candidate
  125030. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  125031. ** the table CCurHint.iTabCur, verify that the same column can be
  125032. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  125033. */
  125034. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  125035. struct CCurHint *pHint = pWalker->u.pCCurHint;
  125036. assert( pHint->pIdx!=0 );
  125037. if( pExpr->op==TK_COLUMN
  125038. && pExpr->iTable==pHint->iTabCur
  125039. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  125040. ){
  125041. pWalker->eCode = 1;
  125042. }
  125043. return WRC_Continue;
  125044. }
  125045. /*
  125046. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  125047. ** should be included in the cursor-hint for a table that is on the rhs
  125048. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  125049. ** expression is not suitable.
  125050. **
  125051. ** An expression is unsuitable if it might evaluate to non NULL even if
  125052. ** a TK_COLUMN node that does affect the value of the expression is set
  125053. ** to NULL. For example:
  125054. **
  125055. ** col IS NULL
  125056. ** col IS NOT NULL
  125057. ** coalesce(col, 1)
  125058. ** CASE WHEN col THEN 0 ELSE 1 END
  125059. */
  125060. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  125061. if( pExpr->op==TK_IS
  125062. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  125063. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  125064. ){
  125065. pWalker->eCode = 1;
  125066. }else if( pExpr->op==TK_FUNCTION ){
  125067. int d1;
  125068. char d2[4];
  125069. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  125070. pWalker->eCode = 1;
  125071. }
  125072. }
  125073. return WRC_Continue;
  125074. }
  125075. /*
  125076. ** This function is called on every node of an expression tree used as an
  125077. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  125078. ** that accesses any table other than the one identified by
  125079. ** CCurHint.iTabCur, then do the following:
  125080. **
  125081. ** 1) allocate a register and code an OP_Column instruction to read
  125082. ** the specified column into the new register, and
  125083. **
  125084. ** 2) transform the expression node to a TK_REGISTER node that reads
  125085. ** from the newly populated register.
  125086. **
  125087. ** Also, if the node is a TK_COLUMN that does access the table idenified
  125088. ** by pCCurHint.iTabCur, and an index is being used (which we will
  125089. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  125090. ** an access of the index rather than the original table.
  125091. */
  125092. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  125093. int rc = WRC_Continue;
  125094. struct CCurHint *pHint = pWalker->u.pCCurHint;
  125095. if( pExpr->op==TK_COLUMN ){
  125096. if( pExpr->iTable!=pHint->iTabCur ){
  125097. Vdbe *v = pWalker->pParse->pVdbe;
  125098. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  125099. sqlite3ExprCodeGetColumnOfTable(
  125100. v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
  125101. );
  125102. pExpr->op = TK_REGISTER;
  125103. pExpr->iTable = reg;
  125104. }else if( pHint->pIdx!=0 ){
  125105. pExpr->iTable = pHint->iIdxCur;
  125106. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  125107. assert( pExpr->iColumn>=0 );
  125108. }
  125109. }else if( pExpr->op==TK_AGG_FUNCTION ){
  125110. /* An aggregate function in the WHERE clause of a query means this must
  125111. ** be a correlated sub-query, and expression pExpr is an aggregate from
  125112. ** the parent context. Do not walk the function arguments in this case.
  125113. **
  125114. ** todo: It should be possible to replace this node with a TK_REGISTER
  125115. ** expression, as the result of the expression must be stored in a
  125116. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  125117. rc = WRC_Prune;
  125118. }
  125119. return rc;
  125120. }
  125121. /*
  125122. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  125123. */
  125124. static void codeCursorHint(
  125125. struct SrcList_item *pTabItem, /* FROM clause item */
  125126. WhereInfo *pWInfo, /* The where clause */
  125127. WhereLevel *pLevel, /* Which loop to provide hints for */
  125128. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  125129. ){
  125130. Parse *pParse = pWInfo->pParse;
  125131. sqlite3 *db = pParse->db;
  125132. Vdbe *v = pParse->pVdbe;
  125133. Expr *pExpr = 0;
  125134. WhereLoop *pLoop = pLevel->pWLoop;
  125135. int iCur;
  125136. WhereClause *pWC;
  125137. WhereTerm *pTerm;
  125138. int i, j;
  125139. struct CCurHint sHint;
  125140. Walker sWalker;
  125141. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  125142. iCur = pLevel->iTabCur;
  125143. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  125144. sHint.iTabCur = iCur;
  125145. sHint.iIdxCur = pLevel->iIdxCur;
  125146. sHint.pIdx = pLoop->u.btree.pIndex;
  125147. memset(&sWalker, 0, sizeof(sWalker));
  125148. sWalker.pParse = pParse;
  125149. sWalker.u.pCCurHint = &sHint;
  125150. pWC = &pWInfo->sWC;
  125151. for(i=0; i<pWC->nTerm; i++){
  125152. pTerm = &pWC->a[i];
  125153. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  125154. if( pTerm->prereqAll & pLevel->notReady ) continue;
  125155. /* Any terms specified as part of the ON(...) clause for any LEFT
  125156. ** JOIN for which the current table is not the rhs are omitted
  125157. ** from the cursor-hint.
  125158. **
  125159. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  125160. ** that were specified as part of the WHERE clause must be excluded.
  125161. ** This is to address the following:
  125162. **
  125163. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  125164. **
  125165. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  125166. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  125167. ** pushed down to the cursor, this row is filtered out, causing
  125168. ** SQLite to synthesize a row of NULL values. Which does match the
  125169. ** WHERE clause, and so the query returns a row. Which is incorrect.
  125170. **
  125171. ** For the same reason, WHERE terms such as:
  125172. **
  125173. ** WHERE 1 = (t2.c IS NULL)
  125174. **
  125175. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  125176. */
  125177. if( pTabItem->fg.jointype & JT_LEFT ){
  125178. Expr *pExpr = pTerm->pExpr;
  125179. if( !ExprHasProperty(pExpr, EP_FromJoin)
  125180. || pExpr->iRightJoinTable!=pTabItem->iCursor
  125181. ){
  125182. sWalker.eCode = 0;
  125183. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  125184. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  125185. if( sWalker.eCode ) continue;
  125186. }
  125187. }else{
  125188. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  125189. }
  125190. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  125191. ** the cursor. These terms are not needed as hints for a pure range
  125192. ** scan (that has no == terms) so omit them. */
  125193. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  125194. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  125195. if( j<pLoop->nLTerm ) continue;
  125196. }
  125197. /* No subqueries or non-deterministic functions allowed */
  125198. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  125199. /* For an index scan, make sure referenced columns are actually in
  125200. ** the index. */
  125201. if( sHint.pIdx!=0 ){
  125202. sWalker.eCode = 0;
  125203. sWalker.xExprCallback = codeCursorHintCheckExpr;
  125204. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  125205. if( sWalker.eCode ) continue;
  125206. }
  125207. /* If we survive all prior tests, that means this term is worth hinting */
  125208. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  125209. }
  125210. if( pExpr!=0 ){
  125211. sWalker.xExprCallback = codeCursorHintFixExpr;
  125212. sqlite3WalkExpr(&sWalker, pExpr);
  125213. sqlite3VdbeAddOp4(v, OP_CursorHint,
  125214. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  125215. (const char*)pExpr, P4_EXPR);
  125216. }
  125217. }
  125218. #else
  125219. # define codeCursorHint(A,B,C,D) /* No-op */
  125220. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  125221. /*
  125222. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  125223. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  125224. ** function generates code to do a deferred seek of cursor iCur to the
  125225. ** rowid stored in register iRowid.
  125226. **
  125227. ** Normally, this is just:
  125228. **
  125229. ** OP_DeferredSeek $iCur $iRowid
  125230. **
  125231. ** However, if the scan currently being coded is a branch of an OR-loop and
  125232. ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
  125233. ** is set to iIdxCur and P4 is set to point to an array of integers
  125234. ** containing one entry for each column of the table cursor iCur is open
  125235. ** on. For each table column, if the column is the i'th column of the
  125236. ** index, then the corresponding array entry is set to (i+1). If the column
  125237. ** does not appear in the index at all, the array entry is set to 0.
  125238. */
  125239. static void codeDeferredSeek(
  125240. WhereInfo *pWInfo, /* Where clause context */
  125241. Index *pIdx, /* Index scan is using */
  125242. int iCur, /* Cursor for IPK b-tree */
  125243. int iIdxCur /* Index cursor */
  125244. ){
  125245. Parse *pParse = pWInfo->pParse; /* Parse context */
  125246. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  125247. assert( iIdxCur>0 );
  125248. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  125249. sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
  125250. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  125251. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  125252. ){
  125253. int i;
  125254. Table *pTab = pIdx->pTable;
  125255. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  125256. if( ai ){
  125257. ai[0] = pTab->nCol;
  125258. for(i=0; i<pIdx->nColumn-1; i++){
  125259. assert( pIdx->aiColumn[i]<pTab->nCol );
  125260. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  125261. }
  125262. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  125263. }
  125264. }
  125265. }
  125266. /*
  125267. ** If the expression passed as the second argument is a vector, generate
  125268. ** code to write the first nReg elements of the vector into an array
  125269. ** of registers starting with iReg.
  125270. **
  125271. ** If the expression is not a vector, then nReg must be passed 1. In
  125272. ** this case, generate code to evaluate the expression and leave the
  125273. ** result in register iReg.
  125274. */
  125275. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  125276. assert( nReg>0 );
  125277. if( p && sqlite3ExprIsVector(p) ){
  125278. #ifndef SQLITE_OMIT_SUBQUERY
  125279. if( (p->flags & EP_xIsSelect) ){
  125280. Vdbe *v = pParse->pVdbe;
  125281. int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
  125282. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  125283. }else
  125284. #endif
  125285. {
  125286. int i;
  125287. ExprList *pList = p->x.pList;
  125288. assert( nReg<=pList->nExpr );
  125289. for(i=0; i<nReg; i++){
  125290. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  125291. }
  125292. }
  125293. }else{
  125294. assert( nReg==1 );
  125295. sqlite3ExprCode(pParse, p, iReg);
  125296. }
  125297. }
  125298. /* An instance of the IdxExprTrans object carries information about a
  125299. ** mapping from an expression on table columns into a column in an index
  125300. ** down through the Walker.
  125301. */
  125302. typedef struct IdxExprTrans {
  125303. Expr *pIdxExpr; /* The index expression */
  125304. int iTabCur; /* The cursor of the corresponding table */
  125305. int iIdxCur; /* The cursor for the index */
  125306. int iIdxCol; /* The column for the index */
  125307. } IdxExprTrans;
  125308. /* The walker node callback used to transform matching expressions into
  125309. ** a reference to an index column for an index on an expression.
  125310. **
  125311. ** If pExpr matches, then transform it into a reference to the index column
  125312. ** that contains the value of pExpr.
  125313. */
  125314. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  125315. IdxExprTrans *pX = p->u.pIdxTrans;
  125316. if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  125317. pExpr->op = TK_COLUMN;
  125318. pExpr->iTable = pX->iIdxCur;
  125319. pExpr->iColumn = pX->iIdxCol;
  125320. pExpr->pTab = 0;
  125321. return WRC_Prune;
  125322. }else{
  125323. return WRC_Continue;
  125324. }
  125325. }
  125326. /*
  125327. ** For an indexes on expression X, locate every instance of expression X
  125328. ** in pExpr and change that subexpression into a reference to the appropriate
  125329. ** column of the index.
  125330. */
  125331. static void whereIndexExprTrans(
  125332. Index *pIdx, /* The Index */
  125333. int iTabCur, /* Cursor of the table that is being indexed */
  125334. int iIdxCur, /* Cursor of the index itself */
  125335. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  125336. ){
  125337. int iIdxCol; /* Column number of the index */
  125338. ExprList *aColExpr; /* Expressions that are indexed */
  125339. Walker w;
  125340. IdxExprTrans x;
  125341. aColExpr = pIdx->aColExpr;
  125342. if( aColExpr==0 ) return; /* Not an index on expressions */
  125343. memset(&w, 0, sizeof(w));
  125344. w.xExprCallback = whereIndexExprTransNode;
  125345. w.u.pIdxTrans = &x;
  125346. x.iTabCur = iTabCur;
  125347. x.iIdxCur = iIdxCur;
  125348. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  125349. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  125350. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  125351. x.iIdxCol = iIdxCol;
  125352. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  125353. sqlite3WalkExpr(&w, pWInfo->pWhere);
  125354. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  125355. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  125356. }
  125357. }
  125358. /*
  125359. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  125360. ** implementation described by pWInfo.
  125361. */
  125362. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  125363. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  125364. int iLevel, /* Which level of pWInfo->a[] should be coded */
  125365. Bitmask notReady /* Which tables are currently available */
  125366. ){
  125367. int j, k; /* Loop counters */
  125368. int iCur; /* The VDBE cursor for the table */
  125369. int addrNxt; /* Where to jump to continue with the next IN case */
  125370. int omitTable; /* True if we use the index only */
  125371. int bRev; /* True if we need to scan in reverse order */
  125372. WhereLevel *pLevel; /* The where level to be coded */
  125373. WhereLoop *pLoop; /* The WhereLoop object being coded */
  125374. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  125375. WhereTerm *pTerm; /* A WHERE clause term */
  125376. Parse *pParse; /* Parsing context */
  125377. sqlite3 *db; /* Database connection */
  125378. Vdbe *v; /* The prepared stmt under constructions */
  125379. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  125380. int addrBrk; /* Jump here to break out of the loop */
  125381. int addrHalt; /* addrBrk for the outermost loop */
  125382. int addrCont; /* Jump here to continue with next cycle */
  125383. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  125384. int iReleaseReg = 0; /* Temp register to free before returning */
  125385. Index *pIdx = 0; /* Index used by loop (if any) */
  125386. int iLoop; /* Iteration of constraint generator loop */
  125387. pParse = pWInfo->pParse;
  125388. v = pParse->pVdbe;
  125389. pWC = &pWInfo->sWC;
  125390. db = pParse->db;
  125391. pLevel = &pWInfo->a[iLevel];
  125392. pLoop = pLevel->pWLoop;
  125393. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  125394. iCur = pTabItem->iCursor;
  125395. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  125396. bRev = (pWInfo->revMask>>iLevel)&1;
  125397. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  125398. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  125399. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  125400. /* Create labels for the "break" and "continue" instructions
  125401. ** for the current loop. Jump to addrBrk to break out of a loop.
  125402. ** Jump to cont to go immediately to the next iteration of the
  125403. ** loop.
  125404. **
  125405. ** When there is an IN operator, we also have a "addrNxt" label that
  125406. ** means to continue with the next IN value combination. When
  125407. ** there are no IN operators in the constraints, the "addrNxt" label
  125408. ** is the same as "addrBrk".
  125409. */
  125410. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  125411. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  125412. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  125413. ** initialize a memory cell that records if this table matches any
  125414. ** row of the left table of the join.
  125415. */
  125416. assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  125417. || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
  125418. );
  125419. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  125420. pLevel->iLeftJoin = ++pParse->nMem;
  125421. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  125422. VdbeComment((v, "init LEFT JOIN no-match flag"));
  125423. }
  125424. /* Compute a safe address to jump to if we discover that the table for
  125425. ** this loop is empty and can never contribute content. */
  125426. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  125427. addrHalt = pWInfo->a[j].addrBrk;
  125428. /* Special case of a FROM clause subquery implemented as a co-routine */
  125429. if( pTabItem->fg.viaCoroutine ){
  125430. int regYield = pTabItem->regReturn;
  125431. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  125432. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  125433. VdbeCoverage(v);
  125434. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  125435. pLevel->op = OP_Goto;
  125436. }else
  125437. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125438. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  125439. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  125440. ** to access the data.
  125441. */
  125442. int iReg; /* P3 Value for OP_VFilter */
  125443. int addrNotFound;
  125444. int nConstraint = pLoop->nLTerm;
  125445. int iIn; /* Counter for IN constraints */
  125446. sqlite3ExprCachePush(pParse);
  125447. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  125448. addrNotFound = pLevel->addrBrk;
  125449. for(j=0; j<nConstraint; j++){
  125450. int iTarget = iReg+j+2;
  125451. pTerm = pLoop->aLTerm[j];
  125452. if( NEVER(pTerm==0) ) continue;
  125453. if( pTerm->eOperator & WO_IN ){
  125454. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  125455. addrNotFound = pLevel->addrNxt;
  125456. }else{
  125457. Expr *pRight = pTerm->pExpr->pRight;
  125458. codeExprOrVector(pParse, pRight, iTarget, 1);
  125459. }
  125460. }
  125461. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  125462. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  125463. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  125464. pLoop->u.vtab.idxStr,
  125465. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  125466. VdbeCoverage(v);
  125467. pLoop->u.vtab.needFree = 0;
  125468. pLevel->p1 = iCur;
  125469. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  125470. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  125471. iIn = pLevel->u.in.nIn;
  125472. for(j=nConstraint-1; j>=0; j--){
  125473. pTerm = pLoop->aLTerm[j];
  125474. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  125475. disableTerm(pLevel, pTerm);
  125476. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  125477. Expr *pCompare; /* The comparison operator */
  125478. Expr *pRight; /* RHS of the comparison */
  125479. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  125480. /* Reload the constraint value into reg[iReg+j+2]. The same value
  125481. ** was loaded into the same register prior to the OP_VFilter, but
  125482. ** the xFilter implementation might have changed the datatype or
  125483. ** encoding of the value in the register, so it *must* be reloaded. */
  125484. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  125485. if( !db->mallocFailed ){
  125486. assert( iIn>0 );
  125487. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  125488. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  125489. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  125490. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  125491. testcase( pOp->opcode==OP_Rowid );
  125492. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  125493. }
  125494. /* Generate code that will continue to the next row if
  125495. ** the IN constraint is not satisfied */
  125496. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  125497. assert( pCompare!=0 || db->mallocFailed );
  125498. if( pCompare ){
  125499. pCompare->pLeft = pTerm->pExpr->pLeft;
  125500. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  125501. if( pRight ){
  125502. pRight->iTable = iReg+j+2;
  125503. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  125504. }
  125505. pCompare->pLeft = 0;
  125506. sqlite3ExprDelete(db, pCompare);
  125507. }
  125508. }
  125509. }
  125510. /* These registers need to be preserved in case there is an IN operator
  125511. ** loop. So we could deallocate the registers here (and potentially
  125512. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  125513. ** simpler and safer to simply not reuse the registers.
  125514. **
  125515. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  125516. */
  125517. sqlite3ExprCachePop(pParse);
  125518. }else
  125519. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125520. if( (pLoop->wsFlags & WHERE_IPK)!=0
  125521. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  125522. ){
  125523. /* Case 2: We can directly reference a single row using an
  125524. ** equality comparison against the ROWID field. Or
  125525. ** we reference multiple rows using a "rowid IN (...)"
  125526. ** construct.
  125527. */
  125528. assert( pLoop->u.btree.nEq==1 );
  125529. pTerm = pLoop->aLTerm[0];
  125530. assert( pTerm!=0 );
  125531. assert( pTerm->pExpr!=0 );
  125532. assert( omitTable==0 );
  125533. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  125534. iReleaseReg = ++pParse->nMem;
  125535. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  125536. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  125537. addrNxt = pLevel->addrNxt;
  125538. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  125539. VdbeCoverage(v);
  125540. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  125541. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  125542. VdbeComment((v, "pk"));
  125543. pLevel->op = OP_Noop;
  125544. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  125545. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  125546. ){
  125547. /* Case 3: We have an inequality comparison against the ROWID field.
  125548. */
  125549. int testOp = OP_Noop;
  125550. int start;
  125551. int memEndValue = 0;
  125552. WhereTerm *pStart, *pEnd;
  125553. assert( omitTable==0 );
  125554. j = 0;
  125555. pStart = pEnd = 0;
  125556. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  125557. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  125558. assert( pStart!=0 || pEnd!=0 );
  125559. if( bRev ){
  125560. pTerm = pStart;
  125561. pStart = pEnd;
  125562. pEnd = pTerm;
  125563. }
  125564. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  125565. if( pStart ){
  125566. Expr *pX; /* The expression that defines the start bound */
  125567. int r1, rTemp; /* Registers for holding the start boundary */
  125568. int op; /* Cursor seek operation */
  125569. /* The following constant maps TK_xx codes into corresponding
  125570. ** seek opcodes. It depends on a particular ordering of TK_xx
  125571. */
  125572. const u8 aMoveOp[] = {
  125573. /* TK_GT */ OP_SeekGT,
  125574. /* TK_LE */ OP_SeekLE,
  125575. /* TK_LT */ OP_SeekLT,
  125576. /* TK_GE */ OP_SeekGE
  125577. };
  125578. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  125579. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  125580. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  125581. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  125582. testcase( pStart->wtFlags & TERM_VIRTUAL );
  125583. pX = pStart->pExpr;
  125584. assert( pX!=0 );
  125585. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  125586. if( sqlite3ExprIsVector(pX->pRight) ){
  125587. r1 = rTemp = sqlite3GetTempReg(pParse);
  125588. codeExprOrVector(pParse, pX->pRight, r1, 1);
  125589. testcase( pX->op==TK_GT );
  125590. testcase( pX->op==TK_GE );
  125591. testcase( pX->op==TK_LT );
  125592. testcase( pX->op==TK_LE );
  125593. op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
  125594. assert( pX->op!=TK_GT || op==OP_SeekGE );
  125595. assert( pX->op!=TK_GE || op==OP_SeekGE );
  125596. assert( pX->op!=TK_LT || op==OP_SeekLE );
  125597. assert( pX->op!=TK_LE || op==OP_SeekLE );
  125598. }else{
  125599. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  125600. disableTerm(pLevel, pStart);
  125601. op = aMoveOp[(pX->op - TK_GT)];
  125602. }
  125603. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  125604. VdbeComment((v, "pk"));
  125605. VdbeCoverageIf(v, pX->op==TK_GT);
  125606. VdbeCoverageIf(v, pX->op==TK_LE);
  125607. VdbeCoverageIf(v, pX->op==TK_LT);
  125608. VdbeCoverageIf(v, pX->op==TK_GE);
  125609. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  125610. sqlite3ReleaseTempReg(pParse, rTemp);
  125611. }else{
  125612. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  125613. VdbeCoverageIf(v, bRev==0);
  125614. VdbeCoverageIf(v, bRev!=0);
  125615. }
  125616. if( pEnd ){
  125617. Expr *pX;
  125618. pX = pEnd->pExpr;
  125619. assert( pX!=0 );
  125620. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  125621. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  125622. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  125623. memEndValue = ++pParse->nMem;
  125624. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  125625. if( 0==sqlite3ExprIsVector(pX->pRight)
  125626. && (pX->op==TK_LT || pX->op==TK_GT)
  125627. ){
  125628. testOp = bRev ? OP_Le : OP_Ge;
  125629. }else{
  125630. testOp = bRev ? OP_Lt : OP_Gt;
  125631. }
  125632. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  125633. disableTerm(pLevel, pEnd);
  125634. }
  125635. }
  125636. start = sqlite3VdbeCurrentAddr(v);
  125637. pLevel->op = bRev ? OP_Prev : OP_Next;
  125638. pLevel->p1 = iCur;
  125639. pLevel->p2 = start;
  125640. assert( pLevel->p5==0 );
  125641. if( testOp!=OP_Noop ){
  125642. iRowidReg = ++pParse->nMem;
  125643. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  125644. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  125645. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  125646. VdbeCoverageIf(v, testOp==OP_Le);
  125647. VdbeCoverageIf(v, testOp==OP_Lt);
  125648. VdbeCoverageIf(v, testOp==OP_Ge);
  125649. VdbeCoverageIf(v, testOp==OP_Gt);
  125650. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  125651. }
  125652. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  125653. /* Case 4: A scan using an index.
  125654. **
  125655. ** The WHERE clause may contain zero or more equality
  125656. ** terms ("==" or "IN" operators) that refer to the N
  125657. ** left-most columns of the index. It may also contain
  125658. ** inequality constraints (>, <, >= or <=) on the indexed
  125659. ** column that immediately follows the N equalities. Only
  125660. ** the right-most column can be an inequality - the rest must
  125661. ** use the "==" and "IN" operators. For example, if the
  125662. ** index is on (x,y,z), then the following clauses are all
  125663. ** optimized:
  125664. **
  125665. ** x=5
  125666. ** x=5 AND y=10
  125667. ** x=5 AND y<10
  125668. ** x=5 AND y>5 AND y<10
  125669. ** x=5 AND y=5 AND z<=10
  125670. **
  125671. ** The z<10 term of the following cannot be used, only
  125672. ** the x=5 term:
  125673. **
  125674. ** x=5 AND z<10
  125675. **
  125676. ** N may be zero if there are inequality constraints.
  125677. ** If there are no inequality constraints, then N is at
  125678. ** least one.
  125679. **
  125680. ** This case is also used when there are no WHERE clause
  125681. ** constraints but an index is selected anyway, in order
  125682. ** to force the output order to conform to an ORDER BY.
  125683. */
  125684. static const u8 aStartOp[] = {
  125685. 0,
  125686. 0,
  125687. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  125688. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  125689. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  125690. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  125691. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  125692. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  125693. };
  125694. static const u8 aEndOp[] = {
  125695. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  125696. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  125697. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  125698. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  125699. };
  125700. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  125701. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  125702. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  125703. int regBase; /* Base register holding constraint values */
  125704. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  125705. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  125706. int startEq; /* True if range start uses ==, >= or <= */
  125707. int endEq; /* True if range end uses ==, >= or <= */
  125708. int start_constraints; /* Start of range is constrained */
  125709. int nConstraint; /* Number of constraint terms */
  125710. int iIdxCur; /* The VDBE cursor for the index */
  125711. int nExtraReg = 0; /* Number of extra registers needed */
  125712. int op; /* Instruction opcode */
  125713. char *zStartAff; /* Affinity for start of range constraint */
  125714. char *zEndAff = 0; /* Affinity for end of range constraint */
  125715. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  125716. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  125717. pIdx = pLoop->u.btree.pIndex;
  125718. iIdxCur = pLevel->iIdxCur;
  125719. assert( nEq>=pLoop->nSkip );
  125720. /* If this loop satisfies a sort order (pOrderBy) request that
  125721. ** was passed to this function to implement a "SELECT min(x) ..."
  125722. ** query, then the caller will only allow the loop to run for
  125723. ** a single iteration. This means that the first row returned
  125724. ** should not have a NULL value stored in 'x'. If column 'x' is
  125725. ** the first one after the nEq equality constraints in the index,
  125726. ** this requires some special handling.
  125727. */
  125728. assert( pWInfo->pOrderBy==0
  125729. || pWInfo->pOrderBy->nExpr==1
  125730. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  125731. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  125732. && pWInfo->nOBSat>0
  125733. && (pIdx->nKeyCol>nEq)
  125734. ){
  125735. assert( pLoop->nSkip==0 );
  125736. bSeekPastNull = 1;
  125737. nExtraReg = 1;
  125738. }
  125739. /* Find any inequality constraint terms for the start and end
  125740. ** of the range.
  125741. */
  125742. j = nEq;
  125743. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  125744. pRangeStart = pLoop->aLTerm[j++];
  125745. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  125746. /* Like optimization range constraints always occur in pairs */
  125747. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  125748. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  125749. }
  125750. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  125751. pRangeEnd = pLoop->aLTerm[j++];
  125752. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  125753. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  125754. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  125755. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  125756. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  125757. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  125758. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  125759. VdbeComment((v, "LIKE loop counter"));
  125760. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  125761. /* iLikeRepCntr actually stores 2x the counter register number. The
  125762. ** bottom bit indicates whether the search order is ASC or DESC. */
  125763. testcase( bRev );
  125764. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  125765. assert( (bRev & ~1)==0 );
  125766. pLevel->iLikeRepCntr <<=1;
  125767. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  125768. }
  125769. #endif
  125770. if( pRangeStart==0 ){
  125771. j = pIdx->aiColumn[nEq];
  125772. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  125773. bSeekPastNull = 1;
  125774. }
  125775. }
  125776. }
  125777. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  125778. /* If we are doing a reverse order scan on an ascending index, or
  125779. ** a forward order scan on a descending index, interchange the
  125780. ** start and end terms (pRangeStart and pRangeEnd).
  125781. */
  125782. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  125783. || (bRev && pIdx->nKeyCol==nEq)
  125784. ){
  125785. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  125786. SWAP(u8, bSeekPastNull, bStopAtNull);
  125787. SWAP(u8, nBtm, nTop);
  125788. }
  125789. /* Generate code to evaluate all constraint terms using == or IN
  125790. ** and store the values of those terms in an array of registers
  125791. ** starting at regBase.
  125792. */
  125793. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  125794. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  125795. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  125796. if( zStartAff && nTop ){
  125797. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  125798. }
  125799. addrNxt = pLevel->addrNxt;
  125800. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  125801. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  125802. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  125803. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  125804. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  125805. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  125806. start_constraints = pRangeStart || nEq>0;
  125807. /* Seek the index cursor to the start of the range. */
  125808. nConstraint = nEq;
  125809. if( pRangeStart ){
  125810. Expr *pRight = pRangeStart->pExpr->pRight;
  125811. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  125812. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  125813. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  125814. && sqlite3ExprCanBeNull(pRight)
  125815. ){
  125816. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  125817. VdbeCoverage(v);
  125818. }
  125819. if( zStartAff ){
  125820. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  125821. }
  125822. nConstraint += nBtm;
  125823. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  125824. if( sqlite3ExprIsVector(pRight)==0 ){
  125825. disableTerm(pLevel, pRangeStart);
  125826. }else{
  125827. startEq = 1;
  125828. }
  125829. bSeekPastNull = 0;
  125830. }else if( bSeekPastNull ){
  125831. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  125832. nConstraint++;
  125833. startEq = 0;
  125834. start_constraints = 1;
  125835. }
  125836. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  125837. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  125838. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  125839. ** above has already left the cursor sitting on the correct row,
  125840. ** so no further seeking is needed */
  125841. }else{
  125842. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  125843. assert( op!=0 );
  125844. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  125845. VdbeCoverage(v);
  125846. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  125847. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  125848. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  125849. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  125850. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  125851. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  125852. }
  125853. /* Load the value for the inequality constraint at the end of the
  125854. ** range (if any).
  125855. */
  125856. nConstraint = nEq;
  125857. if( pRangeEnd ){
  125858. Expr *pRight = pRangeEnd->pExpr->pRight;
  125859. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  125860. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  125861. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  125862. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  125863. && sqlite3ExprCanBeNull(pRight)
  125864. ){
  125865. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  125866. VdbeCoverage(v);
  125867. }
  125868. if( zEndAff ){
  125869. updateRangeAffinityStr(pRight, nTop, zEndAff);
  125870. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  125871. }else{
  125872. assert( pParse->db->mallocFailed );
  125873. }
  125874. nConstraint += nTop;
  125875. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  125876. if( sqlite3ExprIsVector(pRight)==0 ){
  125877. disableTerm(pLevel, pRangeEnd);
  125878. }else{
  125879. endEq = 1;
  125880. }
  125881. }else if( bStopAtNull ){
  125882. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  125883. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  125884. endEq = 0;
  125885. nConstraint++;
  125886. }
  125887. sqlite3DbFree(db, zStartAff);
  125888. sqlite3DbFree(db, zEndAff);
  125889. /* Top of the loop body */
  125890. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  125891. /* Check if the index cursor is past the end of the range. */
  125892. if( nConstraint ){
  125893. op = aEndOp[bRev*2 + endEq];
  125894. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  125895. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  125896. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  125897. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  125898. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  125899. }
  125900. /* Seek the table cursor, if required */
  125901. if( omitTable ){
  125902. /* pIdx is a covering index. No need to access the main table. */
  125903. }else if( HasRowid(pIdx->pTable) ){
  125904. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  125905. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  125906. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  125907. )){
  125908. iRowidReg = ++pParse->nMem;
  125909. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  125910. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  125911. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  125912. VdbeCoverage(v);
  125913. }else{
  125914. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  125915. }
  125916. }else if( iCur!=iIdxCur ){
  125917. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  125918. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  125919. for(j=0; j<pPk->nKeyCol; j++){
  125920. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  125921. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  125922. }
  125923. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  125924. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  125925. }
  125926. /* If pIdx is an index on one or more expressions, then look through
  125927. ** all the expressions in pWInfo and try to transform matching expressions
  125928. ** into reference to index columns.
  125929. **
  125930. ** Do not do this for the RHS of a LEFT JOIN. This is because the
  125931. ** expression may be evaluated after OP_NullRow has been executed on
  125932. ** the cursor. In this case it is important to do the full evaluation,
  125933. ** as the result of the expression may not be NULL, even if all table
  125934. ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a
  125935. */
  125936. if( pLevel->iLeftJoin==0 ){
  125937. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  125938. }
  125939. /* Record the instruction used to terminate the loop. */
  125940. if( pLoop->wsFlags & WHERE_ONEROW ){
  125941. pLevel->op = OP_Noop;
  125942. }else if( bRev ){
  125943. pLevel->op = OP_Prev;
  125944. }else{
  125945. pLevel->op = OP_Next;
  125946. }
  125947. pLevel->p1 = iIdxCur;
  125948. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  125949. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  125950. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  125951. }else{
  125952. assert( pLevel->p5==0 );
  125953. }
  125954. if( omitTable ) pIdx = 0;
  125955. }else
  125956. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  125957. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  125958. /* Case 5: Two or more separately indexed terms connected by OR
  125959. **
  125960. ** Example:
  125961. **
  125962. ** CREATE TABLE t1(a,b,c,d);
  125963. ** CREATE INDEX i1 ON t1(a);
  125964. ** CREATE INDEX i2 ON t1(b);
  125965. ** CREATE INDEX i3 ON t1(c);
  125966. **
  125967. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  125968. **
  125969. ** In the example, there are three indexed terms connected by OR.
  125970. ** The top of the loop looks like this:
  125971. **
  125972. ** Null 1 # Zero the rowset in reg 1
  125973. **
  125974. ** Then, for each indexed term, the following. The arguments to
  125975. ** RowSetTest are such that the rowid of the current row is inserted
  125976. ** into the RowSet. If it is already present, control skips the
  125977. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  125978. **
  125979. ** sqlite3WhereBegin(<term>)
  125980. ** RowSetTest # Insert rowid into rowset
  125981. ** Gosub 2 A
  125982. ** sqlite3WhereEnd()
  125983. **
  125984. ** Following the above, code to terminate the loop. Label A, the target
  125985. ** of the Gosub above, jumps to the instruction right after the Goto.
  125986. **
  125987. ** Null 1 # Zero the rowset in reg 1
  125988. ** Goto B # The loop is finished.
  125989. **
  125990. ** A: <loop body> # Return data, whatever.
  125991. **
  125992. ** Return 2 # Jump back to the Gosub
  125993. **
  125994. ** B: <after the loop>
  125995. **
  125996. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  125997. ** use an ephemeral index instead of a RowSet to record the primary
  125998. ** keys of the rows we have already seen.
  125999. **
  126000. */
  126001. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  126002. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  126003. Index *pCov = 0; /* Potential covering index (or NULL) */
  126004. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  126005. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  126006. int regRowset = 0; /* Register for RowSet object */
  126007. int regRowid = 0; /* Register holding rowid */
  126008. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  126009. int iRetInit; /* Address of regReturn init */
  126010. int untestedTerms = 0; /* Some terms not completely tested */
  126011. int ii; /* Loop counter */
  126012. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  126013. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  126014. Table *pTab = pTabItem->pTab;
  126015. pTerm = pLoop->aLTerm[0];
  126016. assert( pTerm!=0 );
  126017. assert( pTerm->eOperator & WO_OR );
  126018. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  126019. pOrWc = &pTerm->u.pOrInfo->wc;
  126020. pLevel->op = OP_Return;
  126021. pLevel->p1 = regReturn;
  126022. /* Set up a new SrcList in pOrTab containing the table being scanned
  126023. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  126024. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  126025. */
  126026. if( pWInfo->nLevel>1 ){
  126027. int nNotReady; /* The number of notReady tables */
  126028. struct SrcList_item *origSrc; /* Original list of tables */
  126029. nNotReady = pWInfo->nLevel - iLevel - 1;
  126030. pOrTab = sqlite3StackAllocRaw(db,
  126031. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  126032. if( pOrTab==0 ) return notReady;
  126033. pOrTab->nAlloc = (u8)(nNotReady + 1);
  126034. pOrTab->nSrc = pOrTab->nAlloc;
  126035. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  126036. origSrc = pWInfo->pTabList->a;
  126037. for(k=1; k<=nNotReady; k++){
  126038. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  126039. }
  126040. }else{
  126041. pOrTab = pWInfo->pTabList;
  126042. }
  126043. /* Initialize the rowset register to contain NULL. An SQL NULL is
  126044. ** equivalent to an empty rowset. Or, create an ephemeral index
  126045. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  126046. **
  126047. ** Also initialize regReturn to contain the address of the instruction
  126048. ** immediately following the OP_Return at the bottom of the loop. This
  126049. ** is required in a few obscure LEFT JOIN cases where control jumps
  126050. ** over the top of the loop into the body of it. In this case the
  126051. ** correct response for the end-of-loop code (the OP_Return) is to
  126052. ** fall through to the next instruction, just as an OP_Next does if
  126053. ** called on an uninitialized cursor.
  126054. */
  126055. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  126056. if( HasRowid(pTab) ){
  126057. regRowset = ++pParse->nMem;
  126058. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  126059. }else{
  126060. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  126061. regRowset = pParse->nTab++;
  126062. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  126063. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  126064. }
  126065. regRowid = ++pParse->nMem;
  126066. }
  126067. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  126068. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  126069. ** Then for every term xN, evaluate as the subexpression: xN AND z
  126070. ** That way, terms in y that are factored into the disjunction will
  126071. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  126072. **
  126073. ** Actually, each subexpression is converted to "xN AND w" where w is
  126074. ** the "interesting" terms of z - terms that did not originate in the
  126075. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  126076. ** indices.
  126077. **
  126078. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  126079. ** is not contained in the ON clause of a LEFT JOIN.
  126080. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  126081. */
  126082. if( pWC->nTerm>1 ){
  126083. int iTerm;
  126084. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  126085. Expr *pExpr = pWC->a[iTerm].pExpr;
  126086. if( &pWC->a[iTerm] == pTerm ) continue;
  126087. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  126088. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  126089. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  126090. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  126091. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  126092. pExpr = sqlite3ExprDup(db, pExpr, 0);
  126093. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  126094. }
  126095. if( pAndExpr ){
  126096. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
  126097. }
  126098. }
  126099. /* Run a separate WHERE clause for each term of the OR clause. After
  126100. ** eliminating duplicates from other WHERE clauses, the action for each
  126101. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  126102. */
  126103. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  126104. ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
  126105. for(ii=0; ii<pOrWc->nTerm; ii++){
  126106. WhereTerm *pOrTerm = &pOrWc->a[ii];
  126107. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  126108. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  126109. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  126110. int jmp1 = 0; /* Address of jump operation */
  126111. assert( (pTabItem[0].fg.jointype & JT_LEFT)==0
  126112. || ExprHasProperty(pOrExpr, EP_FromJoin)
  126113. );
  126114. if( pAndExpr ){
  126115. pAndExpr->pLeft = pOrExpr;
  126116. pOrExpr = pAndExpr;
  126117. }
  126118. /* Loop through table entries that match term pOrTerm. */
  126119. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  126120. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  126121. wctrlFlags, iCovCur);
  126122. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  126123. if( pSubWInfo ){
  126124. WhereLoop *pSubLoop;
  126125. int addrExplain = sqlite3WhereExplainOneScan(
  126126. pParse, pOrTab, &pSubWInfo->a[0], 0
  126127. );
  126128. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  126129. /* This is the sub-WHERE clause body. First skip over
  126130. ** duplicate rows from prior sub-WHERE clauses, and record the
  126131. ** rowid (or PRIMARY KEY) for the current row so that the same
  126132. ** row will be skipped in subsequent sub-WHERE clauses.
  126133. */
  126134. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  126135. int r;
  126136. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  126137. if( HasRowid(pTab) ){
  126138. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  126139. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  126140. r,iSet);
  126141. VdbeCoverage(v);
  126142. }else{
  126143. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  126144. int nPk = pPk->nKeyCol;
  126145. int iPk;
  126146. /* Read the PK into an array of temp registers. */
  126147. r = sqlite3GetTempRange(pParse, nPk);
  126148. for(iPk=0; iPk<nPk; iPk++){
  126149. int iCol = pPk->aiColumn[iPk];
  126150. sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
  126151. }
  126152. /* Check if the temp table already contains this key. If so,
  126153. ** the row has already been included in the result set and
  126154. ** can be ignored (by jumping past the Gosub below). Otherwise,
  126155. ** insert the key into the temp table and proceed with processing
  126156. ** the row.
  126157. **
  126158. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  126159. ** is zero, assume that the key cannot already be present in
  126160. ** the temp table. And if iSet is -1, assume that there is no
  126161. ** need to insert the key into the temp table, as it will never
  126162. ** be tested for. */
  126163. if( iSet ){
  126164. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  126165. VdbeCoverage(v);
  126166. }
  126167. if( iSet>=0 ){
  126168. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  126169. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  126170. r, nPk);
  126171. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  126172. }
  126173. /* Release the array of temp registers */
  126174. sqlite3ReleaseTempRange(pParse, r, nPk);
  126175. }
  126176. }
  126177. /* Invoke the main loop body as a subroutine */
  126178. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  126179. /* Jump here (skipping the main loop body subroutine) if the
  126180. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  126181. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  126182. /* The pSubWInfo->untestedTerms flag means that this OR term
  126183. ** contained one or more AND term from a notReady table. The
  126184. ** terms from the notReady table could not be tested and will
  126185. ** need to be tested later.
  126186. */
  126187. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  126188. /* If all of the OR-connected terms are optimized using the same
  126189. ** index, and the index is opened using the same cursor number
  126190. ** by each call to sqlite3WhereBegin() made by this loop, it may
  126191. ** be possible to use that index as a covering index.
  126192. **
  126193. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  126194. ** uses an index, and this is either the first OR-connected term
  126195. ** processed or the index is the same as that used by all previous
  126196. ** terms, set pCov to the candidate covering index. Otherwise, set
  126197. ** pCov to NULL to indicate that no candidate covering index will
  126198. ** be available.
  126199. */
  126200. pSubLoop = pSubWInfo->a[0].pWLoop;
  126201. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  126202. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  126203. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  126204. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  126205. ){
  126206. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  126207. pCov = pSubLoop->u.btree.pIndex;
  126208. }else{
  126209. pCov = 0;
  126210. }
  126211. /* Finish the loop through table entries that match term pOrTerm. */
  126212. sqlite3WhereEnd(pSubWInfo);
  126213. }
  126214. }
  126215. }
  126216. ExplainQueryPlanPop(pParse);
  126217. pLevel->u.pCovidx = pCov;
  126218. if( pCov ) pLevel->iIdxCur = iCovCur;
  126219. if( pAndExpr ){
  126220. pAndExpr->pLeft = 0;
  126221. sqlite3ExprDelete(db, pAndExpr);
  126222. }
  126223. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  126224. sqlite3VdbeGoto(v, pLevel->addrBrk);
  126225. sqlite3VdbeResolveLabel(v, iLoopBody);
  126226. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  126227. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  126228. }else
  126229. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  126230. {
  126231. /* Case 6: There is no usable index. We must do a complete
  126232. ** scan of the entire table.
  126233. */
  126234. static const u8 aStep[] = { OP_Next, OP_Prev };
  126235. static const u8 aStart[] = { OP_Rewind, OP_Last };
  126236. assert( bRev==0 || bRev==1 );
  126237. if( pTabItem->fg.isRecursive ){
  126238. /* Tables marked isRecursive have only a single row that is stored in
  126239. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  126240. pLevel->op = OP_Noop;
  126241. }else{
  126242. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  126243. pLevel->op = aStep[bRev];
  126244. pLevel->p1 = iCur;
  126245. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  126246. VdbeCoverageIf(v, bRev==0);
  126247. VdbeCoverageIf(v, bRev!=0);
  126248. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  126249. }
  126250. }
  126251. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  126252. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  126253. #endif
  126254. /* Insert code to test every subexpression that can be completely
  126255. ** computed using the current set of tables.
  126256. **
  126257. ** This loop may run between one and three times, depending on the
  126258. ** constraints to be generated. The value of stack variable iLoop
  126259. ** determines the constraints coded by each iteration, as follows:
  126260. **
  126261. ** iLoop==1: Code only expressions that are entirely covered by pIdx.
  126262. ** iLoop==2: Code remaining expressions that do not contain correlated
  126263. ** sub-queries.
  126264. ** iLoop==3: Code all remaining expressions.
  126265. **
  126266. ** An effort is made to skip unnecessary iterations of the loop.
  126267. */
  126268. iLoop = (pIdx ? 1 : 2);
  126269. do{
  126270. int iNext = 0; /* Next value for iLoop */
  126271. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  126272. Expr *pE;
  126273. int skipLikeAddr = 0;
  126274. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  126275. testcase( pTerm->wtFlags & TERM_CODED );
  126276. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  126277. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  126278. testcase( pWInfo->untestedTerms==0
  126279. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  126280. pWInfo->untestedTerms = 1;
  126281. continue;
  126282. }
  126283. pE = pTerm->pExpr;
  126284. assert( pE!=0 );
  126285. if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
  126286. continue;
  126287. }
  126288. if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  126289. iNext = 2;
  126290. continue;
  126291. }
  126292. if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
  126293. if( iNext==0 ) iNext = 3;
  126294. continue;
  126295. }
  126296. if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
  126297. /* If the TERM_LIKECOND flag is set, that means that the range search
  126298. ** is sufficient to guarantee that the LIKE operator is true, so we
  126299. ** can skip the call to the like(A,B) function. But this only works
  126300. ** for strings. So do not skip the call to the function on the pass
  126301. ** that compares BLOBs. */
  126302. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  126303. continue;
  126304. #else
  126305. u32 x = pLevel->iLikeRepCntr;
  126306. if( x>0 ){
  126307. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
  126308. }
  126309. VdbeCoverage(v);
  126310. #endif
  126311. }
  126312. #ifdef WHERETRACE_ENABLED /* 0xffff */
  126313. if( sqlite3WhereTrace ){
  126314. VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
  126315. pWC->nTerm-j, pTerm, iLoop));
  126316. }
  126317. #endif
  126318. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  126319. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  126320. pTerm->wtFlags |= TERM_CODED;
  126321. }
  126322. iLoop = iNext;
  126323. }while( iLoop>0 );
  126324. /* Insert code to test for implied constraints based on transitivity
  126325. ** of the "==" operator.
  126326. **
  126327. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  126328. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  126329. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  126330. ** the implied "t1.a=123" constraint.
  126331. */
  126332. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  126333. Expr *pE, sEAlt;
  126334. WhereTerm *pAlt;
  126335. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  126336. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  126337. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  126338. if( pTerm->leftCursor!=iCur ) continue;
  126339. if( pLevel->iLeftJoin ) continue;
  126340. pE = pTerm->pExpr;
  126341. assert( !ExprHasProperty(pE, EP_FromJoin) );
  126342. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  126343. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  126344. WO_EQ|WO_IN|WO_IS, 0);
  126345. if( pAlt==0 ) continue;
  126346. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  126347. if( (pAlt->eOperator & WO_IN)
  126348. && (pAlt->pExpr->flags & EP_xIsSelect)
  126349. && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
  126350. ){
  126351. continue;
  126352. }
  126353. testcase( pAlt->eOperator & WO_EQ );
  126354. testcase( pAlt->eOperator & WO_IS );
  126355. testcase( pAlt->eOperator & WO_IN );
  126356. VdbeModuleComment((v, "begin transitive constraint"));
  126357. sEAlt = *pAlt->pExpr;
  126358. sEAlt.pLeft = pE->pLeft;
  126359. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  126360. }
  126361. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  126362. ** at least one row of the right table has matched the left table.
  126363. */
  126364. if( pLevel->iLeftJoin ){
  126365. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  126366. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  126367. VdbeComment((v, "record LEFT JOIN hit"));
  126368. sqlite3ExprCacheClear(pParse);
  126369. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  126370. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  126371. testcase( pTerm->wtFlags & TERM_CODED );
  126372. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  126373. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  126374. assert( pWInfo->untestedTerms );
  126375. continue;
  126376. }
  126377. assert( pTerm->pExpr );
  126378. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  126379. pTerm->wtFlags |= TERM_CODED;
  126380. }
  126381. }
  126382. return pLevel->notReady;
  126383. }
  126384. /************** End of wherecode.c *******************************************/
  126385. /************** Begin file whereexpr.c ***************************************/
  126386. /*
  126387. ** 2015-06-08
  126388. **
  126389. ** The author disclaims copyright to this source code. In place of
  126390. ** a legal notice, here is a blessing:
  126391. **
  126392. ** May you do good and not evil.
  126393. ** May you find forgiveness for yourself and forgive others.
  126394. ** May you share freely, never taking more than you give.
  126395. **
  126396. *************************************************************************
  126397. ** This module contains C code that generates VDBE code used to process
  126398. ** the WHERE clause of SQL statements.
  126399. **
  126400. ** This file was originally part of where.c but was split out to improve
  126401. ** readability and editabiliity. This file contains utility routines for
  126402. ** analyzing Expr objects in the WHERE clause.
  126403. */
  126404. /* #include "sqliteInt.h" */
  126405. /* #include "whereInt.h" */
  126406. /* Forward declarations */
  126407. static void exprAnalyze(SrcList*, WhereClause*, int);
  126408. /*
  126409. ** Deallocate all memory associated with a WhereOrInfo object.
  126410. */
  126411. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  126412. sqlite3WhereClauseClear(&p->wc);
  126413. sqlite3DbFree(db, p);
  126414. }
  126415. /*
  126416. ** Deallocate all memory associated with a WhereAndInfo object.
  126417. */
  126418. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  126419. sqlite3WhereClauseClear(&p->wc);
  126420. sqlite3DbFree(db, p);
  126421. }
  126422. /*
  126423. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  126424. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  126425. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  126426. ** 0 is returned if the new WhereTerm could not be added due to a memory
  126427. ** allocation error. The memory allocation failure will be recorded in
  126428. ** the db->mallocFailed flag so that higher-level functions can detect it.
  126429. **
  126430. ** This routine will increase the size of the pWC->a[] array as necessary.
  126431. **
  126432. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  126433. ** for freeing the expression p is assumed by the WhereClause object pWC.
  126434. ** This is true even if this routine fails to allocate a new WhereTerm.
  126435. **
  126436. ** WARNING: This routine might reallocate the space used to store
  126437. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  126438. ** calling this routine. Such pointers may be reinitialized by referencing
  126439. ** the pWC->a[] array.
  126440. */
  126441. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  126442. WhereTerm *pTerm;
  126443. int idx;
  126444. testcase( wtFlags & TERM_VIRTUAL );
  126445. if( pWC->nTerm>=pWC->nSlot ){
  126446. WhereTerm *pOld = pWC->a;
  126447. sqlite3 *db = pWC->pWInfo->pParse->db;
  126448. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  126449. if( pWC->a==0 ){
  126450. if( wtFlags & TERM_DYNAMIC ){
  126451. sqlite3ExprDelete(db, p);
  126452. }
  126453. pWC->a = pOld;
  126454. return 0;
  126455. }
  126456. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  126457. if( pOld!=pWC->aStatic ){
  126458. sqlite3DbFree(db, pOld);
  126459. }
  126460. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  126461. }
  126462. pTerm = &pWC->a[idx = pWC->nTerm++];
  126463. if( p && ExprHasProperty(p, EP_Unlikely) ){
  126464. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  126465. }else{
  126466. pTerm->truthProb = 1;
  126467. }
  126468. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  126469. pTerm->wtFlags = wtFlags;
  126470. pTerm->pWC = pWC;
  126471. pTerm->iParent = -1;
  126472. memset(&pTerm->eOperator, 0,
  126473. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  126474. return idx;
  126475. }
  126476. /*
  126477. ** Return TRUE if the given operator is one of the operators that is
  126478. ** allowed for an indexable WHERE clause term. The allowed operators are
  126479. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  126480. */
  126481. static int allowedOp(int op){
  126482. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  126483. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  126484. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  126485. assert( TK_GE==TK_EQ+4 );
  126486. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  126487. }
  126488. /*
  126489. ** Commute a comparison operator. Expressions of the form "X op Y"
  126490. ** are converted into "Y op X".
  126491. **
  126492. ** If left/right precedence rules come into play when determining the
  126493. ** collating sequence, then COLLATE operators are adjusted to ensure
  126494. ** that the collating sequence does not change. For example:
  126495. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  126496. ** the left hand side of a comparison overrides any collation sequence
  126497. ** attached to the right. For the same reason the EP_Collate flag
  126498. ** is not commuted.
  126499. */
  126500. static void exprCommute(Parse *pParse, Expr *pExpr){
  126501. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  126502. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  126503. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  126504. if( expRight==expLeft ){
  126505. /* Either X and Y both have COLLATE operator or neither do */
  126506. if( expRight ){
  126507. /* Both X and Y have COLLATE operators. Make sure X is always
  126508. ** used by clearing the EP_Collate flag from Y. */
  126509. pExpr->pRight->flags &= ~EP_Collate;
  126510. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  126511. /* Neither X nor Y have COLLATE operators, but X has a non-default
  126512. ** collating sequence. So add the EP_Collate marker on X to cause
  126513. ** it to be searched first. */
  126514. pExpr->pLeft->flags |= EP_Collate;
  126515. }
  126516. }
  126517. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  126518. if( pExpr->op>=TK_GT ){
  126519. assert( TK_LT==TK_GT+2 );
  126520. assert( TK_GE==TK_LE+2 );
  126521. assert( TK_GT>TK_EQ );
  126522. assert( TK_GT<TK_LE );
  126523. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  126524. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  126525. }
  126526. }
  126527. /*
  126528. ** Translate from TK_xx operator to WO_xx bitmask.
  126529. */
  126530. static u16 operatorMask(int op){
  126531. u16 c;
  126532. assert( allowedOp(op) );
  126533. if( op==TK_IN ){
  126534. c = WO_IN;
  126535. }else if( op==TK_ISNULL ){
  126536. c = WO_ISNULL;
  126537. }else if( op==TK_IS ){
  126538. c = WO_IS;
  126539. }else{
  126540. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  126541. c = (u16)(WO_EQ<<(op-TK_EQ));
  126542. }
  126543. assert( op!=TK_ISNULL || c==WO_ISNULL );
  126544. assert( op!=TK_IN || c==WO_IN );
  126545. assert( op!=TK_EQ || c==WO_EQ );
  126546. assert( op!=TK_LT || c==WO_LT );
  126547. assert( op!=TK_LE || c==WO_LE );
  126548. assert( op!=TK_GT || c==WO_GT );
  126549. assert( op!=TK_GE || c==WO_GE );
  126550. assert( op!=TK_IS || c==WO_IS );
  126551. return c;
  126552. }
  126553. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  126554. /*
  126555. ** Check to see if the given expression is a LIKE or GLOB operator that
  126556. ** can be optimized using inequality constraints. Return TRUE if it is
  126557. ** so and false if not.
  126558. **
  126559. ** In order for the operator to be optimizible, the RHS must be a string
  126560. ** literal that does not begin with a wildcard. The LHS must be a column
  126561. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  126562. ** that virtual tables cannot participate in the LIKE optimization.) The
  126563. ** collating sequence for the column on the LHS must be appropriate for
  126564. ** the operator.
  126565. */
  126566. static int isLikeOrGlob(
  126567. Parse *pParse, /* Parsing and code generating context */
  126568. Expr *pExpr, /* Test this expression */
  126569. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  126570. int *pisComplete, /* True if the only wildcard is % in the last character */
  126571. int *pnoCase /* True if uppercase is equivalent to lowercase */
  126572. ){
  126573. const u8 *z = 0; /* String on RHS of LIKE operator */
  126574. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  126575. ExprList *pList; /* List of operands to the LIKE operator */
  126576. int c; /* One character in z[] */
  126577. int cnt; /* Number of non-wildcard prefix characters */
  126578. char wc[4]; /* Wildcard characters */
  126579. sqlite3 *db = pParse->db; /* Database connection */
  126580. sqlite3_value *pVal = 0;
  126581. int op; /* Opcode of pRight */
  126582. int rc; /* Result code to return */
  126583. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  126584. return 0;
  126585. }
  126586. #ifdef SQLITE_EBCDIC
  126587. if( *pnoCase ) return 0;
  126588. #endif
  126589. pList = pExpr->x.pList;
  126590. pLeft = pList->a[1].pExpr;
  126591. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  126592. op = pRight->op;
  126593. if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  126594. Vdbe *pReprepare = pParse->pReprepare;
  126595. int iCol = pRight->iColumn;
  126596. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  126597. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  126598. z = sqlite3_value_text(pVal);
  126599. }
  126600. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  126601. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  126602. }else if( op==TK_STRING ){
  126603. z = (u8*)pRight->u.zToken;
  126604. }
  126605. if( z ){
  126606. /* If the RHS begins with a digit or a minus sign, then the LHS must
  126607. ** be an ordinary column (not a virtual table column) with TEXT affinity.
  126608. ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
  126609. ** even though "lhs LIKE rhs" is true. But if the RHS does not start
  126610. ** with a digit or '-', then "lhs LIKE rhs" will always be false if
  126611. ** the LHS is numeric and so the optimization still works.
  126612. */
  126613. if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
  126614. if( pLeft->op!=TK_COLUMN
  126615. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  126616. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  126617. ){
  126618. sqlite3ValueFree(pVal);
  126619. return 0;
  126620. }
  126621. }
  126622. /* Count the number of prefix characters prior to the first wildcard */
  126623. cnt = 0;
  126624. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  126625. cnt++;
  126626. if( c==wc[3] && z[cnt]!=0 ) cnt++;
  126627. }
  126628. /* The optimization is possible only if (1) the pattern does not begin
  126629. ** with a wildcard and if (2) the non-wildcard prefix does not end with
  126630. ** an (illegal 0xff) character. The second condition is necessary so
  126631. ** that we can increment the prefix key to find an upper bound for the
  126632. ** range search.
  126633. */
  126634. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  126635. Expr *pPrefix;
  126636. /* A "complete" match if the pattern ends with "*" or "%" */
  126637. *pisComplete = c==wc[0] && z[cnt+1]==0;
  126638. /* Get the pattern prefix. Remove all escapes from the prefix. */
  126639. pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
  126640. if( pPrefix ){
  126641. int iFrom, iTo;
  126642. char *zNew = pPrefix->u.zToken;
  126643. zNew[cnt] = 0;
  126644. for(iFrom=iTo=0; iFrom<cnt; iFrom++){
  126645. if( zNew[iFrom]==wc[3] ) iFrom++;
  126646. zNew[iTo++] = zNew[iFrom];
  126647. }
  126648. zNew[iTo] = 0;
  126649. }
  126650. *ppPrefix = pPrefix;
  126651. /* If the RHS pattern is a bound parameter, make arrangements to
  126652. ** reprepare the statement when that parameter is rebound */
  126653. if( op==TK_VARIABLE ){
  126654. Vdbe *v = pParse->pVdbe;
  126655. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  126656. if( *pisComplete && pRight->u.zToken[1] ){
  126657. /* If the rhs of the LIKE expression is a variable, and the current
  126658. ** value of the variable means there is no need to invoke the LIKE
  126659. ** function, then no OP_Variable will be added to the program.
  126660. ** This causes problems for the sqlite3_bind_parameter_name()
  126661. ** API. To work around them, add a dummy OP_Variable here.
  126662. */
  126663. int r1 = sqlite3GetTempReg(pParse);
  126664. sqlite3ExprCodeTarget(pParse, pRight, r1);
  126665. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  126666. sqlite3ReleaseTempReg(pParse, r1);
  126667. }
  126668. }
  126669. }else{
  126670. z = 0;
  126671. }
  126672. }
  126673. rc = (z!=0);
  126674. sqlite3ValueFree(pVal);
  126675. return rc;
  126676. }
  126677. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  126678. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126679. /*
  126680. ** Check to see if the pExpr expression is a form that needs to be passed
  126681. ** to the xBestIndex method of virtual tables. Forms of interest include:
  126682. **
  126683. ** Expression Virtual Table Operator
  126684. ** ----------------------- ---------------------------------
  126685. ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
  126686. ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
  126687. ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
  126688. ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
  126689. ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
  126690. ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
  126691. ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
  126692. ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
  126693. ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
  126694. **
  126695. ** In every case, "column" must be a column of a virtual table. If there
  126696. ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
  126697. ** "expr" expression (even though in forms (6) and (8) the column is on the
  126698. ** right and the expression is on the left). Also set *peOp2 to the
  126699. ** appropriate virtual table operator. The return value is 1 or 2 if there
  126700. ** is a match. The usual return is 1, but if the RHS is also a column
  126701. ** of virtual table in forms (5) or (7) then return 2.
  126702. **
  126703. ** If the expression matches none of the patterns above, return 0.
  126704. */
  126705. static int isAuxiliaryVtabOperator(
  126706. Expr *pExpr, /* Test this expression */
  126707. unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
  126708. Expr **ppLeft, /* Column expression to left of MATCH/op2 */
  126709. Expr **ppRight /* Expression to left of MATCH/op2 */
  126710. ){
  126711. if( pExpr->op==TK_FUNCTION ){
  126712. static const struct Op2 {
  126713. const char *zOp;
  126714. unsigned char eOp2;
  126715. } aOp[] = {
  126716. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  126717. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  126718. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  126719. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  126720. };
  126721. ExprList *pList;
  126722. Expr *pCol; /* Column reference */
  126723. int i;
  126724. pList = pExpr->x.pList;
  126725. if( pList==0 || pList->nExpr!=2 ){
  126726. return 0;
  126727. }
  126728. pCol = pList->a[1].pExpr;
  126729. if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
  126730. return 0;
  126731. }
  126732. for(i=0; i<ArraySize(aOp); i++){
  126733. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  126734. *peOp2 = aOp[i].eOp2;
  126735. *ppRight = pList->a[0].pExpr;
  126736. *ppLeft = pCol;
  126737. return 1;
  126738. }
  126739. }
  126740. }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
  126741. int res = 0;
  126742. Expr *pLeft = pExpr->pLeft;
  126743. Expr *pRight = pExpr->pRight;
  126744. if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
  126745. res++;
  126746. }
  126747. if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
  126748. res++;
  126749. SWAP(Expr*, pLeft, pRight);
  126750. }
  126751. *ppLeft = pLeft;
  126752. *ppRight = pRight;
  126753. if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
  126754. if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
  126755. if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
  126756. return res;
  126757. }
  126758. return 0;
  126759. }
  126760. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  126761. /*
  126762. ** If the pBase expression originated in the ON or USING clause of
  126763. ** a join, then transfer the appropriate markings over to derived.
  126764. */
  126765. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  126766. if( pDerived ){
  126767. pDerived->flags |= pBase->flags & EP_FromJoin;
  126768. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  126769. }
  126770. }
  126771. /*
  126772. ** Mark term iChild as being a child of term iParent
  126773. */
  126774. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  126775. pWC->a[iChild].iParent = iParent;
  126776. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  126777. pWC->a[iParent].nChild++;
  126778. }
  126779. /*
  126780. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  126781. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  126782. ** the number of available subterms, return NULL.
  126783. */
  126784. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  126785. if( pTerm->eOperator!=WO_AND ){
  126786. return N==0 ? pTerm : 0;
  126787. }
  126788. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  126789. return &pTerm->u.pAndInfo->wc.a[N];
  126790. }
  126791. return 0;
  126792. }
  126793. /*
  126794. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  126795. ** two subterms are in disjunction - they are OR-ed together.
  126796. **
  126797. ** If these two terms are both of the form: "A op B" with the same
  126798. ** A and B values but different operators and if the operators are
  126799. ** compatible (if one is = and the other is <, for example) then
  126800. ** add a new virtual AND term to pWC that is the combination of the
  126801. ** two.
  126802. **
  126803. ** Some examples:
  126804. **
  126805. ** x<y OR x=y --> x<=y
  126806. ** x=y OR x=y --> x=y
  126807. ** x<=y OR x<y --> x<=y
  126808. **
  126809. ** The following is NOT generated:
  126810. **
  126811. ** x<y OR x>y --> x!=y
  126812. */
  126813. static void whereCombineDisjuncts(
  126814. SrcList *pSrc, /* the FROM clause */
  126815. WhereClause *pWC, /* The complete WHERE clause */
  126816. WhereTerm *pOne, /* First disjunct */
  126817. WhereTerm *pTwo /* Second disjunct */
  126818. ){
  126819. u16 eOp = pOne->eOperator | pTwo->eOperator;
  126820. sqlite3 *db; /* Database connection (for malloc) */
  126821. Expr *pNew; /* New virtual expression */
  126822. int op; /* Operator for the combined expression */
  126823. int idxNew; /* Index in pWC of the next virtual term */
  126824. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  126825. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  126826. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  126827. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  126828. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  126829. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  126830. if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  126831. if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
  126832. /* If we reach this point, it means the two subterms can be combined */
  126833. if( (eOp & (eOp-1))!=0 ){
  126834. if( eOp & (WO_LT|WO_LE) ){
  126835. eOp = WO_LE;
  126836. }else{
  126837. assert( eOp & (WO_GT|WO_GE) );
  126838. eOp = WO_GE;
  126839. }
  126840. }
  126841. db = pWC->pWInfo->pParse->db;
  126842. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  126843. if( pNew==0 ) return;
  126844. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  126845. pNew->op = op;
  126846. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  126847. exprAnalyze(pSrc, pWC, idxNew);
  126848. }
  126849. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  126850. /*
  126851. ** Analyze a term that consists of two or more OR-connected
  126852. ** subterms. So in:
  126853. **
  126854. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  126855. ** ^^^^^^^^^^^^^^^^^^^^
  126856. **
  126857. ** This routine analyzes terms such as the middle term in the above example.
  126858. ** A WhereOrTerm object is computed and attached to the term under
  126859. ** analysis, regardless of the outcome of the analysis. Hence:
  126860. **
  126861. ** WhereTerm.wtFlags |= TERM_ORINFO
  126862. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  126863. **
  126864. ** The term being analyzed must have two or more of OR-connected subterms.
  126865. ** A single subterm might be a set of AND-connected sub-subterms.
  126866. ** Examples of terms under analysis:
  126867. **
  126868. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  126869. ** (B) x=expr1 OR expr2=x OR x=expr3
  126870. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  126871. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  126872. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  126873. ** (F) x>A OR (x=A AND y>=B)
  126874. **
  126875. ** CASE 1:
  126876. **
  126877. ** If all subterms are of the form T.C=expr for some single column of C and
  126878. ** a single table T (as shown in example B above) then create a new virtual
  126879. ** term that is an equivalent IN expression. In other words, if the term
  126880. ** being analyzed is:
  126881. **
  126882. ** x = expr1 OR expr2 = x OR x = expr3
  126883. **
  126884. ** then create a new virtual term like this:
  126885. **
  126886. ** x IN (expr1,expr2,expr3)
  126887. **
  126888. ** CASE 2:
  126889. **
  126890. ** If there are exactly two disjuncts and one side has x>A and the other side
  126891. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  126892. ** WHERE clause of the form "x>=A". Example:
  126893. **
  126894. ** x>A OR (x=A AND y>B) adds: x>=A
  126895. **
  126896. ** The added conjunct can sometimes be helpful in query planning.
  126897. **
  126898. ** CASE 3:
  126899. **
  126900. ** If all subterms are indexable by a single table T, then set
  126901. **
  126902. ** WhereTerm.eOperator = WO_OR
  126903. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  126904. **
  126905. ** A subterm is "indexable" if it is of the form
  126906. ** "T.C <op> <expr>" where C is any column of table T and
  126907. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  126908. ** A subterm is also indexable if it is an AND of two or more
  126909. ** subsubterms at least one of which is indexable. Indexable AND
  126910. ** subterms have their eOperator set to WO_AND and they have
  126911. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  126912. **
  126913. ** From another point of view, "indexable" means that the subterm could
  126914. ** potentially be used with an index if an appropriate index exists.
  126915. ** This analysis does not consider whether or not the index exists; that
  126916. ** is decided elsewhere. This analysis only looks at whether subterms
  126917. ** appropriate for indexing exist.
  126918. **
  126919. ** All examples A through E above satisfy case 3. But if a term
  126920. ** also satisfies case 1 (such as B) we know that the optimizer will
  126921. ** always prefer case 1, so in that case we pretend that case 3 is not
  126922. ** satisfied.
  126923. **
  126924. ** It might be the case that multiple tables are indexable. For example,
  126925. ** (E) above is indexable on tables P, Q, and R.
  126926. **
  126927. ** Terms that satisfy case 3 are candidates for lookup by using
  126928. ** separate indices to find rowids for each subterm and composing
  126929. ** the union of all rowids using a RowSet object. This is similar
  126930. ** to "bitmap indices" in other database engines.
  126931. **
  126932. ** OTHERWISE:
  126933. **
  126934. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  126935. ** zero. This term is not useful for search.
  126936. */
  126937. static void exprAnalyzeOrTerm(
  126938. SrcList *pSrc, /* the FROM clause */
  126939. WhereClause *pWC, /* the complete WHERE clause */
  126940. int idxTerm /* Index of the OR-term to be analyzed */
  126941. ){
  126942. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  126943. Parse *pParse = pWInfo->pParse; /* Parser context */
  126944. sqlite3 *db = pParse->db; /* Database connection */
  126945. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  126946. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  126947. int i; /* Loop counters */
  126948. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  126949. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  126950. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  126951. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  126952. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  126953. /*
  126954. ** Break the OR clause into its separate subterms. The subterms are
  126955. ** stored in a WhereClause structure containing within the WhereOrInfo
  126956. ** object that is attached to the original OR clause term.
  126957. */
  126958. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  126959. assert( pExpr->op==TK_OR );
  126960. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  126961. if( pOrInfo==0 ) return;
  126962. pTerm->wtFlags |= TERM_ORINFO;
  126963. pOrWc = &pOrInfo->wc;
  126964. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  126965. sqlite3WhereClauseInit(pOrWc, pWInfo);
  126966. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  126967. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  126968. if( db->mallocFailed ) return;
  126969. assert( pOrWc->nTerm>=2 );
  126970. /*
  126971. ** Compute the set of tables that might satisfy cases 1 or 3.
  126972. */
  126973. indexable = ~(Bitmask)0;
  126974. chngToIN = ~(Bitmask)0;
  126975. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  126976. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  126977. WhereAndInfo *pAndInfo;
  126978. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  126979. chngToIN = 0;
  126980. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  126981. if( pAndInfo ){
  126982. WhereClause *pAndWC;
  126983. WhereTerm *pAndTerm;
  126984. int j;
  126985. Bitmask b = 0;
  126986. pOrTerm->u.pAndInfo = pAndInfo;
  126987. pOrTerm->wtFlags |= TERM_ANDINFO;
  126988. pOrTerm->eOperator = WO_AND;
  126989. pAndWC = &pAndInfo->wc;
  126990. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  126991. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  126992. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  126993. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  126994. pAndWC->pOuter = pWC;
  126995. if( !db->mallocFailed ){
  126996. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  126997. assert( pAndTerm->pExpr );
  126998. if( allowedOp(pAndTerm->pExpr->op)
  126999. || pAndTerm->eOperator==WO_AUX
  127000. ){
  127001. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  127002. }
  127003. }
  127004. }
  127005. indexable &= b;
  127006. }
  127007. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  127008. /* Skip this term for now. We revisit it when we process the
  127009. ** corresponding TERM_VIRTUAL term */
  127010. }else{
  127011. Bitmask b;
  127012. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  127013. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  127014. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  127015. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  127016. }
  127017. indexable &= b;
  127018. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  127019. chngToIN = 0;
  127020. }else{
  127021. chngToIN &= b;
  127022. }
  127023. }
  127024. }
  127025. /*
  127026. ** Record the set of tables that satisfy case 3. The set might be
  127027. ** empty.
  127028. */
  127029. pOrInfo->indexable = indexable;
  127030. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  127031. /* For a two-way OR, attempt to implementation case 2.
  127032. */
  127033. if( indexable && pOrWc->nTerm==2 ){
  127034. int iOne = 0;
  127035. WhereTerm *pOne;
  127036. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  127037. int iTwo = 0;
  127038. WhereTerm *pTwo;
  127039. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  127040. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  127041. }
  127042. }
  127043. }
  127044. /*
  127045. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  127046. ** we have to do some additional checking to see if case 1 really
  127047. ** is satisfied.
  127048. **
  127049. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  127050. ** that there is no possibility of transforming the OR clause into an
  127051. ** IN operator because one or more terms in the OR clause contain
  127052. ** something other than == on a column in the single table. The 1-bit
  127053. ** case means that every term of the OR clause is of the form
  127054. ** "table.column=expr" for some single table. The one bit that is set
  127055. ** will correspond to the common table. We still need to check to make
  127056. ** sure the same column is used on all terms. The 2-bit case is when
  127057. ** the all terms are of the form "table1.column=table2.column". It
  127058. ** might be possible to form an IN operator with either table1.column
  127059. ** or table2.column as the LHS if either is common to every term of
  127060. ** the OR clause.
  127061. **
  127062. ** Note that terms of the form "table.column1=table.column2" (the
  127063. ** same table on both sizes of the ==) cannot be optimized.
  127064. */
  127065. if( chngToIN ){
  127066. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  127067. int iColumn = -1; /* Column index on lhs of IN operator */
  127068. int iCursor = -1; /* Table cursor common to all terms */
  127069. int j = 0; /* Loop counter */
  127070. /* Search for a table and column that appears on one side or the
  127071. ** other of the == operator in every subterm. That table and column
  127072. ** will be recorded in iCursor and iColumn. There might not be any
  127073. ** such table and column. Set okToChngToIN if an appropriate table
  127074. ** and column is found but leave okToChngToIN false if not found.
  127075. */
  127076. for(j=0; j<2 && !okToChngToIN; j++){
  127077. pOrTerm = pOrWc->a;
  127078. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  127079. assert( pOrTerm->eOperator & WO_EQ );
  127080. pOrTerm->wtFlags &= ~TERM_OR_OK;
  127081. if( pOrTerm->leftCursor==iCursor ){
  127082. /* This is the 2-bit case and we are on the second iteration and
  127083. ** current term is from the first iteration. So skip this term. */
  127084. assert( j==1 );
  127085. continue;
  127086. }
  127087. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  127088. pOrTerm->leftCursor))==0 ){
  127089. /* This term must be of the form t1.a==t2.b where t2 is in the
  127090. ** chngToIN set but t1 is not. This term will be either preceded
  127091. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  127092. ** and use its inversion. */
  127093. testcase( pOrTerm->wtFlags & TERM_COPIED );
  127094. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  127095. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  127096. continue;
  127097. }
  127098. iColumn = pOrTerm->u.leftColumn;
  127099. iCursor = pOrTerm->leftCursor;
  127100. break;
  127101. }
  127102. if( i<0 ){
  127103. /* No candidate table+column was found. This can only occur
  127104. ** on the second iteration */
  127105. assert( j==1 );
  127106. assert( IsPowerOfTwo(chngToIN) );
  127107. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  127108. break;
  127109. }
  127110. testcase( j==1 );
  127111. /* We have found a candidate table and column. Check to see if that
  127112. ** table and column is common to every term in the OR clause */
  127113. okToChngToIN = 1;
  127114. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  127115. assert( pOrTerm->eOperator & WO_EQ );
  127116. if( pOrTerm->leftCursor!=iCursor ){
  127117. pOrTerm->wtFlags &= ~TERM_OR_OK;
  127118. }else if( pOrTerm->u.leftColumn!=iColumn ){
  127119. okToChngToIN = 0;
  127120. }else{
  127121. int affLeft, affRight;
  127122. /* If the right-hand side is also a column, then the affinities
  127123. ** of both right and left sides must be such that no type
  127124. ** conversions are required on the right. (Ticket #2249)
  127125. */
  127126. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  127127. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  127128. if( affRight!=0 && affRight!=affLeft ){
  127129. okToChngToIN = 0;
  127130. }else{
  127131. pOrTerm->wtFlags |= TERM_OR_OK;
  127132. }
  127133. }
  127134. }
  127135. }
  127136. /* At this point, okToChngToIN is true if original pTerm satisfies
  127137. ** case 1. In that case, construct a new virtual term that is
  127138. ** pTerm converted into an IN operator.
  127139. */
  127140. if( okToChngToIN ){
  127141. Expr *pDup; /* A transient duplicate expression */
  127142. ExprList *pList = 0; /* The RHS of the IN operator */
  127143. Expr *pLeft = 0; /* The LHS of the IN operator */
  127144. Expr *pNew; /* The complete IN operator */
  127145. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  127146. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  127147. assert( pOrTerm->eOperator & WO_EQ );
  127148. assert( pOrTerm->leftCursor==iCursor );
  127149. assert( pOrTerm->u.leftColumn==iColumn );
  127150. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  127151. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  127152. pLeft = pOrTerm->pExpr->pLeft;
  127153. }
  127154. assert( pLeft!=0 );
  127155. pDup = sqlite3ExprDup(db, pLeft, 0);
  127156. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  127157. if( pNew ){
  127158. int idxNew;
  127159. transferJoinMarkings(pNew, pExpr);
  127160. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  127161. pNew->x.pList = pList;
  127162. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  127163. testcase( idxNew==0 );
  127164. exprAnalyze(pSrc, pWC, idxNew);
  127165. pTerm = &pWC->a[idxTerm];
  127166. markTermAsChild(pWC, idxNew, idxTerm);
  127167. }else{
  127168. sqlite3ExprListDelete(db, pList);
  127169. }
  127170. }
  127171. }
  127172. }
  127173. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  127174. /*
  127175. ** We already know that pExpr is a binary operator where both operands are
  127176. ** column references. This routine checks to see if pExpr is an equivalence
  127177. ** relation:
  127178. ** 1. The SQLITE_Transitive optimization must be enabled
  127179. ** 2. Must be either an == or an IS operator
  127180. ** 3. Not originating in the ON clause of an OUTER JOIN
  127181. ** 4. The affinities of A and B must be compatible
  127182. ** 5a. Both operands use the same collating sequence OR
  127183. ** 5b. The overall collating sequence is BINARY
  127184. ** If this routine returns TRUE, that means that the RHS can be substituted
  127185. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  127186. ** This is an optimization. No harm comes from returning 0. But if 1 is
  127187. ** returned when it should not be, then incorrect answers might result.
  127188. */
  127189. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  127190. char aff1, aff2;
  127191. CollSeq *pColl;
  127192. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  127193. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  127194. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  127195. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  127196. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  127197. if( aff1!=aff2
  127198. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  127199. ){
  127200. return 0;
  127201. }
  127202. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  127203. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  127204. return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
  127205. }
  127206. /*
  127207. ** Recursively walk the expressions of a SELECT statement and generate
  127208. ** a bitmask indicating which tables are used in that expression
  127209. ** tree.
  127210. */
  127211. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  127212. Bitmask mask = 0;
  127213. while( pS ){
  127214. SrcList *pSrc = pS->pSrc;
  127215. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  127216. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  127217. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  127218. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  127219. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  127220. if( ALWAYS(pSrc!=0) ){
  127221. int i;
  127222. for(i=0; i<pSrc->nSrc; i++){
  127223. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  127224. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  127225. if( pSrc->a[i].fg.isTabFunc ){
  127226. mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
  127227. }
  127228. }
  127229. }
  127230. pS = pS->pPrior;
  127231. }
  127232. return mask;
  127233. }
  127234. /*
  127235. ** Expression pExpr is one operand of a comparison operator that might
  127236. ** be useful for indexing. This routine checks to see if pExpr appears
  127237. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  127238. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  127239. ** number of the table that is indexed and aiCurCol[1] to the column number
  127240. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  127241. ** indexed.
  127242. **
  127243. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  127244. ** true even if that particular column is not indexed, because the column
  127245. ** might be added to an automatic index later.
  127246. */
  127247. static SQLITE_NOINLINE int exprMightBeIndexed2(
  127248. SrcList *pFrom, /* The FROM clause */
  127249. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  127250. int *aiCurCol, /* Write the referenced table cursor and column here */
  127251. Expr *pExpr /* An operand of a comparison operator */
  127252. ){
  127253. Index *pIdx;
  127254. int i;
  127255. int iCur;
  127256. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  127257. iCur = pFrom->a[i].iCursor;
  127258. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  127259. if( pIdx->aColExpr==0 ) continue;
  127260. for(i=0; i<pIdx->nKeyCol; i++){
  127261. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  127262. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  127263. aiCurCol[0] = iCur;
  127264. aiCurCol[1] = XN_EXPR;
  127265. return 1;
  127266. }
  127267. }
  127268. }
  127269. return 0;
  127270. }
  127271. static int exprMightBeIndexed(
  127272. SrcList *pFrom, /* The FROM clause */
  127273. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  127274. int *aiCurCol, /* Write the referenced table cursor & column here */
  127275. Expr *pExpr, /* An operand of a comparison operator */
  127276. int op /* The specific comparison operator */
  127277. ){
  127278. /* If this expression is a vector to the left or right of a
  127279. ** inequality constraint (>, <, >= or <=), perform the processing
  127280. ** on the first element of the vector. */
  127281. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  127282. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  127283. assert( op<=TK_GE );
  127284. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  127285. pExpr = pExpr->x.pList->a[0].pExpr;
  127286. }
  127287. if( pExpr->op==TK_COLUMN ){
  127288. aiCurCol[0] = pExpr->iTable;
  127289. aiCurCol[1] = pExpr->iColumn;
  127290. return 1;
  127291. }
  127292. if( mPrereq==0 ) return 0; /* No table references */
  127293. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  127294. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  127295. }
  127296. /*
  127297. ** The input to this routine is an WhereTerm structure with only the
  127298. ** "pExpr" field filled in. The job of this routine is to analyze the
  127299. ** subexpression and populate all the other fields of the WhereTerm
  127300. ** structure.
  127301. **
  127302. ** If the expression is of the form "<expr> <op> X" it gets commuted
  127303. ** to the standard form of "X <op> <expr>".
  127304. **
  127305. ** If the expression is of the form "X <op> Y" where both X and Y are
  127306. ** columns, then the original expression is unchanged and a new virtual
  127307. ** term of the form "Y <op> X" is added to the WHERE clause and
  127308. ** analyzed separately. The original term is marked with TERM_COPIED
  127309. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  127310. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  127311. ** is a commuted copy of a prior term.) The original term has nChild=1
  127312. ** and the copy has idxParent set to the index of the original term.
  127313. */
  127314. static void exprAnalyze(
  127315. SrcList *pSrc, /* the FROM clause */
  127316. WhereClause *pWC, /* the WHERE clause */
  127317. int idxTerm /* Index of the term to be analyzed */
  127318. ){
  127319. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  127320. WhereTerm *pTerm; /* The term to be analyzed */
  127321. WhereMaskSet *pMaskSet; /* Set of table index masks */
  127322. Expr *pExpr; /* The expression to be analyzed */
  127323. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  127324. Bitmask prereqAll; /* Prerequesites of pExpr */
  127325. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  127326. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  127327. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  127328. int noCase = 0; /* uppercase equivalent to lowercase */
  127329. int op; /* Top-level operator. pExpr->op */
  127330. Parse *pParse = pWInfo->pParse; /* Parsing context */
  127331. sqlite3 *db = pParse->db; /* Database connection */
  127332. unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
  127333. int nLeft; /* Number of elements on left side vector */
  127334. if( db->mallocFailed ){
  127335. return;
  127336. }
  127337. pTerm = &pWC->a[idxTerm];
  127338. pMaskSet = &pWInfo->sMaskSet;
  127339. pExpr = pTerm->pExpr;
  127340. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  127341. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  127342. op = pExpr->op;
  127343. if( op==TK_IN ){
  127344. assert( pExpr->pRight==0 );
  127345. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  127346. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  127347. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  127348. }else{
  127349. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  127350. }
  127351. }else if( op==TK_ISNULL ){
  127352. pTerm->prereqRight = 0;
  127353. }else{
  127354. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  127355. }
  127356. pMaskSet->bVarSelect = 0;
  127357. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  127358. if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
  127359. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  127360. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  127361. prereqAll |= x;
  127362. extraRight = x-1; /* ON clause terms may not be used with an index
  127363. ** on left table of a LEFT JOIN. Ticket #3015 */
  127364. if( (prereqAll>>1)>=x ){
  127365. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  127366. return;
  127367. }
  127368. }
  127369. pTerm->prereqAll = prereqAll;
  127370. pTerm->leftCursor = -1;
  127371. pTerm->iParent = -1;
  127372. pTerm->eOperator = 0;
  127373. if( allowedOp(op) ){
  127374. int aiCurCol[2];
  127375. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  127376. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  127377. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  127378. if( pTerm->iField>0 ){
  127379. assert( op==TK_IN );
  127380. assert( pLeft->op==TK_VECTOR );
  127381. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  127382. }
  127383. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  127384. pTerm->leftCursor = aiCurCol[0];
  127385. pTerm->u.leftColumn = aiCurCol[1];
  127386. pTerm->eOperator = operatorMask(op) & opMask;
  127387. }
  127388. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  127389. if( pRight
  127390. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  127391. ){
  127392. WhereTerm *pNew;
  127393. Expr *pDup;
  127394. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  127395. assert( pTerm->iField==0 );
  127396. if( pTerm->leftCursor>=0 ){
  127397. int idxNew;
  127398. pDup = sqlite3ExprDup(db, pExpr, 0);
  127399. if( db->mallocFailed ){
  127400. sqlite3ExprDelete(db, pDup);
  127401. return;
  127402. }
  127403. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  127404. if( idxNew==0 ) return;
  127405. pNew = &pWC->a[idxNew];
  127406. markTermAsChild(pWC, idxNew, idxTerm);
  127407. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  127408. pTerm = &pWC->a[idxTerm];
  127409. pTerm->wtFlags |= TERM_COPIED;
  127410. if( termIsEquivalence(pParse, pDup) ){
  127411. pTerm->eOperator |= WO_EQUIV;
  127412. eExtraOp = WO_EQUIV;
  127413. }
  127414. }else{
  127415. pDup = pExpr;
  127416. pNew = pTerm;
  127417. }
  127418. exprCommute(pParse, pDup);
  127419. pNew->leftCursor = aiCurCol[0];
  127420. pNew->u.leftColumn = aiCurCol[1];
  127421. testcase( (prereqLeft | extraRight) != prereqLeft );
  127422. pNew->prereqRight = prereqLeft | extraRight;
  127423. pNew->prereqAll = prereqAll;
  127424. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  127425. }
  127426. }
  127427. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  127428. /* If a term is the BETWEEN operator, create two new virtual terms
  127429. ** that define the range that the BETWEEN implements. For example:
  127430. **
  127431. ** a BETWEEN b AND c
  127432. **
  127433. ** is converted into:
  127434. **
  127435. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  127436. **
  127437. ** The two new terms are added onto the end of the WhereClause object.
  127438. ** The new terms are "dynamic" and are children of the original BETWEEN
  127439. ** term. That means that if the BETWEEN term is coded, the children are
  127440. ** skipped. Or, if the children are satisfied by an index, the original
  127441. ** BETWEEN term is skipped.
  127442. */
  127443. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  127444. ExprList *pList = pExpr->x.pList;
  127445. int i;
  127446. static const u8 ops[] = {TK_GE, TK_LE};
  127447. assert( pList!=0 );
  127448. assert( pList->nExpr==2 );
  127449. for(i=0; i<2; i++){
  127450. Expr *pNewExpr;
  127451. int idxNew;
  127452. pNewExpr = sqlite3PExpr(pParse, ops[i],
  127453. sqlite3ExprDup(db, pExpr->pLeft, 0),
  127454. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  127455. transferJoinMarkings(pNewExpr, pExpr);
  127456. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  127457. testcase( idxNew==0 );
  127458. exprAnalyze(pSrc, pWC, idxNew);
  127459. pTerm = &pWC->a[idxTerm];
  127460. markTermAsChild(pWC, idxNew, idxTerm);
  127461. }
  127462. }
  127463. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  127464. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  127465. /* Analyze a term that is composed of two or more subterms connected by
  127466. ** an OR operator.
  127467. */
  127468. else if( pExpr->op==TK_OR ){
  127469. assert( pWC->op==TK_AND );
  127470. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  127471. pTerm = &pWC->a[idxTerm];
  127472. }
  127473. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  127474. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  127475. /* Add constraints to reduce the search space on a LIKE or GLOB
  127476. ** operator.
  127477. **
  127478. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  127479. **
  127480. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  127481. **
  127482. ** The last character of the prefix "abc" is incremented to form the
  127483. ** termination condition "abd". If case is not significant (the default
  127484. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  127485. ** bound is made all lowercase so that the bounds also work when comparing
  127486. ** BLOBs.
  127487. */
  127488. if( pWC->op==TK_AND
  127489. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  127490. ){
  127491. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  127492. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  127493. Expr *pNewExpr1;
  127494. Expr *pNewExpr2;
  127495. int idxNew1;
  127496. int idxNew2;
  127497. const char *zCollSeqName; /* Name of collating sequence */
  127498. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  127499. pLeft = pExpr->x.pList->a[1].pExpr;
  127500. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  127501. /* Convert the lower bound to upper-case and the upper bound to
  127502. ** lower-case (upper-case is less than lower-case in ASCII) so that
  127503. ** the range constraints also work for BLOBs
  127504. */
  127505. if( noCase && !pParse->db->mallocFailed ){
  127506. int i;
  127507. char c;
  127508. pTerm->wtFlags |= TERM_LIKE;
  127509. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  127510. pStr1->u.zToken[i] = sqlite3Toupper(c);
  127511. pStr2->u.zToken[i] = sqlite3Tolower(c);
  127512. }
  127513. }
  127514. if( !db->mallocFailed ){
  127515. u8 c, *pC; /* Last character before the first wildcard */
  127516. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  127517. c = *pC;
  127518. if( noCase ){
  127519. /* The point is to increment the last character before the first
  127520. ** wildcard. But if we increment '@', that will push it into the
  127521. ** alphabetic range where case conversions will mess up the
  127522. ** inequality. To avoid this, make sure to also run the full
  127523. ** LIKE on all candidate expressions by clearing the isComplete flag
  127524. */
  127525. if( c=='A'-1 ) isComplete = 0;
  127526. c = sqlite3UpperToLower[c];
  127527. }
  127528. *pC = c + 1;
  127529. }
  127530. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  127531. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  127532. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  127533. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  127534. pStr1);
  127535. transferJoinMarkings(pNewExpr1, pExpr);
  127536. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  127537. testcase( idxNew1==0 );
  127538. exprAnalyze(pSrc, pWC, idxNew1);
  127539. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  127540. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  127541. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  127542. pStr2);
  127543. transferJoinMarkings(pNewExpr2, pExpr);
  127544. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  127545. testcase( idxNew2==0 );
  127546. exprAnalyze(pSrc, pWC, idxNew2);
  127547. pTerm = &pWC->a[idxTerm];
  127548. if( isComplete ){
  127549. markTermAsChild(pWC, idxNew1, idxTerm);
  127550. markTermAsChild(pWC, idxNew2, idxTerm);
  127551. }
  127552. }
  127553. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  127554. #ifndef SQLITE_OMIT_VIRTUALTABLE
  127555. /* Add a WO_AUX auxiliary term to the constraint set if the
  127556. ** current expression is of the form "column OP expr" where OP
  127557. ** is an operator that gets passed into virtual tables but which is
  127558. ** not normally optimized for ordinary tables. In other words, OP
  127559. ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
  127560. ** This information is used by the xBestIndex methods of
  127561. ** virtual tables. The native query optimizer does not attempt
  127562. ** to do anything with MATCH functions.
  127563. */
  127564. if( pWC->op==TK_AND ){
  127565. Expr *pRight = 0, *pLeft = 0;
  127566. int res = isAuxiliaryVtabOperator(pExpr, &eOp2, &pLeft, &pRight);
  127567. while( res-- > 0 ){
  127568. int idxNew;
  127569. WhereTerm *pNewTerm;
  127570. Bitmask prereqColumn, prereqExpr;
  127571. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  127572. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  127573. if( (prereqExpr & prereqColumn)==0 ){
  127574. Expr *pNewExpr;
  127575. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  127576. 0, sqlite3ExprDup(db, pRight, 0));
  127577. if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
  127578. ExprSetProperty(pNewExpr, EP_FromJoin);
  127579. }
  127580. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  127581. testcase( idxNew==0 );
  127582. pNewTerm = &pWC->a[idxNew];
  127583. pNewTerm->prereqRight = prereqExpr;
  127584. pNewTerm->leftCursor = pLeft->iTable;
  127585. pNewTerm->u.leftColumn = pLeft->iColumn;
  127586. pNewTerm->eOperator = WO_AUX;
  127587. pNewTerm->eMatchOp = eOp2;
  127588. markTermAsChild(pWC, idxNew, idxTerm);
  127589. pTerm = &pWC->a[idxTerm];
  127590. pTerm->wtFlags |= TERM_COPIED;
  127591. pNewTerm->prereqAll = pTerm->prereqAll;
  127592. }
  127593. SWAP(Expr*, pLeft, pRight);
  127594. }
  127595. }
  127596. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  127597. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  127598. ** new terms for each component comparison - "a = ?" and "b = ?". The
  127599. ** new terms completely replace the original vector comparison, which is
  127600. ** no longer used.
  127601. **
  127602. ** This is only required if at least one side of the comparison operation
  127603. ** is not a sub-select. */
  127604. if( pWC->op==TK_AND
  127605. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  127606. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  127607. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  127608. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  127609. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  127610. ){
  127611. int i;
  127612. for(i=0; i<nLeft; i++){
  127613. int idxNew;
  127614. Expr *pNew;
  127615. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  127616. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  127617. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  127618. transferJoinMarkings(pNew, pExpr);
  127619. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  127620. exprAnalyze(pSrc, pWC, idxNew);
  127621. }
  127622. pTerm = &pWC->a[idxTerm];
  127623. pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  127624. pTerm->eOperator = 0;
  127625. }
  127626. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  127627. ** a virtual term for each vector component. The expression object
  127628. ** used by each such virtual term is pExpr (the full vector IN(...)
  127629. ** expression). The WhereTerm.iField variable identifies the index within
  127630. ** the vector on the LHS that the virtual term represents.
  127631. **
  127632. ** This only works if the RHS is a simple SELECT, not a compound
  127633. */
  127634. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  127635. && pExpr->pLeft->op==TK_VECTOR
  127636. && pExpr->x.pSelect->pPrior==0
  127637. ){
  127638. int i;
  127639. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  127640. int idxNew;
  127641. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  127642. pWC->a[idxNew].iField = i+1;
  127643. exprAnalyze(pSrc, pWC, idxNew);
  127644. markTermAsChild(pWC, idxNew, idxTerm);
  127645. }
  127646. }
  127647. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127648. /* When sqlite_stat3 histogram data is available an operator of the
  127649. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  127650. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  127651. ** virtual term of that form.
  127652. **
  127653. ** Note that the virtual term must be tagged with TERM_VNULL.
  127654. */
  127655. if( pExpr->op==TK_NOTNULL
  127656. && pExpr->pLeft->op==TK_COLUMN
  127657. && pExpr->pLeft->iColumn>=0
  127658. && OptimizationEnabled(db, SQLITE_Stat34)
  127659. ){
  127660. Expr *pNewExpr;
  127661. Expr *pLeft = pExpr->pLeft;
  127662. int idxNew;
  127663. WhereTerm *pNewTerm;
  127664. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  127665. sqlite3ExprDup(db, pLeft, 0),
  127666. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  127667. idxNew = whereClauseInsert(pWC, pNewExpr,
  127668. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  127669. if( idxNew ){
  127670. pNewTerm = &pWC->a[idxNew];
  127671. pNewTerm->prereqRight = 0;
  127672. pNewTerm->leftCursor = pLeft->iTable;
  127673. pNewTerm->u.leftColumn = pLeft->iColumn;
  127674. pNewTerm->eOperator = WO_GT;
  127675. markTermAsChild(pWC, idxNew, idxTerm);
  127676. pTerm = &pWC->a[idxTerm];
  127677. pTerm->wtFlags |= TERM_COPIED;
  127678. pNewTerm->prereqAll = pTerm->prereqAll;
  127679. }
  127680. }
  127681. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  127682. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  127683. ** an index for tables to the left of the join.
  127684. */
  127685. testcase( pTerm!=&pWC->a[idxTerm] );
  127686. pTerm = &pWC->a[idxTerm];
  127687. pTerm->prereqRight |= extraRight;
  127688. }
  127689. /***************************************************************************
  127690. ** Routines with file scope above. Interface to the rest of the where.c
  127691. ** subsystem follows.
  127692. ***************************************************************************/
  127693. /*
  127694. ** This routine identifies subexpressions in the WHERE clause where
  127695. ** each subexpression is separated by the AND operator or some other
  127696. ** operator specified in the op parameter. The WhereClause structure
  127697. ** is filled with pointers to subexpressions. For example:
  127698. **
  127699. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  127700. ** \________/ \_______________/ \________________/
  127701. ** slot[0] slot[1] slot[2]
  127702. **
  127703. ** The original WHERE clause in pExpr is unaltered. All this routine
  127704. ** does is make slot[] entries point to substructure within pExpr.
  127705. **
  127706. ** In the previous sentence and in the diagram, "slot[]" refers to
  127707. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  127708. ** all terms of the WHERE clause.
  127709. */
  127710. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  127711. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  127712. pWC->op = op;
  127713. if( pE2==0 ) return;
  127714. if( pE2->op!=op ){
  127715. whereClauseInsert(pWC, pExpr, 0);
  127716. }else{
  127717. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  127718. sqlite3WhereSplit(pWC, pE2->pRight, op);
  127719. }
  127720. }
  127721. /*
  127722. ** Initialize a preallocated WhereClause structure.
  127723. */
  127724. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  127725. WhereClause *pWC, /* The WhereClause to be initialized */
  127726. WhereInfo *pWInfo /* The WHERE processing context */
  127727. ){
  127728. pWC->pWInfo = pWInfo;
  127729. pWC->pOuter = 0;
  127730. pWC->nTerm = 0;
  127731. pWC->nSlot = ArraySize(pWC->aStatic);
  127732. pWC->a = pWC->aStatic;
  127733. }
  127734. /*
  127735. ** Deallocate a WhereClause structure. The WhereClause structure
  127736. ** itself is not freed. This routine is the inverse of
  127737. ** sqlite3WhereClauseInit().
  127738. */
  127739. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  127740. int i;
  127741. WhereTerm *a;
  127742. sqlite3 *db = pWC->pWInfo->pParse->db;
  127743. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  127744. if( a->wtFlags & TERM_DYNAMIC ){
  127745. sqlite3ExprDelete(db, a->pExpr);
  127746. }
  127747. if( a->wtFlags & TERM_ORINFO ){
  127748. whereOrInfoDelete(db, a->u.pOrInfo);
  127749. }else if( a->wtFlags & TERM_ANDINFO ){
  127750. whereAndInfoDelete(db, a->u.pAndInfo);
  127751. }
  127752. }
  127753. if( pWC->a!=pWC->aStatic ){
  127754. sqlite3DbFree(db, pWC->a);
  127755. }
  127756. }
  127757. /*
  127758. ** These routines walk (recursively) an expression tree and generate
  127759. ** a bitmask indicating which tables are used in that expression
  127760. ** tree.
  127761. */
  127762. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  127763. Bitmask mask;
  127764. if( p==0 ) return 0;
  127765. if( p->op==TK_COLUMN ){
  127766. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  127767. }
  127768. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  127769. assert( !ExprHasProperty(p, EP_TokenOnly) );
  127770. if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  127771. if( p->pRight ){
  127772. mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
  127773. assert( p->x.pList==0 );
  127774. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  127775. if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
  127776. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  127777. }else if( p->x.pList ){
  127778. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  127779. }
  127780. return mask;
  127781. }
  127782. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  127783. int i;
  127784. Bitmask mask = 0;
  127785. if( pList ){
  127786. for(i=0; i<pList->nExpr; i++){
  127787. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  127788. }
  127789. }
  127790. return mask;
  127791. }
  127792. /*
  127793. ** Call exprAnalyze on all terms in a WHERE clause.
  127794. **
  127795. ** Note that exprAnalyze() might add new virtual terms onto the
  127796. ** end of the WHERE clause. We do not want to analyze these new
  127797. ** virtual terms, so start analyzing at the end and work forward
  127798. ** so that the added virtual terms are never processed.
  127799. */
  127800. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  127801. SrcList *pTabList, /* the FROM clause */
  127802. WhereClause *pWC /* the WHERE clause to be analyzed */
  127803. ){
  127804. int i;
  127805. for(i=pWC->nTerm-1; i>=0; i--){
  127806. exprAnalyze(pTabList, pWC, i);
  127807. }
  127808. }
  127809. /*
  127810. ** For table-valued-functions, transform the function arguments into
  127811. ** new WHERE clause terms.
  127812. **
  127813. ** Each function argument translates into an equality constraint against
  127814. ** a HIDDEN column in the table.
  127815. */
  127816. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  127817. Parse *pParse, /* Parsing context */
  127818. struct SrcList_item *pItem, /* The FROM clause term to process */
  127819. WhereClause *pWC /* Xfer function arguments to here */
  127820. ){
  127821. Table *pTab;
  127822. int j, k;
  127823. ExprList *pArgs;
  127824. Expr *pColRef;
  127825. Expr *pTerm;
  127826. if( pItem->fg.isTabFunc==0 ) return;
  127827. pTab = pItem->pTab;
  127828. assert( pTab!=0 );
  127829. pArgs = pItem->u1.pFuncArg;
  127830. if( pArgs==0 ) return;
  127831. for(j=k=0; j<pArgs->nExpr; j++){
  127832. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  127833. if( k>=pTab->nCol ){
  127834. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  127835. pTab->zName, j);
  127836. return;
  127837. }
  127838. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  127839. if( pColRef==0 ) return;
  127840. pColRef->iTable = pItem->iCursor;
  127841. pColRef->iColumn = k++;
  127842. pColRef->pTab = pTab;
  127843. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  127844. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
  127845. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  127846. }
  127847. }
  127848. /************** End of whereexpr.c *******************************************/
  127849. /************** Begin file where.c *******************************************/
  127850. /*
  127851. ** 2001 September 15
  127852. **
  127853. ** The author disclaims copyright to this source code. In place of
  127854. ** a legal notice, here is a blessing:
  127855. **
  127856. ** May you do good and not evil.
  127857. ** May you find forgiveness for yourself and forgive others.
  127858. ** May you share freely, never taking more than you give.
  127859. **
  127860. *************************************************************************
  127861. ** This module contains C code that generates VDBE code used to process
  127862. ** the WHERE clause of SQL statements. This module is responsible for
  127863. ** generating the code that loops through a table looking for applicable
  127864. ** rows. Indices are selected and used to speed the search when doing
  127865. ** so is applicable. Because this module is responsible for selecting
  127866. ** indices, you might also think of this module as the "query optimizer".
  127867. */
  127868. /* #include "sqliteInt.h" */
  127869. /* #include "whereInt.h" */
  127870. /*
  127871. ** Extra information appended to the end of sqlite3_index_info but not
  127872. ** visible to the xBestIndex function, at least not directly. The
  127873. ** sqlite3_vtab_collation() interface knows how to reach it, however.
  127874. **
  127875. ** This object is not an API and can be changed from one release to the
  127876. ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
  127877. ** agree on the structure, all will be well.
  127878. */
  127879. typedef struct HiddenIndexInfo HiddenIndexInfo;
  127880. struct HiddenIndexInfo {
  127881. WhereClause *pWC; /* The Where clause being analyzed */
  127882. Parse *pParse; /* The parsing context */
  127883. };
  127884. /* Forward declaration of methods */
  127885. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  127886. /* Test variable that can be set to enable WHERE tracing */
  127887. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  127888. /***/ int sqlite3WhereTrace = 0;
  127889. #endif
  127890. /*
  127891. ** Return the estimated number of output rows from a WHERE clause
  127892. */
  127893. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  127894. return pWInfo->nRowOut;
  127895. }
  127896. /*
  127897. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  127898. ** WHERE clause returns outputs for DISTINCT processing.
  127899. */
  127900. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  127901. return pWInfo->eDistinct;
  127902. }
  127903. /*
  127904. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  127905. ** Return FALSE if the output needs to be sorted.
  127906. */
  127907. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  127908. return pWInfo->nOBSat;
  127909. }
  127910. /*
  127911. ** Return TRUE if the innermost loop of the WHERE clause implementation
  127912. ** returns rows in ORDER BY order for complete run of the inner loop.
  127913. **
  127914. ** Across multiple iterations of outer loops, the output rows need not be
  127915. ** sorted. As long as rows are sorted for just the innermost loop, this
  127916. ** routine can return TRUE.
  127917. */
  127918. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
  127919. return pWInfo->bOrderedInnerLoop;
  127920. }
  127921. /*
  127922. ** Return the VDBE address or label to jump to in order to continue
  127923. ** immediately with the next row of a WHERE clause.
  127924. */
  127925. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  127926. assert( pWInfo->iContinue!=0 );
  127927. return pWInfo->iContinue;
  127928. }
  127929. /*
  127930. ** Return the VDBE address or label to jump to in order to break
  127931. ** out of a WHERE loop.
  127932. */
  127933. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  127934. return pWInfo->iBreak;
  127935. }
  127936. /*
  127937. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  127938. ** operate directly on the rowis returned by a WHERE clause. Return
  127939. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  127940. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  127941. ** optimization can be used on multiple
  127942. **
  127943. ** If the ONEPASS optimization is used (if this routine returns true)
  127944. ** then also write the indices of open cursors used by ONEPASS
  127945. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  127946. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  127947. ** Either value may be -1, indicating that cursor is not used.
  127948. ** Any cursors returned will have been opened for writing.
  127949. **
  127950. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  127951. ** unable to use the ONEPASS optimization.
  127952. */
  127953. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  127954. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  127955. #ifdef WHERETRACE_ENABLED
  127956. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  127957. sqlite3DebugPrintf("%s cursors: %d %d\n",
  127958. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  127959. aiCur[0], aiCur[1]);
  127960. }
  127961. #endif
  127962. return pWInfo->eOnePass;
  127963. }
  127964. /*
  127965. ** Move the content of pSrc into pDest
  127966. */
  127967. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  127968. pDest->n = pSrc->n;
  127969. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  127970. }
  127971. /*
  127972. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  127973. **
  127974. ** The new entry might overwrite an existing entry, or it might be
  127975. ** appended, or it might be discarded. Do whatever is the right thing
  127976. ** so that pSet keeps the N_OR_COST best entries seen so far.
  127977. */
  127978. static int whereOrInsert(
  127979. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  127980. Bitmask prereq, /* Prerequisites of the new entry */
  127981. LogEst rRun, /* Run-cost of the new entry */
  127982. LogEst nOut /* Number of outputs for the new entry */
  127983. ){
  127984. u16 i;
  127985. WhereOrCost *p;
  127986. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  127987. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  127988. goto whereOrInsert_done;
  127989. }
  127990. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  127991. return 0;
  127992. }
  127993. }
  127994. if( pSet->n<N_OR_COST ){
  127995. p = &pSet->a[pSet->n++];
  127996. p->nOut = nOut;
  127997. }else{
  127998. p = pSet->a;
  127999. for(i=1; i<pSet->n; i++){
  128000. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  128001. }
  128002. if( p->rRun<=rRun ) return 0;
  128003. }
  128004. whereOrInsert_done:
  128005. p->prereq = prereq;
  128006. p->rRun = rRun;
  128007. if( p->nOut>nOut ) p->nOut = nOut;
  128008. return 1;
  128009. }
  128010. /*
  128011. ** Return the bitmask for the given cursor number. Return 0 if
  128012. ** iCursor is not in the set.
  128013. */
  128014. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  128015. int i;
  128016. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  128017. for(i=0; i<pMaskSet->n; i++){
  128018. if( pMaskSet->ix[i]==iCursor ){
  128019. return MASKBIT(i);
  128020. }
  128021. }
  128022. return 0;
  128023. }
  128024. /*
  128025. ** Create a new mask for cursor iCursor.
  128026. **
  128027. ** There is one cursor per table in the FROM clause. The number of
  128028. ** tables in the FROM clause is limited by a test early in the
  128029. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  128030. ** array will never overflow.
  128031. */
  128032. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  128033. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  128034. pMaskSet->ix[pMaskSet->n++] = iCursor;
  128035. }
  128036. /*
  128037. ** Advance to the next WhereTerm that matches according to the criteria
  128038. ** established when the pScan object was initialized by whereScanInit().
  128039. ** Return NULL if there are no more matching WhereTerms.
  128040. */
  128041. static WhereTerm *whereScanNext(WhereScan *pScan){
  128042. int iCur; /* The cursor on the LHS of the term */
  128043. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  128044. Expr *pX; /* An expression being tested */
  128045. WhereClause *pWC; /* Shorthand for pScan->pWC */
  128046. WhereTerm *pTerm; /* The term being tested */
  128047. int k = pScan->k; /* Where to start scanning */
  128048. assert( pScan->iEquiv<=pScan->nEquiv );
  128049. pWC = pScan->pWC;
  128050. while(1){
  128051. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  128052. iCur = pScan->aiCur[pScan->iEquiv-1];
  128053. assert( pWC!=0 );
  128054. do{
  128055. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  128056. if( pTerm->leftCursor==iCur
  128057. && pTerm->u.leftColumn==iColumn
  128058. && (iColumn!=XN_EXPR
  128059. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  128060. pScan->pIdxExpr,iCur)==0)
  128061. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  128062. ){
  128063. if( (pTerm->eOperator & WO_EQUIV)!=0
  128064. && pScan->nEquiv<ArraySize(pScan->aiCur)
  128065. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  128066. ){
  128067. int j;
  128068. for(j=0; j<pScan->nEquiv; j++){
  128069. if( pScan->aiCur[j]==pX->iTable
  128070. && pScan->aiColumn[j]==pX->iColumn ){
  128071. break;
  128072. }
  128073. }
  128074. if( j==pScan->nEquiv ){
  128075. pScan->aiCur[j] = pX->iTable;
  128076. pScan->aiColumn[j] = pX->iColumn;
  128077. pScan->nEquiv++;
  128078. }
  128079. }
  128080. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  128081. /* Verify the affinity and collating sequence match */
  128082. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  128083. CollSeq *pColl;
  128084. Parse *pParse = pWC->pWInfo->pParse;
  128085. pX = pTerm->pExpr;
  128086. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  128087. continue;
  128088. }
  128089. assert(pX->pLeft);
  128090. pColl = sqlite3BinaryCompareCollSeq(pParse,
  128091. pX->pLeft, pX->pRight);
  128092. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  128093. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  128094. continue;
  128095. }
  128096. }
  128097. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  128098. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  128099. && pX->iTable==pScan->aiCur[0]
  128100. && pX->iColumn==pScan->aiColumn[0]
  128101. ){
  128102. testcase( pTerm->eOperator & WO_IS );
  128103. continue;
  128104. }
  128105. pScan->pWC = pWC;
  128106. pScan->k = k+1;
  128107. return pTerm;
  128108. }
  128109. }
  128110. }
  128111. pWC = pWC->pOuter;
  128112. k = 0;
  128113. }while( pWC!=0 );
  128114. if( pScan->iEquiv>=pScan->nEquiv ) break;
  128115. pWC = pScan->pOrigWC;
  128116. k = 0;
  128117. pScan->iEquiv++;
  128118. }
  128119. return 0;
  128120. }
  128121. /*
  128122. ** Initialize a WHERE clause scanner object. Return a pointer to the
  128123. ** first match. Return NULL if there are no matches.
  128124. **
  128125. ** The scanner will be searching the WHERE clause pWC. It will look
  128126. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  128127. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  128128. ** must be one of the indexes of table iCur.
  128129. **
  128130. ** The <op> must be one of the operators described by opMask.
  128131. **
  128132. ** If the search is for X and the WHERE clause contains terms of the
  128133. ** form X=Y then this routine might also return terms of the form
  128134. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  128135. ** but is enough to handle most commonly occurring SQL statements.
  128136. **
  128137. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  128138. ** index pIdx.
  128139. */
  128140. static WhereTerm *whereScanInit(
  128141. WhereScan *pScan, /* The WhereScan object being initialized */
  128142. WhereClause *pWC, /* The WHERE clause to be scanned */
  128143. int iCur, /* Cursor to scan for */
  128144. int iColumn, /* Column to scan for */
  128145. u32 opMask, /* Operator(s) to scan for */
  128146. Index *pIdx /* Must be compatible with this index */
  128147. ){
  128148. pScan->pOrigWC = pWC;
  128149. pScan->pWC = pWC;
  128150. pScan->pIdxExpr = 0;
  128151. pScan->idxaff = 0;
  128152. pScan->zCollName = 0;
  128153. if( pIdx ){
  128154. int j = iColumn;
  128155. iColumn = pIdx->aiColumn[j];
  128156. if( iColumn==XN_EXPR ){
  128157. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  128158. pScan->zCollName = pIdx->azColl[j];
  128159. }else if( iColumn==pIdx->pTable->iPKey ){
  128160. iColumn = XN_ROWID;
  128161. }else if( iColumn>=0 ){
  128162. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  128163. pScan->zCollName = pIdx->azColl[j];
  128164. }
  128165. }else if( iColumn==XN_EXPR ){
  128166. return 0;
  128167. }
  128168. pScan->opMask = opMask;
  128169. pScan->k = 0;
  128170. pScan->aiCur[0] = iCur;
  128171. pScan->aiColumn[0] = iColumn;
  128172. pScan->nEquiv = 1;
  128173. pScan->iEquiv = 1;
  128174. return whereScanNext(pScan);
  128175. }
  128176. /*
  128177. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  128178. ** where X is a reference to the iColumn of table iCur or of index pIdx
  128179. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  128180. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  128181. **
  128182. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  128183. ** Search for terms matching the iColumn-th column of pIdx
  128184. ** rather than the iColumn-th column of table iCur.
  128185. **
  128186. ** The term returned might by Y=<expr> if there is another constraint in
  128187. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  128188. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  128189. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  128190. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  128191. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  128192. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  128193. **
  128194. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  128195. ** then try for the one with no dependencies on <expr> - in other words where
  128196. ** <expr> is a constant expression of some kind. Only return entries of
  128197. ** the form "X <op> Y" where Y is a column in another table if no terms of
  128198. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  128199. ** exist, try to return a term that does not use WO_EQUIV.
  128200. */
  128201. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  128202. WhereClause *pWC, /* The WHERE clause to be searched */
  128203. int iCur, /* Cursor number of LHS */
  128204. int iColumn, /* Column number of LHS */
  128205. Bitmask notReady, /* RHS must not overlap with this mask */
  128206. u32 op, /* Mask of WO_xx values describing operator */
  128207. Index *pIdx /* Must be compatible with this index, if not NULL */
  128208. ){
  128209. WhereTerm *pResult = 0;
  128210. WhereTerm *p;
  128211. WhereScan scan;
  128212. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  128213. op &= WO_EQ|WO_IS;
  128214. while( p ){
  128215. if( (p->prereqRight & notReady)==0 ){
  128216. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  128217. testcase( p->eOperator & WO_IS );
  128218. return p;
  128219. }
  128220. if( pResult==0 ) pResult = p;
  128221. }
  128222. p = whereScanNext(&scan);
  128223. }
  128224. return pResult;
  128225. }
  128226. /*
  128227. ** This function searches pList for an entry that matches the iCol-th column
  128228. ** of index pIdx.
  128229. **
  128230. ** If such an expression is found, its index in pList->a[] is returned. If
  128231. ** no expression is found, -1 is returned.
  128232. */
  128233. static int findIndexCol(
  128234. Parse *pParse, /* Parse context */
  128235. ExprList *pList, /* Expression list to search */
  128236. int iBase, /* Cursor for table associated with pIdx */
  128237. Index *pIdx, /* Index to match column of */
  128238. int iCol /* Column of index to match */
  128239. ){
  128240. int i;
  128241. const char *zColl = pIdx->azColl[iCol];
  128242. for(i=0; i<pList->nExpr; i++){
  128243. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  128244. if( p->op==TK_COLUMN
  128245. && p->iColumn==pIdx->aiColumn[iCol]
  128246. && p->iTable==iBase
  128247. ){
  128248. CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
  128249. if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
  128250. return i;
  128251. }
  128252. }
  128253. }
  128254. return -1;
  128255. }
  128256. /*
  128257. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  128258. */
  128259. static int indexColumnNotNull(Index *pIdx, int iCol){
  128260. int j;
  128261. assert( pIdx!=0 );
  128262. assert( iCol>=0 && iCol<pIdx->nColumn );
  128263. j = pIdx->aiColumn[iCol];
  128264. if( j>=0 ){
  128265. return pIdx->pTable->aCol[j].notNull;
  128266. }else if( j==(-1) ){
  128267. return 1;
  128268. }else{
  128269. assert( j==(-2) );
  128270. return 0; /* Assume an indexed expression can always yield a NULL */
  128271. }
  128272. }
  128273. /*
  128274. ** Return true if the DISTINCT expression-list passed as the third argument
  128275. ** is redundant.
  128276. **
  128277. ** A DISTINCT list is redundant if any subset of the columns in the
  128278. ** DISTINCT list are collectively unique and individually non-null.
  128279. */
  128280. static int isDistinctRedundant(
  128281. Parse *pParse, /* Parsing context */
  128282. SrcList *pTabList, /* The FROM clause */
  128283. WhereClause *pWC, /* The WHERE clause */
  128284. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  128285. ){
  128286. Table *pTab;
  128287. Index *pIdx;
  128288. int i;
  128289. int iBase;
  128290. /* If there is more than one table or sub-select in the FROM clause of
  128291. ** this query, then it will not be possible to show that the DISTINCT
  128292. ** clause is redundant. */
  128293. if( pTabList->nSrc!=1 ) return 0;
  128294. iBase = pTabList->a[0].iCursor;
  128295. pTab = pTabList->a[0].pTab;
  128296. /* If any of the expressions is an IPK column on table iBase, then return
  128297. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  128298. ** current SELECT is a correlated sub-query.
  128299. */
  128300. for(i=0; i<pDistinct->nExpr; i++){
  128301. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  128302. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  128303. }
  128304. /* Loop through all indices on the table, checking each to see if it makes
  128305. ** the DISTINCT qualifier redundant. It does so if:
  128306. **
  128307. ** 1. The index is itself UNIQUE, and
  128308. **
  128309. ** 2. All of the columns in the index are either part of the pDistinct
  128310. ** list, or else the WHERE clause contains a term of the form "col=X",
  128311. ** where X is a constant value. The collation sequences of the
  128312. ** comparison and select-list expressions must match those of the index.
  128313. **
  128314. ** 3. All of those index columns for which the WHERE clause does not
  128315. ** contain a "col=X" term are subject to a NOT NULL constraint.
  128316. */
  128317. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  128318. if( !IsUniqueIndex(pIdx) ) continue;
  128319. for(i=0; i<pIdx->nKeyCol; i++){
  128320. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  128321. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  128322. if( indexColumnNotNull(pIdx, i)==0 ) break;
  128323. }
  128324. }
  128325. if( i==pIdx->nKeyCol ){
  128326. /* This index implies that the DISTINCT qualifier is redundant. */
  128327. return 1;
  128328. }
  128329. }
  128330. return 0;
  128331. }
  128332. /*
  128333. ** Estimate the logarithm of the input value to base 2.
  128334. */
  128335. static LogEst estLog(LogEst N){
  128336. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  128337. }
  128338. /*
  128339. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  128340. **
  128341. ** This routine runs over generated VDBE code and translates OP_Column
  128342. ** opcodes into OP_Copy when the table is being accessed via co-routine
  128343. ** instead of via table lookup.
  128344. **
  128345. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  128346. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  128347. ** then each OP_Rowid is transformed into an instruction to increment the
  128348. ** value stored in its output register.
  128349. */
  128350. static void translateColumnToCopy(
  128351. Parse *pParse, /* Parsing context */
  128352. int iStart, /* Translate from this opcode to the end */
  128353. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  128354. int iRegister, /* The first column is in this register */
  128355. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  128356. ){
  128357. Vdbe *v = pParse->pVdbe;
  128358. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  128359. int iEnd = sqlite3VdbeCurrentAddr(v);
  128360. if( pParse->db->mallocFailed ) return;
  128361. for(; iStart<iEnd; iStart++, pOp++){
  128362. if( pOp->p1!=iTabCur ) continue;
  128363. if( pOp->opcode==OP_Column ){
  128364. pOp->opcode = OP_Copy;
  128365. pOp->p1 = pOp->p2 + iRegister;
  128366. pOp->p2 = pOp->p3;
  128367. pOp->p3 = 0;
  128368. }else if( pOp->opcode==OP_Rowid ){
  128369. if( bIncrRowid ){
  128370. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  128371. pOp->opcode = OP_AddImm;
  128372. pOp->p1 = pOp->p2;
  128373. pOp->p2 = 1;
  128374. }else{
  128375. pOp->opcode = OP_Null;
  128376. pOp->p1 = 0;
  128377. pOp->p3 = 0;
  128378. }
  128379. }
  128380. }
  128381. }
  128382. /*
  128383. ** Two routines for printing the content of an sqlite3_index_info
  128384. ** structure. Used for testing and debugging only. If neither
  128385. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  128386. ** are no-ops.
  128387. */
  128388. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  128389. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  128390. int i;
  128391. if( !sqlite3WhereTrace ) return;
  128392. for(i=0; i<p->nConstraint; i++){
  128393. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  128394. i,
  128395. p->aConstraint[i].iColumn,
  128396. p->aConstraint[i].iTermOffset,
  128397. p->aConstraint[i].op,
  128398. p->aConstraint[i].usable);
  128399. }
  128400. for(i=0; i<p->nOrderBy; i++){
  128401. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  128402. i,
  128403. p->aOrderBy[i].iColumn,
  128404. p->aOrderBy[i].desc);
  128405. }
  128406. }
  128407. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  128408. int i;
  128409. if( !sqlite3WhereTrace ) return;
  128410. for(i=0; i<p->nConstraint; i++){
  128411. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  128412. i,
  128413. p->aConstraintUsage[i].argvIndex,
  128414. p->aConstraintUsage[i].omit);
  128415. }
  128416. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  128417. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  128418. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  128419. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  128420. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  128421. }
  128422. #else
  128423. #define TRACE_IDX_INPUTS(A)
  128424. #define TRACE_IDX_OUTPUTS(A)
  128425. #endif
  128426. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  128427. /*
  128428. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  128429. ** could be used with an index to access pSrc, assuming an appropriate
  128430. ** index existed.
  128431. */
  128432. static int termCanDriveIndex(
  128433. WhereTerm *pTerm, /* WHERE clause term to check */
  128434. struct SrcList_item *pSrc, /* Table we are trying to access */
  128435. Bitmask notReady /* Tables in outer loops of the join */
  128436. ){
  128437. char aff;
  128438. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  128439. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  128440. if( (pSrc->fg.jointype & JT_LEFT)
  128441. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  128442. && (pTerm->eOperator & WO_IS)
  128443. ){
  128444. /* Cannot use an IS term from the WHERE clause as an index driver for
  128445. ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
  128446. ** the ON clause. */
  128447. return 0;
  128448. }
  128449. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  128450. if( pTerm->u.leftColumn<0 ) return 0;
  128451. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  128452. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  128453. testcase( pTerm->pExpr->op==TK_IS );
  128454. return 1;
  128455. }
  128456. #endif
  128457. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  128458. /*
  128459. ** Generate code to construct the Index object for an automatic index
  128460. ** and to set up the WhereLevel object pLevel so that the code generator
  128461. ** makes use of the automatic index.
  128462. */
  128463. static void constructAutomaticIndex(
  128464. Parse *pParse, /* The parsing context */
  128465. WhereClause *pWC, /* The WHERE clause */
  128466. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  128467. Bitmask notReady, /* Mask of cursors that are not available */
  128468. WhereLevel *pLevel /* Write new index here */
  128469. ){
  128470. int nKeyCol; /* Number of columns in the constructed index */
  128471. WhereTerm *pTerm; /* A single term of the WHERE clause */
  128472. WhereTerm *pWCEnd; /* End of pWC->a[] */
  128473. Index *pIdx; /* Object describing the transient index */
  128474. Vdbe *v; /* Prepared statement under construction */
  128475. int addrInit; /* Address of the initialization bypass jump */
  128476. Table *pTable; /* The table being indexed */
  128477. int addrTop; /* Top of the index fill loop */
  128478. int regRecord; /* Register holding an index record */
  128479. int n; /* Column counter */
  128480. int i; /* Loop counter */
  128481. int mxBitCol; /* Maximum column in pSrc->colUsed */
  128482. CollSeq *pColl; /* Collating sequence to on a column */
  128483. WhereLoop *pLoop; /* The Loop object */
  128484. char *zNotUsed; /* Extra space on the end of pIdx */
  128485. Bitmask idxCols; /* Bitmap of columns used for indexing */
  128486. Bitmask extraCols; /* Bitmap of additional columns */
  128487. u8 sentWarning = 0; /* True if a warnning has been issued */
  128488. Expr *pPartial = 0; /* Partial Index Expression */
  128489. int iContinue = 0; /* Jump here to skip excluded rows */
  128490. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  128491. int addrCounter = 0; /* Address where integer counter is initialized */
  128492. int regBase; /* Array of registers where record is assembled */
  128493. /* Generate code to skip over the creation and initialization of the
  128494. ** transient index on 2nd and subsequent iterations of the loop. */
  128495. v = pParse->pVdbe;
  128496. assert( v!=0 );
  128497. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  128498. /* Count the number of columns that will be added to the index
  128499. ** and used to match WHERE clause constraints */
  128500. nKeyCol = 0;
  128501. pTable = pSrc->pTab;
  128502. pWCEnd = &pWC->a[pWC->nTerm];
  128503. pLoop = pLevel->pWLoop;
  128504. idxCols = 0;
  128505. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  128506. Expr *pExpr = pTerm->pExpr;
  128507. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  128508. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  128509. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  128510. if( pLoop->prereq==0
  128511. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  128512. && !ExprHasProperty(pExpr, EP_FromJoin)
  128513. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  128514. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  128515. sqlite3ExprDup(pParse->db, pExpr, 0));
  128516. }
  128517. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  128518. int iCol = pTerm->u.leftColumn;
  128519. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  128520. testcase( iCol==BMS );
  128521. testcase( iCol==BMS-1 );
  128522. if( !sentWarning ){
  128523. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  128524. "automatic index on %s(%s)", pTable->zName,
  128525. pTable->aCol[iCol].zName);
  128526. sentWarning = 1;
  128527. }
  128528. if( (idxCols & cMask)==0 ){
  128529. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  128530. goto end_auto_index_create;
  128531. }
  128532. pLoop->aLTerm[nKeyCol++] = pTerm;
  128533. idxCols |= cMask;
  128534. }
  128535. }
  128536. }
  128537. assert( nKeyCol>0 );
  128538. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  128539. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  128540. | WHERE_AUTO_INDEX;
  128541. /* Count the number of additional columns needed to create a
  128542. ** covering index. A "covering index" is an index that contains all
  128543. ** columns that are needed by the query. With a covering index, the
  128544. ** original table never needs to be accessed. Automatic indices must
  128545. ** be a covering index because the index will not be updated if the
  128546. ** original table changes and the index and table cannot both be used
  128547. ** if they go out of sync.
  128548. */
  128549. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  128550. mxBitCol = MIN(BMS-1,pTable->nCol);
  128551. testcase( pTable->nCol==BMS-1 );
  128552. testcase( pTable->nCol==BMS-2 );
  128553. for(i=0; i<mxBitCol; i++){
  128554. if( extraCols & MASKBIT(i) ) nKeyCol++;
  128555. }
  128556. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  128557. nKeyCol += pTable->nCol - BMS + 1;
  128558. }
  128559. /* Construct the Index object to describe this index */
  128560. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  128561. if( pIdx==0 ) goto end_auto_index_create;
  128562. pLoop->u.btree.pIndex = pIdx;
  128563. pIdx->zName = "auto-index";
  128564. pIdx->pTable = pTable;
  128565. n = 0;
  128566. idxCols = 0;
  128567. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  128568. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  128569. int iCol = pTerm->u.leftColumn;
  128570. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  128571. testcase( iCol==BMS-1 );
  128572. testcase( iCol==BMS );
  128573. if( (idxCols & cMask)==0 ){
  128574. Expr *pX = pTerm->pExpr;
  128575. idxCols |= cMask;
  128576. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  128577. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  128578. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  128579. n++;
  128580. }
  128581. }
  128582. }
  128583. assert( (u32)n==pLoop->u.btree.nEq );
  128584. /* Add additional columns needed to make the automatic index into
  128585. ** a covering index */
  128586. for(i=0; i<mxBitCol; i++){
  128587. if( extraCols & MASKBIT(i) ){
  128588. pIdx->aiColumn[n] = i;
  128589. pIdx->azColl[n] = sqlite3StrBINARY;
  128590. n++;
  128591. }
  128592. }
  128593. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  128594. for(i=BMS-1; i<pTable->nCol; i++){
  128595. pIdx->aiColumn[n] = i;
  128596. pIdx->azColl[n] = sqlite3StrBINARY;
  128597. n++;
  128598. }
  128599. }
  128600. assert( n==nKeyCol );
  128601. pIdx->aiColumn[n] = XN_ROWID;
  128602. pIdx->azColl[n] = sqlite3StrBINARY;
  128603. /* Create the automatic index */
  128604. assert( pLevel->iIdxCur>=0 );
  128605. pLevel->iIdxCur = pParse->nTab++;
  128606. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  128607. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  128608. VdbeComment((v, "for %s", pTable->zName));
  128609. /* Fill the automatic index with content */
  128610. sqlite3ExprCachePush(pParse);
  128611. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  128612. if( pTabItem->fg.viaCoroutine ){
  128613. int regYield = pTabItem->regReturn;
  128614. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  128615. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  128616. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  128617. VdbeCoverage(v);
  128618. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  128619. }else{
  128620. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  128621. }
  128622. if( pPartial ){
  128623. iContinue = sqlite3VdbeMakeLabel(v);
  128624. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  128625. pLoop->wsFlags |= WHERE_PARTIALIDX;
  128626. }
  128627. regRecord = sqlite3GetTempReg(pParse);
  128628. regBase = sqlite3GenerateIndexKey(
  128629. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  128630. );
  128631. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  128632. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  128633. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  128634. if( pTabItem->fg.viaCoroutine ){
  128635. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  128636. testcase( pParse->db->mallocFailed );
  128637. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  128638. pTabItem->regResult, 1);
  128639. sqlite3VdbeGoto(v, addrTop);
  128640. pTabItem->fg.viaCoroutine = 0;
  128641. }else{
  128642. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  128643. }
  128644. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  128645. sqlite3VdbeJumpHere(v, addrTop);
  128646. sqlite3ReleaseTempReg(pParse, regRecord);
  128647. sqlite3ExprCachePop(pParse);
  128648. /* Jump here when skipping the initialization */
  128649. sqlite3VdbeJumpHere(v, addrInit);
  128650. end_auto_index_create:
  128651. sqlite3ExprDelete(pParse->db, pPartial);
  128652. }
  128653. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  128654. #ifndef SQLITE_OMIT_VIRTUALTABLE
  128655. /*
  128656. ** Allocate and populate an sqlite3_index_info structure. It is the
  128657. ** responsibility of the caller to eventually release the structure
  128658. ** by passing the pointer returned by this function to sqlite3_free().
  128659. */
  128660. static sqlite3_index_info *allocateIndexInfo(
  128661. Parse *pParse, /* The parsing context */
  128662. WhereClause *pWC, /* The WHERE clause being analyzed */
  128663. Bitmask mUnusable, /* Ignore terms with these prereqs */
  128664. struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */
  128665. ExprList *pOrderBy, /* The ORDER BY clause */
  128666. u16 *pmNoOmit /* Mask of terms not to omit */
  128667. ){
  128668. int i, j;
  128669. int nTerm;
  128670. struct sqlite3_index_constraint *pIdxCons;
  128671. struct sqlite3_index_orderby *pIdxOrderBy;
  128672. struct sqlite3_index_constraint_usage *pUsage;
  128673. struct HiddenIndexInfo *pHidden;
  128674. WhereTerm *pTerm;
  128675. int nOrderBy;
  128676. sqlite3_index_info *pIdxInfo;
  128677. u16 mNoOmit = 0;
  128678. /* Count the number of possible WHERE clause constraints referring
  128679. ** to this virtual table */
  128680. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  128681. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  128682. if( pTerm->prereqRight & mUnusable ) continue;
  128683. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  128684. testcase( pTerm->eOperator & WO_IN );
  128685. testcase( pTerm->eOperator & WO_ISNULL );
  128686. testcase( pTerm->eOperator & WO_IS );
  128687. testcase( pTerm->eOperator & WO_ALL );
  128688. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  128689. if( pTerm->wtFlags & TERM_VNULL ) continue;
  128690. assert( pTerm->u.leftColumn>=(-1) );
  128691. nTerm++;
  128692. }
  128693. /* If the ORDER BY clause contains only columns in the current
  128694. ** virtual table then allocate space for the aOrderBy part of
  128695. ** the sqlite3_index_info structure.
  128696. */
  128697. nOrderBy = 0;
  128698. if( pOrderBy ){
  128699. int n = pOrderBy->nExpr;
  128700. for(i=0; i<n; i++){
  128701. Expr *pExpr = pOrderBy->a[i].pExpr;
  128702. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  128703. }
  128704. if( i==n){
  128705. nOrderBy = n;
  128706. }
  128707. }
  128708. /* Allocate the sqlite3_index_info structure
  128709. */
  128710. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  128711. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  128712. + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
  128713. if( pIdxInfo==0 ){
  128714. sqlite3ErrorMsg(pParse, "out of memory");
  128715. return 0;
  128716. }
  128717. /* Initialize the structure. The sqlite3_index_info structure contains
  128718. ** many fields that are declared "const" to prevent xBestIndex from
  128719. ** changing them. We have to do some funky casting in order to
  128720. ** initialize those fields.
  128721. */
  128722. pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
  128723. pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
  128724. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  128725. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  128726. *(int*)&pIdxInfo->nConstraint = nTerm;
  128727. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  128728. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  128729. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  128730. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  128731. pUsage;
  128732. pHidden->pWC = pWC;
  128733. pHidden->pParse = pParse;
  128734. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  128735. u16 op;
  128736. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  128737. if( pTerm->prereqRight & mUnusable ) continue;
  128738. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  128739. testcase( pTerm->eOperator & WO_IN );
  128740. testcase( pTerm->eOperator & WO_IS );
  128741. testcase( pTerm->eOperator & WO_ISNULL );
  128742. testcase( pTerm->eOperator & WO_ALL );
  128743. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  128744. if( pTerm->wtFlags & TERM_VNULL ) continue;
  128745. assert( pTerm->u.leftColumn>=(-1) );
  128746. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  128747. pIdxCons[j].iTermOffset = i;
  128748. op = pTerm->eOperator & WO_ALL;
  128749. if( op==WO_IN ) op = WO_EQ;
  128750. if( op==WO_AUX ){
  128751. pIdxCons[j].op = pTerm->eMatchOp;
  128752. }else if( op & (WO_ISNULL|WO_IS) ){
  128753. if( op==WO_ISNULL ){
  128754. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
  128755. }else{
  128756. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
  128757. }
  128758. }else{
  128759. pIdxCons[j].op = (u8)op;
  128760. /* The direct assignment in the previous line is possible only because
  128761. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  128762. ** following asserts verify this fact. */
  128763. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  128764. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  128765. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  128766. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  128767. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  128768. assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
  128769. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  128770. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  128771. ){
  128772. if( i<16 ) mNoOmit |= (1 << i);
  128773. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  128774. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  128775. }
  128776. }
  128777. j++;
  128778. }
  128779. for(i=0; i<nOrderBy; i++){
  128780. Expr *pExpr = pOrderBy->a[i].pExpr;
  128781. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  128782. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  128783. }
  128784. *pmNoOmit = mNoOmit;
  128785. return pIdxInfo;
  128786. }
  128787. /*
  128788. ** The table object reference passed as the second argument to this function
  128789. ** must represent a virtual table. This function invokes the xBestIndex()
  128790. ** method of the virtual table with the sqlite3_index_info object that
  128791. ** comes in as the 3rd argument to this function.
  128792. **
  128793. ** If an error occurs, pParse is populated with an error message and a
  128794. ** non-zero value is returned. Otherwise, 0 is returned and the output
  128795. ** part of the sqlite3_index_info structure is left populated.
  128796. **
  128797. ** Whether or not an error is returned, it is the responsibility of the
  128798. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  128799. ** that this is required.
  128800. */
  128801. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  128802. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  128803. int rc;
  128804. TRACE_IDX_INPUTS(p);
  128805. rc = pVtab->pModule->xBestIndex(pVtab, p);
  128806. TRACE_IDX_OUTPUTS(p);
  128807. if( rc!=SQLITE_OK ){
  128808. if( rc==SQLITE_NOMEM ){
  128809. sqlite3OomFault(pParse->db);
  128810. }else if( !pVtab->zErrMsg ){
  128811. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  128812. }else{
  128813. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  128814. }
  128815. }
  128816. sqlite3_free(pVtab->zErrMsg);
  128817. pVtab->zErrMsg = 0;
  128818. #if 0
  128819. /* This error is now caught by the caller.
  128820. ** Search for "xBestIndex malfunction" below */
  128821. for(i=0; i<p->nConstraint; i++){
  128822. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  128823. sqlite3ErrorMsg(pParse,
  128824. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  128825. }
  128826. }
  128827. #endif
  128828. return pParse->nErr;
  128829. }
  128830. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  128831. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  128832. /*
  128833. ** Estimate the location of a particular key among all keys in an
  128834. ** index. Store the results in aStat as follows:
  128835. **
  128836. ** aStat[0] Est. number of rows less than pRec
  128837. ** aStat[1] Est. number of rows equal to pRec
  128838. **
  128839. ** Return the index of the sample that is the smallest sample that
  128840. ** is greater than or equal to pRec. Note that this index is not an index
  128841. ** into the aSample[] array - it is an index into a virtual set of samples
  128842. ** based on the contents of aSample[] and the number of fields in record
  128843. ** pRec.
  128844. */
  128845. static int whereKeyStats(
  128846. Parse *pParse, /* Database connection */
  128847. Index *pIdx, /* Index to consider domain of */
  128848. UnpackedRecord *pRec, /* Vector of values to consider */
  128849. int roundUp, /* Round up if true. Round down if false */
  128850. tRowcnt *aStat /* OUT: stats written here */
  128851. ){
  128852. IndexSample *aSample = pIdx->aSample;
  128853. int iCol; /* Index of required stats in anEq[] etc. */
  128854. int i; /* Index of first sample >= pRec */
  128855. int iSample; /* Smallest sample larger than or equal to pRec */
  128856. int iMin = 0; /* Smallest sample not yet tested */
  128857. int iTest; /* Next sample to test */
  128858. int res; /* Result of comparison operation */
  128859. int nField; /* Number of fields in pRec */
  128860. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  128861. #ifndef SQLITE_DEBUG
  128862. UNUSED_PARAMETER( pParse );
  128863. #endif
  128864. assert( pRec!=0 );
  128865. assert( pIdx->nSample>0 );
  128866. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  128867. /* Do a binary search to find the first sample greater than or equal
  128868. ** to pRec. If pRec contains a single field, the set of samples to search
  128869. ** is simply the aSample[] array. If the samples in aSample[] contain more
  128870. ** than one fields, all fields following the first are ignored.
  128871. **
  128872. ** If pRec contains N fields, where N is more than one, then as well as the
  128873. ** samples in aSample[] (truncated to N fields), the search also has to
  128874. ** consider prefixes of those samples. For example, if the set of samples
  128875. ** in aSample is:
  128876. **
  128877. ** aSample[0] = (a, 5)
  128878. ** aSample[1] = (a, 10)
  128879. ** aSample[2] = (b, 5)
  128880. ** aSample[3] = (c, 100)
  128881. ** aSample[4] = (c, 105)
  128882. **
  128883. ** Then the search space should ideally be the samples above and the
  128884. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  128885. ** the code actually searches this set:
  128886. **
  128887. ** 0: (a)
  128888. ** 1: (a, 5)
  128889. ** 2: (a, 10)
  128890. ** 3: (a, 10)
  128891. ** 4: (b)
  128892. ** 5: (b, 5)
  128893. ** 6: (c)
  128894. ** 7: (c, 100)
  128895. ** 8: (c, 105)
  128896. ** 9: (c, 105)
  128897. **
  128898. ** For each sample in the aSample[] array, N samples are present in the
  128899. ** effective sample array. In the above, samples 0 and 1 are based on
  128900. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  128901. **
  128902. ** Often, sample i of each block of N effective samples has (i+1) fields.
  128903. ** Except, each sample may be extended to ensure that it is greater than or
  128904. ** equal to the previous sample in the array. For example, in the above,
  128905. ** sample 2 is the first sample of a block of N samples, so at first it
  128906. ** appears that it should be 1 field in size. However, that would make it
  128907. ** smaller than sample 1, so the binary search would not work. As a result,
  128908. ** it is extended to two fields. The duplicates that this creates do not
  128909. ** cause any problems.
  128910. */
  128911. nField = pRec->nField;
  128912. iCol = 0;
  128913. iSample = pIdx->nSample * nField;
  128914. do{
  128915. int iSamp; /* Index in aSample[] of test sample */
  128916. int n; /* Number of fields in test sample */
  128917. iTest = (iMin+iSample)/2;
  128918. iSamp = iTest / nField;
  128919. if( iSamp>0 ){
  128920. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  128921. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  128922. ** fields that is greater than the previous effective sample. */
  128923. for(n=(iTest % nField) + 1; n<nField; n++){
  128924. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  128925. }
  128926. }else{
  128927. n = iTest + 1;
  128928. }
  128929. pRec->nField = n;
  128930. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  128931. if( res<0 ){
  128932. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  128933. iMin = iTest+1;
  128934. }else if( res==0 && n<nField ){
  128935. iLower = aSample[iSamp].anLt[n-1];
  128936. iMin = iTest+1;
  128937. res = -1;
  128938. }else{
  128939. iSample = iTest;
  128940. iCol = n-1;
  128941. }
  128942. }while( res && iMin<iSample );
  128943. i = iSample / nField;
  128944. #ifdef SQLITE_DEBUG
  128945. /* The following assert statements check that the binary search code
  128946. ** above found the right answer. This block serves no purpose other
  128947. ** than to invoke the asserts. */
  128948. if( pParse->db->mallocFailed==0 ){
  128949. if( res==0 ){
  128950. /* If (res==0) is true, then pRec must be equal to sample i. */
  128951. assert( i<pIdx->nSample );
  128952. assert( iCol==nField-1 );
  128953. pRec->nField = nField;
  128954. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  128955. || pParse->db->mallocFailed
  128956. );
  128957. }else{
  128958. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  128959. ** all samples in the aSample[] array, pRec must be smaller than the
  128960. ** (iCol+1) field prefix of sample i. */
  128961. assert( i<=pIdx->nSample && i>=0 );
  128962. pRec->nField = iCol+1;
  128963. assert( i==pIdx->nSample
  128964. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  128965. || pParse->db->mallocFailed );
  128966. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  128967. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  128968. ** be greater than or equal to the (iCol) field prefix of sample i.
  128969. ** If (i>0), then pRec must also be greater than sample (i-1). */
  128970. if( iCol>0 ){
  128971. pRec->nField = iCol;
  128972. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  128973. || pParse->db->mallocFailed );
  128974. }
  128975. if( i>0 ){
  128976. pRec->nField = nField;
  128977. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  128978. || pParse->db->mallocFailed );
  128979. }
  128980. }
  128981. }
  128982. #endif /* ifdef SQLITE_DEBUG */
  128983. if( res==0 ){
  128984. /* Record pRec is equal to sample i */
  128985. assert( iCol==nField-1 );
  128986. aStat[0] = aSample[i].anLt[iCol];
  128987. aStat[1] = aSample[i].anEq[iCol];
  128988. }else{
  128989. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  128990. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  128991. ** is larger than all samples in the array. */
  128992. tRowcnt iUpper, iGap;
  128993. if( i>=pIdx->nSample ){
  128994. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  128995. }else{
  128996. iUpper = aSample[i].anLt[iCol];
  128997. }
  128998. if( iLower>=iUpper ){
  128999. iGap = 0;
  129000. }else{
  129001. iGap = iUpper - iLower;
  129002. }
  129003. if( roundUp ){
  129004. iGap = (iGap*2)/3;
  129005. }else{
  129006. iGap = iGap/3;
  129007. }
  129008. aStat[0] = iLower + iGap;
  129009. aStat[1] = pIdx->aAvgEq[nField-1];
  129010. }
  129011. /* Restore the pRec->nField value before returning. */
  129012. pRec->nField = nField;
  129013. return i;
  129014. }
  129015. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  129016. /*
  129017. ** If it is not NULL, pTerm is a term that provides an upper or lower
  129018. ** bound on a range scan. Without considering pTerm, it is estimated
  129019. ** that the scan will visit nNew rows. This function returns the number
  129020. ** estimated to be visited after taking pTerm into account.
  129021. **
  129022. ** If the user explicitly specified a likelihood() value for this term,
  129023. ** then the return value is the likelihood multiplied by the number of
  129024. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  129025. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  129026. */
  129027. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  129028. LogEst nRet = nNew;
  129029. if( pTerm ){
  129030. if( pTerm->truthProb<=0 ){
  129031. nRet += pTerm->truthProb;
  129032. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  129033. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  129034. }
  129035. }
  129036. return nRet;
  129037. }
  129038. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  129039. /*
  129040. ** Return the affinity for a single column of an index.
  129041. */
  129042. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  129043. assert( iCol>=0 && iCol<pIdx->nColumn );
  129044. if( !pIdx->zColAff ){
  129045. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  129046. }
  129047. return pIdx->zColAff[iCol];
  129048. }
  129049. #endif
  129050. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  129051. /*
  129052. ** This function is called to estimate the number of rows visited by a
  129053. ** range-scan on a skip-scan index. For example:
  129054. **
  129055. ** CREATE INDEX i1 ON t1(a, b, c);
  129056. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  129057. **
  129058. ** Value pLoop->nOut is currently set to the estimated number of rows
  129059. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  129060. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  129061. ** on the stat4 data for the index. this scan will be peformed multiple
  129062. ** times (once for each (a,b) combination that matches a=?) is dealt with
  129063. ** by the caller.
  129064. **
  129065. ** It does this by scanning through all stat4 samples, comparing values
  129066. ** extracted from pLower and pUpper with the corresponding column in each
  129067. ** sample. If L and U are the number of samples found to be less than or
  129068. ** equal to the values extracted from pLower and pUpper respectively, and
  129069. ** N is the total number of samples, the pLoop->nOut value is adjusted
  129070. ** as follows:
  129071. **
  129072. ** nOut = nOut * ( min(U - L, 1) / N )
  129073. **
  129074. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  129075. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  129076. ** U is set to N.
  129077. **
  129078. ** Normally, this function sets *pbDone to 1 before returning. However,
  129079. ** if no value can be extracted from either pLower or pUpper (and so the
  129080. ** estimate of the number of rows delivered remains unchanged), *pbDone
  129081. ** is left as is.
  129082. **
  129083. ** If an error occurs, an SQLite error code is returned. Otherwise,
  129084. ** SQLITE_OK.
  129085. */
  129086. static int whereRangeSkipScanEst(
  129087. Parse *pParse, /* Parsing & code generating context */
  129088. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  129089. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  129090. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  129091. int *pbDone /* Set to true if at least one expr. value extracted */
  129092. ){
  129093. Index *p = pLoop->u.btree.pIndex;
  129094. int nEq = pLoop->u.btree.nEq;
  129095. sqlite3 *db = pParse->db;
  129096. int nLower = -1;
  129097. int nUpper = p->nSample+1;
  129098. int rc = SQLITE_OK;
  129099. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  129100. CollSeq *pColl;
  129101. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  129102. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  129103. sqlite3_value *pVal = 0; /* Value extracted from record */
  129104. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  129105. if( pLower ){
  129106. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  129107. nLower = 0;
  129108. }
  129109. if( pUpper && rc==SQLITE_OK ){
  129110. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  129111. nUpper = p2 ? 0 : p->nSample;
  129112. }
  129113. if( p1 || p2 ){
  129114. int i;
  129115. int nDiff;
  129116. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  129117. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  129118. if( rc==SQLITE_OK && p1 ){
  129119. int res = sqlite3MemCompare(p1, pVal, pColl);
  129120. if( res>=0 ) nLower++;
  129121. }
  129122. if( rc==SQLITE_OK && p2 ){
  129123. int res = sqlite3MemCompare(p2, pVal, pColl);
  129124. if( res>=0 ) nUpper++;
  129125. }
  129126. }
  129127. nDiff = (nUpper - nLower);
  129128. if( nDiff<=0 ) nDiff = 1;
  129129. /* If there is both an upper and lower bound specified, and the
  129130. ** comparisons indicate that they are close together, use the fallback
  129131. ** method (assume that the scan visits 1/64 of the rows) for estimating
  129132. ** the number of rows visited. Otherwise, estimate the number of rows
  129133. ** using the method described in the header comment for this function. */
  129134. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  129135. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  129136. pLoop->nOut -= nAdjust;
  129137. *pbDone = 1;
  129138. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  129139. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  129140. }
  129141. }else{
  129142. assert( *pbDone==0 );
  129143. }
  129144. sqlite3ValueFree(p1);
  129145. sqlite3ValueFree(p2);
  129146. sqlite3ValueFree(pVal);
  129147. return rc;
  129148. }
  129149. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  129150. /*
  129151. ** This function is used to estimate the number of rows that will be visited
  129152. ** by scanning an index for a range of values. The range may have an upper
  129153. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  129154. ** and lower bounds are represented by pLower and pUpper respectively. For
  129155. ** example, assuming that index p is on t1(a):
  129156. **
  129157. ** ... FROM t1 WHERE a > ? AND a < ? ...
  129158. ** |_____| |_____|
  129159. ** | |
  129160. ** pLower pUpper
  129161. **
  129162. ** If either of the upper or lower bound is not present, then NULL is passed in
  129163. ** place of the corresponding WhereTerm.
  129164. **
  129165. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  129166. ** column subject to the range constraint. Or, equivalently, the number of
  129167. ** equality constraints optimized by the proposed index scan. For example,
  129168. ** assuming index p is on t1(a, b), and the SQL query is:
  129169. **
  129170. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  129171. **
  129172. ** then nEq is set to 1 (as the range restricted column, b, is the second
  129173. ** left-most column of the index). Or, if the query is:
  129174. **
  129175. ** ... FROM t1 WHERE a > ? AND a < ? ...
  129176. **
  129177. ** then nEq is set to 0.
  129178. **
  129179. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  129180. ** number of rows that the index scan is expected to visit without
  129181. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  129182. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  129183. ** to account for the range constraints pLower and pUpper.
  129184. **
  129185. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  129186. ** used, a single range inequality reduces the search space by a factor of 4.
  129187. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  129188. ** rows visited by a factor of 64.
  129189. */
  129190. static int whereRangeScanEst(
  129191. Parse *pParse, /* Parsing & code generating context */
  129192. WhereLoopBuilder *pBuilder,
  129193. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  129194. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  129195. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  129196. ){
  129197. int rc = SQLITE_OK;
  129198. int nOut = pLoop->nOut;
  129199. LogEst nNew;
  129200. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  129201. Index *p = pLoop->u.btree.pIndex;
  129202. int nEq = pLoop->u.btree.nEq;
  129203. if( p->nSample>0 && nEq<p->nSampleCol ){
  129204. if( nEq==pBuilder->nRecValid ){
  129205. UnpackedRecord *pRec = pBuilder->pRec;
  129206. tRowcnt a[2];
  129207. int nBtm = pLoop->u.btree.nBtm;
  129208. int nTop = pLoop->u.btree.nTop;
  129209. /* Variable iLower will be set to the estimate of the number of rows in
  129210. ** the index that are less than the lower bound of the range query. The
  129211. ** lower bound being the concatenation of $P and $L, where $P is the
  129212. ** key-prefix formed by the nEq values matched against the nEq left-most
  129213. ** columns of the index, and $L is the value in pLower.
  129214. **
  129215. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  129216. ** is not a simple variable or literal value), the lower bound of the
  129217. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  129218. ** if $L is available, whereKeyStats() is called for both ($P) and
  129219. ** ($P:$L) and the larger of the two returned values is used.
  129220. **
  129221. ** Similarly, iUpper is to be set to the estimate of the number of rows
  129222. ** less than the upper bound of the range query. Where the upper bound
  129223. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  129224. ** of iUpper are requested of whereKeyStats() and the smaller used.
  129225. **
  129226. ** The number of rows between the two bounds is then just iUpper-iLower.
  129227. */
  129228. tRowcnt iLower; /* Rows less than the lower bound */
  129229. tRowcnt iUpper; /* Rows less than the upper bound */
  129230. int iLwrIdx = -2; /* aSample[] for the lower bound */
  129231. int iUprIdx = -1; /* aSample[] for the upper bound */
  129232. if( pRec ){
  129233. testcase( pRec->nField!=pBuilder->nRecValid );
  129234. pRec->nField = pBuilder->nRecValid;
  129235. }
  129236. /* Determine iLower and iUpper using ($P) only. */
  129237. if( nEq==0 ){
  129238. iLower = 0;
  129239. iUpper = p->nRowEst0;
  129240. }else{
  129241. /* Note: this call could be optimized away - since the same values must
  129242. ** have been requested when testing key $P in whereEqualScanEst(). */
  129243. whereKeyStats(pParse, p, pRec, 0, a);
  129244. iLower = a[0];
  129245. iUpper = a[0] + a[1];
  129246. }
  129247. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  129248. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  129249. assert( p->aSortOrder!=0 );
  129250. if( p->aSortOrder[nEq] ){
  129251. /* The roles of pLower and pUpper are swapped for a DESC index */
  129252. SWAP(WhereTerm*, pLower, pUpper);
  129253. SWAP(int, nBtm, nTop);
  129254. }
  129255. /* If possible, improve on the iLower estimate using ($P:$L). */
  129256. if( pLower ){
  129257. int n; /* Values extracted from pExpr */
  129258. Expr *pExpr = pLower->pExpr->pRight;
  129259. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  129260. if( rc==SQLITE_OK && n ){
  129261. tRowcnt iNew;
  129262. u16 mask = WO_GT|WO_LE;
  129263. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  129264. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  129265. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  129266. if( iNew>iLower ) iLower = iNew;
  129267. nOut--;
  129268. pLower = 0;
  129269. }
  129270. }
  129271. /* If possible, improve on the iUpper estimate using ($P:$U). */
  129272. if( pUpper ){
  129273. int n; /* Values extracted from pExpr */
  129274. Expr *pExpr = pUpper->pExpr->pRight;
  129275. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  129276. if( rc==SQLITE_OK && n ){
  129277. tRowcnt iNew;
  129278. u16 mask = WO_GT|WO_LE;
  129279. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  129280. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  129281. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  129282. if( iNew<iUpper ) iUpper = iNew;
  129283. nOut--;
  129284. pUpper = 0;
  129285. }
  129286. }
  129287. pBuilder->pRec = pRec;
  129288. if( rc==SQLITE_OK ){
  129289. if( iUpper>iLower ){
  129290. nNew = sqlite3LogEst(iUpper - iLower);
  129291. /* TUNING: If both iUpper and iLower are derived from the same
  129292. ** sample, then assume they are 4x more selective. This brings
  129293. ** the estimated selectivity more in line with what it would be
  129294. ** if estimated without the use of STAT3/4 tables. */
  129295. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  129296. }else{
  129297. nNew = 10; assert( 10==sqlite3LogEst(2) );
  129298. }
  129299. if( nNew<nOut ){
  129300. nOut = nNew;
  129301. }
  129302. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  129303. (u32)iLower, (u32)iUpper, nOut));
  129304. }
  129305. }else{
  129306. int bDone = 0;
  129307. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  129308. if( bDone ) return rc;
  129309. }
  129310. }
  129311. #else
  129312. UNUSED_PARAMETER(pParse);
  129313. UNUSED_PARAMETER(pBuilder);
  129314. assert( pLower || pUpper );
  129315. #endif
  129316. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  129317. nNew = whereRangeAdjust(pLower, nOut);
  129318. nNew = whereRangeAdjust(pUpper, nNew);
  129319. /* TUNING: If there is both an upper and lower limit and neither limit
  129320. ** has an application-defined likelihood(), assume the range is
  129321. ** reduced by an additional 75%. This means that, by default, an open-ended
  129322. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  129323. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  129324. ** match 1/64 of the index. */
  129325. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  129326. nNew -= 20;
  129327. }
  129328. nOut -= (pLower!=0) + (pUpper!=0);
  129329. if( nNew<10 ) nNew = 10;
  129330. if( nNew<nOut ) nOut = nNew;
  129331. #if defined(WHERETRACE_ENABLED)
  129332. if( pLoop->nOut>nOut ){
  129333. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  129334. pLoop->nOut, nOut));
  129335. }
  129336. #endif
  129337. pLoop->nOut = (LogEst)nOut;
  129338. return rc;
  129339. }
  129340. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  129341. /*
  129342. ** Estimate the number of rows that will be returned based on
  129343. ** an equality constraint x=VALUE and where that VALUE occurs in
  129344. ** the histogram data. This only works when x is the left-most
  129345. ** column of an index and sqlite_stat3 histogram data is available
  129346. ** for that index. When pExpr==NULL that means the constraint is
  129347. ** "x IS NULL" instead of "x=VALUE".
  129348. **
  129349. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  129350. ** If unable to make an estimate, leave *pnRow unchanged and return
  129351. ** non-zero.
  129352. **
  129353. ** This routine can fail if it is unable to load a collating sequence
  129354. ** required for string comparison, or if unable to allocate memory
  129355. ** for a UTF conversion required for comparison. The error is stored
  129356. ** in the pParse structure.
  129357. */
  129358. static int whereEqualScanEst(
  129359. Parse *pParse, /* Parsing & code generating context */
  129360. WhereLoopBuilder *pBuilder,
  129361. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  129362. tRowcnt *pnRow /* Write the revised row estimate here */
  129363. ){
  129364. Index *p = pBuilder->pNew->u.btree.pIndex;
  129365. int nEq = pBuilder->pNew->u.btree.nEq;
  129366. UnpackedRecord *pRec = pBuilder->pRec;
  129367. int rc; /* Subfunction return code */
  129368. tRowcnt a[2]; /* Statistics */
  129369. int bOk;
  129370. assert( nEq>=1 );
  129371. assert( nEq<=p->nColumn );
  129372. assert( p->aSample!=0 );
  129373. assert( p->nSample>0 );
  129374. assert( pBuilder->nRecValid<nEq );
  129375. /* If values are not available for all fields of the index to the left
  129376. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  129377. if( pBuilder->nRecValid<(nEq-1) ){
  129378. return SQLITE_NOTFOUND;
  129379. }
  129380. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  129381. ** below would return the same value. */
  129382. if( nEq>=p->nColumn ){
  129383. *pnRow = 1;
  129384. return SQLITE_OK;
  129385. }
  129386. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  129387. pBuilder->pRec = pRec;
  129388. if( rc!=SQLITE_OK ) return rc;
  129389. if( bOk==0 ) return SQLITE_NOTFOUND;
  129390. pBuilder->nRecValid = nEq;
  129391. whereKeyStats(pParse, p, pRec, 0, a);
  129392. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  129393. p->zName, nEq-1, (int)a[1]));
  129394. *pnRow = a[1];
  129395. return rc;
  129396. }
  129397. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  129398. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  129399. /*
  129400. ** Estimate the number of rows that will be returned based on
  129401. ** an IN constraint where the right-hand side of the IN operator
  129402. ** is a list of values. Example:
  129403. **
  129404. ** WHERE x IN (1,2,3,4)
  129405. **
  129406. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  129407. ** If unable to make an estimate, leave *pnRow unchanged and return
  129408. ** non-zero.
  129409. **
  129410. ** This routine can fail if it is unable to load a collating sequence
  129411. ** required for string comparison, or if unable to allocate memory
  129412. ** for a UTF conversion required for comparison. The error is stored
  129413. ** in the pParse structure.
  129414. */
  129415. static int whereInScanEst(
  129416. Parse *pParse, /* Parsing & code generating context */
  129417. WhereLoopBuilder *pBuilder,
  129418. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  129419. tRowcnt *pnRow /* Write the revised row estimate here */
  129420. ){
  129421. Index *p = pBuilder->pNew->u.btree.pIndex;
  129422. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  129423. int nRecValid = pBuilder->nRecValid;
  129424. int rc = SQLITE_OK; /* Subfunction return code */
  129425. tRowcnt nEst; /* Number of rows for a single term */
  129426. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  129427. int i; /* Loop counter */
  129428. assert( p->aSample!=0 );
  129429. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  129430. nEst = nRow0;
  129431. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  129432. nRowEst += nEst;
  129433. pBuilder->nRecValid = nRecValid;
  129434. }
  129435. if( rc==SQLITE_OK ){
  129436. if( nRowEst > nRow0 ) nRowEst = nRow0;
  129437. *pnRow = nRowEst;
  129438. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  129439. }
  129440. assert( pBuilder->nRecValid==nRecValid );
  129441. return rc;
  129442. }
  129443. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  129444. #ifdef WHERETRACE_ENABLED
  129445. /*
  129446. ** Print the content of a WhereTerm object
  129447. */
  129448. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  129449. if( pTerm==0 ){
  129450. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  129451. }else{
  129452. char zType[4];
  129453. char zLeft[50];
  129454. memcpy(zType, "...", 4);
  129455. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  129456. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  129457. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  129458. if( pTerm->eOperator & WO_SINGLE ){
  129459. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  129460. pTerm->leftCursor, pTerm->u.leftColumn);
  129461. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  129462. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  129463. pTerm->u.pOrInfo->indexable);
  129464. }else{
  129465. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  129466. }
  129467. sqlite3DebugPrintf(
  129468. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  129469. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  129470. pTerm->eOperator, pTerm->wtFlags);
  129471. if( pTerm->iField ){
  129472. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  129473. }else{
  129474. sqlite3DebugPrintf("\n");
  129475. }
  129476. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  129477. }
  129478. }
  129479. #endif
  129480. #ifdef WHERETRACE_ENABLED
  129481. /*
  129482. ** Show the complete content of a WhereClause
  129483. */
  129484. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  129485. int i;
  129486. for(i=0; i<pWC->nTerm; i++){
  129487. whereTermPrint(&pWC->a[i], i);
  129488. }
  129489. }
  129490. #endif
  129491. #ifdef WHERETRACE_ENABLED
  129492. /*
  129493. ** Print a WhereLoop object for debugging purposes
  129494. */
  129495. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  129496. WhereInfo *pWInfo = pWC->pWInfo;
  129497. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  129498. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  129499. Table *pTab = pItem->pTab;
  129500. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  129501. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  129502. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  129503. sqlite3DebugPrintf(" %12s",
  129504. pItem->zAlias ? pItem->zAlias : pTab->zName);
  129505. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  129506. const char *zName;
  129507. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  129508. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  129509. int i = sqlite3Strlen30(zName) - 1;
  129510. while( zName[i]!='_' ) i--;
  129511. zName += i;
  129512. }
  129513. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  129514. }else{
  129515. sqlite3DebugPrintf("%20s","");
  129516. }
  129517. }else{
  129518. char *z;
  129519. if( p->u.vtab.idxStr ){
  129520. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  129521. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  129522. }else{
  129523. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  129524. }
  129525. sqlite3DebugPrintf(" %-19s", z);
  129526. sqlite3_free(z);
  129527. }
  129528. if( p->wsFlags & WHERE_SKIPSCAN ){
  129529. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  129530. }else{
  129531. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  129532. }
  129533. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  129534. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  129535. int i;
  129536. for(i=0; i<p->nLTerm; i++){
  129537. whereTermPrint(p->aLTerm[i], i);
  129538. }
  129539. }
  129540. }
  129541. #endif
  129542. /*
  129543. ** Convert bulk memory into a valid WhereLoop that can be passed
  129544. ** to whereLoopClear harmlessly.
  129545. */
  129546. static void whereLoopInit(WhereLoop *p){
  129547. p->aLTerm = p->aLTermSpace;
  129548. p->nLTerm = 0;
  129549. p->nLSlot = ArraySize(p->aLTermSpace);
  129550. p->wsFlags = 0;
  129551. }
  129552. /*
  129553. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  129554. */
  129555. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  129556. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  129557. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  129558. sqlite3_free(p->u.vtab.idxStr);
  129559. p->u.vtab.needFree = 0;
  129560. p->u.vtab.idxStr = 0;
  129561. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  129562. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  129563. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  129564. p->u.btree.pIndex = 0;
  129565. }
  129566. }
  129567. }
  129568. /*
  129569. ** Deallocate internal memory used by a WhereLoop object
  129570. */
  129571. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  129572. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  129573. whereLoopClearUnion(db, p);
  129574. whereLoopInit(p);
  129575. }
  129576. /*
  129577. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  129578. */
  129579. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  129580. WhereTerm **paNew;
  129581. if( p->nLSlot>=n ) return SQLITE_OK;
  129582. n = (n+7)&~7;
  129583. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  129584. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  129585. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  129586. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  129587. p->aLTerm = paNew;
  129588. p->nLSlot = n;
  129589. return SQLITE_OK;
  129590. }
  129591. /*
  129592. ** Transfer content from the second pLoop into the first.
  129593. */
  129594. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  129595. whereLoopClearUnion(db, pTo);
  129596. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  129597. memset(&pTo->u, 0, sizeof(pTo->u));
  129598. return SQLITE_NOMEM_BKPT;
  129599. }
  129600. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  129601. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  129602. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  129603. pFrom->u.vtab.needFree = 0;
  129604. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  129605. pFrom->u.btree.pIndex = 0;
  129606. }
  129607. return SQLITE_OK;
  129608. }
  129609. /*
  129610. ** Delete a WhereLoop object
  129611. */
  129612. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  129613. whereLoopClear(db, p);
  129614. sqlite3DbFreeNN(db, p);
  129615. }
  129616. /*
  129617. ** Free a WhereInfo structure
  129618. */
  129619. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  129620. int i;
  129621. assert( pWInfo!=0 );
  129622. for(i=0; i<pWInfo->nLevel; i++){
  129623. WhereLevel *pLevel = &pWInfo->a[i];
  129624. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  129625. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  129626. }
  129627. }
  129628. sqlite3WhereClauseClear(&pWInfo->sWC);
  129629. while( pWInfo->pLoops ){
  129630. WhereLoop *p = pWInfo->pLoops;
  129631. pWInfo->pLoops = p->pNextLoop;
  129632. whereLoopDelete(db, p);
  129633. }
  129634. sqlite3DbFreeNN(db, pWInfo);
  129635. }
  129636. /*
  129637. ** Return TRUE if all of the following are true:
  129638. **
  129639. ** (1) X has the same or lower cost that Y
  129640. ** (2) X uses fewer WHERE clause terms than Y
  129641. ** (3) Every WHERE clause term used by X is also used by Y
  129642. ** (4) X skips at least as many columns as Y
  129643. ** (5) If X is a covering index, than Y is too
  129644. **
  129645. ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
  129646. ** If X is a proper subset of Y then Y is a better choice and ought
  129647. ** to have a lower cost. This routine returns TRUE when that cost
  129648. ** relationship is inverted and needs to be adjusted. Constraint (4)
  129649. ** was added because if X uses skip-scan less than Y it still might
  129650. ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
  129651. ** was added because a covering index probably deserves to have a lower cost
  129652. ** than a non-covering index even if it is a proper subset.
  129653. */
  129654. static int whereLoopCheaperProperSubset(
  129655. const WhereLoop *pX, /* First WhereLoop to compare */
  129656. const WhereLoop *pY /* Compare against this WhereLoop */
  129657. ){
  129658. int i, j;
  129659. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  129660. return 0; /* X is not a subset of Y */
  129661. }
  129662. if( pY->nSkip > pX->nSkip ) return 0;
  129663. if( pX->rRun >= pY->rRun ){
  129664. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  129665. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  129666. }
  129667. for(i=pX->nLTerm-1; i>=0; i--){
  129668. if( pX->aLTerm[i]==0 ) continue;
  129669. for(j=pY->nLTerm-1; j>=0; j--){
  129670. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  129671. }
  129672. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  129673. }
  129674. if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
  129675. && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
  129676. return 0; /* Constraint (5) */
  129677. }
  129678. return 1; /* All conditions meet */
  129679. }
  129680. /*
  129681. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  129682. ** that:
  129683. **
  129684. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  129685. ** subset of pTemplate
  129686. **
  129687. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  129688. ** is a proper subset.
  129689. **
  129690. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  129691. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  129692. ** also used by Y.
  129693. */
  129694. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  129695. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  129696. for(; p; p=p->pNextLoop){
  129697. if( p->iTab!=pTemplate->iTab ) continue;
  129698. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  129699. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  129700. /* Adjust pTemplate cost downward so that it is cheaper than its
  129701. ** subset p. */
  129702. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  129703. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  129704. pTemplate->rRun = p->rRun;
  129705. pTemplate->nOut = p->nOut - 1;
  129706. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  129707. /* Adjust pTemplate cost upward so that it is costlier than p since
  129708. ** pTemplate is a proper subset of p */
  129709. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  129710. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  129711. pTemplate->rRun = p->rRun;
  129712. pTemplate->nOut = p->nOut + 1;
  129713. }
  129714. }
  129715. }
  129716. /*
  129717. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  129718. ** replaced by pTemplate.
  129719. **
  129720. ** Return NULL if pTemplate does not belong on the WhereLoop list.
  129721. ** In other words if pTemplate ought to be dropped from further consideration.
  129722. **
  129723. ** If pX is a WhereLoop that pTemplate can replace, then return the
  129724. ** link that points to pX.
  129725. **
  129726. ** If pTemplate cannot replace any existing element of the list but needs
  129727. ** to be added to the list as a new entry, then return a pointer to the
  129728. ** tail of the list.
  129729. */
  129730. static WhereLoop **whereLoopFindLesser(
  129731. WhereLoop **ppPrev,
  129732. const WhereLoop *pTemplate
  129733. ){
  129734. WhereLoop *p;
  129735. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  129736. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  129737. /* If either the iTab or iSortIdx values for two WhereLoop are different
  129738. ** then those WhereLoops need to be considered separately. Neither is
  129739. ** a candidate to replace the other. */
  129740. continue;
  129741. }
  129742. /* In the current implementation, the rSetup value is either zero
  129743. ** or the cost of building an automatic index (NlogN) and the NlogN
  129744. ** is the same for compatible WhereLoops. */
  129745. assert( p->rSetup==0 || pTemplate->rSetup==0
  129746. || p->rSetup==pTemplate->rSetup );
  129747. /* whereLoopAddBtree() always generates and inserts the automatic index
  129748. ** case first. Hence compatible candidate WhereLoops never have a larger
  129749. ** rSetup. Call this SETUP-INVARIANT */
  129750. assert( p->rSetup>=pTemplate->rSetup );
  129751. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  129752. ** UNIQUE constraint) with one or more == constraints is better
  129753. ** than an automatic index. Unless it is a skip-scan. */
  129754. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  129755. && (pTemplate->nSkip)==0
  129756. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  129757. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  129758. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  129759. ){
  129760. break;
  129761. }
  129762. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  129763. ** discarded. WhereLoop p is better if:
  129764. ** (1) p has no more dependencies than pTemplate, and
  129765. ** (2) p has an equal or lower cost than pTemplate
  129766. */
  129767. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  129768. && p->rSetup<=pTemplate->rSetup /* (2a) */
  129769. && p->rRun<=pTemplate->rRun /* (2b) */
  129770. && p->nOut<=pTemplate->nOut /* (2c) */
  129771. ){
  129772. return 0; /* Discard pTemplate */
  129773. }
  129774. /* If pTemplate is always better than p, then cause p to be overwritten
  129775. ** with pTemplate. pTemplate is better than p if:
  129776. ** (1) pTemplate has no more dependences than p, and
  129777. ** (2) pTemplate has an equal or lower cost than p.
  129778. */
  129779. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  129780. && p->rRun>=pTemplate->rRun /* (2a) */
  129781. && p->nOut>=pTemplate->nOut /* (2b) */
  129782. ){
  129783. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  129784. break; /* Cause p to be overwritten by pTemplate */
  129785. }
  129786. }
  129787. return ppPrev;
  129788. }
  129789. /*
  129790. ** Insert or replace a WhereLoop entry using the template supplied.
  129791. **
  129792. ** An existing WhereLoop entry might be overwritten if the new template
  129793. ** is better and has fewer dependencies. Or the template will be ignored
  129794. ** and no insert will occur if an existing WhereLoop is faster and has
  129795. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  129796. ** added based on the template.
  129797. **
  129798. ** If pBuilder->pOrSet is not NULL then we care about only the
  129799. ** prerequisites and rRun and nOut costs of the N best loops. That
  129800. ** information is gathered in the pBuilder->pOrSet object. This special
  129801. ** processing mode is used only for OR clause processing.
  129802. **
  129803. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  129804. ** still might overwrite similar loops with the new template if the
  129805. ** new template is better. Loops may be overwritten if the following
  129806. ** conditions are met:
  129807. **
  129808. ** (1) They have the same iTab.
  129809. ** (2) They have the same iSortIdx.
  129810. ** (3) The template has same or fewer dependencies than the current loop
  129811. ** (4) The template has the same or lower cost than the current loop
  129812. */
  129813. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  129814. WhereLoop **ppPrev, *p;
  129815. WhereInfo *pWInfo = pBuilder->pWInfo;
  129816. sqlite3 *db = pWInfo->pParse->db;
  129817. int rc;
  129818. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  129819. ** and prereqs.
  129820. */
  129821. if( pBuilder->pOrSet!=0 ){
  129822. if( pTemplate->nLTerm ){
  129823. #if WHERETRACE_ENABLED
  129824. u16 n = pBuilder->pOrSet->n;
  129825. int x =
  129826. #endif
  129827. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  129828. pTemplate->nOut);
  129829. #if WHERETRACE_ENABLED /* 0x8 */
  129830. if( sqlite3WhereTrace & 0x8 ){
  129831. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  129832. whereLoopPrint(pTemplate, pBuilder->pWC);
  129833. }
  129834. #endif
  129835. }
  129836. return SQLITE_OK;
  129837. }
  129838. /* Look for an existing WhereLoop to replace with pTemplate
  129839. */
  129840. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  129841. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  129842. if( ppPrev==0 ){
  129843. /* There already exists a WhereLoop on the list that is better
  129844. ** than pTemplate, so just ignore pTemplate */
  129845. #if WHERETRACE_ENABLED /* 0x8 */
  129846. if( sqlite3WhereTrace & 0x8 ){
  129847. sqlite3DebugPrintf(" skip: ");
  129848. whereLoopPrint(pTemplate, pBuilder->pWC);
  129849. }
  129850. #endif
  129851. return SQLITE_OK;
  129852. }else{
  129853. p = *ppPrev;
  129854. }
  129855. /* If we reach this point it means that either p[] should be overwritten
  129856. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  129857. ** WhereLoop and insert it.
  129858. */
  129859. #if WHERETRACE_ENABLED /* 0x8 */
  129860. if( sqlite3WhereTrace & 0x8 ){
  129861. if( p!=0 ){
  129862. sqlite3DebugPrintf("replace: ");
  129863. whereLoopPrint(p, pBuilder->pWC);
  129864. sqlite3DebugPrintf(" with: ");
  129865. }else{
  129866. sqlite3DebugPrintf(" add: ");
  129867. }
  129868. whereLoopPrint(pTemplate, pBuilder->pWC);
  129869. }
  129870. #endif
  129871. if( p==0 ){
  129872. /* Allocate a new WhereLoop to add to the end of the list */
  129873. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  129874. if( p==0 ) return SQLITE_NOMEM_BKPT;
  129875. whereLoopInit(p);
  129876. p->pNextLoop = 0;
  129877. }else{
  129878. /* We will be overwriting WhereLoop p[]. But before we do, first
  129879. ** go through the rest of the list and delete any other entries besides
  129880. ** p[] that are also supplated by pTemplate */
  129881. WhereLoop **ppTail = &p->pNextLoop;
  129882. WhereLoop *pToDel;
  129883. while( *ppTail ){
  129884. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  129885. if( ppTail==0 ) break;
  129886. pToDel = *ppTail;
  129887. if( pToDel==0 ) break;
  129888. *ppTail = pToDel->pNextLoop;
  129889. #if WHERETRACE_ENABLED /* 0x8 */
  129890. if( sqlite3WhereTrace & 0x8 ){
  129891. sqlite3DebugPrintf(" delete: ");
  129892. whereLoopPrint(pToDel, pBuilder->pWC);
  129893. }
  129894. #endif
  129895. whereLoopDelete(db, pToDel);
  129896. }
  129897. }
  129898. rc = whereLoopXfer(db, p, pTemplate);
  129899. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  129900. Index *pIndex = p->u.btree.pIndex;
  129901. if( pIndex && pIndex->tnum==0 ){
  129902. p->u.btree.pIndex = 0;
  129903. }
  129904. }
  129905. return rc;
  129906. }
  129907. /*
  129908. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  129909. ** WHERE clause that reference the loop but which are not used by an
  129910. ** index.
  129911. *
  129912. ** For every WHERE clause term that is not used by the index
  129913. ** and which has a truth probability assigned by one of the likelihood(),
  129914. ** likely(), or unlikely() SQL functions, reduce the estimated number
  129915. ** of output rows by the probability specified.
  129916. **
  129917. ** TUNING: For every WHERE clause term that is not used by the index
  129918. ** and which does not have an assigned truth probability, heuristics
  129919. ** described below are used to try to estimate the truth probability.
  129920. ** TODO --> Perhaps this is something that could be improved by better
  129921. ** table statistics.
  129922. **
  129923. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  129924. ** value corresponds to -1 in LogEst notation, so this means decrement
  129925. ** the WhereLoop.nOut field for every such WHERE clause term.
  129926. **
  129927. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  129928. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  129929. ** final output row estimate is no greater than 1/4 of the total number
  129930. ** of rows in the table. In other words, assume that x==EXPR will filter
  129931. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  129932. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  129933. ** on the "x" column and so in that case only cap the output row estimate
  129934. ** at 1/2 instead of 1/4.
  129935. */
  129936. static void whereLoopOutputAdjust(
  129937. WhereClause *pWC, /* The WHERE clause */
  129938. WhereLoop *pLoop, /* The loop to adjust downward */
  129939. LogEst nRow /* Number of rows in the entire table */
  129940. ){
  129941. WhereTerm *pTerm, *pX;
  129942. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  129943. int i, j, k;
  129944. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  129945. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  129946. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  129947. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  129948. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  129949. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  129950. for(j=pLoop->nLTerm-1; j>=0; j--){
  129951. pX = pLoop->aLTerm[j];
  129952. if( pX==0 ) continue;
  129953. if( pX==pTerm ) break;
  129954. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  129955. }
  129956. if( j<0 ){
  129957. if( pTerm->truthProb<=0 ){
  129958. /* If a truth probability is specified using the likelihood() hints,
  129959. ** then use the probability provided by the application. */
  129960. pLoop->nOut += pTerm->truthProb;
  129961. }else{
  129962. /* In the absence of explicit truth probabilities, use heuristics to
  129963. ** guess a reasonable truth probability. */
  129964. pLoop->nOut--;
  129965. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  129966. Expr *pRight = pTerm->pExpr->pRight;
  129967. testcase( pTerm->pExpr->op==TK_IS );
  129968. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  129969. k = 10;
  129970. }else{
  129971. k = 20;
  129972. }
  129973. if( iReduce<k ) iReduce = k;
  129974. }
  129975. }
  129976. }
  129977. }
  129978. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  129979. }
  129980. /*
  129981. ** Term pTerm is a vector range comparison operation. The first comparison
  129982. ** in the vector can be optimized using column nEq of the index. This
  129983. ** function returns the total number of vector elements that can be used
  129984. ** as part of the range comparison.
  129985. **
  129986. ** For example, if the query is:
  129987. **
  129988. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  129989. **
  129990. ** and the index:
  129991. **
  129992. ** CREATE INDEX ... ON (a, b, c, d, e)
  129993. **
  129994. ** then this function would be invoked with nEq=1. The value returned in
  129995. ** this case is 3.
  129996. */
  129997. static int whereRangeVectorLen(
  129998. Parse *pParse, /* Parsing context */
  129999. int iCur, /* Cursor open on pIdx */
  130000. Index *pIdx, /* The index to be used for a inequality constraint */
  130001. int nEq, /* Number of prior equality constraints on same index */
  130002. WhereTerm *pTerm /* The vector inequality constraint */
  130003. ){
  130004. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  130005. int i;
  130006. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  130007. for(i=1; i<nCmp; i++){
  130008. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  130009. ** of the index. If not, exit the loop. */
  130010. char aff; /* Comparison affinity */
  130011. char idxaff = 0; /* Indexed columns affinity */
  130012. CollSeq *pColl; /* Comparison collation sequence */
  130013. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  130014. Expr *pRhs = pTerm->pExpr->pRight;
  130015. if( pRhs->flags & EP_xIsSelect ){
  130016. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  130017. }else{
  130018. pRhs = pRhs->x.pList->a[i].pExpr;
  130019. }
  130020. /* Check that the LHS of the comparison is a column reference to
  130021. ** the right column of the right source table. And that the sort
  130022. ** order of the index column is the same as the sort order of the
  130023. ** leftmost index column. */
  130024. if( pLhs->op!=TK_COLUMN
  130025. || pLhs->iTable!=iCur
  130026. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  130027. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  130028. ){
  130029. break;
  130030. }
  130031. testcase( pLhs->iColumn==XN_ROWID );
  130032. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  130033. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  130034. if( aff!=idxaff ) break;
  130035. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  130036. if( pColl==0 ) break;
  130037. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  130038. }
  130039. return i;
  130040. }
  130041. /*
  130042. ** Adjust the cost C by the costMult facter T. This only occurs if
  130043. ** compiled with -DSQLITE_ENABLE_COSTMULT
  130044. */
  130045. #ifdef SQLITE_ENABLE_COSTMULT
  130046. # define ApplyCostMultiplier(C,T) C += T
  130047. #else
  130048. # define ApplyCostMultiplier(C,T)
  130049. #endif
  130050. /*
  130051. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  130052. ** index pIndex. Try to match one more.
  130053. **
  130054. ** When this function is called, pBuilder->pNew->nOut contains the
  130055. ** number of rows expected to be visited by filtering using the nEq
  130056. ** terms only. If it is modified, this value is restored before this
  130057. ** function returns.
  130058. **
  130059. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  130060. ** INTEGER PRIMARY KEY.
  130061. */
  130062. static int whereLoopAddBtreeIndex(
  130063. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  130064. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  130065. Index *pProbe, /* An index on pSrc */
  130066. LogEst nInMul /* log(Number of iterations due to IN) */
  130067. ){
  130068. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  130069. Parse *pParse = pWInfo->pParse; /* Parsing context */
  130070. sqlite3 *db = pParse->db; /* Database connection malloc context */
  130071. WhereLoop *pNew; /* Template WhereLoop under construction */
  130072. WhereTerm *pTerm; /* A WhereTerm under consideration */
  130073. int opMask; /* Valid operators for constraints */
  130074. WhereScan scan; /* Iterator for WHERE terms */
  130075. Bitmask saved_prereq; /* Original value of pNew->prereq */
  130076. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  130077. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  130078. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  130079. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  130080. u16 saved_nSkip; /* Original value of pNew->nSkip */
  130081. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  130082. LogEst saved_nOut; /* Original value of pNew->nOut */
  130083. int rc = SQLITE_OK; /* Return code */
  130084. LogEst rSize; /* Number of rows in the table */
  130085. LogEst rLogSize; /* Logarithm of table size */
  130086. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  130087. pNew = pBuilder->pNew;
  130088. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  130089. WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d\n",
  130090. pProbe->pTable->zName,pProbe->zName, pNew->u.btree.nEq));
  130091. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  130092. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  130093. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  130094. opMask = WO_LT|WO_LE;
  130095. }else{
  130096. assert( pNew->u.btree.nBtm==0 );
  130097. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  130098. }
  130099. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  130100. assert( pNew->u.btree.nEq<pProbe->nColumn );
  130101. saved_nEq = pNew->u.btree.nEq;
  130102. saved_nBtm = pNew->u.btree.nBtm;
  130103. saved_nTop = pNew->u.btree.nTop;
  130104. saved_nSkip = pNew->nSkip;
  130105. saved_nLTerm = pNew->nLTerm;
  130106. saved_wsFlags = pNew->wsFlags;
  130107. saved_prereq = pNew->prereq;
  130108. saved_nOut = pNew->nOut;
  130109. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  130110. opMask, pProbe);
  130111. pNew->rSetup = 0;
  130112. rSize = pProbe->aiRowLogEst[0];
  130113. rLogSize = estLog(rSize);
  130114. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  130115. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  130116. LogEst rCostIdx;
  130117. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  130118. int nIn = 0;
  130119. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  130120. int nRecValid = pBuilder->nRecValid;
  130121. #endif
  130122. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  130123. && indexColumnNotNull(pProbe, saved_nEq)
  130124. ){
  130125. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  130126. }
  130127. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  130128. /* Do not allow the upper bound of a LIKE optimization range constraint
  130129. ** to mix with a lower range bound from some other source */
  130130. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  130131. /* Do not allow constraints from the WHERE clause to be used by the
  130132. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  130133. ** allowed */
  130134. if( (pSrc->fg.jointype & JT_LEFT)!=0
  130135. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  130136. ){
  130137. continue;
  130138. }
  130139. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  130140. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  130141. }else{
  130142. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  130143. }
  130144. pNew->wsFlags = saved_wsFlags;
  130145. pNew->u.btree.nEq = saved_nEq;
  130146. pNew->u.btree.nBtm = saved_nBtm;
  130147. pNew->u.btree.nTop = saved_nTop;
  130148. pNew->nLTerm = saved_nLTerm;
  130149. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  130150. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  130151. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  130152. assert( nInMul==0
  130153. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  130154. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  130155. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  130156. );
  130157. if( eOp & WO_IN ){
  130158. Expr *pExpr = pTerm->pExpr;
  130159. pNew->wsFlags |= WHERE_COLUMN_IN;
  130160. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  130161. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  130162. int i;
  130163. nIn = 46; assert( 46==sqlite3LogEst(25) );
  130164. /* The expression may actually be of the form (x, y) IN (SELECT...).
  130165. ** In this case there is a separate term for each of (x) and (y).
  130166. ** However, the nIn multiplier should only be applied once, not once
  130167. ** for each such term. The following loop checks that pTerm is the
  130168. ** first such term in use, and sets nIn back to 0 if it is not. */
  130169. for(i=0; i<pNew->nLTerm-1; i++){
  130170. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  130171. }
  130172. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  130173. /* "x IN (value, value, ...)" */
  130174. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  130175. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  130176. ** changes "x IN (?)" into "x=?". */
  130177. }
  130178. }else if( eOp & (WO_EQ|WO_IS) ){
  130179. int iCol = pProbe->aiColumn[saved_nEq];
  130180. pNew->wsFlags |= WHERE_COLUMN_EQ;
  130181. assert( saved_nEq==pNew->u.btree.nEq );
  130182. if( iCol==XN_ROWID
  130183. || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  130184. ){
  130185. if( iCol==XN_ROWID || pProbe->uniqNotNull
  130186. || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
  130187. ){
  130188. pNew->wsFlags |= WHERE_ONEROW;
  130189. }else{
  130190. pNew->wsFlags |= WHERE_UNQ_WANTED;
  130191. }
  130192. }
  130193. }else if( eOp & WO_ISNULL ){
  130194. pNew->wsFlags |= WHERE_COLUMN_NULL;
  130195. }else if( eOp & (WO_GT|WO_GE) ){
  130196. testcase( eOp & WO_GT );
  130197. testcase( eOp & WO_GE );
  130198. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  130199. pNew->u.btree.nBtm = whereRangeVectorLen(
  130200. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  130201. );
  130202. pBtm = pTerm;
  130203. pTop = 0;
  130204. if( pTerm->wtFlags & TERM_LIKEOPT ){
  130205. /* Range contraints that come from the LIKE optimization are
  130206. ** always used in pairs. */
  130207. pTop = &pTerm[1];
  130208. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  130209. assert( pTop->wtFlags & TERM_LIKEOPT );
  130210. assert( pTop->eOperator==WO_LT );
  130211. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  130212. pNew->aLTerm[pNew->nLTerm++] = pTop;
  130213. pNew->wsFlags |= WHERE_TOP_LIMIT;
  130214. pNew->u.btree.nTop = 1;
  130215. }
  130216. }else{
  130217. assert( eOp & (WO_LT|WO_LE) );
  130218. testcase( eOp & WO_LT );
  130219. testcase( eOp & WO_LE );
  130220. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  130221. pNew->u.btree.nTop = whereRangeVectorLen(
  130222. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  130223. );
  130224. pTop = pTerm;
  130225. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  130226. pNew->aLTerm[pNew->nLTerm-2] : 0;
  130227. }
  130228. /* At this point pNew->nOut is set to the number of rows expected to
  130229. ** be visited by the index scan before considering term pTerm, or the
  130230. ** values of nIn and nInMul. In other words, assuming that all
  130231. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  130232. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  130233. assert( pNew->nOut==saved_nOut );
  130234. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  130235. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  130236. ** data, using some other estimate. */
  130237. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  130238. }else{
  130239. int nEq = ++pNew->u.btree.nEq;
  130240. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  130241. assert( pNew->nOut==saved_nOut );
  130242. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  130243. assert( (eOp & WO_IN) || nIn==0 );
  130244. testcase( eOp & WO_IN );
  130245. pNew->nOut += pTerm->truthProb;
  130246. pNew->nOut -= nIn;
  130247. }else{
  130248. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  130249. tRowcnt nOut = 0;
  130250. if( nInMul==0
  130251. && pProbe->nSample
  130252. && pNew->u.btree.nEq<=pProbe->nSampleCol
  130253. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  130254. ){
  130255. Expr *pExpr = pTerm->pExpr;
  130256. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  130257. testcase( eOp & WO_EQ );
  130258. testcase( eOp & WO_IS );
  130259. testcase( eOp & WO_ISNULL );
  130260. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  130261. }else{
  130262. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  130263. }
  130264. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  130265. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  130266. if( nOut ){
  130267. pNew->nOut = sqlite3LogEst(nOut);
  130268. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  130269. pNew->nOut -= nIn;
  130270. }
  130271. }
  130272. if( nOut==0 )
  130273. #endif
  130274. {
  130275. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  130276. if( eOp & WO_ISNULL ){
  130277. /* TUNING: If there is no likelihood() value, assume that a
  130278. ** "col IS NULL" expression matches twice as many rows
  130279. ** as (col=?). */
  130280. pNew->nOut += 10;
  130281. }
  130282. }
  130283. }
  130284. }
  130285. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  130286. ** it to pNew->rRun, which is currently set to the cost of the index
  130287. ** seek only. Then, if this is a non-covering index, add the cost of
  130288. ** visiting the rows in the main table. */
  130289. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  130290. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  130291. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  130292. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  130293. }
  130294. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  130295. nOutUnadjusted = pNew->nOut;
  130296. pNew->rRun += nInMul + nIn;
  130297. pNew->nOut += nInMul + nIn;
  130298. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  130299. rc = whereLoopInsert(pBuilder, pNew);
  130300. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  130301. pNew->nOut = saved_nOut;
  130302. }else{
  130303. pNew->nOut = nOutUnadjusted;
  130304. }
  130305. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  130306. && pNew->u.btree.nEq<pProbe->nColumn
  130307. ){
  130308. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  130309. }
  130310. pNew->nOut = saved_nOut;
  130311. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  130312. pBuilder->nRecValid = nRecValid;
  130313. #endif
  130314. }
  130315. pNew->prereq = saved_prereq;
  130316. pNew->u.btree.nEq = saved_nEq;
  130317. pNew->u.btree.nBtm = saved_nBtm;
  130318. pNew->u.btree.nTop = saved_nTop;
  130319. pNew->nSkip = saved_nSkip;
  130320. pNew->wsFlags = saved_wsFlags;
  130321. pNew->nOut = saved_nOut;
  130322. pNew->nLTerm = saved_nLTerm;
  130323. /* Consider using a skip-scan if there are no WHERE clause constraints
  130324. ** available for the left-most terms of the index, and if the average
  130325. ** number of repeats in the left-most terms is at least 18.
  130326. **
  130327. ** The magic number 18 is selected on the basis that scanning 17 rows
  130328. ** is almost always quicker than an index seek (even though if the index
  130329. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  130330. ** the code). And, even if it is not, it should not be too much slower.
  130331. ** On the other hand, the extra seeks could end up being significantly
  130332. ** more expensive. */
  130333. assert( 42==sqlite3LogEst(18) );
  130334. if( saved_nEq==saved_nSkip
  130335. && saved_nEq+1<pProbe->nKeyCol
  130336. && pProbe->noSkipScan==0
  130337. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  130338. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  130339. ){
  130340. LogEst nIter;
  130341. pNew->u.btree.nEq++;
  130342. pNew->nSkip++;
  130343. pNew->aLTerm[pNew->nLTerm++] = 0;
  130344. pNew->wsFlags |= WHERE_SKIPSCAN;
  130345. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  130346. pNew->nOut -= nIter;
  130347. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  130348. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  130349. nIter += 5;
  130350. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  130351. pNew->nOut = saved_nOut;
  130352. pNew->u.btree.nEq = saved_nEq;
  130353. pNew->nSkip = saved_nSkip;
  130354. pNew->wsFlags = saved_wsFlags;
  130355. }
  130356. WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
  130357. pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
  130358. return rc;
  130359. }
  130360. /*
  130361. ** Return True if it is possible that pIndex might be useful in
  130362. ** implementing the ORDER BY clause in pBuilder.
  130363. **
  130364. ** Return False if pBuilder does not contain an ORDER BY clause or
  130365. ** if there is no way for pIndex to be useful in implementing that
  130366. ** ORDER BY clause.
  130367. */
  130368. static int indexMightHelpWithOrderBy(
  130369. WhereLoopBuilder *pBuilder,
  130370. Index *pIndex,
  130371. int iCursor
  130372. ){
  130373. ExprList *pOB;
  130374. ExprList *aColExpr;
  130375. int ii, jj;
  130376. if( pIndex->bUnordered ) return 0;
  130377. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  130378. for(ii=0; ii<pOB->nExpr; ii++){
  130379. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  130380. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  130381. if( pExpr->iColumn<0 ) return 1;
  130382. for(jj=0; jj<pIndex->nKeyCol; jj++){
  130383. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  130384. }
  130385. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  130386. for(jj=0; jj<pIndex->nKeyCol; jj++){
  130387. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  130388. if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  130389. return 1;
  130390. }
  130391. }
  130392. }
  130393. }
  130394. return 0;
  130395. }
  130396. /*
  130397. ** Return a bitmask where 1s indicate that the corresponding column of
  130398. ** the table is used by an index. Only the first 63 columns are considered.
  130399. */
  130400. static Bitmask columnsInIndex(Index *pIdx){
  130401. Bitmask m = 0;
  130402. int j;
  130403. for(j=pIdx->nColumn-1; j>=0; j--){
  130404. int x = pIdx->aiColumn[j];
  130405. if( x>=0 ){
  130406. testcase( x==BMS-1 );
  130407. testcase( x==BMS-2 );
  130408. if( x<BMS-1 ) m |= MASKBIT(x);
  130409. }
  130410. }
  130411. return m;
  130412. }
  130413. /* Check to see if a partial index with pPartIndexWhere can be used
  130414. ** in the current query. Return true if it can be and false if not.
  130415. */
  130416. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  130417. int i;
  130418. WhereTerm *pTerm;
  130419. Parse *pParse = pWC->pWInfo->pParse;
  130420. while( pWhere->op==TK_AND ){
  130421. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  130422. pWhere = pWhere->pRight;
  130423. }
  130424. if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
  130425. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  130426. Expr *pExpr = pTerm->pExpr;
  130427. if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  130428. && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
  130429. ){
  130430. return 1;
  130431. }
  130432. }
  130433. return 0;
  130434. }
  130435. /*
  130436. ** Add all WhereLoop objects for a single table of the join where the table
  130437. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  130438. ** a b-tree table, not a virtual table.
  130439. **
  130440. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  130441. ** are calculated as follows:
  130442. **
  130443. ** For a full scan, assuming the table (or index) contains nRow rows:
  130444. **
  130445. ** cost = nRow * 3.0 // full-table scan
  130446. ** cost = nRow * K // scan of covering index
  130447. ** cost = nRow * (K+3.0) // scan of non-covering index
  130448. **
  130449. ** where K is a value between 1.1 and 3.0 set based on the relative
  130450. ** estimated average size of the index and table records.
  130451. **
  130452. ** For an index scan, where nVisit is the number of index rows visited
  130453. ** by the scan, and nSeek is the number of seek operations required on
  130454. ** the index b-tree:
  130455. **
  130456. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  130457. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  130458. **
  130459. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  130460. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  130461. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  130462. **
  130463. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  130464. ** of uncertainty. For this reason, scoring is designed to pick plans that
  130465. ** "do the least harm" if the estimates are inaccurate. For example, a
  130466. ** log(nRow) factor is omitted from a non-covering index scan in order to
  130467. ** bias the scoring in favor of using an index, since the worst-case
  130468. ** performance of using an index is far better than the worst-case performance
  130469. ** of a full table scan.
  130470. */
  130471. static int whereLoopAddBtree(
  130472. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  130473. Bitmask mPrereq /* Extra prerequesites for using this table */
  130474. ){
  130475. WhereInfo *pWInfo; /* WHERE analysis context */
  130476. Index *pProbe; /* An index we are evaluating */
  130477. Index sPk; /* A fake index object for the primary key */
  130478. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  130479. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  130480. SrcList *pTabList; /* The FROM clause */
  130481. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  130482. WhereLoop *pNew; /* Template WhereLoop object */
  130483. int rc = SQLITE_OK; /* Return code */
  130484. int iSortIdx = 1; /* Index number */
  130485. int b; /* A boolean value */
  130486. LogEst rSize; /* number of rows in the table */
  130487. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  130488. WhereClause *pWC; /* The parsed WHERE clause */
  130489. Table *pTab; /* Table being queried */
  130490. pNew = pBuilder->pNew;
  130491. pWInfo = pBuilder->pWInfo;
  130492. pTabList = pWInfo->pTabList;
  130493. pSrc = pTabList->a + pNew->iTab;
  130494. pTab = pSrc->pTab;
  130495. pWC = pBuilder->pWC;
  130496. assert( !IsVirtual(pSrc->pTab) );
  130497. if( pSrc->pIBIndex ){
  130498. /* An INDEXED BY clause specifies a particular index to use */
  130499. pProbe = pSrc->pIBIndex;
  130500. }else if( !HasRowid(pTab) ){
  130501. pProbe = pTab->pIndex;
  130502. }else{
  130503. /* There is no INDEXED BY clause. Create a fake Index object in local
  130504. ** variable sPk to represent the rowid primary key index. Make this
  130505. ** fake index the first in a chain of Index objects with all of the real
  130506. ** indices to follow */
  130507. Index *pFirst; /* First of real indices on the table */
  130508. memset(&sPk, 0, sizeof(Index));
  130509. sPk.nKeyCol = 1;
  130510. sPk.nColumn = 1;
  130511. sPk.aiColumn = &aiColumnPk;
  130512. sPk.aiRowLogEst = aiRowEstPk;
  130513. sPk.onError = OE_Replace;
  130514. sPk.pTable = pTab;
  130515. sPk.szIdxRow = pTab->szTabRow;
  130516. aiRowEstPk[0] = pTab->nRowLogEst;
  130517. aiRowEstPk[1] = 0;
  130518. pFirst = pSrc->pTab->pIndex;
  130519. if( pSrc->fg.notIndexed==0 ){
  130520. /* The real indices of the table are only considered if the
  130521. ** NOT INDEXED qualifier is omitted from the FROM clause */
  130522. sPk.pNext = pFirst;
  130523. }
  130524. pProbe = &sPk;
  130525. }
  130526. rSize = pTab->nRowLogEst;
  130527. rLogSize = estLog(rSize);
  130528. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  130529. /* Automatic indexes */
  130530. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  130531. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  130532. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  130533. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  130534. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  130535. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  130536. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  130537. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  130538. ){
  130539. /* Generate auto-index WhereLoops */
  130540. WhereTerm *pTerm;
  130541. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  130542. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  130543. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  130544. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  130545. pNew->u.btree.nEq = 1;
  130546. pNew->nSkip = 0;
  130547. pNew->u.btree.pIndex = 0;
  130548. pNew->nLTerm = 1;
  130549. pNew->aLTerm[0] = pTerm;
  130550. /* TUNING: One-time cost for computing the automatic index is
  130551. ** estimated to be X*N*log2(N) where N is the number of rows in
  130552. ** the table being indexed and where X is 7 (LogEst=28) for normal
  130553. ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
  130554. ** of X is smaller for views and subqueries so that the query planner
  130555. ** will be more aggressive about generating automatic indexes for
  130556. ** those objects, since there is no opportunity to add schema
  130557. ** indexes on subqueries and views. */
  130558. pNew->rSetup = rLogSize + rSize;
  130559. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  130560. pNew->rSetup += 28;
  130561. }else{
  130562. pNew->rSetup -= 10;
  130563. }
  130564. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  130565. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  130566. /* TUNING: Each index lookup yields 20 rows in the table. This
  130567. ** is more than the usual guess of 10 rows, since we have no way
  130568. ** of knowing how selective the index will ultimately be. It would
  130569. ** not be unreasonable to make this value much larger. */
  130570. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  130571. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  130572. pNew->wsFlags = WHERE_AUTO_INDEX;
  130573. pNew->prereq = mPrereq | pTerm->prereqRight;
  130574. rc = whereLoopInsert(pBuilder, pNew);
  130575. }
  130576. }
  130577. }
  130578. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  130579. /* Loop over all indices. If there was an INDEXED BY clause, then only
  130580. ** consider index pProbe. */
  130581. for(; rc==SQLITE_OK && pProbe;
  130582. pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
  130583. ){
  130584. if( pProbe->pPartIdxWhere!=0
  130585. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  130586. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  130587. continue; /* Partial index inappropriate for this query */
  130588. }
  130589. if( pProbe->bNoQuery ) continue;
  130590. rSize = pProbe->aiRowLogEst[0];
  130591. pNew->u.btree.nEq = 0;
  130592. pNew->u.btree.nBtm = 0;
  130593. pNew->u.btree.nTop = 0;
  130594. pNew->nSkip = 0;
  130595. pNew->nLTerm = 0;
  130596. pNew->iSortIdx = 0;
  130597. pNew->rSetup = 0;
  130598. pNew->prereq = mPrereq;
  130599. pNew->nOut = rSize;
  130600. pNew->u.btree.pIndex = pProbe;
  130601. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  130602. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  130603. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  130604. if( pProbe->tnum<=0 ){
  130605. /* Integer primary key index */
  130606. pNew->wsFlags = WHERE_IPK;
  130607. /* Full table scan */
  130608. pNew->iSortIdx = b ? iSortIdx : 0;
  130609. /* TUNING: Cost of full table scan is (N*3.0). */
  130610. pNew->rRun = rSize + 16;
  130611. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  130612. whereLoopOutputAdjust(pWC, pNew, rSize);
  130613. rc = whereLoopInsert(pBuilder, pNew);
  130614. pNew->nOut = rSize;
  130615. if( rc ) break;
  130616. }else{
  130617. Bitmask m;
  130618. if( pProbe->isCovering ){
  130619. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  130620. m = 0;
  130621. }else{
  130622. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  130623. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  130624. }
  130625. /* Full scan via index */
  130626. if( b
  130627. || !HasRowid(pTab)
  130628. || pProbe->pPartIdxWhere!=0
  130629. || ( m==0
  130630. && pProbe->bUnordered==0
  130631. && (pProbe->szIdxRow<pTab->szTabRow)
  130632. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  130633. && sqlite3GlobalConfig.bUseCis
  130634. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  130635. )
  130636. ){
  130637. pNew->iSortIdx = b ? iSortIdx : 0;
  130638. /* The cost of visiting the index rows is N*K, where K is
  130639. ** between 1.1 and 3.0, depending on the relative sizes of the
  130640. ** index and table rows. */
  130641. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  130642. if( m!=0 ){
  130643. /* If this is a non-covering index scan, add in the cost of
  130644. ** doing table lookups. The cost will be 3x the number of
  130645. ** lookups. Take into account WHERE clause terms that can be
  130646. ** satisfied using just the index, and that do not require a
  130647. ** table lookup. */
  130648. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  130649. int ii;
  130650. int iCur = pSrc->iCursor;
  130651. WhereClause *pWC2 = &pWInfo->sWC;
  130652. for(ii=0; ii<pWC2->nTerm; ii++){
  130653. WhereTerm *pTerm = &pWC2->a[ii];
  130654. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  130655. break;
  130656. }
  130657. /* pTerm can be evaluated using just the index. So reduce
  130658. ** the expected number of table lookups accordingly */
  130659. if( pTerm->truthProb<=0 ){
  130660. nLookup += pTerm->truthProb;
  130661. }else{
  130662. nLookup--;
  130663. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  130664. }
  130665. }
  130666. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  130667. }
  130668. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  130669. whereLoopOutputAdjust(pWC, pNew, rSize);
  130670. rc = whereLoopInsert(pBuilder, pNew);
  130671. pNew->nOut = rSize;
  130672. if( rc ) break;
  130673. }
  130674. }
  130675. pBuilder->bldFlags = 0;
  130676. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  130677. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  130678. /* If a non-unique index is used, or if a prefix of the key for
  130679. ** unique index is used (making the index functionally non-unique)
  130680. ** then the sqlite_stat1 data becomes important for scoring the
  130681. ** plan */
  130682. pTab->tabFlags |= TF_StatsUsed;
  130683. }
  130684. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  130685. sqlite3Stat4ProbeFree(pBuilder->pRec);
  130686. pBuilder->nRecValid = 0;
  130687. pBuilder->pRec = 0;
  130688. #endif
  130689. }
  130690. return rc;
  130691. }
  130692. #ifndef SQLITE_OMIT_VIRTUALTABLE
  130693. /*
  130694. ** Argument pIdxInfo is already populated with all constraints that may
  130695. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  130696. ** function marks a subset of those constraints usable, invokes the
  130697. ** xBestIndex method and adds the returned plan to pBuilder.
  130698. **
  130699. ** A constraint is marked usable if:
  130700. **
  130701. ** * Argument mUsable indicates that its prerequisites are available, and
  130702. **
  130703. ** * It is not one of the operators specified in the mExclude mask passed
  130704. ** as the fourth argument (which in practice is either WO_IN or 0).
  130705. **
  130706. ** Argument mPrereq is a mask of tables that must be scanned before the
  130707. ** virtual table in question. These are added to the plans prerequisites
  130708. ** before it is added to pBuilder.
  130709. **
  130710. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  130711. ** uses one or more WO_IN terms, or false otherwise.
  130712. */
  130713. static int whereLoopAddVirtualOne(
  130714. WhereLoopBuilder *pBuilder,
  130715. Bitmask mPrereq, /* Mask of tables that must be used. */
  130716. Bitmask mUsable, /* Mask of usable tables */
  130717. u16 mExclude, /* Exclude terms using these operators */
  130718. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  130719. u16 mNoOmit, /* Do not omit these constraints */
  130720. int *pbIn /* OUT: True if plan uses an IN(...) op */
  130721. ){
  130722. WhereClause *pWC = pBuilder->pWC;
  130723. struct sqlite3_index_constraint *pIdxCons;
  130724. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  130725. int i;
  130726. int mxTerm;
  130727. int rc = SQLITE_OK;
  130728. WhereLoop *pNew = pBuilder->pNew;
  130729. Parse *pParse = pBuilder->pWInfo->pParse;
  130730. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  130731. int nConstraint = pIdxInfo->nConstraint;
  130732. assert( (mUsable & mPrereq)==mPrereq );
  130733. *pbIn = 0;
  130734. pNew->prereq = mPrereq;
  130735. /* Set the usable flag on the subset of constraints identified by
  130736. ** arguments mUsable and mExclude. */
  130737. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  130738. for(i=0; i<nConstraint; i++, pIdxCons++){
  130739. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  130740. pIdxCons->usable = 0;
  130741. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  130742. && (pTerm->eOperator & mExclude)==0
  130743. ){
  130744. pIdxCons->usable = 1;
  130745. }
  130746. }
  130747. /* Initialize the output fields of the sqlite3_index_info structure */
  130748. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  130749. assert( pIdxInfo->needToFreeIdxStr==0 );
  130750. pIdxInfo->idxStr = 0;
  130751. pIdxInfo->idxNum = 0;
  130752. pIdxInfo->orderByConsumed = 0;
  130753. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  130754. pIdxInfo->estimatedRows = 25;
  130755. pIdxInfo->idxFlags = 0;
  130756. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  130757. /* Invoke the virtual table xBestIndex() method */
  130758. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  130759. if( rc ) return rc;
  130760. mxTerm = -1;
  130761. assert( pNew->nLSlot>=nConstraint );
  130762. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  130763. pNew->u.vtab.omitMask = 0;
  130764. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  130765. for(i=0; i<nConstraint; i++, pIdxCons++){
  130766. int iTerm;
  130767. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  130768. WhereTerm *pTerm;
  130769. int j = pIdxCons->iTermOffset;
  130770. if( iTerm>=nConstraint
  130771. || j<0
  130772. || j>=pWC->nTerm
  130773. || pNew->aLTerm[iTerm]!=0
  130774. || pIdxCons->usable==0
  130775. ){
  130776. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  130777. testcase( pIdxInfo->needToFreeIdxStr );
  130778. return SQLITE_ERROR;
  130779. }
  130780. testcase( iTerm==nConstraint-1 );
  130781. testcase( j==0 );
  130782. testcase( j==pWC->nTerm-1 );
  130783. pTerm = &pWC->a[j];
  130784. pNew->prereq |= pTerm->prereqRight;
  130785. assert( iTerm<pNew->nLSlot );
  130786. pNew->aLTerm[iTerm] = pTerm;
  130787. if( iTerm>mxTerm ) mxTerm = iTerm;
  130788. testcase( iTerm==15 );
  130789. testcase( iTerm==16 );
  130790. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  130791. if( (pTerm->eOperator & WO_IN)!=0 ){
  130792. /* A virtual table that is constrained by an IN clause may not
  130793. ** consume the ORDER BY clause because (1) the order of IN terms
  130794. ** is not necessarily related to the order of output terms and
  130795. ** (2) Multiple outputs from a single IN value will not merge
  130796. ** together. */
  130797. pIdxInfo->orderByConsumed = 0;
  130798. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  130799. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  130800. }
  130801. }
  130802. }
  130803. pNew->u.vtab.omitMask &= ~mNoOmit;
  130804. pNew->nLTerm = mxTerm+1;
  130805. for(i=0; i<=mxTerm; i++){
  130806. if( pNew->aLTerm[i]==0 ){
  130807. /* The non-zero argvIdx values must be contiguous. Raise an
  130808. ** error if they are not */
  130809. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  130810. testcase( pIdxInfo->needToFreeIdxStr );
  130811. return SQLITE_ERROR;
  130812. }
  130813. }
  130814. assert( pNew->nLTerm<=pNew->nLSlot );
  130815. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  130816. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  130817. pIdxInfo->needToFreeIdxStr = 0;
  130818. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  130819. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  130820. pIdxInfo->nOrderBy : 0);
  130821. pNew->rSetup = 0;
  130822. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  130823. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  130824. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  130825. ** that the scan will visit at most one row. Clear it otherwise. */
  130826. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  130827. pNew->wsFlags |= WHERE_ONEROW;
  130828. }else{
  130829. pNew->wsFlags &= ~WHERE_ONEROW;
  130830. }
  130831. rc = whereLoopInsert(pBuilder, pNew);
  130832. if( pNew->u.vtab.needFree ){
  130833. sqlite3_free(pNew->u.vtab.idxStr);
  130834. pNew->u.vtab.needFree = 0;
  130835. }
  130836. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  130837. *pbIn, (sqlite3_uint64)mPrereq,
  130838. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  130839. return rc;
  130840. }
  130841. /*
  130842. ** If this function is invoked from within an xBestIndex() callback, it
  130843. ** returns a pointer to a buffer containing the name of the collation
  130844. ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
  130845. ** array. Or, if iCons is out of range or there is no active xBestIndex
  130846. ** call, return NULL.
  130847. */
  130848. SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  130849. HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  130850. const char *zRet = 0;
  130851. if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
  130852. CollSeq *pC = 0;
  130853. int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
  130854. Expr *pX = pHidden->pWC->a[iTerm].pExpr;
  130855. if( pX->pLeft ){
  130856. pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
  130857. }
  130858. zRet = (pC ? pC->zName : "BINARY");
  130859. }
  130860. return zRet;
  130861. }
  130862. /*
  130863. ** Add all WhereLoop objects for a table of the join identified by
  130864. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  130865. **
  130866. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  130867. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  130868. ** entries that occur before the virtual table in the FROM clause and are
  130869. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  130870. ** mUnusable mask contains all FROM clause entries that occur after the
  130871. ** virtual table and are separated from it by at least one LEFT or
  130872. ** CROSS JOIN.
  130873. **
  130874. ** For example, if the query were:
  130875. **
  130876. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  130877. **
  130878. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  130879. **
  130880. ** All the tables in mPrereq must be scanned before the current virtual
  130881. ** table. So any terms for which all prerequisites are satisfied by
  130882. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  130883. ** Conversely, all tables in mUnusable must be scanned after the current
  130884. ** virtual table, so any terms for which the prerequisites overlap with
  130885. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  130886. */
  130887. static int whereLoopAddVirtual(
  130888. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  130889. Bitmask mPrereq, /* Tables that must be scanned before this one */
  130890. Bitmask mUnusable /* Tables that must be scanned after this one */
  130891. ){
  130892. int rc = SQLITE_OK; /* Return code */
  130893. WhereInfo *pWInfo; /* WHERE analysis context */
  130894. Parse *pParse; /* The parsing context */
  130895. WhereClause *pWC; /* The WHERE clause */
  130896. struct SrcList_item *pSrc; /* The FROM clause term to search */
  130897. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  130898. int nConstraint; /* Number of constraints in p */
  130899. int bIn; /* True if plan uses IN(...) operator */
  130900. WhereLoop *pNew;
  130901. Bitmask mBest; /* Tables used by best possible plan */
  130902. u16 mNoOmit;
  130903. assert( (mPrereq & mUnusable)==0 );
  130904. pWInfo = pBuilder->pWInfo;
  130905. pParse = pWInfo->pParse;
  130906. pWC = pBuilder->pWC;
  130907. pNew = pBuilder->pNew;
  130908. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  130909. assert( IsVirtual(pSrc->pTab) );
  130910. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  130911. &mNoOmit);
  130912. if( p==0 ) return SQLITE_NOMEM_BKPT;
  130913. pNew->rSetup = 0;
  130914. pNew->wsFlags = WHERE_VIRTUALTABLE;
  130915. pNew->nLTerm = 0;
  130916. pNew->u.vtab.needFree = 0;
  130917. nConstraint = p->nConstraint;
  130918. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  130919. sqlite3DbFree(pParse->db, p);
  130920. return SQLITE_NOMEM_BKPT;
  130921. }
  130922. /* First call xBestIndex() with all constraints usable. */
  130923. WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
  130924. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  130925. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  130926. /* If the call to xBestIndex() with all terms enabled produced a plan
  130927. ** that does not require any source tables (IOW: a plan with mBest==0),
  130928. ** then there is no point in making any further calls to xBestIndex()
  130929. ** since they will all return the same result (if the xBestIndex()
  130930. ** implementation is sane). */
  130931. if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
  130932. int seenZero = 0; /* True if a plan with no prereqs seen */
  130933. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  130934. Bitmask mPrev = 0;
  130935. Bitmask mBestNoIn = 0;
  130936. /* If the plan produced by the earlier call uses an IN(...) term, call
  130937. ** xBestIndex again, this time with IN(...) terms disabled. */
  130938. if( bIn ){
  130939. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  130940. rc = whereLoopAddVirtualOne(
  130941. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  130942. assert( bIn==0 );
  130943. mBestNoIn = pNew->prereq & ~mPrereq;
  130944. if( mBestNoIn==0 ){
  130945. seenZero = 1;
  130946. seenZeroNoIN = 1;
  130947. }
  130948. }
  130949. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  130950. ** in the set of terms that apply to the current virtual table. */
  130951. while( rc==SQLITE_OK ){
  130952. int i;
  130953. Bitmask mNext = ALLBITS;
  130954. assert( mNext>0 );
  130955. for(i=0; i<nConstraint; i++){
  130956. Bitmask mThis = (
  130957. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  130958. );
  130959. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  130960. }
  130961. mPrev = mNext;
  130962. if( mNext==ALLBITS ) break;
  130963. if( mNext==mBest || mNext==mBestNoIn ) continue;
  130964. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  130965. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  130966. rc = whereLoopAddVirtualOne(
  130967. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  130968. if( pNew->prereq==mPrereq ){
  130969. seenZero = 1;
  130970. if( bIn==0 ) seenZeroNoIN = 1;
  130971. }
  130972. }
  130973. /* If the calls to xBestIndex() in the above loop did not find a plan
  130974. ** that requires no source tables at all (i.e. one guaranteed to be
  130975. ** usable), make a call here with all source tables disabled */
  130976. if( rc==SQLITE_OK && seenZero==0 ){
  130977. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  130978. rc = whereLoopAddVirtualOne(
  130979. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  130980. if( bIn==0 ) seenZeroNoIN = 1;
  130981. }
  130982. /* If the calls to xBestIndex() have so far failed to find a plan
  130983. ** that requires no source tables at all and does not use an IN(...)
  130984. ** operator, make a final call to obtain one here. */
  130985. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  130986. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  130987. rc = whereLoopAddVirtualOne(
  130988. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  130989. }
  130990. }
  130991. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  130992. sqlite3DbFreeNN(pParse->db, p);
  130993. WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  130994. return rc;
  130995. }
  130996. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  130997. /*
  130998. ** Add WhereLoop entries to handle OR terms. This works for either
  130999. ** btrees or virtual tables.
  131000. */
  131001. static int whereLoopAddOr(
  131002. WhereLoopBuilder *pBuilder,
  131003. Bitmask mPrereq,
  131004. Bitmask mUnusable
  131005. ){
  131006. WhereInfo *pWInfo = pBuilder->pWInfo;
  131007. WhereClause *pWC;
  131008. WhereLoop *pNew;
  131009. WhereTerm *pTerm, *pWCEnd;
  131010. int rc = SQLITE_OK;
  131011. int iCur;
  131012. WhereClause tempWC;
  131013. WhereLoopBuilder sSubBuild;
  131014. WhereOrSet sSum, sCur;
  131015. struct SrcList_item *pItem;
  131016. pWC = pBuilder->pWC;
  131017. pWCEnd = pWC->a + pWC->nTerm;
  131018. pNew = pBuilder->pNew;
  131019. memset(&sSum, 0, sizeof(sSum));
  131020. pItem = pWInfo->pTabList->a + pNew->iTab;
  131021. iCur = pItem->iCursor;
  131022. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  131023. if( (pTerm->eOperator & WO_OR)!=0
  131024. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  131025. ){
  131026. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  131027. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  131028. WhereTerm *pOrTerm;
  131029. int once = 1;
  131030. int i, j;
  131031. sSubBuild = *pBuilder;
  131032. sSubBuild.pOrderBy = 0;
  131033. sSubBuild.pOrSet = &sCur;
  131034. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  131035. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  131036. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  131037. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  131038. }else if( pOrTerm->leftCursor==iCur ){
  131039. tempWC.pWInfo = pWC->pWInfo;
  131040. tempWC.pOuter = pWC;
  131041. tempWC.op = TK_AND;
  131042. tempWC.nTerm = 1;
  131043. tempWC.a = pOrTerm;
  131044. sSubBuild.pWC = &tempWC;
  131045. }else{
  131046. continue;
  131047. }
  131048. sCur.n = 0;
  131049. #ifdef WHERETRACE_ENABLED
  131050. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  131051. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  131052. if( sqlite3WhereTrace & 0x400 ){
  131053. sqlite3WhereClausePrint(sSubBuild.pWC);
  131054. }
  131055. #endif
  131056. #ifndef SQLITE_OMIT_VIRTUALTABLE
  131057. if( IsVirtual(pItem->pTab) ){
  131058. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  131059. }else
  131060. #endif
  131061. {
  131062. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  131063. }
  131064. if( rc==SQLITE_OK ){
  131065. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  131066. }
  131067. assert( rc==SQLITE_OK || sCur.n==0 );
  131068. if( sCur.n==0 ){
  131069. sSum.n = 0;
  131070. break;
  131071. }else if( once ){
  131072. whereOrMove(&sSum, &sCur);
  131073. once = 0;
  131074. }else{
  131075. WhereOrSet sPrev;
  131076. whereOrMove(&sPrev, &sSum);
  131077. sSum.n = 0;
  131078. for(i=0; i<sPrev.n; i++){
  131079. for(j=0; j<sCur.n; j++){
  131080. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  131081. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  131082. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  131083. }
  131084. }
  131085. }
  131086. }
  131087. pNew->nLTerm = 1;
  131088. pNew->aLTerm[0] = pTerm;
  131089. pNew->wsFlags = WHERE_MULTI_OR;
  131090. pNew->rSetup = 0;
  131091. pNew->iSortIdx = 0;
  131092. memset(&pNew->u, 0, sizeof(pNew->u));
  131093. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  131094. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  131095. ** of all sub-scans required by the OR-scan. However, due to rounding
  131096. ** errors, it may be that the cost of the OR-scan is equal to its
  131097. ** most expensive sub-scan. Add the smallest possible penalty
  131098. ** (equivalent to multiplying the cost by 1.07) to ensure that
  131099. ** this does not happen. Otherwise, for WHERE clauses such as the
  131100. ** following where there is an index on "y":
  131101. **
  131102. ** WHERE likelihood(x=?, 0.99) OR y=?
  131103. **
  131104. ** the planner may elect to "OR" together a full-table scan and an
  131105. ** index lookup. And other similarly odd results. */
  131106. pNew->rRun = sSum.a[i].rRun + 1;
  131107. pNew->nOut = sSum.a[i].nOut;
  131108. pNew->prereq = sSum.a[i].prereq;
  131109. rc = whereLoopInsert(pBuilder, pNew);
  131110. }
  131111. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  131112. }
  131113. }
  131114. return rc;
  131115. }
  131116. /*
  131117. ** Add all WhereLoop objects for all tables
  131118. */
  131119. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  131120. WhereInfo *pWInfo = pBuilder->pWInfo;
  131121. Bitmask mPrereq = 0;
  131122. Bitmask mPrior = 0;
  131123. int iTab;
  131124. SrcList *pTabList = pWInfo->pTabList;
  131125. struct SrcList_item *pItem;
  131126. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  131127. sqlite3 *db = pWInfo->pParse->db;
  131128. int rc = SQLITE_OK;
  131129. WhereLoop *pNew;
  131130. u8 priorJointype = 0;
  131131. /* Loop over the tables in the join, from left to right */
  131132. pNew = pBuilder->pNew;
  131133. whereLoopInit(pNew);
  131134. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  131135. Bitmask mUnusable = 0;
  131136. pNew->iTab = iTab;
  131137. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  131138. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  131139. /* This condition is true when pItem is the FROM clause term on the
  131140. ** right-hand-side of a LEFT or CROSS JOIN. */
  131141. mPrereq = mPrior;
  131142. }
  131143. priorJointype = pItem->fg.jointype;
  131144. #ifndef SQLITE_OMIT_VIRTUALTABLE
  131145. if( IsVirtual(pItem->pTab) ){
  131146. struct SrcList_item *p;
  131147. for(p=&pItem[1]; p<pEnd; p++){
  131148. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  131149. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  131150. }
  131151. }
  131152. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  131153. }else
  131154. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  131155. {
  131156. rc = whereLoopAddBtree(pBuilder, mPrereq);
  131157. }
  131158. if( rc==SQLITE_OK ){
  131159. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  131160. }
  131161. mPrior |= pNew->maskSelf;
  131162. if( rc || db->mallocFailed ) break;
  131163. }
  131164. whereLoopClear(db, pNew);
  131165. return rc;
  131166. }
  131167. /*
  131168. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  131169. ** parameters) to see if it outputs rows in the requested ORDER BY
  131170. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  131171. **
  131172. ** N>0: N terms of the ORDER BY clause are satisfied
  131173. ** N==0: No terms of the ORDER BY clause are satisfied
  131174. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  131175. **
  131176. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  131177. ** strict. With GROUP BY and DISTINCT the only requirement is that
  131178. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  131179. ** and DISTINCT do not require rows to appear in any particular order as long
  131180. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  131181. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  131182. ** pOrderBy terms must be matched in strict left-to-right order.
  131183. */
  131184. static i8 wherePathSatisfiesOrderBy(
  131185. WhereInfo *pWInfo, /* The WHERE clause */
  131186. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  131187. WherePath *pPath, /* The WherePath to check */
  131188. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  131189. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  131190. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  131191. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  131192. ){
  131193. u8 revSet; /* True if rev is known */
  131194. u8 rev; /* Composite sort order */
  131195. u8 revIdx; /* Index sort order */
  131196. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  131197. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  131198. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  131199. u16 eqOpMask; /* Allowed equality operators */
  131200. u16 nKeyCol; /* Number of key columns in pIndex */
  131201. u16 nColumn; /* Total number of ordered columns in the index */
  131202. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  131203. int iLoop; /* Index of WhereLoop in pPath being processed */
  131204. int i, j; /* Loop counters */
  131205. int iCur; /* Cursor number for current WhereLoop */
  131206. int iColumn; /* A column number within table iCur */
  131207. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  131208. WhereTerm *pTerm; /* A single term of the WHERE clause */
  131209. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  131210. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  131211. Index *pIndex; /* The index associated with pLoop */
  131212. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  131213. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  131214. Bitmask obDone; /* Mask of all ORDER BY terms */
  131215. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  131216. Bitmask ready; /* Mask of inner loops */
  131217. /*
  131218. ** We say the WhereLoop is "one-row" if it generates no more than one
  131219. ** row of output. A WhereLoop is one-row if all of the following are true:
  131220. ** (a) All index columns match with WHERE_COLUMN_EQ.
  131221. ** (b) The index is unique
  131222. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  131223. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  131224. **
  131225. ** We say the WhereLoop is "order-distinct" if the set of columns from
  131226. ** that WhereLoop that are in the ORDER BY clause are different for every
  131227. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  131228. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  131229. ** is not order-distinct. To be order-distinct is not quite the same as being
  131230. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  131231. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  131232. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  131233. **
  131234. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  131235. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  131236. ** automatically order-distinct.
  131237. */
  131238. assert( pOrderBy!=0 );
  131239. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  131240. nOrderBy = pOrderBy->nExpr;
  131241. testcase( nOrderBy==BMS-1 );
  131242. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  131243. isOrderDistinct = 1;
  131244. obDone = MASKBIT(nOrderBy)-1;
  131245. orderDistinctMask = 0;
  131246. ready = 0;
  131247. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  131248. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  131249. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  131250. if( iLoop>0 ) ready |= pLoop->maskSelf;
  131251. if( iLoop<nLoop ){
  131252. pLoop = pPath->aLoop[iLoop];
  131253. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  131254. }else{
  131255. pLoop = pLast;
  131256. }
  131257. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  131258. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  131259. break;
  131260. }else{
  131261. pLoop->u.btree.nIdxCol = 0;
  131262. }
  131263. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  131264. /* Mark off any ORDER BY term X that is a column in the table of
  131265. ** the current loop for which there is term in the WHERE
  131266. ** clause of the form X IS NULL or X=? that reference only outer
  131267. ** loops.
  131268. */
  131269. for(i=0; i<nOrderBy; i++){
  131270. if( MASKBIT(i) & obSat ) continue;
  131271. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  131272. if( pOBExpr->op!=TK_COLUMN ) continue;
  131273. if( pOBExpr->iTable!=iCur ) continue;
  131274. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  131275. ~ready, eqOpMask, 0);
  131276. if( pTerm==0 ) continue;
  131277. if( pTerm->eOperator==WO_IN ){
  131278. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  131279. ** optimization, and then only if they are actually used
  131280. ** by the query plan */
  131281. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  131282. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  131283. if( j>=pLoop->nLTerm ) continue;
  131284. }
  131285. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  131286. if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
  131287. pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
  131288. continue;
  131289. }
  131290. testcase( pTerm->pExpr->op==TK_IS );
  131291. }
  131292. obSat |= MASKBIT(i);
  131293. }
  131294. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  131295. if( pLoop->wsFlags & WHERE_IPK ){
  131296. pIndex = 0;
  131297. nKeyCol = 0;
  131298. nColumn = 1;
  131299. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  131300. return 0;
  131301. }else{
  131302. nKeyCol = pIndex->nKeyCol;
  131303. nColumn = pIndex->nColumn;
  131304. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  131305. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  131306. || !HasRowid(pIndex->pTable));
  131307. isOrderDistinct = IsUniqueIndex(pIndex);
  131308. }
  131309. /* Loop through all columns of the index and deal with the ones
  131310. ** that are not constrained by == or IN.
  131311. */
  131312. rev = revSet = 0;
  131313. distinctColumns = 0;
  131314. for(j=0; j<nColumn; j++){
  131315. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  131316. assert( j>=pLoop->u.btree.nEq
  131317. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  131318. );
  131319. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  131320. u16 eOp = pLoop->aLTerm[j]->eOperator;
  131321. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  131322. ** doing WHERE_ORDERBY_LIMIT processing).
  131323. **
  131324. ** If the current term is a column of an ((?,?) IN (SELECT...))
  131325. ** expression for which the SELECT returns more than one column,
  131326. ** check that it is the only column used by this loop. Otherwise,
  131327. ** if it is one of two or more, none of the columns can be
  131328. ** considered to match an ORDER BY term. */
  131329. if( (eOp & eqOpMask)!=0 ){
  131330. if( eOp & WO_ISNULL ){
  131331. testcase( isOrderDistinct );
  131332. isOrderDistinct = 0;
  131333. }
  131334. continue;
  131335. }else if( ALWAYS(eOp & WO_IN) ){
  131336. /* ALWAYS() justification: eOp is an equality operator due to the
  131337. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  131338. ** than WO_IN is captured by the previous "if". So this one
  131339. ** always has to be WO_IN. */
  131340. Expr *pX = pLoop->aLTerm[j]->pExpr;
  131341. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  131342. if( pLoop->aLTerm[i]->pExpr==pX ){
  131343. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  131344. bOnce = 0;
  131345. break;
  131346. }
  131347. }
  131348. }
  131349. }
  131350. /* Get the column number in the table (iColumn) and sort order
  131351. ** (revIdx) for the j-th column of the index.
  131352. */
  131353. if( pIndex ){
  131354. iColumn = pIndex->aiColumn[j];
  131355. revIdx = pIndex->aSortOrder[j];
  131356. if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
  131357. }else{
  131358. iColumn = XN_ROWID;
  131359. revIdx = 0;
  131360. }
  131361. /* An unconstrained column that might be NULL means that this
  131362. ** WhereLoop is not well-ordered
  131363. */
  131364. if( isOrderDistinct
  131365. && iColumn>=0
  131366. && j>=pLoop->u.btree.nEq
  131367. && pIndex->pTable->aCol[iColumn].notNull==0
  131368. ){
  131369. isOrderDistinct = 0;
  131370. }
  131371. /* Find the ORDER BY term that corresponds to the j-th column
  131372. ** of the index and mark that ORDER BY term off
  131373. */
  131374. isMatch = 0;
  131375. for(i=0; bOnce && i<nOrderBy; i++){
  131376. if( MASKBIT(i) & obSat ) continue;
  131377. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  131378. testcase( wctrlFlags & WHERE_GROUPBY );
  131379. testcase( wctrlFlags & WHERE_DISTINCTBY );
  131380. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  131381. if( iColumn>=XN_ROWID ){
  131382. if( pOBExpr->op!=TK_COLUMN ) continue;
  131383. if( pOBExpr->iTable!=iCur ) continue;
  131384. if( pOBExpr->iColumn!=iColumn ) continue;
  131385. }else{
  131386. Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
  131387. if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
  131388. continue;
  131389. }
  131390. }
  131391. if( iColumn!=XN_ROWID ){
  131392. pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  131393. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  131394. }
  131395. pLoop->u.btree.nIdxCol = j+1;
  131396. isMatch = 1;
  131397. break;
  131398. }
  131399. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  131400. /* Make sure the sort order is compatible in an ORDER BY clause.
  131401. ** Sort order is irrelevant for a GROUP BY clause. */
  131402. if( revSet ){
  131403. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  131404. }else{
  131405. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  131406. if( rev ) *pRevMask |= MASKBIT(iLoop);
  131407. revSet = 1;
  131408. }
  131409. }
  131410. if( isMatch ){
  131411. if( iColumn==XN_ROWID ){
  131412. testcase( distinctColumns==0 );
  131413. distinctColumns = 1;
  131414. }
  131415. obSat |= MASKBIT(i);
  131416. }else{
  131417. /* No match found */
  131418. if( j==0 || j<nKeyCol ){
  131419. testcase( isOrderDistinct!=0 );
  131420. isOrderDistinct = 0;
  131421. }
  131422. break;
  131423. }
  131424. } /* end Loop over all index columns */
  131425. if( distinctColumns ){
  131426. testcase( isOrderDistinct==0 );
  131427. isOrderDistinct = 1;
  131428. }
  131429. } /* end-if not one-row */
  131430. /* Mark off any other ORDER BY terms that reference pLoop */
  131431. if( isOrderDistinct ){
  131432. orderDistinctMask |= pLoop->maskSelf;
  131433. for(i=0; i<nOrderBy; i++){
  131434. Expr *p;
  131435. Bitmask mTerm;
  131436. if( MASKBIT(i) & obSat ) continue;
  131437. p = pOrderBy->a[i].pExpr;
  131438. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  131439. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  131440. if( (mTerm&~orderDistinctMask)==0 ){
  131441. obSat |= MASKBIT(i);
  131442. }
  131443. }
  131444. }
  131445. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  131446. if( obSat==obDone ) return (i8)nOrderBy;
  131447. if( !isOrderDistinct ){
  131448. for(i=nOrderBy-1; i>0; i--){
  131449. Bitmask m = MASKBIT(i) - 1;
  131450. if( (obSat&m)==m ) return i;
  131451. }
  131452. return 0;
  131453. }
  131454. return -1;
  131455. }
  131456. /*
  131457. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  131458. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  131459. ** BY clause - and so any order that groups rows as required satisfies the
  131460. ** request.
  131461. **
  131462. ** Normally, in this case it is not possible for the caller to determine
  131463. ** whether or not the rows are really being delivered in sorted order, or
  131464. ** just in some other order that provides the required grouping. However,
  131465. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  131466. ** this function may be called on the returned WhereInfo object. It returns
  131467. ** true if the rows really will be sorted in the specified order, or false
  131468. ** otherwise.
  131469. **
  131470. ** For example, assuming:
  131471. **
  131472. ** CREATE INDEX i1 ON t1(x, Y);
  131473. **
  131474. ** then
  131475. **
  131476. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  131477. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  131478. */
  131479. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  131480. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  131481. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  131482. return pWInfo->sorted;
  131483. }
  131484. #ifdef WHERETRACE_ENABLED
  131485. /* For debugging use only: */
  131486. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  131487. static char zName[65];
  131488. int i;
  131489. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  131490. if( pLast ) zName[i++] = pLast->cId;
  131491. zName[i] = 0;
  131492. return zName;
  131493. }
  131494. #endif
  131495. /*
  131496. ** Return the cost of sorting nRow rows, assuming that the keys have
  131497. ** nOrderby columns and that the first nSorted columns are already in
  131498. ** order.
  131499. */
  131500. static LogEst whereSortingCost(
  131501. WhereInfo *pWInfo,
  131502. LogEst nRow,
  131503. int nOrderBy,
  131504. int nSorted
  131505. ){
  131506. /* TUNING: Estimated cost of a full external sort, where N is
  131507. ** the number of rows to sort is:
  131508. **
  131509. ** cost = (3.0 * N * log(N)).
  131510. **
  131511. ** Or, if the order-by clause has X terms but only the last Y
  131512. ** terms are out of order, then block-sorting will reduce the
  131513. ** sorting cost to:
  131514. **
  131515. ** cost = (3.0 * N * log(N)) * (Y/X)
  131516. **
  131517. ** The (Y/X) term is implemented using stack variable rScale
  131518. ** below. */
  131519. LogEst rScale, rSortCost;
  131520. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  131521. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  131522. rSortCost = nRow + rScale + 16;
  131523. /* Multiple by log(M) where M is the number of output rows.
  131524. ** Use the LIMIT for M if it is smaller */
  131525. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  131526. nRow = pWInfo->iLimit;
  131527. }
  131528. rSortCost += estLog(nRow);
  131529. return rSortCost;
  131530. }
  131531. /*
  131532. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  131533. ** attempts to find the lowest cost path that visits each WhereLoop
  131534. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  131535. **
  131536. ** Assume that the total number of output rows that will need to be sorted
  131537. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  131538. ** costs if nRowEst==0.
  131539. **
  131540. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  131541. ** error occurs.
  131542. */
  131543. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  131544. int mxChoice; /* Maximum number of simultaneous paths tracked */
  131545. int nLoop; /* Number of terms in the join */
  131546. Parse *pParse; /* Parsing context */
  131547. sqlite3 *db; /* The database connection */
  131548. int iLoop; /* Loop counter over the terms of the join */
  131549. int ii, jj; /* Loop counters */
  131550. int mxI = 0; /* Index of next entry to replace */
  131551. int nOrderBy; /* Number of ORDER BY clause terms */
  131552. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  131553. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  131554. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  131555. WherePath *aFrom; /* All nFrom paths at the previous level */
  131556. WherePath *aTo; /* The nTo best paths at the current level */
  131557. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  131558. WherePath *pTo; /* An element of aTo[] that we are working on */
  131559. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  131560. WhereLoop **pX; /* Used to divy up the pSpace memory */
  131561. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  131562. char *pSpace; /* Temporary memory used by this routine */
  131563. int nSpace; /* Bytes of space allocated at pSpace */
  131564. pParse = pWInfo->pParse;
  131565. db = pParse->db;
  131566. nLoop = pWInfo->nLevel;
  131567. /* TUNING: For simple queries, only the best path is tracked.
  131568. ** For 2-way joins, the 5 best paths are followed.
  131569. ** For joins of 3 or more tables, track the 10 best paths */
  131570. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  131571. assert( nLoop<=pWInfo->pTabList->nSrc );
  131572. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  131573. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  131574. ** case the purpose of this call is to estimate the number of rows returned
  131575. ** by the overall query. Once this estimate has been obtained, the caller
  131576. ** will invoke this function a second time, passing the estimate as the
  131577. ** nRowEst parameter. */
  131578. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  131579. nOrderBy = 0;
  131580. }else{
  131581. nOrderBy = pWInfo->pOrderBy->nExpr;
  131582. }
  131583. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  131584. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  131585. nSpace += sizeof(LogEst) * nOrderBy;
  131586. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  131587. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  131588. aTo = (WherePath*)pSpace;
  131589. aFrom = aTo+mxChoice;
  131590. memset(aFrom, 0, sizeof(aFrom[0]));
  131591. pX = (WhereLoop**)(aFrom+mxChoice);
  131592. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  131593. pFrom->aLoop = pX;
  131594. }
  131595. if( nOrderBy ){
  131596. /* If there is an ORDER BY clause and it is not being ignored, set up
  131597. ** space for the aSortCost[] array. Each element of the aSortCost array
  131598. ** is either zero - meaning it has not yet been initialized - or the
  131599. ** cost of sorting nRowEst rows of data where the first X terms of
  131600. ** the ORDER BY clause are already in order, where X is the array
  131601. ** index. */
  131602. aSortCost = (LogEst*)pX;
  131603. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  131604. }
  131605. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  131606. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  131607. /* Seed the search with a single WherePath containing zero WhereLoops.
  131608. **
  131609. ** TUNING: Do not let the number of iterations go above 28. If the cost
  131610. ** of computing an automatic index is not paid back within the first 28
  131611. ** rows, then do not use the automatic index. */
  131612. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  131613. nFrom = 1;
  131614. assert( aFrom[0].isOrdered==0 );
  131615. if( nOrderBy ){
  131616. /* If nLoop is zero, then there are no FROM terms in the query. Since
  131617. ** in this case the query may return a maximum of one row, the results
  131618. ** are already in the requested order. Set isOrdered to nOrderBy to
  131619. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  131620. ** -1, indicating that the result set may or may not be ordered,
  131621. ** depending on the loops added to the current plan. */
  131622. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  131623. }
  131624. /* Compute successively longer WherePaths using the previous generation
  131625. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  131626. ** best paths at each generation */
  131627. for(iLoop=0; iLoop<nLoop; iLoop++){
  131628. nTo = 0;
  131629. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  131630. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  131631. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  131632. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  131633. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  131634. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  131635. Bitmask maskNew; /* Mask of src visited by (..) */
  131636. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  131637. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  131638. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  131639. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
  131640. /* Do not use an automatic index if the this loop is expected
  131641. ** to run less than 1.25 times. It is tempting to also exclude
  131642. ** automatic index usage on an outer loop, but sometimes an automatic
  131643. ** index is useful in the outer loop of a correlated subquery. */
  131644. assert( 10==sqlite3LogEst(2) );
  131645. continue;
  131646. }
  131647. /* At this point, pWLoop is a candidate to be the next loop.
  131648. ** Compute its cost */
  131649. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  131650. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  131651. nOut = pFrom->nRow + pWLoop->nOut;
  131652. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  131653. if( isOrdered<0 ){
  131654. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  131655. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  131656. iLoop, pWLoop, &revMask);
  131657. }else{
  131658. revMask = pFrom->revLoop;
  131659. }
  131660. if( isOrdered>=0 && isOrdered<nOrderBy ){
  131661. if( aSortCost[isOrdered]==0 ){
  131662. aSortCost[isOrdered] = whereSortingCost(
  131663. pWInfo, nRowEst, nOrderBy, isOrdered
  131664. );
  131665. }
  131666. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  131667. WHERETRACE(0x002,
  131668. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  131669. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  131670. rUnsorted, rCost));
  131671. }else{
  131672. rCost = rUnsorted;
  131673. rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
  131674. }
  131675. /* Check to see if pWLoop should be added to the set of
  131676. ** mxChoice best-so-far paths.
  131677. **
  131678. ** First look for an existing path among best-so-far paths
  131679. ** that covers the same set of loops and has the same isOrdered
  131680. ** setting as the current path candidate.
  131681. **
  131682. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  131683. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  131684. ** of legal values for isOrdered, -1..64.
  131685. */
  131686. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  131687. if( pTo->maskLoop==maskNew
  131688. && ((pTo->isOrdered^isOrdered)&0x80)==0
  131689. ){
  131690. testcase( jj==nTo-1 );
  131691. break;
  131692. }
  131693. }
  131694. if( jj>=nTo ){
  131695. /* None of the existing best-so-far paths match the candidate. */
  131696. if( nTo>=mxChoice
  131697. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  131698. ){
  131699. /* The current candidate is no better than any of the mxChoice
  131700. ** paths currently in the best-so-far buffer. So discard
  131701. ** this candidate as not viable. */
  131702. #ifdef WHERETRACE_ENABLED /* 0x4 */
  131703. if( sqlite3WhereTrace&0x4 ){
  131704. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
  131705. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  131706. isOrdered>=0 ? isOrdered+'0' : '?');
  131707. }
  131708. #endif
  131709. continue;
  131710. }
  131711. /* If we reach this points it means that the new candidate path
  131712. ** needs to be added to the set of best-so-far paths. */
  131713. if( nTo<mxChoice ){
  131714. /* Increase the size of the aTo set by one */
  131715. jj = nTo++;
  131716. }else{
  131717. /* New path replaces the prior worst to keep count below mxChoice */
  131718. jj = mxI;
  131719. }
  131720. pTo = &aTo[jj];
  131721. #ifdef WHERETRACE_ENABLED /* 0x4 */
  131722. if( sqlite3WhereTrace&0x4 ){
  131723. sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
  131724. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  131725. isOrdered>=0 ? isOrdered+'0' : '?');
  131726. }
  131727. #endif
  131728. }else{
  131729. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  131730. ** same set of loops and has the same isOrdered setting as the
  131731. ** candidate path. Check to see if the candidate should replace
  131732. ** pTo or if the candidate should be skipped.
  131733. **
  131734. ** The conditional is an expanded vector comparison equivalent to:
  131735. ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
  131736. */
  131737. if( pTo->rCost<rCost
  131738. || (pTo->rCost==rCost
  131739. && (pTo->nRow<nOut
  131740. || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
  131741. )
  131742. )
  131743. ){
  131744. #ifdef WHERETRACE_ENABLED /* 0x4 */
  131745. if( sqlite3WhereTrace&0x4 ){
  131746. sqlite3DebugPrintf(
  131747. "Skip %s cost=%-3d,%3d,%3d order=%c",
  131748. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  131749. isOrdered>=0 ? isOrdered+'0' : '?');
  131750. sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
  131751. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  131752. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  131753. }
  131754. #endif
  131755. /* Discard the candidate path from further consideration */
  131756. testcase( pTo->rCost==rCost );
  131757. continue;
  131758. }
  131759. testcase( pTo->rCost==rCost+1 );
  131760. /* Control reaches here if the candidate path is better than the
  131761. ** pTo path. Replace pTo with the candidate. */
  131762. #ifdef WHERETRACE_ENABLED /* 0x4 */
  131763. if( sqlite3WhereTrace&0x4 ){
  131764. sqlite3DebugPrintf(
  131765. "Update %s cost=%-3d,%3d,%3d order=%c",
  131766. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  131767. isOrdered>=0 ? isOrdered+'0' : '?');
  131768. sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
  131769. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  131770. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  131771. }
  131772. #endif
  131773. }
  131774. /* pWLoop is a winner. Add it to the set of best so far */
  131775. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  131776. pTo->revLoop = revMask;
  131777. pTo->nRow = nOut;
  131778. pTo->rCost = rCost;
  131779. pTo->rUnsorted = rUnsorted;
  131780. pTo->isOrdered = isOrdered;
  131781. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  131782. pTo->aLoop[iLoop] = pWLoop;
  131783. if( nTo>=mxChoice ){
  131784. mxI = 0;
  131785. mxCost = aTo[0].rCost;
  131786. mxUnsorted = aTo[0].nRow;
  131787. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  131788. if( pTo->rCost>mxCost
  131789. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  131790. ){
  131791. mxCost = pTo->rCost;
  131792. mxUnsorted = pTo->rUnsorted;
  131793. mxI = jj;
  131794. }
  131795. }
  131796. }
  131797. }
  131798. }
  131799. #ifdef WHERETRACE_ENABLED /* >=2 */
  131800. if( sqlite3WhereTrace & 0x02 ){
  131801. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  131802. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  131803. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  131804. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  131805. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  131806. if( pTo->isOrdered>0 ){
  131807. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  131808. }else{
  131809. sqlite3DebugPrintf("\n");
  131810. }
  131811. }
  131812. }
  131813. #endif
  131814. /* Swap the roles of aFrom and aTo for the next generation */
  131815. pFrom = aTo;
  131816. aTo = aFrom;
  131817. aFrom = pFrom;
  131818. nFrom = nTo;
  131819. }
  131820. if( nFrom==0 ){
  131821. sqlite3ErrorMsg(pParse, "no query solution");
  131822. sqlite3DbFreeNN(db, pSpace);
  131823. return SQLITE_ERROR;
  131824. }
  131825. /* Find the lowest cost path. pFrom will be left pointing to that path */
  131826. pFrom = aFrom;
  131827. for(ii=1; ii<nFrom; ii++){
  131828. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  131829. }
  131830. assert( pWInfo->nLevel==nLoop );
  131831. /* Load the lowest cost path into pWInfo */
  131832. for(iLoop=0; iLoop<nLoop; iLoop++){
  131833. WhereLevel *pLevel = pWInfo->a + iLoop;
  131834. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  131835. pLevel->iFrom = pWLoop->iTab;
  131836. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  131837. }
  131838. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  131839. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  131840. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  131841. && nRowEst
  131842. ){
  131843. Bitmask notUsed;
  131844. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  131845. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  131846. if( rc==pWInfo->pResultSet->nExpr ){
  131847. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  131848. }
  131849. }
  131850. if( pWInfo->pOrderBy ){
  131851. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  131852. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  131853. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  131854. }
  131855. }else{
  131856. pWInfo->nOBSat = pFrom->isOrdered;
  131857. pWInfo->revMask = pFrom->revLoop;
  131858. if( pWInfo->nOBSat<=0 ){
  131859. pWInfo->nOBSat = 0;
  131860. if( nLoop>0 ){
  131861. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  131862. if( (wsFlags & WHERE_ONEROW)==0
  131863. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  131864. ){
  131865. Bitmask m = 0;
  131866. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  131867. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  131868. testcase( wsFlags & WHERE_IPK );
  131869. testcase( wsFlags & WHERE_COLUMN_IN );
  131870. if( rc==pWInfo->pOrderBy->nExpr ){
  131871. pWInfo->bOrderedInnerLoop = 1;
  131872. pWInfo->revMask = m;
  131873. }
  131874. }
  131875. }
  131876. }
  131877. }
  131878. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  131879. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  131880. ){
  131881. Bitmask revMask = 0;
  131882. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  131883. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  131884. );
  131885. assert( pWInfo->sorted==0 );
  131886. if( nOrder==pWInfo->pOrderBy->nExpr ){
  131887. pWInfo->sorted = 1;
  131888. pWInfo->revMask = revMask;
  131889. }
  131890. }
  131891. }
  131892. pWInfo->nRowOut = pFrom->nRow;
  131893. /* Free temporary memory and return success */
  131894. sqlite3DbFreeNN(db, pSpace);
  131895. return SQLITE_OK;
  131896. }
  131897. /*
  131898. ** Most queries use only a single table (they are not joins) and have
  131899. ** simple == constraints against indexed fields. This routine attempts
  131900. ** to plan those simple cases using much less ceremony than the
  131901. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  131902. ** times for the common case.
  131903. **
  131904. ** Return non-zero on success, if this query can be handled by this
  131905. ** no-frills query planner. Return zero if this query needs the
  131906. ** general-purpose query planner.
  131907. */
  131908. static int whereShortCut(WhereLoopBuilder *pBuilder){
  131909. WhereInfo *pWInfo;
  131910. struct SrcList_item *pItem;
  131911. WhereClause *pWC;
  131912. WhereTerm *pTerm;
  131913. WhereLoop *pLoop;
  131914. int iCur;
  131915. int j;
  131916. Table *pTab;
  131917. Index *pIdx;
  131918. pWInfo = pBuilder->pWInfo;
  131919. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  131920. assert( pWInfo->pTabList->nSrc>=1 );
  131921. pItem = pWInfo->pTabList->a;
  131922. pTab = pItem->pTab;
  131923. if( IsVirtual(pTab) ) return 0;
  131924. if( pItem->fg.isIndexedBy ) return 0;
  131925. iCur = pItem->iCursor;
  131926. pWC = &pWInfo->sWC;
  131927. pLoop = pBuilder->pNew;
  131928. pLoop->wsFlags = 0;
  131929. pLoop->nSkip = 0;
  131930. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  131931. if( pTerm ){
  131932. testcase( pTerm->eOperator & WO_IS );
  131933. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  131934. pLoop->aLTerm[0] = pTerm;
  131935. pLoop->nLTerm = 1;
  131936. pLoop->u.btree.nEq = 1;
  131937. /* TUNING: Cost of a rowid lookup is 10 */
  131938. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  131939. }else{
  131940. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  131941. int opMask;
  131942. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  131943. if( !IsUniqueIndex(pIdx)
  131944. || pIdx->pPartIdxWhere!=0
  131945. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  131946. ) continue;
  131947. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  131948. for(j=0; j<pIdx->nKeyCol; j++){
  131949. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  131950. if( pTerm==0 ) break;
  131951. testcase( pTerm->eOperator & WO_IS );
  131952. pLoop->aLTerm[j] = pTerm;
  131953. }
  131954. if( j!=pIdx->nKeyCol ) continue;
  131955. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  131956. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  131957. pLoop->wsFlags |= WHERE_IDX_ONLY;
  131958. }
  131959. pLoop->nLTerm = j;
  131960. pLoop->u.btree.nEq = j;
  131961. pLoop->u.btree.pIndex = pIdx;
  131962. /* TUNING: Cost of a unique index lookup is 15 */
  131963. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  131964. break;
  131965. }
  131966. }
  131967. if( pLoop->wsFlags ){
  131968. pLoop->nOut = (LogEst)1;
  131969. pWInfo->a[0].pWLoop = pLoop;
  131970. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  131971. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  131972. pWInfo->a[0].iTabCur = iCur;
  131973. pWInfo->nRowOut = 1;
  131974. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  131975. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  131976. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  131977. }
  131978. #ifdef SQLITE_DEBUG
  131979. pLoop->cId = '0';
  131980. #endif
  131981. return 1;
  131982. }
  131983. return 0;
  131984. }
  131985. /*
  131986. ** Helper function for exprIsDeterministic().
  131987. */
  131988. static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
  131989. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
  131990. pWalker->eCode = 0;
  131991. return WRC_Abort;
  131992. }
  131993. return WRC_Continue;
  131994. }
  131995. /*
  131996. ** Return true if the expression contains no non-deterministic SQL
  131997. ** functions. Do not consider non-deterministic SQL functions that are
  131998. ** part of sub-select statements.
  131999. */
  132000. static int exprIsDeterministic(Expr *p){
  132001. Walker w;
  132002. memset(&w, 0, sizeof(w));
  132003. w.eCode = 1;
  132004. w.xExprCallback = exprNodeIsDeterministic;
  132005. w.xSelectCallback = sqlite3SelectWalkFail;
  132006. sqlite3WalkExpr(&w, p);
  132007. return w.eCode;
  132008. }
  132009. /*
  132010. ** Generate the beginning of the loop used for WHERE clause processing.
  132011. ** The return value is a pointer to an opaque structure that contains
  132012. ** information needed to terminate the loop. Later, the calling routine
  132013. ** should invoke sqlite3WhereEnd() with the return value of this function
  132014. ** in order to complete the WHERE clause processing.
  132015. **
  132016. ** If an error occurs, this routine returns NULL.
  132017. **
  132018. ** The basic idea is to do a nested loop, one loop for each table in
  132019. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  132020. ** same as a SELECT with only a single table in the FROM clause.) For
  132021. ** example, if the SQL is this:
  132022. **
  132023. ** SELECT * FROM t1, t2, t3 WHERE ...;
  132024. **
  132025. ** Then the code generated is conceptually like the following:
  132026. **
  132027. ** foreach row1 in t1 do \ Code generated
  132028. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  132029. ** foreach row3 in t3 do /
  132030. ** ...
  132031. ** end \ Code generated
  132032. ** end |-- by sqlite3WhereEnd()
  132033. ** end /
  132034. **
  132035. ** Note that the loops might not be nested in the order in which they
  132036. ** appear in the FROM clause if a different order is better able to make
  132037. ** use of indices. Note also that when the IN operator appears in
  132038. ** the WHERE clause, it might result in additional nested loops for
  132039. ** scanning through all values on the right-hand side of the IN.
  132040. **
  132041. ** There are Btree cursors associated with each table. t1 uses cursor
  132042. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  132043. ** And so forth. This routine generates code to open those VDBE cursors
  132044. ** and sqlite3WhereEnd() generates the code to close them.
  132045. **
  132046. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  132047. ** in pTabList pointing at their appropriate entries. The [...] code
  132048. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  132049. ** data from the various tables of the loop.
  132050. **
  132051. ** If the WHERE clause is empty, the foreach loops must each scan their
  132052. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  132053. ** the tables have indices and there are terms in the WHERE clause that
  132054. ** refer to those indices, a complete table scan can be avoided and the
  132055. ** code will run much faster. Most of the work of this routine is checking
  132056. ** to see if there are indices that can be used to speed up the loop.
  132057. **
  132058. ** Terms of the WHERE clause are also used to limit which rows actually
  132059. ** make it to the "..." in the middle of the loop. After each "foreach",
  132060. ** terms of the WHERE clause that use only terms in that loop and outer
  132061. ** loops are evaluated and if false a jump is made around all subsequent
  132062. ** inner loops (or around the "..." if the test occurs within the inner-
  132063. ** most loop)
  132064. **
  132065. ** OUTER JOINS
  132066. **
  132067. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  132068. **
  132069. ** foreach row1 in t1 do
  132070. ** flag = 0
  132071. ** foreach row2 in t2 do
  132072. ** start:
  132073. ** ...
  132074. ** flag = 1
  132075. ** end
  132076. ** if flag==0 then
  132077. ** move the row2 cursor to a null row
  132078. ** goto start
  132079. ** fi
  132080. ** end
  132081. **
  132082. ** ORDER BY CLAUSE PROCESSING
  132083. **
  132084. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  132085. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  132086. ** if there is one. If there is no ORDER BY clause or if this routine
  132087. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  132088. **
  132089. ** The iIdxCur parameter is the cursor number of an index. If
  132090. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  132091. ** to use for OR clause processing. The WHERE clause should use this
  132092. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  132093. ** the first cursor in an array of cursors for all indices. iIdxCur should
  132094. ** be used to compute the appropriate cursor depending on which index is
  132095. ** used.
  132096. */
  132097. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  132098. Parse *pParse, /* The parser context */
  132099. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  132100. Expr *pWhere, /* The WHERE clause */
  132101. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  132102. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  132103. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  132104. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  132105. ** If WHERE_USE_LIMIT, then the limit amount */
  132106. ){
  132107. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  132108. int nTabList; /* Number of elements in pTabList */
  132109. WhereInfo *pWInfo; /* Will become the return value of this function */
  132110. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  132111. Bitmask notReady; /* Cursors that are not yet positioned */
  132112. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  132113. WhereMaskSet *pMaskSet; /* The expression mask set */
  132114. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  132115. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  132116. int ii; /* Loop counter */
  132117. sqlite3 *db; /* Database connection */
  132118. int rc; /* Return code */
  132119. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  132120. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  132121. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  132122. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  132123. ));
  132124. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  132125. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  132126. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  132127. /* Variable initialization */
  132128. db = pParse->db;
  132129. memset(&sWLB, 0, sizeof(sWLB));
  132130. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  132131. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  132132. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  132133. sWLB.pOrderBy = pOrderBy;
  132134. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  132135. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  132136. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  132137. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  132138. }
  132139. /* The number of tables in the FROM clause is limited by the number of
  132140. ** bits in a Bitmask
  132141. */
  132142. testcase( pTabList->nSrc==BMS );
  132143. if( pTabList->nSrc>BMS ){
  132144. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  132145. return 0;
  132146. }
  132147. /* This function normally generates a nested loop for all tables in
  132148. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  132149. ** only generate code for the first table in pTabList and assume that
  132150. ** any cursors associated with subsequent tables are uninitialized.
  132151. */
  132152. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  132153. /* Allocate and initialize the WhereInfo structure that will become the
  132154. ** return value. A single allocation is used to store the WhereInfo
  132155. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  132156. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  132157. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  132158. ** some architectures. Hence the ROUND8() below.
  132159. */
  132160. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  132161. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  132162. if( db->mallocFailed ){
  132163. sqlite3DbFree(db, pWInfo);
  132164. pWInfo = 0;
  132165. goto whereBeginError;
  132166. }
  132167. pWInfo->pParse = pParse;
  132168. pWInfo->pTabList = pTabList;
  132169. pWInfo->pOrderBy = pOrderBy;
  132170. pWInfo->pWhere = pWhere;
  132171. pWInfo->pResultSet = pResultSet;
  132172. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  132173. pWInfo->nLevel = nTabList;
  132174. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  132175. pWInfo->wctrlFlags = wctrlFlags;
  132176. pWInfo->iLimit = iAuxArg;
  132177. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  132178. memset(&pWInfo->nOBSat, 0,
  132179. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  132180. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  132181. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  132182. pMaskSet = &pWInfo->sMaskSet;
  132183. sWLB.pWInfo = pWInfo;
  132184. sWLB.pWC = &pWInfo->sWC;
  132185. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  132186. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  132187. whereLoopInit(sWLB.pNew);
  132188. #ifdef SQLITE_DEBUG
  132189. sWLB.pNew->cId = '*';
  132190. #endif
  132191. /* Split the WHERE clause into separate subexpressions where each
  132192. ** subexpression is separated by an AND operator.
  132193. */
  132194. initMaskSet(pMaskSet);
  132195. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  132196. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  132197. /* Special case: No FROM clause
  132198. */
  132199. if( nTabList==0 ){
  132200. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  132201. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  132202. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  132203. }
  132204. ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
  132205. }else{
  132206. /* Assign a bit from the bitmask to every term in the FROM clause.
  132207. **
  132208. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  132209. **
  132210. ** The rule of the previous sentence ensures thta if X is the bitmask for
  132211. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  132212. ** Knowing the bitmask for all tables to the left of a left join is
  132213. ** important. Ticket #3015.
  132214. **
  132215. ** Note that bitmasks are created for all pTabList->nSrc tables in
  132216. ** pTabList, not just the first nTabList tables. nTabList is normally
  132217. ** equal to pTabList->nSrc but might be shortened to 1 if the
  132218. ** WHERE_OR_SUBCLAUSE flag is set.
  132219. */
  132220. ii = 0;
  132221. do{
  132222. createMask(pMaskSet, pTabList->a[ii].iCursor);
  132223. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  132224. }while( (++ii)<pTabList->nSrc );
  132225. #ifdef SQLITE_DEBUG
  132226. {
  132227. Bitmask mx = 0;
  132228. for(ii=0; ii<pTabList->nSrc; ii++){
  132229. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  132230. assert( m>=mx );
  132231. mx = m;
  132232. }
  132233. }
  132234. #endif
  132235. }
  132236. /* Analyze all of the subexpressions. */
  132237. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  132238. if( db->mallocFailed ) goto whereBeginError;
  132239. /* Special case: WHERE terms that do not refer to any tables in the join
  132240. ** (constant expressions). Evaluate each such term, and jump over all the
  132241. ** generated code if the result is not true.
  132242. **
  132243. ** Do not do this if the expression contains non-deterministic functions
  132244. ** that are not within a sub-select. This is not strictly required, but
  132245. ** preserves SQLite's legacy behaviour in the following two cases:
  132246. **
  132247. ** FROM ... WHERE random()>0; -- eval random() once per row
  132248. ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
  132249. */
  132250. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  132251. WhereTerm *pT = &sWLB.pWC->a[ii];
  132252. if( pT->wtFlags & TERM_VIRTUAL ) continue;
  132253. if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
  132254. sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  132255. pT->wtFlags |= TERM_CODED;
  132256. }
  132257. }
  132258. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  132259. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  132260. /* The DISTINCT marking is pointless. Ignore it. */
  132261. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  132262. }else if( pOrderBy==0 ){
  132263. /* Try to ORDER BY the result set to make distinct processing easier */
  132264. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  132265. pWInfo->pOrderBy = pResultSet;
  132266. }
  132267. }
  132268. /* Construct the WhereLoop objects */
  132269. #if defined(WHERETRACE_ENABLED)
  132270. if( sqlite3WhereTrace & 0xffff ){
  132271. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  132272. if( wctrlFlags & WHERE_USE_LIMIT ){
  132273. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  132274. }
  132275. sqlite3DebugPrintf(")\n");
  132276. }
  132277. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  132278. sqlite3WhereClausePrint(sWLB.pWC);
  132279. }
  132280. #endif
  132281. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  132282. rc = whereLoopAddAll(&sWLB);
  132283. if( rc ) goto whereBeginError;
  132284. #ifdef WHERETRACE_ENABLED
  132285. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  132286. WhereLoop *p;
  132287. int i;
  132288. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  132289. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  132290. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  132291. p->cId = zLabel[i%(sizeof(zLabel)-1)];
  132292. whereLoopPrint(p, sWLB.pWC);
  132293. }
  132294. }
  132295. #endif
  132296. wherePathSolver(pWInfo, 0);
  132297. if( db->mallocFailed ) goto whereBeginError;
  132298. if( pWInfo->pOrderBy ){
  132299. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  132300. if( db->mallocFailed ) goto whereBeginError;
  132301. }
  132302. }
  132303. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  132304. pWInfo->revMask = ALLBITS;
  132305. }
  132306. if( pParse->nErr || NEVER(db->mallocFailed) ){
  132307. goto whereBeginError;
  132308. }
  132309. #ifdef WHERETRACE_ENABLED
  132310. if( sqlite3WhereTrace ){
  132311. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  132312. if( pWInfo->nOBSat>0 ){
  132313. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  132314. }
  132315. switch( pWInfo->eDistinct ){
  132316. case WHERE_DISTINCT_UNIQUE: {
  132317. sqlite3DebugPrintf(" DISTINCT=unique");
  132318. break;
  132319. }
  132320. case WHERE_DISTINCT_ORDERED: {
  132321. sqlite3DebugPrintf(" DISTINCT=ordered");
  132322. break;
  132323. }
  132324. case WHERE_DISTINCT_UNORDERED: {
  132325. sqlite3DebugPrintf(" DISTINCT=unordered");
  132326. break;
  132327. }
  132328. }
  132329. sqlite3DebugPrintf("\n");
  132330. for(ii=0; ii<pWInfo->nLevel; ii++){
  132331. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  132332. }
  132333. }
  132334. #endif
  132335. /* Attempt to omit tables from the join that do not affect the result.
  132336. ** For a table to not affect the result, the following must be true:
  132337. **
  132338. ** 1) The query must not be an aggregate.
  132339. ** 2) The table must be the RHS of a LEFT JOIN.
  132340. ** 3) Either the query must be DISTINCT, or else the ON or USING clause
  132341. ** must contain a constraint that limits the scan of the table to
  132342. ** at most a single row.
  132343. ** 4) The table must not be referenced by any part of the query apart
  132344. ** from its own USING or ON clause.
  132345. **
  132346. ** For example, given:
  132347. **
  132348. ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
  132349. ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
  132350. ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
  132351. **
  132352. ** then table t2 can be omitted from the following:
  132353. **
  132354. ** SELECT v1, v3 FROM t1
  132355. ** LEFT JOIN t2 USING (t1.ipk=t2.ipk)
  132356. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  132357. **
  132358. ** or from:
  132359. **
  132360. ** SELECT DISTINCT v1, v3 FROM t1
  132361. ** LEFT JOIN t2
  132362. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  132363. */
  132364. notReady = ~(Bitmask)0;
  132365. if( pWInfo->nLevel>=2
  132366. && pResultSet!=0 /* guarantees condition (1) above */
  132367. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  132368. ){
  132369. int i;
  132370. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  132371. if( sWLB.pOrderBy ){
  132372. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  132373. }
  132374. for(i=pWInfo->nLevel-1; i>=1; i--){
  132375. WhereTerm *pTerm, *pEnd;
  132376. struct SrcList_item *pItem;
  132377. pLoop = pWInfo->a[i].pWLoop;
  132378. pItem = &pWInfo->pTabList->a[pLoop->iTab];
  132379. if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
  132380. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  132381. && (pLoop->wsFlags & WHERE_ONEROW)==0
  132382. ){
  132383. continue;
  132384. }
  132385. if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
  132386. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  132387. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  132388. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  132389. if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  132390. || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
  132391. ){
  132392. break;
  132393. }
  132394. }
  132395. }
  132396. if( pTerm<pEnd ) continue;
  132397. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  132398. notReady &= ~pLoop->maskSelf;
  132399. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  132400. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  132401. pTerm->wtFlags |= TERM_CODED;
  132402. }
  132403. }
  132404. if( i!=pWInfo->nLevel-1 ){
  132405. int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
  132406. memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
  132407. }
  132408. pWInfo->nLevel--;
  132409. nTabList--;
  132410. }
  132411. }
  132412. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  132413. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  132414. /* If the caller is an UPDATE or DELETE statement that is requesting
  132415. ** to use a one-pass algorithm, determine if this is appropriate.
  132416. **
  132417. ** A one-pass approach can be used if the caller has requested one
  132418. ** and either (a) the scan visits at most one row or (b) each
  132419. ** of the following are true:
  132420. **
  132421. ** * the caller has indicated that a one-pass approach can be used
  132422. ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
  132423. ** * the table is not a virtual table, and
  132424. ** * either the scan does not use the OR optimization or the caller
  132425. ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
  132426. ** for DELETE).
  132427. **
  132428. ** The last qualification is because an UPDATE statement uses
  132429. ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
  132430. ** use a one-pass approach, and this is not set accurately for scans
  132431. ** that use the OR optimization.
  132432. */
  132433. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  132434. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  132435. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  132436. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  132437. if( bOnerow || (
  132438. 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
  132439. && 0==(wsFlags & WHERE_VIRTUALTABLE)
  132440. && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
  132441. )){
  132442. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  132443. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  132444. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  132445. bFordelete = OPFLAG_FORDELETE;
  132446. }
  132447. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  132448. }
  132449. }
  132450. }
  132451. /* Open all tables in the pTabList and any indices selected for
  132452. ** searching those tables.
  132453. */
  132454. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  132455. Table *pTab; /* Table to open */
  132456. int iDb; /* Index of database containing table/index */
  132457. struct SrcList_item *pTabItem;
  132458. pTabItem = &pTabList->a[pLevel->iFrom];
  132459. pTab = pTabItem->pTab;
  132460. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  132461. pLoop = pLevel->pWLoop;
  132462. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  132463. /* Do nothing */
  132464. }else
  132465. #ifndef SQLITE_OMIT_VIRTUALTABLE
  132466. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  132467. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  132468. int iCur = pTabItem->iCursor;
  132469. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  132470. }else if( IsVirtual(pTab) ){
  132471. /* noop */
  132472. }else
  132473. #endif
  132474. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  132475. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  132476. int op = OP_OpenRead;
  132477. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  132478. op = OP_OpenWrite;
  132479. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  132480. };
  132481. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  132482. assert( pTabItem->iCursor==pLevel->iTabCur );
  132483. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  132484. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  132485. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  132486. Bitmask b = pTabItem->colUsed;
  132487. int n = 0;
  132488. for(; b; b=b>>1, n++){}
  132489. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  132490. assert( n<=pTab->nCol );
  132491. }
  132492. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  132493. if( pLoop->u.btree.pIndex!=0 ){
  132494. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  132495. }else
  132496. #endif
  132497. {
  132498. sqlite3VdbeChangeP5(v, bFordelete);
  132499. }
  132500. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  132501. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  132502. (const u8*)&pTabItem->colUsed, P4_INT64);
  132503. #endif
  132504. }else{
  132505. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  132506. }
  132507. if( pLoop->wsFlags & WHERE_INDEXED ){
  132508. Index *pIx = pLoop->u.btree.pIndex;
  132509. int iIndexCur;
  132510. int op = OP_OpenRead;
  132511. /* iAuxArg is always set to a positive value if ONEPASS is possible */
  132512. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  132513. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  132514. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  132515. ){
  132516. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  132517. ** WITHOUT ROWID table. No need for a separate index */
  132518. iIndexCur = pLevel->iTabCur;
  132519. op = 0;
  132520. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  132521. Index *pJ = pTabItem->pTab->pIndex;
  132522. iIndexCur = iAuxArg;
  132523. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  132524. while( ALWAYS(pJ) && pJ!=pIx ){
  132525. iIndexCur++;
  132526. pJ = pJ->pNext;
  132527. }
  132528. op = OP_OpenWrite;
  132529. pWInfo->aiCurOnePass[1] = iIndexCur;
  132530. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  132531. iIndexCur = iAuxArg;
  132532. op = OP_ReopenIdx;
  132533. }else{
  132534. iIndexCur = pParse->nTab++;
  132535. }
  132536. pLevel->iIdxCur = iIndexCur;
  132537. assert( pIx->pSchema==pTab->pSchema );
  132538. assert( iIndexCur>=0 );
  132539. if( op ){
  132540. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  132541. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  132542. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  132543. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  132544. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  132545. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  132546. ){
  132547. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  132548. }
  132549. VdbeComment((v, "%s", pIx->zName));
  132550. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  132551. {
  132552. u64 colUsed = 0;
  132553. int ii, jj;
  132554. for(ii=0; ii<pIx->nColumn; ii++){
  132555. jj = pIx->aiColumn[ii];
  132556. if( jj<0 ) continue;
  132557. if( jj>63 ) jj = 63;
  132558. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  132559. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  132560. }
  132561. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  132562. (u8*)&colUsed, P4_INT64);
  132563. }
  132564. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  132565. }
  132566. }
  132567. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  132568. }
  132569. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  132570. if( db->mallocFailed ) goto whereBeginError;
  132571. /* Generate the code to do the search. Each iteration of the for
  132572. ** loop below generates code for a single nested loop of the VM
  132573. ** program.
  132574. */
  132575. for(ii=0; ii<nTabList; ii++){
  132576. int addrExplain;
  132577. int wsFlags;
  132578. pLevel = &pWInfo->a[ii];
  132579. wsFlags = pLevel->pWLoop->wsFlags;
  132580. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  132581. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  132582. constructAutomaticIndex(pParse, &pWInfo->sWC,
  132583. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  132584. if( db->mallocFailed ) goto whereBeginError;
  132585. }
  132586. #endif
  132587. addrExplain = sqlite3WhereExplainOneScan(
  132588. pParse, pTabList, pLevel, wctrlFlags
  132589. );
  132590. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  132591. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  132592. pWInfo->iContinue = pLevel->addrCont;
  132593. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  132594. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  132595. }
  132596. }
  132597. /* Done. */
  132598. VdbeModuleComment((v, "Begin WHERE-core"));
  132599. return pWInfo;
  132600. /* Jump here if malloc fails */
  132601. whereBeginError:
  132602. if( pWInfo ){
  132603. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  132604. whereInfoFree(db, pWInfo);
  132605. }
  132606. return 0;
  132607. }
  132608. /*
  132609. ** Generate the end of the WHERE loop. See comments on
  132610. ** sqlite3WhereBegin() for additional information.
  132611. */
  132612. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  132613. Parse *pParse = pWInfo->pParse;
  132614. Vdbe *v = pParse->pVdbe;
  132615. int i;
  132616. WhereLevel *pLevel;
  132617. WhereLoop *pLoop;
  132618. SrcList *pTabList = pWInfo->pTabList;
  132619. sqlite3 *db = pParse->db;
  132620. /* Generate loop termination code.
  132621. */
  132622. VdbeModuleComment((v, "End WHERE-core"));
  132623. sqlite3ExprCacheClear(pParse);
  132624. for(i=pWInfo->nLevel-1; i>=0; i--){
  132625. int addr;
  132626. pLevel = &pWInfo->a[i];
  132627. pLoop = pLevel->pWLoop;
  132628. if( pLevel->op!=OP_Noop ){
  132629. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  132630. int addrSeek = 0;
  132631. Index *pIdx;
  132632. int n;
  132633. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  132634. && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
  132635. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  132636. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  132637. && (n = pLoop->u.btree.nIdxCol)>0
  132638. && pIdx->aiRowLogEst[n]>=36
  132639. ){
  132640. int r1 = pParse->nMem+1;
  132641. int j, op;
  132642. for(j=0; j<n; j++){
  132643. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  132644. }
  132645. pParse->nMem += n+1;
  132646. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  132647. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  132648. VdbeCoverageIf(v, op==OP_SeekLT);
  132649. VdbeCoverageIf(v, op==OP_SeekGT);
  132650. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  132651. }
  132652. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  132653. /* The common case: Advance to the next row */
  132654. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  132655. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  132656. sqlite3VdbeChangeP5(v, pLevel->p5);
  132657. VdbeCoverage(v);
  132658. VdbeCoverageIf(v, pLevel->op==OP_Next);
  132659. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  132660. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  132661. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  132662. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  132663. #endif
  132664. }else{
  132665. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  132666. }
  132667. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  132668. struct InLoop *pIn;
  132669. int j;
  132670. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  132671. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  132672. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  132673. if( pIn->eEndLoopOp!=OP_Noop ){
  132674. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  132675. VdbeCoverage(v);
  132676. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  132677. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  132678. }
  132679. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  132680. }
  132681. }
  132682. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  132683. if( pLevel->addrSkip ){
  132684. sqlite3VdbeGoto(v, pLevel->addrSkip);
  132685. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  132686. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  132687. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  132688. }
  132689. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  132690. if( pLevel->addrLikeRep ){
  132691. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  132692. pLevel->addrLikeRep);
  132693. VdbeCoverage(v);
  132694. }
  132695. #endif
  132696. if( pLevel->iLeftJoin ){
  132697. int ws = pLoop->wsFlags;
  132698. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  132699. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  132700. if( (ws & WHERE_IDX_ONLY)==0 ){
  132701. assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
  132702. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
  132703. }
  132704. if( (ws & WHERE_INDEXED)
  132705. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  132706. ){
  132707. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  132708. }
  132709. if( pLevel->op==OP_Return ){
  132710. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  132711. }else{
  132712. sqlite3VdbeGoto(v, pLevel->addrFirst);
  132713. }
  132714. sqlite3VdbeJumpHere(v, addr);
  132715. }
  132716. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  132717. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  132718. }
  132719. /* The "break" point is here, just past the end of the outer loop.
  132720. ** Set it.
  132721. */
  132722. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  132723. assert( pWInfo->nLevel<=pTabList->nSrc );
  132724. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  132725. int k, last;
  132726. VdbeOp *pOp;
  132727. Index *pIdx = 0;
  132728. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  132729. Table *pTab = pTabItem->pTab;
  132730. assert( pTab!=0 );
  132731. pLoop = pLevel->pWLoop;
  132732. /* For a co-routine, change all OP_Column references to the table of
  132733. ** the co-routine into OP_Copy of result contained in a register.
  132734. ** OP_Rowid becomes OP_Null.
  132735. */
  132736. if( pTabItem->fg.viaCoroutine ){
  132737. testcase( pParse->db->mallocFailed );
  132738. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  132739. pTabItem->regResult, 0);
  132740. continue;
  132741. }
  132742. /* If this scan uses an index, make VDBE code substitutions to read data
  132743. ** from the index instead of from the table where possible. In some cases
  132744. ** this optimization prevents the table from ever being read, which can
  132745. ** yield a significant performance boost.
  132746. **
  132747. ** Calls to the code generator in between sqlite3WhereBegin and
  132748. ** sqlite3WhereEnd will have created code that references the table
  132749. ** directly. This loop scans all that code looking for opcodes
  132750. ** that reference the table and converts them into opcodes that
  132751. ** reference the index.
  132752. */
  132753. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  132754. pIdx = pLoop->u.btree.pIndex;
  132755. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  132756. pIdx = pLevel->u.pCovidx;
  132757. }
  132758. if( pIdx
  132759. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  132760. && !db->mallocFailed
  132761. ){
  132762. last = sqlite3VdbeCurrentAddr(v);
  132763. k = pLevel->addrBody;
  132764. pOp = sqlite3VdbeGetOp(v, k);
  132765. for(; k<last; k++, pOp++){
  132766. if( pOp->p1!=pLevel->iTabCur ) continue;
  132767. if( pOp->opcode==OP_Column
  132768. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  132769. || pOp->opcode==OP_Offset
  132770. #endif
  132771. ){
  132772. int x = pOp->p2;
  132773. assert( pIdx->pTable==pTab );
  132774. if( !HasRowid(pTab) ){
  132775. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  132776. x = pPk->aiColumn[x];
  132777. assert( x>=0 );
  132778. }
  132779. x = sqlite3ColumnOfIndex(pIdx, x);
  132780. if( x>=0 ){
  132781. pOp->p2 = x;
  132782. pOp->p1 = pLevel->iIdxCur;
  132783. }
  132784. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  132785. || pWInfo->eOnePass );
  132786. }else if( pOp->opcode==OP_Rowid ){
  132787. pOp->p1 = pLevel->iIdxCur;
  132788. pOp->opcode = OP_IdxRowid;
  132789. }else if( pOp->opcode==OP_IfNullRow ){
  132790. pOp->p1 = pLevel->iIdxCur;
  132791. }
  132792. }
  132793. }
  132794. }
  132795. /* Final cleanup
  132796. */
  132797. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  132798. whereInfoFree(db, pWInfo);
  132799. return;
  132800. }
  132801. /************** End of where.c ***********************************************/
  132802. /************** Begin file parse.c *******************************************/
  132803. /*
  132804. ** 2000-05-29
  132805. **
  132806. ** The author disclaims copyright to this source code. In place of
  132807. ** a legal notice, here is a blessing:
  132808. **
  132809. ** May you do good and not evil.
  132810. ** May you find forgiveness for yourself and forgive others.
  132811. ** May you share freely, never taking more than you give.
  132812. **
  132813. *************************************************************************
  132814. ** Driver template for the LEMON parser generator.
  132815. **
  132816. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  132817. ** this template to construct a parser. The "lemon" program inserts text
  132818. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  132819. ** interstitial "-" characters) contained in this template is changed into
  132820. ** the value of the %name directive from the grammar. Otherwise, the content
  132821. ** of this template is copied straight through into the generate parser
  132822. ** source file.
  132823. **
  132824. ** The following is the concatenation of all %include directives from the
  132825. ** input grammar file:
  132826. */
  132827. /* #include <stdio.h> */
  132828. /************ Begin %include sections from the grammar ************************/
  132829. /* #include "sqliteInt.h" */
  132830. /*
  132831. ** Disable all error recovery processing in the parser push-down
  132832. ** automaton.
  132833. */
  132834. #define YYNOERRORRECOVERY 1
  132835. /*
  132836. ** Make yytestcase() the same as testcase()
  132837. */
  132838. #define yytestcase(X) testcase(X)
  132839. /*
  132840. ** Indicate that sqlite3ParserFree() will never be called with a null
  132841. ** pointer.
  132842. */
  132843. #define YYPARSEFREENEVERNULL 1
  132844. /*
  132845. ** In the amalgamation, the parse.c file generated by lemon and the
  132846. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  132847. ** has access to the the size of the yyParser object and so the parser
  132848. ** engine can be allocated from stack. In that case, only the
  132849. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  132850. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  132851. ** omitted.
  132852. */
  132853. #ifdef SQLITE_AMALGAMATION
  132854. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  132855. #endif
  132856. /*
  132857. ** Alternative datatype for the argument to the malloc() routine passed
  132858. ** into sqlite3ParserAlloc(). The default is size_t.
  132859. */
  132860. #define YYMALLOCARGTYPE u64
  132861. /*
  132862. ** An instance of the following structure describes the event of a
  132863. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  132864. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  132865. **
  132866. ** UPDATE ON (a,b,c)
  132867. **
  132868. ** Then the "b" IdList records the list "a,b,c".
  132869. */
  132870. struct TrigEvent { int a; IdList * b; };
  132871. /*
  132872. ** Disable lookaside memory allocation for objects that might be
  132873. ** shared across database connections.
  132874. */
  132875. static void disableLookaside(Parse *pParse){
  132876. pParse->disableLookaside++;
  132877. pParse->db->lookaside.bDisable++;
  132878. }
  132879. /*
  132880. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  132881. ** all elements in the list. And make sure list length does not exceed
  132882. ** SQLITE_LIMIT_COMPOUND_SELECT.
  132883. */
  132884. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  132885. if( p->pPrior ){
  132886. Select *pNext = 0, *pLoop;
  132887. int mxSelect, cnt = 0;
  132888. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  132889. pLoop->pNext = pNext;
  132890. pLoop->selFlags |= SF_Compound;
  132891. }
  132892. if( (p->selFlags & SF_MultiValue)==0 &&
  132893. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  132894. cnt>mxSelect
  132895. ){
  132896. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  132897. }
  132898. }
  132899. }
  132900. /* Construct a new Expr object from a single identifier. Use the
  132901. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  132902. ** that created the expression.
  132903. */
  132904. static Expr *tokenExpr(Parse *pParse, int op, Token t){
  132905. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  132906. if( p ){
  132907. memset(p, 0, sizeof(Expr));
  132908. p->op = (u8)op;
  132909. p->flags = EP_Leaf;
  132910. p->iAgg = -1;
  132911. p->u.zToken = (char*)&p[1];
  132912. memcpy(p->u.zToken, t.z, t.n);
  132913. p->u.zToken[t.n] = 0;
  132914. if( sqlite3Isquote(p->u.zToken[0]) ){
  132915. if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
  132916. sqlite3Dequote(p->u.zToken);
  132917. }
  132918. #if SQLITE_MAX_EXPR_DEPTH>0
  132919. p->nHeight = 1;
  132920. #endif
  132921. }
  132922. return p;
  132923. }
  132924. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  132925. ** unary TK_ISNULL or TK_NOTNULL expression. */
  132926. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  132927. sqlite3 *db = pParse->db;
  132928. if( pA && pY && pY->op==TK_NULL ){
  132929. pA->op = (u8)op;
  132930. sqlite3ExprDelete(db, pA->pRight);
  132931. pA->pRight = 0;
  132932. }
  132933. }
  132934. /* Add a single new term to an ExprList that is used to store a
  132935. ** list of identifiers. Report an error if the ID list contains
  132936. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  132937. ** error while parsing a legacy schema.
  132938. */
  132939. static ExprList *parserAddExprIdListTerm(
  132940. Parse *pParse,
  132941. ExprList *pPrior,
  132942. Token *pIdToken,
  132943. int hasCollate,
  132944. int sortOrder
  132945. ){
  132946. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  132947. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  132948. && pParse->db->init.busy==0
  132949. ){
  132950. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  132951. pIdToken->n, pIdToken->z);
  132952. }
  132953. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  132954. return p;
  132955. }
  132956. /**************** End of %include directives **********************************/
  132957. /* These constants specify the various numeric values for terminal symbols
  132958. ** in a format understandable to "makeheaders". This section is blank unless
  132959. ** "lemon" is run with the "-m" command-line option.
  132960. ***************** Begin makeheaders token definitions *************************/
  132961. /**************** End makeheaders token definitions ***************************/
  132962. /* The next sections is a series of control #defines.
  132963. ** various aspects of the generated parser.
  132964. ** YYCODETYPE is the data type used to store the integer codes
  132965. ** that represent terminal and non-terminal symbols.
  132966. ** "unsigned char" is used if there are fewer than
  132967. ** 256 symbols. Larger types otherwise.
  132968. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  132969. ** any terminal or nonterminal symbol.
  132970. ** YYFALLBACK If defined, this indicates that one or more tokens
  132971. ** (also known as: "terminal symbols") have fall-back
  132972. ** values which should be used if the original symbol
  132973. ** would not parse. This permits keywords to sometimes
  132974. ** be used as identifiers, for example.
  132975. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  132976. ** that indicate what to do in response to the next
  132977. ** token.
  132978. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  132979. ** symbols. Background: A "minor type" is a semantic
  132980. ** value associated with a terminal or non-terminal
  132981. ** symbols. For example, for an "ID" terminal symbol,
  132982. ** the minor type might be the name of the identifier.
  132983. ** Each non-terminal can have a different minor type.
  132984. ** Terminal symbols all have the same minor type, though.
  132985. ** This macros defines the minor type for terminal
  132986. ** symbols.
  132987. ** YYMINORTYPE is the data type used for all minor types.
  132988. ** This is typically a union of many types, one of
  132989. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  132990. ** for terminal symbols is called "yy0".
  132991. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  132992. ** zero the stack is dynamically sized using realloc()
  132993. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  132994. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  132995. ** sqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  132996. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  132997. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  132998. ** sqlite3ParserCTX_* As sqlite3ParserARG_ except for %extra_context
  132999. ** YYERRORSYMBOL is the code number of the error symbol. If not
  133000. ** defined, then do no error processing.
  133001. ** YYNSTATE the combined number of states.
  133002. ** YYNRULE the number of rules in the grammar
  133003. ** YYNTOKEN Number of terminal symbols
  133004. ** YY_MAX_SHIFT Maximum value for shift actions
  133005. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  133006. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  133007. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  133008. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  133009. ** YY_NO_ACTION The yy_action[] code for no-op
  133010. ** YY_MIN_REDUCE Minimum value for reduce actions
  133011. ** YY_MAX_REDUCE Maximum value for reduce actions
  133012. */
  133013. #ifndef INTERFACE
  133014. # define INTERFACE 1
  133015. #endif
  133016. /************* Begin control #defines *****************************************/
  133017. #define YYCODETYPE unsigned char
  133018. #define YYNOCODE 255
  133019. #define YYACTIONTYPE unsigned short int
  133020. #define YYWILDCARD 84
  133021. #define sqlite3ParserTOKENTYPE Token
  133022. typedef union {
  133023. int yyinit;
  133024. sqlite3ParserTOKENTYPE yy0;
  133025. const char* yy36;
  133026. TriggerStep* yy47;
  133027. With* yy91;
  133028. struct {int value; int mask;} yy107;
  133029. Expr* yy182;
  133030. Upsert* yy198;
  133031. ExprList* yy232;
  133032. struct TrigEvent yy300;
  133033. Select* yy399;
  133034. SrcList* yy427;
  133035. int yy502;
  133036. IdList* yy510;
  133037. } YYMINORTYPE;
  133038. #ifndef YYSTACKDEPTH
  133039. #define YYSTACKDEPTH 100
  133040. #endif
  133041. #define sqlite3ParserARG_SDECL
  133042. #define sqlite3ParserARG_PDECL
  133043. #define sqlite3ParserARG_PARAM
  133044. #define sqlite3ParserARG_FETCH
  133045. #define sqlite3ParserARG_STORE
  133046. #define sqlite3ParserCTX_SDECL Parse *pParse;
  133047. #define sqlite3ParserCTX_PDECL ,Parse *pParse
  133048. #define sqlite3ParserCTX_PARAM ,pParse
  133049. #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
  133050. #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
  133051. #define YYFALLBACK 1
  133052. #define YYNSTATE 490
  133053. #define YYNRULE 341
  133054. #define YYNTOKEN 145
  133055. #define YY_MAX_SHIFT 489
  133056. #define YY_MIN_SHIFTREDUCE 705
  133057. #define YY_MAX_SHIFTREDUCE 1045
  133058. #define YY_ERROR_ACTION 1046
  133059. #define YY_ACCEPT_ACTION 1047
  133060. #define YY_NO_ACTION 1048
  133061. #define YY_MIN_REDUCE 1049
  133062. #define YY_MAX_REDUCE 1389
  133063. /************* End control #defines *******************************************/
  133064. /* Define the yytestcase() macro to be a no-op if is not already defined
  133065. ** otherwise.
  133066. **
  133067. ** Applications can choose to define yytestcase() in the %include section
  133068. ** to a macro that can assist in verifying code coverage. For production
  133069. ** code the yytestcase() macro should be turned off. But it is useful
  133070. ** for testing.
  133071. */
  133072. #ifndef yytestcase
  133073. # define yytestcase(X)
  133074. #endif
  133075. /* Next are the tables used to determine what action to take based on the
  133076. ** current state and lookahead token. These tables are used to implement
  133077. ** functions that take a state number and lookahead value and return an
  133078. ** action integer.
  133079. **
  133080. ** Suppose the action integer is N. Then the action is determined as
  133081. ** follows
  133082. **
  133083. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  133084. ** token onto the stack and goto state N.
  133085. **
  133086. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  133087. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  133088. **
  133089. ** N == YY_ERROR_ACTION A syntax error has occurred.
  133090. **
  133091. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  133092. **
  133093. ** N == YY_NO_ACTION No such action. Denotes unused
  133094. ** slots in the yy_action[] table.
  133095. **
  133096. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  133097. ** and YY_MAX_REDUCE
  133098. **
  133099. ** The action table is constructed as a single large table named yy_action[].
  133100. ** Given state S and lookahead X, the action is computed as either:
  133101. **
  133102. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  133103. ** (B) N = yy_default[S]
  133104. **
  133105. ** The (A) formula is preferred. The B formula is used instead if
  133106. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
  133107. **
  133108. ** The formulas above are for computing the action when the lookahead is
  133109. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  133110. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  133111. ** the yy_shift_ofst[] array.
  133112. **
  133113. ** The following are the tables generated in this section:
  133114. **
  133115. ** yy_action[] A single table containing all actions.
  133116. ** yy_lookahead[] A table containing the lookahead for each entry in
  133117. ** yy_action. Used to detect hash collisions.
  133118. ** yy_shift_ofst[] For each state, the offset into yy_action for
  133119. ** shifting terminals.
  133120. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  133121. ** shifting non-terminals after a reduce.
  133122. ** yy_default[] Default action for each state.
  133123. **
  133124. *********** Begin parsing tables **********************************************/
  133125. #define YY_ACTTAB_COUNT (1657)
  133126. static const YYACTIONTYPE yy_action[] = {
  133127. /* 0 */ 349, 99, 96, 185, 99, 96, 185, 233, 1047, 1,
  133128. /* 10 */ 1, 489, 2, 1051, 484, 477, 477, 477, 260, 351,
  133129. /* 20 */ 121, 1310, 1120, 1120, 1178, 1115, 1094, 1128, 380, 380,
  133130. /* 30 */ 380, 835, 454, 410, 1115, 59, 59, 1357, 425, 836,
  133131. /* 40 */ 710, 711, 712, 106, 107, 97, 1023, 1023, 900, 903,
  133132. /* 50 */ 892, 892, 104, 104, 105, 105, 105, 105, 346, 238,
  133133. /* 60 */ 238, 99, 96, 185, 238, 238, 889, 889, 901, 904,
  133134. /* 70 */ 460, 481, 351, 99, 96, 185, 481, 347, 1177, 82,
  133135. /* 80 */ 388, 214, 182, 23, 194, 103, 103, 103, 103, 102,
  133136. /* 90 */ 102, 101, 101, 101, 100, 381, 106, 107, 97, 1023,
  133137. /* 100 */ 1023, 900, 903, 892, 892, 104, 104, 105, 105, 105,
  133138. /* 110 */ 105, 10, 385, 484, 24, 484, 1333, 489, 2, 1051,
  133139. /* 120 */ 335, 1043, 108, 893, 260, 351, 121, 99, 96, 185,
  133140. /* 130 */ 100, 381, 386, 1128, 59, 59, 59, 59, 103, 103,
  133141. /* 140 */ 103, 103, 102, 102, 101, 101, 101, 100, 381, 106,
  133142. /* 150 */ 107, 97, 1023, 1023, 900, 903, 892, 892, 104, 104,
  133143. /* 160 */ 105, 105, 105, 105, 360, 238, 238, 170, 170, 467,
  133144. /* 170 */ 455, 467, 464, 67, 381, 329, 169, 481, 351, 343,
  133145. /* 180 */ 338, 400, 1044, 68, 101, 101, 101, 100, 381, 393,
  133146. /* 190 */ 194, 103, 103, 103, 103, 102, 102, 101, 101, 101,
  133147. /* 200 */ 100, 381, 106, 107, 97, 1023, 1023, 900, 903, 892,
  133148. /* 210 */ 892, 104, 104, 105, 105, 105, 105, 483, 385, 103,
  133149. /* 220 */ 103, 103, 103, 102, 102, 101, 101, 101, 100, 381,
  133150. /* 230 */ 268, 351, 946, 946, 422, 296, 102, 102, 101, 101,
  133151. /* 240 */ 101, 100, 381, 861, 103, 103, 103, 103, 102, 102,
  133152. /* 250 */ 101, 101, 101, 100, 381, 106, 107, 97, 1023, 1023,
  133153. /* 260 */ 900, 903, 892, 892, 104, 104, 105, 105, 105, 105,
  133154. /* 270 */ 484, 983, 1383, 206, 1353, 1383, 438, 435, 434, 281,
  133155. /* 280 */ 396, 269, 1089, 941, 351, 1002, 433, 861, 743, 401,
  133156. /* 290 */ 282, 57, 57, 482, 145, 791, 791, 103, 103, 103,
  133157. /* 300 */ 103, 102, 102, 101, 101, 101, 100, 381, 106, 107,
  133158. /* 310 */ 97, 1023, 1023, 900, 903, 892, 892, 104, 104, 105,
  133159. /* 320 */ 105, 105, 105, 281, 1002, 1003, 1004, 206, 879, 319,
  133160. /* 330 */ 438, 435, 434, 981, 259, 474, 360, 351, 1118, 1118,
  133161. /* 340 */ 433, 736, 379, 378, 872, 1002, 1356, 322, 871, 766,
  133162. /* 350 */ 103, 103, 103, 103, 102, 102, 101, 101, 101, 100,
  133163. /* 360 */ 381, 106, 107, 97, 1023, 1023, 900, 903, 892, 892,
  133164. /* 370 */ 104, 104, 105, 105, 105, 105, 484, 801, 484, 871,
  133165. /* 380 */ 871, 873, 401, 282, 1002, 1003, 1004, 1030, 360, 1030,
  133166. /* 390 */ 351, 983, 1384, 213, 880, 1384, 145, 59, 59, 59,
  133167. /* 400 */ 59, 1002, 244, 103, 103, 103, 103, 102, 102, 101,
  133168. /* 410 */ 101, 101, 100, 381, 106, 107, 97, 1023, 1023, 900,
  133169. /* 420 */ 903, 892, 892, 104, 104, 105, 105, 105, 105, 274,
  133170. /* 430 */ 484, 110, 467, 479, 467, 444, 259, 474, 232, 232,
  133171. /* 440 */ 1002, 1003, 1004, 351, 210, 335, 982, 866, 1385, 336,
  133172. /* 450 */ 481, 59, 59, 981, 245, 307, 103, 103, 103, 103,
  133173. /* 460 */ 102, 102, 101, 101, 101, 100, 381, 106, 107, 97,
  133174. /* 470 */ 1023, 1023, 900, 903, 892, 892, 104, 104, 105, 105,
  133175. /* 480 */ 105, 105, 453, 459, 484, 408, 377, 259, 474, 271,
  133176. /* 490 */ 183, 273, 209, 208, 207, 356, 351, 307, 178, 177,
  133177. /* 500 */ 127, 1006, 1098, 14, 14, 43, 43, 1044, 425, 103,
  133178. /* 510 */ 103, 103, 103, 102, 102, 101, 101, 101, 100, 381,
  133179. /* 520 */ 106, 107, 97, 1023, 1023, 900, 903, 892, 892, 104,
  133180. /* 530 */ 104, 105, 105, 105, 105, 294, 1132, 408, 160, 484,
  133181. /* 540 */ 408, 1006, 129, 962, 1209, 239, 239, 481, 307, 425,
  133182. /* 550 */ 1309, 1097, 351, 235, 243, 272, 820, 481, 963, 425,
  133183. /* 560 */ 11, 11, 103, 103, 103, 103, 102, 102, 101, 101,
  133184. /* 570 */ 101, 100, 381, 964, 362, 1002, 106, 107, 97, 1023,
  133185. /* 580 */ 1023, 900, 903, 892, 892, 104, 104, 105, 105, 105,
  133186. /* 590 */ 105, 1275, 161, 126, 777, 289, 1209, 292, 1072, 357,
  133187. /* 600 */ 1209, 1127, 476, 357, 778, 425, 247, 425, 351, 248,
  133188. /* 610 */ 414, 364, 414, 171, 1002, 1003, 1004, 84, 103, 103,
  133189. /* 620 */ 103, 103, 102, 102, 101, 101, 101, 100, 381, 1002,
  133190. /* 630 */ 184, 484, 106, 107, 97, 1023, 1023, 900, 903, 892,
  133191. /* 640 */ 892, 104, 104, 105, 105, 105, 105, 1123, 1209, 287,
  133192. /* 650 */ 484, 1209, 11, 11, 179, 820, 259, 474, 307, 237,
  133193. /* 660 */ 182, 351, 321, 365, 414, 308, 367, 366, 1002, 1003,
  133194. /* 670 */ 1004, 44, 44, 87, 103, 103, 103, 103, 102, 102,
  133195. /* 680 */ 101, 101, 101, 100, 381, 106, 107, 97, 1023, 1023,
  133196. /* 690 */ 900, 903, 892, 892, 104, 104, 105, 105, 105, 105,
  133197. /* 700 */ 246, 368, 280, 128, 10, 358, 146, 796, 835, 258,
  133198. /* 710 */ 1020, 88, 795, 86, 351, 421, 836, 943, 376, 348,
  133199. /* 720 */ 191, 943, 1318, 267, 308, 279, 456, 103, 103, 103,
  133200. /* 730 */ 103, 102, 102, 101, 101, 101, 100, 381, 106, 95,
  133201. /* 740 */ 97, 1023, 1023, 900, 903, 892, 892, 104, 104, 105,
  133202. /* 750 */ 105, 105, 105, 420, 249, 238, 238, 238, 238, 79,
  133203. /* 760 */ 375, 125, 305, 29, 262, 978, 351, 481, 337, 481,
  133204. /* 770 */ 756, 755, 304, 278, 415, 15, 81, 940, 1126, 940,
  133205. /* 780 */ 103, 103, 103, 103, 102, 102, 101, 101, 101, 100,
  133206. /* 790 */ 381, 107, 97, 1023, 1023, 900, 903, 892, 892, 104,
  133207. /* 800 */ 104, 105, 105, 105, 105, 457, 263, 484, 174, 484,
  133208. /* 810 */ 238, 238, 863, 407, 402, 216, 216, 351, 409, 193,
  133209. /* 820 */ 283, 216, 481, 81, 763, 764, 266, 5, 13, 13,
  133210. /* 830 */ 34, 34, 103, 103, 103, 103, 102, 102, 101, 101,
  133211. /* 840 */ 101, 100, 381, 97, 1023, 1023, 900, 903, 892, 892,
  133212. /* 850 */ 104, 104, 105, 105, 105, 105, 93, 475, 1002, 4,
  133213. /* 860 */ 403, 1002, 340, 431, 1002, 297, 212, 1277, 81, 746,
  133214. /* 870 */ 1163, 152, 926, 478, 166, 212, 757, 829, 930, 939,
  133215. /* 880 */ 216, 939, 858, 103, 103, 103, 103, 102, 102, 101,
  133216. /* 890 */ 101, 101, 100, 381, 238, 238, 382, 1002, 1003, 1004,
  133217. /* 900 */ 1002, 1003, 1004, 1002, 1003, 1004, 481, 439, 472, 746,
  133218. /* 910 */ 105, 105, 105, 105, 98, 758, 1162, 145, 930, 412,
  133219. /* 920 */ 879, 406, 793, 81, 395, 89, 90, 91, 105, 105,
  133220. /* 930 */ 105, 105, 1323, 92, 484, 382, 486, 485, 240, 275,
  133221. /* 940 */ 871, 103, 103, 103, 103, 102, 102, 101, 101, 101,
  133222. /* 950 */ 100, 381, 1096, 371, 355, 45, 45, 259, 474, 103,
  133223. /* 960 */ 103, 103, 103, 102, 102, 101, 101, 101, 100, 381,
  133224. /* 970 */ 1150, 871, 871, 873, 874, 21, 1332, 991, 384, 730,
  133225. /* 980 */ 722, 242, 123, 1298, 124, 875, 333, 333, 332, 227,
  133226. /* 990 */ 330, 991, 384, 719, 256, 242, 484, 391, 413, 1297,
  133227. /* 1000 */ 333, 333, 332, 227, 330, 748, 187, 719, 265, 470,
  133228. /* 1010 */ 1279, 1002, 484, 417, 391, 390, 264, 11, 11, 284,
  133229. /* 1020 */ 187, 732, 265, 93, 475, 875, 4, 1279, 1281, 419,
  133230. /* 1030 */ 264, 369, 416, 11, 11, 1159, 288, 484, 399, 1346,
  133231. /* 1040 */ 478, 379, 378, 291, 484, 293, 189, 250, 295, 1027,
  133232. /* 1050 */ 1002, 1003, 1004, 190, 1029, 1111, 140, 188, 11, 11,
  133233. /* 1060 */ 189, 732, 1028, 382, 923, 46, 46, 190, 1095, 230,
  133234. /* 1070 */ 140, 188, 462, 93, 475, 472, 4, 300, 309, 391,
  133235. /* 1080 */ 373, 6, 1069, 217, 739, 310, 1030, 879, 1030, 1171,
  133236. /* 1090 */ 478, 352, 1279, 90, 91, 800, 259, 474, 1208, 484,
  133237. /* 1100 */ 92, 1268, 382, 486, 485, 352, 1002, 871, 879, 426,
  133238. /* 1110 */ 259, 474, 172, 382, 238, 238, 1146, 170, 1021, 389,
  133239. /* 1120 */ 47, 47, 1157, 739, 872, 472, 481, 469, 871, 350,
  133240. /* 1130 */ 1214, 83, 475, 389, 4, 1078, 1071, 879, 871, 871,
  133241. /* 1140 */ 873, 874, 21, 90, 91, 1002, 1003, 1004, 478, 251,
  133242. /* 1150 */ 92, 251, 382, 486, 485, 443, 370, 871, 1021, 871,
  133243. /* 1160 */ 871, 873, 224, 241, 306, 441, 301, 440, 211, 1060,
  133244. /* 1170 */ 820, 382, 822, 447, 299, 1059, 484, 1061, 1143, 962,
  133245. /* 1180 */ 430, 796, 484, 472, 1340, 312, 795, 465, 871, 871,
  133246. /* 1190 */ 873, 874, 21, 314, 963, 879, 316, 59, 59, 1002,
  133247. /* 1200 */ 9, 90, 91, 48, 48, 238, 238, 210, 92, 964,
  133248. /* 1210 */ 382, 486, 485, 176, 334, 871, 242, 481, 1193, 238,
  133249. /* 1220 */ 238, 333, 333, 332, 227, 330, 394, 270, 719, 277,
  133250. /* 1230 */ 471, 481, 467, 466, 484, 145, 217, 1201, 1002, 1003,
  133251. /* 1240 */ 1004, 187, 3, 265, 184, 445, 871, 871, 873, 874,
  133252. /* 1250 */ 21, 264, 1337, 450, 1051, 39, 39, 392, 356, 260,
  133253. /* 1260 */ 342, 121, 468, 411, 436, 821, 180, 1094, 1128, 820,
  133254. /* 1270 */ 303, 1021, 1272, 1271, 299, 259, 474, 238, 238, 1002,
  133255. /* 1280 */ 473, 189, 484, 318, 327, 238, 238, 484, 190, 481,
  133256. /* 1290 */ 446, 140, 188, 1343, 238, 238, 1038, 481, 148, 175,
  133257. /* 1300 */ 238, 238, 484, 49, 49, 219, 481, 484, 35, 35,
  133258. /* 1310 */ 1317, 1021, 481, 484, 1035, 484, 1315, 484, 1002, 1003,
  133259. /* 1320 */ 1004, 484, 66, 36, 36, 194, 352, 484, 38, 38,
  133260. /* 1330 */ 484, 259, 474, 69, 50, 50, 51, 51, 52, 52,
  133261. /* 1340 */ 359, 484, 12, 12, 484, 1198, 484, 158, 53, 53,
  133262. /* 1350 */ 405, 112, 112, 385, 389, 484, 26, 484, 143, 484,
  133263. /* 1360 */ 150, 484, 54, 54, 397, 40, 40, 55, 55, 484,
  133264. /* 1370 */ 79, 484, 153, 1190, 484, 154, 56, 56, 41, 41,
  133265. /* 1380 */ 58, 58, 133, 133, 484, 398, 484, 429, 484, 155,
  133266. /* 1390 */ 134, 134, 135, 135, 484, 63, 63, 484, 341, 484,
  133267. /* 1400 */ 339, 484, 196, 484, 156, 42, 42, 113, 113, 60,
  133268. /* 1410 */ 60, 484, 404, 484, 27, 114, 114, 1204, 115, 115,
  133269. /* 1420 */ 111, 111, 132, 132, 131, 131, 1266, 418, 484, 162,
  133270. /* 1430 */ 484, 200, 119, 119, 118, 118, 484, 74, 424, 484,
  133271. /* 1440 */ 1286, 484, 231, 484, 202, 484, 167, 286, 427, 116,
  133272. /* 1450 */ 116, 117, 117, 290, 203, 442, 1062, 62, 62, 204,
  133273. /* 1460 */ 64, 64, 61, 61, 33, 33, 37, 37, 344, 372,
  133274. /* 1470 */ 1114, 1105, 748, 1113, 374, 1112, 254, 458, 1086, 255,
  133275. /* 1480 */ 345, 1085, 302, 1084, 1355, 78, 1154, 311, 1104, 449,
  133276. /* 1490 */ 452, 1155, 1153, 218, 7, 313, 315, 320, 1152, 85,
  133277. /* 1500 */ 1252, 317, 109, 80, 463, 225, 461, 1068, 25, 487,
  133278. /* 1510 */ 997, 323, 257, 226, 229, 228, 1136, 324, 325, 326,
  133279. /* 1520 */ 488, 136, 1057, 1052, 1302, 1303, 1301, 706, 1300, 137,
  133280. /* 1530 */ 122, 138, 383, 173, 1082, 261, 186, 252, 1081, 65,
  133281. /* 1540 */ 387, 120, 938, 936, 855, 353, 149, 1079, 139, 151,
  133282. /* 1550 */ 192, 780, 195, 276, 952, 157, 141, 361, 70, 363,
  133283. /* 1560 */ 859, 159, 71, 72, 142, 73, 955, 354, 147, 197,
  133284. /* 1570 */ 198, 951, 130, 16, 199, 285, 216, 1032, 201, 423,
  133285. /* 1580 */ 164, 944, 163, 28, 721, 428, 304, 165, 205, 759,
  133286. /* 1590 */ 75, 432, 298, 17, 18, 437, 76, 253, 878, 144,
  133287. /* 1600 */ 877, 906, 77, 986, 30, 448, 987, 31, 451, 181,
  133288. /* 1610 */ 234, 236, 168, 828, 823, 89, 910, 921, 81, 907,
  133289. /* 1620 */ 215, 905, 909, 961, 960, 19, 221, 20, 220, 22,
  133290. /* 1630 */ 32, 331, 876, 731, 94, 790, 794, 8, 992, 222,
  133291. /* 1640 */ 480, 328, 1048, 1048, 1048, 1048, 1048, 1048, 1048, 1048,
  133292. /* 1650 */ 223, 1048, 1048, 1048, 1048, 1348, 1347,
  133293. };
  133294. static const YYCODETYPE yy_lookahead[] = {
  133295. /* 0 */ 174, 226, 227, 228, 226, 227, 228, 172, 145, 146,
  133296. /* 10 */ 147, 148, 149, 150, 153, 169, 170, 171, 155, 19,
  133297. /* 20 */ 157, 246, 192, 193, 177, 181, 182, 164, 169, 170,
  133298. /* 30 */ 171, 31, 164, 153, 190, 174, 175, 187, 153, 39,
  133299. /* 40 */ 7, 8, 9, 43, 44, 45, 46, 47, 48, 49,
  133300. /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 174, 196,
  133301. /* 60 */ 197, 226, 227, 228, 196, 197, 46, 47, 48, 49,
  133302. /* 70 */ 209, 208, 19, 226, 227, 228, 208, 174, 177, 26,
  133303. /* 80 */ 195, 213, 214, 22, 221, 85, 86, 87, 88, 89,
  133304. /* 90 */ 90, 91, 92, 93, 94, 95, 43, 44, 45, 46,
  133305. /* 100 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  133306. /* 110 */ 57, 172, 249, 153, 53, 153, 147, 148, 149, 150,
  133307. /* 120 */ 22, 23, 69, 103, 155, 19, 157, 226, 227, 228,
  133308. /* 130 */ 94, 95, 247, 164, 174, 175, 174, 175, 85, 86,
  133309. /* 140 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 43,
  133310. /* 150 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  133311. /* 160 */ 54, 55, 56, 57, 153, 196, 197, 153, 153, 209,
  133312. /* 170 */ 210, 209, 210, 67, 95, 161, 237, 208, 19, 165,
  133313. /* 180 */ 165, 242, 84, 24, 91, 92, 93, 94, 95, 223,
  133314. /* 190 */ 221, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  133315. /* 200 */ 94, 95, 43, 44, 45, 46, 47, 48, 49, 50,
  133316. /* 210 */ 51, 52, 53, 54, 55, 56, 57, 153, 249, 85,
  133317. /* 220 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  133318. /* 230 */ 219, 19, 109, 110, 111, 23, 89, 90, 91, 92,
  133319. /* 240 */ 93, 94, 95, 73, 85, 86, 87, 88, 89, 90,
  133320. /* 250 */ 91, 92, 93, 94, 95, 43, 44, 45, 46, 47,
  133321. /* 260 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  133322. /* 270 */ 153, 22, 23, 101, 173, 26, 104, 105, 106, 109,
  133323. /* 280 */ 110, 111, 181, 11, 19, 59, 114, 73, 23, 110,
  133324. /* 290 */ 111, 174, 175, 116, 80, 118, 119, 85, 86, 87,
  133325. /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 43, 44,
  133326. /* 310 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  133327. /* 320 */ 55, 56, 57, 109, 98, 99, 100, 101, 83, 153,
  133328. /* 330 */ 104, 105, 106, 84, 120, 121, 153, 19, 192, 193,
  133329. /* 340 */ 114, 23, 89, 90, 99, 59, 23, 230, 103, 26,
  133330. /* 350 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  133331. /* 360 */ 95, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  133332. /* 370 */ 52, 53, 54, 55, 56, 57, 153, 91, 153, 134,
  133333. /* 380 */ 135, 136, 110, 111, 98, 99, 100, 134, 153, 136,
  133334. /* 390 */ 19, 22, 23, 26, 23, 26, 80, 174, 175, 174,
  133335. /* 400 */ 175, 59, 219, 85, 86, 87, 88, 89, 90, 91,
  133336. /* 410 */ 92, 93, 94, 95, 43, 44, 45, 46, 47, 48,
  133337. /* 420 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 16,
  133338. /* 430 */ 153, 22, 209, 210, 209, 210, 120, 121, 196, 197,
  133339. /* 440 */ 98, 99, 100, 19, 46, 22, 23, 23, 252, 253,
  133340. /* 450 */ 208, 174, 175, 84, 219, 153, 85, 86, 87, 88,
  133341. /* 460 */ 89, 90, 91, 92, 93, 94, 95, 43, 44, 45,
  133342. /* 470 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  133343. /* 480 */ 56, 57, 153, 153, 153, 153, 209, 120, 121, 76,
  133344. /* 490 */ 153, 78, 109, 110, 111, 97, 19, 153, 89, 90,
  133345. /* 500 */ 198, 59, 183, 174, 175, 174, 175, 84, 153, 85,
  133346. /* 510 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  133347. /* 520 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  133348. /* 530 */ 53, 54, 55, 56, 57, 16, 197, 153, 22, 153,
  133349. /* 540 */ 153, 99, 198, 12, 153, 196, 197, 208, 153, 153,
  133350. /* 550 */ 195, 183, 19, 23, 222, 142, 26, 208, 27, 153,
  133351. /* 560 */ 174, 175, 85, 86, 87, 88, 89, 90, 91, 92,
  133352. /* 570 */ 93, 94, 95, 42, 188, 59, 43, 44, 45, 46,
  133353. /* 580 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  133354. /* 590 */ 57, 195, 22, 198, 63, 76, 153, 78, 167, 168,
  133355. /* 600 */ 153, 195, 167, 168, 73, 153, 222, 153, 19, 222,
  133356. /* 610 */ 153, 220, 153, 24, 98, 99, 100, 140, 85, 86,
  133357. /* 620 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 59,
  133358. /* 630 */ 100, 153, 43, 44, 45, 46, 47, 48, 49, 50,
  133359. /* 640 */ 51, 52, 53, 54, 55, 56, 57, 195, 153, 195,
  133360. /* 650 */ 153, 153, 174, 175, 26, 125, 120, 121, 153, 213,
  133361. /* 660 */ 214, 19, 153, 220, 153, 153, 188, 220, 98, 99,
  133362. /* 670 */ 100, 174, 175, 140, 85, 86, 87, 88, 89, 90,
  133363. /* 680 */ 91, 92, 93, 94, 95, 43, 44, 45, 46, 47,
  133364. /* 690 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  133365. /* 700 */ 243, 189, 243, 198, 172, 250, 251, 117, 31, 201,
  133366. /* 710 */ 26, 139, 122, 141, 19, 220, 39, 29, 220, 211,
  133367. /* 720 */ 24, 33, 153, 164, 153, 164, 19, 85, 86, 87,
  133368. /* 730 */ 88, 89, 90, 91, 92, 93, 94, 95, 43, 44,
  133369. /* 740 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  133370. /* 750 */ 55, 56, 57, 65, 243, 196, 197, 196, 197, 131,
  133371. /* 760 */ 189, 22, 103, 24, 153, 23, 19, 208, 26, 208,
  133372. /* 770 */ 102, 103, 113, 23, 242, 22, 26, 134, 164, 136,
  133373. /* 780 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  133374. /* 790 */ 95, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  133375. /* 800 */ 53, 54, 55, 56, 57, 98, 153, 153, 124, 153,
  133376. /* 810 */ 196, 197, 23, 23, 61, 26, 26, 19, 23, 123,
  133377. /* 820 */ 23, 26, 208, 26, 7, 8, 153, 22, 174, 175,
  133378. /* 830 */ 174, 175, 85, 86, 87, 88, 89, 90, 91, 92,
  133379. /* 840 */ 93, 94, 95, 45, 46, 47, 48, 49, 50, 51,
  133380. /* 850 */ 52, 53, 54, 55, 56, 57, 19, 20, 59, 22,
  133381. /* 860 */ 111, 59, 164, 23, 59, 23, 26, 153, 26, 59,
  133382. /* 870 */ 153, 72, 23, 36, 72, 26, 35, 23, 59, 134,
  133383. /* 880 */ 26, 136, 133, 85, 86, 87, 88, 89, 90, 91,
  133384. /* 890 */ 92, 93, 94, 95, 196, 197, 59, 98, 99, 100,
  133385. /* 900 */ 98, 99, 100, 98, 99, 100, 208, 66, 71, 99,
  133386. /* 910 */ 54, 55, 56, 57, 58, 74, 153, 80, 99, 19,
  133387. /* 920 */ 83, 223, 23, 26, 153, 26, 89, 90, 54, 55,
  133388. /* 930 */ 56, 57, 153, 96, 153, 98, 99, 100, 22, 153,
  133389. /* 940 */ 103, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  133390. /* 950 */ 94, 95, 183, 112, 158, 174, 175, 120, 121, 85,
  133391. /* 960 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  133392. /* 970 */ 215, 134, 135, 136, 137, 138, 0, 1, 2, 23,
  133393. /* 980 */ 21, 5, 26, 153, 22, 59, 10, 11, 12, 13,
  133394. /* 990 */ 14, 1, 2, 17, 212, 5, 153, 153, 98, 153,
  133395. /* 1000 */ 10, 11, 12, 13, 14, 108, 30, 17, 32, 193,
  133396. /* 1010 */ 153, 59, 153, 153, 170, 171, 40, 174, 175, 153,
  133397. /* 1020 */ 30, 59, 32, 19, 20, 99, 22, 170, 171, 233,
  133398. /* 1030 */ 40, 188, 236, 174, 175, 153, 153, 153, 79, 123,
  133399. /* 1040 */ 36, 89, 90, 153, 153, 153, 70, 188, 153, 97,
  133400. /* 1050 */ 98, 99, 100, 77, 102, 153, 80, 81, 174, 175,
  133401. /* 1060 */ 70, 99, 110, 59, 105, 174, 175, 77, 153, 238,
  133402. /* 1070 */ 80, 81, 188, 19, 20, 71, 22, 153, 153, 235,
  133403. /* 1080 */ 19, 22, 164, 24, 59, 153, 134, 83, 136, 153,
  133404. /* 1090 */ 36, 115, 235, 89, 90, 91, 120, 121, 153, 153,
  133405. /* 1100 */ 96, 142, 98, 99, 100, 115, 59, 103, 83, 239,
  133406. /* 1110 */ 120, 121, 199, 59, 196, 197, 153, 153, 59, 143,
  133407. /* 1120 */ 174, 175, 153, 98, 99, 71, 208, 153, 103, 165,
  133408. /* 1130 */ 153, 19, 20, 143, 22, 153, 153, 83, 134, 135,
  133409. /* 1140 */ 136, 137, 138, 89, 90, 98, 99, 100, 36, 185,
  133410. /* 1150 */ 96, 187, 98, 99, 100, 91, 95, 103, 99, 134,
  133411. /* 1160 */ 135, 136, 101, 102, 103, 104, 105, 106, 107, 153,
  133412. /* 1170 */ 26, 59, 125, 164, 113, 153, 153, 153, 212, 12,
  133413. /* 1180 */ 19, 117, 153, 71, 153, 212, 122, 164, 134, 135,
  133414. /* 1190 */ 136, 137, 138, 212, 27, 83, 212, 174, 175, 59,
  133415. /* 1200 */ 200, 89, 90, 174, 175, 196, 197, 46, 96, 42,
  133416. /* 1210 */ 98, 99, 100, 172, 151, 103, 5, 208, 203, 196,
  133417. /* 1220 */ 197, 10, 11, 12, 13, 14, 216, 216, 17, 244,
  133418. /* 1230 */ 63, 208, 209, 210, 153, 80, 24, 203, 98, 99,
  133419. /* 1240 */ 100, 30, 22, 32, 100, 164, 134, 135, 136, 137,
  133420. /* 1250 */ 138, 40, 148, 164, 150, 174, 175, 102, 97, 155,
  133421. /* 1260 */ 203, 157, 164, 244, 178, 125, 186, 182, 164, 125,
  133422. /* 1270 */ 177, 59, 177, 177, 113, 120, 121, 196, 197, 59,
  133423. /* 1280 */ 232, 70, 153, 216, 202, 196, 197, 153, 77, 208,
  133424. /* 1290 */ 209, 80, 81, 156, 196, 197, 60, 208, 248, 200,
  133425. /* 1300 */ 196, 197, 153, 174, 175, 123, 208, 153, 174, 175,
  133426. /* 1310 */ 160, 99, 208, 153, 38, 153, 160, 153, 98, 99,
  133427. /* 1320 */ 100, 153, 245, 174, 175, 221, 115, 153, 174, 175,
  133428. /* 1330 */ 153, 120, 121, 245, 174, 175, 174, 175, 174, 175,
  133429. /* 1340 */ 160, 153, 174, 175, 153, 225, 153, 22, 174, 175,
  133430. /* 1350 */ 97, 174, 175, 249, 143, 153, 224, 153, 43, 153,
  133431. /* 1360 */ 191, 153, 174, 175, 18, 174, 175, 174, 175, 153,
  133432. /* 1370 */ 131, 153, 194, 203, 153, 194, 174, 175, 174, 175,
  133433. /* 1380 */ 174, 175, 174, 175, 153, 160, 153, 18, 153, 194,
  133434. /* 1390 */ 174, 175, 174, 175, 153, 174, 175, 153, 225, 153,
  133435. /* 1400 */ 203, 153, 159, 153, 194, 174, 175, 174, 175, 174,
  133436. /* 1410 */ 175, 153, 203, 153, 224, 174, 175, 191, 174, 175,
  133437. /* 1420 */ 174, 175, 174, 175, 174, 175, 203, 160, 153, 191,
  133438. /* 1430 */ 153, 159, 174, 175, 174, 175, 153, 139, 62, 153,
  133439. /* 1440 */ 241, 153, 160, 153, 159, 153, 22, 240, 179, 174,
  133440. /* 1450 */ 175, 174, 175, 160, 159, 97, 160, 174, 175, 159,
  133441. /* 1460 */ 174, 175, 174, 175, 174, 175, 174, 175, 179, 64,
  133442. /* 1470 */ 176, 184, 108, 176, 95, 176, 234, 126, 176, 234,
  133443. /* 1480 */ 179, 178, 176, 176, 176, 97, 218, 217, 184, 179,
  133444. /* 1490 */ 179, 218, 218, 160, 22, 217, 217, 160, 218, 139,
  133445. /* 1500 */ 229, 217, 130, 129, 127, 25, 128, 163, 26, 162,
  133446. /* 1510 */ 13, 206, 231, 154, 6, 154, 207, 205, 204, 203,
  133447. /* 1520 */ 152, 166, 152, 152, 172, 172, 172, 4, 172, 166,
  133448. /* 1530 */ 180, 166, 3, 22, 172, 144, 15, 180, 172, 172,
  133449. /* 1540 */ 82, 16, 23, 23, 121, 254, 132, 172, 112, 124,
  133450. /* 1550 */ 24, 20, 126, 16, 1, 124, 112, 61, 53, 37,
  133451. /* 1560 */ 133, 132, 53, 53, 112, 53, 98, 254, 251, 34,
  133452. /* 1570 */ 123, 1, 5, 22, 97, 142, 26, 75, 123, 41,
  133453. /* 1580 */ 97, 68, 68, 24, 20, 19, 113, 22, 107, 28,
  133454. /* 1590 */ 22, 67, 23, 22, 22, 67, 22, 67, 23, 37,
  133455. /* 1600 */ 23, 23, 26, 23, 22, 24, 23, 22, 24, 123,
  133456. /* 1610 */ 23, 23, 22, 98, 125, 26, 11, 23, 26, 23,
  133457. /* 1620 */ 34, 23, 23, 23, 23, 34, 22, 34, 26, 22,
  133458. /* 1630 */ 22, 15, 23, 23, 22, 117, 23, 22, 1, 123,
  133459. /* 1640 */ 26, 23, 255, 255, 255, 255, 255, 255, 255, 255,
  133460. /* 1650 */ 123, 255, 255, 255, 255, 123, 123, 255, 255, 255,
  133461. /* 1660 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133462. /* 1670 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133463. /* 1680 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133464. /* 1690 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133465. /* 1700 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133466. /* 1710 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133467. /* 1720 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133468. /* 1730 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133469. /* 1740 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133470. /* 1750 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133471. /* 1760 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133472. /* 1770 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133473. /* 1780 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133474. /* 1790 */ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  133475. /* 1800 */ 255, 255,
  133476. };
  133477. #define YY_SHIFT_COUNT (489)
  133478. #define YY_SHIFT_MIN (0)
  133479. #define YY_SHIFT_MAX (1637)
  133480. static const unsigned short int yy_shift_ofst[] = {
  133481. /* 0 */ 990, 976, 1211, 837, 837, 316, 1054, 1054, 1054, 1054,
  133482. /* 10 */ 214, 0, 0, 106, 642, 1054, 1054, 1054, 1054, 1054,
  133483. /* 20 */ 1054, 1054, 1054, 952, 952, 226, 1155, 316, 316, 316,
  133484. /* 30 */ 316, 316, 316, 53, 159, 212, 265, 318, 371, 424,
  133485. /* 40 */ 477, 533, 589, 642, 642, 642, 642, 642, 642, 642,
  133486. /* 50 */ 642, 642, 642, 642, 642, 642, 642, 642, 642, 642,
  133487. /* 60 */ 695, 642, 747, 798, 798, 1004, 1054, 1054, 1054, 1054,
  133488. /* 70 */ 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054,
  133489. /* 80 */ 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054,
  133490. /* 90 */ 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1112, 1054, 1054,
  133491. /* 100 */ 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054, 1054,
  133492. /* 110 */ 1054, 856, 874, 874, 874, 874, 874, 134, 147, 93,
  133493. /* 120 */ 342, 959, 1161, 253, 253, 342, 367, 367, 367, 367,
  133494. /* 130 */ 179, 36, 79, 1657, 1657, 1657, 1061, 1061, 1061, 516,
  133495. /* 140 */ 799, 516, 516, 531, 531, 802, 249, 369, 342, 342,
  133496. /* 150 */ 342, 342, 342, 342, 342, 342, 342, 342, 342, 342,
  133497. /* 160 */ 342, 342, 342, 342, 342, 342, 342, 342, 342, 272,
  133498. /* 170 */ 442, 442, 536, 1657, 1657, 1657, 1025, 245, 245, 570,
  133499. /* 180 */ 172, 286, 805, 1047, 1140, 1220, 342, 342, 342, 342,
  133500. /* 190 */ 342, 342, 342, 342, 170, 342, 342, 342, 342, 342,
  133501. /* 200 */ 342, 342, 342, 342, 342, 342, 342, 841, 841, 841,
  133502. /* 210 */ 342, 342, 342, 342, 530, 342, 342, 342, 1059, 342,
  133503. /* 220 */ 342, 1167, 342, 342, 342, 342, 342, 342, 342, 342,
  133504. /* 230 */ 123, 688, 177, 1212, 1212, 1212, 1212, 1144, 177, 177,
  133505. /* 240 */ 1064, 409, 33, 628, 707, 707, 900, 628, 628, 900,
  133506. /* 250 */ 897, 323, 398, 677, 677, 677, 707, 572, 684, 590,
  133507. /* 260 */ 739, 1236, 1182, 1182, 1276, 1276, 1182, 1253, 1325, 1315,
  133508. /* 270 */ 1239, 1346, 1346, 1346, 1346, 1182, 1369, 1239, 1239, 1253,
  133509. /* 280 */ 1325, 1315, 1315, 1239, 1182, 1369, 1298, 1376, 1182, 1369,
  133510. /* 290 */ 1424, 1182, 1369, 1182, 1369, 1424, 1358, 1358, 1358, 1405,
  133511. /* 300 */ 1424, 1358, 1364, 1358, 1405, 1358, 1358, 1424, 1379, 1379,
  133512. /* 310 */ 1424, 1351, 1388, 1351, 1388, 1351, 1388, 1351, 1388, 1182,
  133513. /* 320 */ 1472, 1182, 1360, 1372, 1377, 1374, 1378, 1239, 1480, 1482,
  133514. /* 330 */ 1497, 1497, 1508, 1508, 1508, 1657, 1657, 1657, 1657, 1657,
  133515. /* 340 */ 1657, 1657, 1657, 1657, 1657, 1657, 1657, 1657, 1657, 1657,
  133516. /* 350 */ 1657, 20, 413, 98, 423, 519, 383, 962, 742, 61,
  133517. /* 360 */ 696, 749, 750, 753, 789, 790, 795, 797, 840, 842,
  133518. /* 370 */ 810, 668, 817, 659, 819, 849, 854, 899, 643, 745,
  133519. /* 380 */ 956, 926, 916, 1523, 1529, 1511, 1391, 1521, 1458, 1525,
  133520. /* 390 */ 1519, 1520, 1423, 1414, 1436, 1526, 1425, 1531, 1426, 1537,
  133521. /* 400 */ 1553, 1431, 1427, 1444, 1496, 1522, 1429, 1505, 1509, 1510,
  133522. /* 410 */ 1512, 1452, 1468, 1535, 1447, 1570, 1567, 1551, 1477, 1433,
  133523. /* 420 */ 1513, 1550, 1514, 1502, 1538, 1455, 1483, 1559, 1564, 1566,
  133524. /* 430 */ 1473, 1481, 1565, 1524, 1568, 1571, 1569, 1572, 1528, 1561,
  133525. /* 440 */ 1574, 1530, 1562, 1575, 1577, 1578, 1576, 1580, 1582, 1581,
  133526. /* 450 */ 1583, 1585, 1584, 1486, 1587, 1588, 1515, 1586, 1590, 1489,
  133527. /* 460 */ 1589, 1591, 1592, 1593, 1594, 1596, 1598, 1589, 1599, 1600,
  133528. /* 470 */ 1602, 1601, 1604, 1605, 1607, 1608, 1609, 1610, 1612, 1613,
  133529. /* 480 */ 1615, 1614, 1518, 1516, 1527, 1532, 1533, 1618, 1616, 1637,
  133530. };
  133531. #define YY_REDUCE_COUNT (350)
  133532. #define YY_REDUCE_MIN (-225)
  133533. #define YY_REDUCE_MAX (1375)
  133534. static const short yy_reduce_ofst[] = {
  133535. /* 0 */ -137, -31, 1104, 1023, 1081, -132, -40, -38, 223, 225,
  133536. /* 10 */ 698, -153, -99, -225, -165, 386, 478, 843, 859, -139,
  133537. /* 20 */ 884, 117, 277, 844, 857, 964, 559, 561, 614, 918,
  133538. /* 30 */ 1009, 1089, 1098, -222, -222, -222, -222, -222, -222, -222,
  133539. /* 40 */ -222, -222, -222, -222, -222, -222, -222, -222, -222, -222,
  133540. /* 50 */ -222, -222, -222, -222, -222, -222, -222, -222, -222, -222,
  133541. /* 60 */ -222, -222, -222, -222, -222, 329, 331, 497, 654, 656,
  133542. /* 70 */ 781, 891, 946, 1029, 1129, 1134, 1149, 1154, 1160, 1162,
  133543. /* 80 */ 1164, 1168, 1174, 1177, 1188, 1191, 1193, 1202, 1204, 1206,
  133544. /* 90 */ 1208, 1216, 1218, 1221, 1231, 1233, 1235, 1241, 1244, 1246,
  133545. /* 100 */ 1248, 1250, 1258, 1260, 1275, 1277, 1283, 1286, 1288, 1290,
  133546. /* 110 */ 1292, -222, -222, -222, -222, -222, -222, -222, -222, -222,
  133547. /* 120 */ -115, 796, -156, -154, -141, 14, 242, 349, 242, 349,
  133548. /* 130 */ -61, -222, -222, -222, -222, -222, 101, 101, 101, 332,
  133549. /* 140 */ 302, 384, 387, -170, 146, 344, 196, 196, 15, 11,
  133550. /* 150 */ 183, 235, 395, 355, 396, 406, 452, 457, 391, 459,
  133551. /* 160 */ 443, 447, 511, 495, 454, 512, 505, 571, 498, 532,
  133552. /* 170 */ 431, 435, 339, 455, 446, 508, -174, -116, -97, -120,
  133553. /* 180 */ -150, 64, 176, 330, 337, 509, 569, 611, 653, 673,
  133554. /* 190 */ 714, 717, 763, 771, -34, 779, 786, 830, 846, 860,
  133555. /* 200 */ 866, 882, 883, 890, 892, 895, 902, 319, 368, 769,
  133556. /* 210 */ 915, 924, 925, 932, 755, 936, 945, 963, 782, 969,
  133557. /* 220 */ 974, 816, 977, 64, 982, 983, 1016, 1022, 1024, 1031,
  133558. /* 230 */ 870, 831, 913, 966, 973, 981, 984, 755, 913, 913,
  133559. /* 240 */ 1000, 1041, 1063, 1015, 1010, 1011, 985, 1034, 1057, 1019,
  133560. /* 250 */ 1086, 1080, 1085, 1093, 1095, 1096, 1067, 1048, 1082, 1099,
  133561. /* 260 */ 1137, 1050, 1150, 1156, 1077, 1088, 1180, 1120, 1132, 1169,
  133562. /* 270 */ 1170, 1178, 1181, 1195, 1210, 1225, 1243, 1197, 1209, 1173,
  133563. /* 280 */ 1190, 1226, 1238, 1223, 1267, 1272, 1199, 1207, 1282, 1285,
  133564. /* 290 */ 1269, 1293, 1295, 1296, 1300, 1289, 1294, 1297, 1299, 1287,
  133565. /* 300 */ 1301, 1302, 1303, 1306, 1304, 1307, 1308, 1310, 1242, 1245,
  133566. /* 310 */ 1311, 1268, 1270, 1273, 1278, 1274, 1279, 1280, 1284, 1333,
  133567. /* 320 */ 1271, 1337, 1281, 1309, 1305, 1312, 1314, 1316, 1344, 1347,
  133568. /* 330 */ 1359, 1361, 1368, 1370, 1371, 1291, 1313, 1317, 1355, 1352,
  133569. /* 340 */ 1353, 1354, 1356, 1363, 1350, 1357, 1362, 1366, 1367, 1375,
  133570. /* 350 */ 1365,
  133571. };
  133572. static const YYACTIONTYPE yy_default[] = {
  133573. /* 0 */ 1389, 1389, 1389, 1261, 1046, 1151, 1261, 1261, 1261, 1261,
  133574. /* 10 */ 1046, 1181, 1181, 1312, 1077, 1046, 1046, 1046, 1046, 1046,
  133575. /* 20 */ 1046, 1260, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133576. /* 30 */ 1046, 1046, 1046, 1187, 1046, 1046, 1046, 1046, 1262, 1263,
  133577. /* 40 */ 1046, 1046, 1046, 1311, 1313, 1197, 1196, 1195, 1194, 1294,
  133578. /* 50 */ 1168, 1192, 1185, 1189, 1256, 1257, 1255, 1259, 1262, 1263,
  133579. /* 60 */ 1046, 1188, 1226, 1240, 1225, 1046, 1046, 1046, 1046, 1046,
  133580. /* 70 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133581. /* 80 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133582. /* 90 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133583. /* 100 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133584. /* 110 */ 1046, 1234, 1239, 1246, 1238, 1235, 1228, 1227, 1229, 1230,
  133585. /* 120 */ 1046, 1067, 1116, 1046, 1046, 1046, 1329, 1328, 1046, 1046,
  133586. /* 130 */ 1077, 1231, 1232, 1243, 1242, 1241, 1319, 1345, 1344, 1046,
  133587. /* 140 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133588. /* 150 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133589. /* 160 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1077,
  133590. /* 170 */ 1073, 1073, 1046, 1324, 1151, 1142, 1046, 1046, 1046, 1046,
  133591. /* 180 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1316, 1314, 1046,
  133592. /* 190 */ 1276, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133593. /* 200 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133594. /* 210 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1147, 1046,
  133595. /* 220 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1339,
  133596. /* 230 */ 1046, 1289, 1130, 1147, 1147, 1147, 1147, 1149, 1131, 1129,
  133597. /* 240 */ 1141, 1077, 1053, 1191, 1170, 1170, 1378, 1191, 1191, 1378,
  133598. /* 250 */ 1091, 1359, 1088, 1181, 1181, 1181, 1170, 1258, 1148, 1141,
  133599. /* 260 */ 1046, 1381, 1156, 1156, 1380, 1380, 1156, 1200, 1206, 1119,
  133600. /* 270 */ 1191, 1125, 1125, 1125, 1125, 1156, 1064, 1191, 1191, 1200,
  133601. /* 280 */ 1206, 1119, 1119, 1191, 1156, 1064, 1293, 1375, 1156, 1064,
  133602. /* 290 */ 1269, 1156, 1064, 1156, 1064, 1269, 1117, 1117, 1117, 1106,
  133603. /* 300 */ 1269, 1117, 1091, 1117, 1106, 1117, 1117, 1269, 1273, 1273,
  133604. /* 310 */ 1269, 1174, 1169, 1174, 1169, 1174, 1169, 1174, 1169, 1156,
  133605. /* 320 */ 1264, 1156, 1046, 1186, 1175, 1184, 1182, 1191, 1070, 1109,
  133606. /* 330 */ 1342, 1342, 1338, 1338, 1338, 1386, 1386, 1324, 1354, 1077,
  133607. /* 340 */ 1077, 1077, 1077, 1354, 1093, 1093, 1077, 1077, 1077, 1077,
  133608. /* 350 */ 1354, 1046, 1046, 1046, 1046, 1046, 1046, 1349, 1046, 1278,
  133609. /* 360 */ 1160, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133610. /* 370 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133611. /* 380 */ 1046, 1046, 1211, 1046, 1049, 1321, 1046, 1046, 1320, 1046,
  133612. /* 390 */ 1046, 1046, 1046, 1046, 1046, 1161, 1046, 1046, 1046, 1046,
  133613. /* 400 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133614. /* 410 */ 1046, 1046, 1046, 1046, 1377, 1046, 1046, 1046, 1046, 1046,
  133615. /* 420 */ 1046, 1292, 1291, 1046, 1046, 1158, 1046, 1046, 1046, 1046,
  133616. /* 430 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133617. /* 440 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133618. /* 450 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133619. /* 460 */ 1183, 1046, 1176, 1046, 1046, 1046, 1046, 1368, 1046, 1046,
  133620. /* 470 */ 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046, 1046,
  133621. /* 480 */ 1046, 1363, 1133, 1213, 1046, 1212, 1216, 1046, 1058, 1046,
  133622. };
  133623. /********** End of lemon-generated parsing tables *****************************/
  133624. /* The next table maps tokens (terminal symbols) into fallback tokens.
  133625. ** If a construct like the following:
  133626. **
  133627. ** %fallback ID X Y Z.
  133628. **
  133629. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  133630. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  133631. ** but it does not parse, the type of the token is changed to ID and
  133632. ** the parse is retried before an error is thrown.
  133633. **
  133634. ** This feature can be used, for example, to cause some keywords in a language
  133635. ** to revert to identifiers if they keyword does not apply in the context where
  133636. ** it appears.
  133637. */
  133638. #ifdef YYFALLBACK
  133639. static const YYCODETYPE yyFallback[] = {
  133640. 0, /* $ => nothing */
  133641. 0, /* SEMI => nothing */
  133642. 59, /* EXPLAIN => ID */
  133643. 59, /* QUERY => ID */
  133644. 59, /* PLAN => ID */
  133645. 59, /* BEGIN => ID */
  133646. 0, /* TRANSACTION => nothing */
  133647. 59, /* DEFERRED => ID */
  133648. 59, /* IMMEDIATE => ID */
  133649. 59, /* EXCLUSIVE => ID */
  133650. 0, /* COMMIT => nothing */
  133651. 59, /* END => ID */
  133652. 59, /* ROLLBACK => ID */
  133653. 59, /* SAVEPOINT => ID */
  133654. 59, /* RELEASE => ID */
  133655. 0, /* TO => nothing */
  133656. 0, /* TABLE => nothing */
  133657. 0, /* CREATE => nothing */
  133658. 59, /* IF => ID */
  133659. 0, /* NOT => nothing */
  133660. 0, /* EXISTS => nothing */
  133661. 59, /* TEMP => ID */
  133662. 0, /* LP => nothing */
  133663. 0, /* RP => nothing */
  133664. 0, /* AS => nothing */
  133665. 59, /* WITHOUT => ID */
  133666. 0, /* COMMA => nothing */
  133667. 59, /* ABORT => ID */
  133668. 59, /* ACTION => ID */
  133669. 59, /* AFTER => ID */
  133670. 59, /* ANALYZE => ID */
  133671. 59, /* ASC => ID */
  133672. 59, /* ATTACH => ID */
  133673. 59, /* BEFORE => ID */
  133674. 59, /* BY => ID */
  133675. 59, /* CASCADE => ID */
  133676. 59, /* CAST => ID */
  133677. 59, /* CONFLICT => ID */
  133678. 59, /* DATABASE => ID */
  133679. 59, /* DESC => ID */
  133680. 59, /* DETACH => ID */
  133681. 59, /* EACH => ID */
  133682. 59, /* FAIL => ID */
  133683. 0, /* OR => nothing */
  133684. 0, /* AND => nothing */
  133685. 0, /* IS => nothing */
  133686. 59, /* MATCH => ID */
  133687. 59, /* LIKE_KW => ID */
  133688. 0, /* BETWEEN => nothing */
  133689. 0, /* IN => nothing */
  133690. 0, /* ISNULL => nothing */
  133691. 0, /* NOTNULL => nothing */
  133692. 0, /* NE => nothing */
  133693. 0, /* EQ => nothing */
  133694. 0, /* GT => nothing */
  133695. 0, /* LE => nothing */
  133696. 0, /* LT => nothing */
  133697. 0, /* GE => nothing */
  133698. 0, /* ESCAPE => nothing */
  133699. 0, /* ID => nothing */
  133700. 59, /* COLUMNKW => ID */
  133701. 59, /* DO => ID */
  133702. 59, /* FOR => ID */
  133703. 59, /* IGNORE => ID */
  133704. 59, /* INITIALLY => ID */
  133705. 59, /* INSTEAD => ID */
  133706. 59, /* NO => ID */
  133707. 59, /* KEY => ID */
  133708. 59, /* OF => ID */
  133709. 59, /* OFFSET => ID */
  133710. 59, /* PRAGMA => ID */
  133711. 59, /* RAISE => ID */
  133712. 59, /* RECURSIVE => ID */
  133713. 59, /* REPLACE => ID */
  133714. 59, /* RESTRICT => ID */
  133715. 59, /* ROW => ID */
  133716. 59, /* TRIGGER => ID */
  133717. 59, /* VACUUM => ID */
  133718. 59, /* VIEW => ID */
  133719. 59, /* VIRTUAL => ID */
  133720. 59, /* WITH => ID */
  133721. 59, /* REINDEX => ID */
  133722. 59, /* RENAME => ID */
  133723. 59, /* CTIME_KW => ID */
  133724. };
  133725. #endif /* YYFALLBACK */
  133726. /* The following structure represents a single element of the
  133727. ** parser's stack. Information stored includes:
  133728. **
  133729. ** + The state number for the parser at this level of the stack.
  133730. **
  133731. ** + The value of the token stored at this level of the stack.
  133732. ** (In other words, the "major" token.)
  133733. **
  133734. ** + The semantic value stored at this level of the stack. This is
  133735. ** the information used by the action routines in the grammar.
  133736. ** It is sometimes called the "minor" token.
  133737. **
  133738. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  133739. ** actually contains the reduce action for the second half of the
  133740. ** SHIFTREDUCE.
  133741. */
  133742. struct yyStackEntry {
  133743. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  133744. YYCODETYPE major; /* The major token value. This is the code
  133745. ** number for the token at this stack level */
  133746. YYMINORTYPE minor; /* The user-supplied minor token value. This
  133747. ** is the value of the token */
  133748. };
  133749. typedef struct yyStackEntry yyStackEntry;
  133750. /* The state of the parser is completely contained in an instance of
  133751. ** the following structure */
  133752. struct yyParser {
  133753. yyStackEntry *yytos; /* Pointer to top element of the stack */
  133754. #ifdef YYTRACKMAXSTACKDEPTH
  133755. int yyhwm; /* High-water mark of the stack */
  133756. #endif
  133757. #ifndef YYNOERRORRECOVERY
  133758. int yyerrcnt; /* Shifts left before out of the error */
  133759. #endif
  133760. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  133761. sqlite3ParserCTX_SDECL /* A place to hold %extra_context */
  133762. #if YYSTACKDEPTH<=0
  133763. int yystksz; /* Current side of the stack */
  133764. yyStackEntry *yystack; /* The parser's stack */
  133765. yyStackEntry yystk0; /* First stack entry */
  133766. #else
  133767. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  133768. yyStackEntry *yystackEnd; /* Last entry in the stack */
  133769. #endif
  133770. };
  133771. typedef struct yyParser yyParser;
  133772. #ifndef NDEBUG
  133773. /* #include <stdio.h> */
  133774. static FILE *yyTraceFILE = 0;
  133775. static char *yyTracePrompt = 0;
  133776. #endif /* NDEBUG */
  133777. #ifndef NDEBUG
  133778. /*
  133779. ** Turn parser tracing on by giving a stream to which to write the trace
  133780. ** and a prompt to preface each trace message. Tracing is turned off
  133781. ** by making either argument NULL
  133782. **
  133783. ** Inputs:
  133784. ** <ul>
  133785. ** <li> A FILE* to which trace output should be written.
  133786. ** If NULL, then tracing is turned off.
  133787. ** <li> A prefix string written at the beginning of every
  133788. ** line of trace output. If NULL, then tracing is
  133789. ** turned off.
  133790. ** </ul>
  133791. **
  133792. ** Outputs:
  133793. ** None.
  133794. */
  133795. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  133796. yyTraceFILE = TraceFILE;
  133797. yyTracePrompt = zTracePrompt;
  133798. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  133799. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  133800. }
  133801. #endif /* NDEBUG */
  133802. #if defined(YYCOVERAGE) || !defined(NDEBUG)
  133803. /* For tracing shifts, the names of all terminals and nonterminals
  133804. ** are required. The following table supplies these names */
  133805. static const char *const yyTokenName[] = {
  133806. /* 0 */ "$",
  133807. /* 1 */ "SEMI",
  133808. /* 2 */ "EXPLAIN",
  133809. /* 3 */ "QUERY",
  133810. /* 4 */ "PLAN",
  133811. /* 5 */ "BEGIN",
  133812. /* 6 */ "TRANSACTION",
  133813. /* 7 */ "DEFERRED",
  133814. /* 8 */ "IMMEDIATE",
  133815. /* 9 */ "EXCLUSIVE",
  133816. /* 10 */ "COMMIT",
  133817. /* 11 */ "END",
  133818. /* 12 */ "ROLLBACK",
  133819. /* 13 */ "SAVEPOINT",
  133820. /* 14 */ "RELEASE",
  133821. /* 15 */ "TO",
  133822. /* 16 */ "TABLE",
  133823. /* 17 */ "CREATE",
  133824. /* 18 */ "IF",
  133825. /* 19 */ "NOT",
  133826. /* 20 */ "EXISTS",
  133827. /* 21 */ "TEMP",
  133828. /* 22 */ "LP",
  133829. /* 23 */ "RP",
  133830. /* 24 */ "AS",
  133831. /* 25 */ "WITHOUT",
  133832. /* 26 */ "COMMA",
  133833. /* 27 */ "ABORT",
  133834. /* 28 */ "ACTION",
  133835. /* 29 */ "AFTER",
  133836. /* 30 */ "ANALYZE",
  133837. /* 31 */ "ASC",
  133838. /* 32 */ "ATTACH",
  133839. /* 33 */ "BEFORE",
  133840. /* 34 */ "BY",
  133841. /* 35 */ "CASCADE",
  133842. /* 36 */ "CAST",
  133843. /* 37 */ "CONFLICT",
  133844. /* 38 */ "DATABASE",
  133845. /* 39 */ "DESC",
  133846. /* 40 */ "DETACH",
  133847. /* 41 */ "EACH",
  133848. /* 42 */ "FAIL",
  133849. /* 43 */ "OR",
  133850. /* 44 */ "AND",
  133851. /* 45 */ "IS",
  133852. /* 46 */ "MATCH",
  133853. /* 47 */ "LIKE_KW",
  133854. /* 48 */ "BETWEEN",
  133855. /* 49 */ "IN",
  133856. /* 50 */ "ISNULL",
  133857. /* 51 */ "NOTNULL",
  133858. /* 52 */ "NE",
  133859. /* 53 */ "EQ",
  133860. /* 54 */ "GT",
  133861. /* 55 */ "LE",
  133862. /* 56 */ "LT",
  133863. /* 57 */ "GE",
  133864. /* 58 */ "ESCAPE",
  133865. /* 59 */ "ID",
  133866. /* 60 */ "COLUMNKW",
  133867. /* 61 */ "DO",
  133868. /* 62 */ "FOR",
  133869. /* 63 */ "IGNORE",
  133870. /* 64 */ "INITIALLY",
  133871. /* 65 */ "INSTEAD",
  133872. /* 66 */ "NO",
  133873. /* 67 */ "KEY",
  133874. /* 68 */ "OF",
  133875. /* 69 */ "OFFSET",
  133876. /* 70 */ "PRAGMA",
  133877. /* 71 */ "RAISE",
  133878. /* 72 */ "RECURSIVE",
  133879. /* 73 */ "REPLACE",
  133880. /* 74 */ "RESTRICT",
  133881. /* 75 */ "ROW",
  133882. /* 76 */ "TRIGGER",
  133883. /* 77 */ "VACUUM",
  133884. /* 78 */ "VIEW",
  133885. /* 79 */ "VIRTUAL",
  133886. /* 80 */ "WITH",
  133887. /* 81 */ "REINDEX",
  133888. /* 82 */ "RENAME",
  133889. /* 83 */ "CTIME_KW",
  133890. /* 84 */ "ANY",
  133891. /* 85 */ "BITAND",
  133892. /* 86 */ "BITOR",
  133893. /* 87 */ "LSHIFT",
  133894. /* 88 */ "RSHIFT",
  133895. /* 89 */ "PLUS",
  133896. /* 90 */ "MINUS",
  133897. /* 91 */ "STAR",
  133898. /* 92 */ "SLASH",
  133899. /* 93 */ "REM",
  133900. /* 94 */ "CONCAT",
  133901. /* 95 */ "COLLATE",
  133902. /* 96 */ "BITNOT",
  133903. /* 97 */ "ON",
  133904. /* 98 */ "INDEXED",
  133905. /* 99 */ "STRING",
  133906. /* 100 */ "JOIN_KW",
  133907. /* 101 */ "CONSTRAINT",
  133908. /* 102 */ "DEFAULT",
  133909. /* 103 */ "NULL",
  133910. /* 104 */ "PRIMARY",
  133911. /* 105 */ "UNIQUE",
  133912. /* 106 */ "CHECK",
  133913. /* 107 */ "REFERENCES",
  133914. /* 108 */ "AUTOINCR",
  133915. /* 109 */ "INSERT",
  133916. /* 110 */ "DELETE",
  133917. /* 111 */ "UPDATE",
  133918. /* 112 */ "SET",
  133919. /* 113 */ "DEFERRABLE",
  133920. /* 114 */ "FOREIGN",
  133921. /* 115 */ "DROP",
  133922. /* 116 */ "UNION",
  133923. /* 117 */ "ALL",
  133924. /* 118 */ "EXCEPT",
  133925. /* 119 */ "INTERSECT",
  133926. /* 120 */ "SELECT",
  133927. /* 121 */ "VALUES",
  133928. /* 122 */ "DISTINCT",
  133929. /* 123 */ "DOT",
  133930. /* 124 */ "FROM",
  133931. /* 125 */ "JOIN",
  133932. /* 126 */ "USING",
  133933. /* 127 */ "ORDER",
  133934. /* 128 */ "GROUP",
  133935. /* 129 */ "HAVING",
  133936. /* 130 */ "LIMIT",
  133937. /* 131 */ "WHERE",
  133938. /* 132 */ "INTO",
  133939. /* 133 */ "NOTHING",
  133940. /* 134 */ "FLOAT",
  133941. /* 135 */ "BLOB",
  133942. /* 136 */ "INTEGER",
  133943. /* 137 */ "VARIABLE",
  133944. /* 138 */ "CASE",
  133945. /* 139 */ "WHEN",
  133946. /* 140 */ "THEN",
  133947. /* 141 */ "ELSE",
  133948. /* 142 */ "INDEX",
  133949. /* 143 */ "ALTER",
  133950. /* 144 */ "ADD",
  133951. /* 145 */ "input",
  133952. /* 146 */ "cmdlist",
  133953. /* 147 */ "ecmd",
  133954. /* 148 */ "cmdx",
  133955. /* 149 */ "explain",
  133956. /* 150 */ "cmd",
  133957. /* 151 */ "transtype",
  133958. /* 152 */ "trans_opt",
  133959. /* 153 */ "nm",
  133960. /* 154 */ "savepoint_opt",
  133961. /* 155 */ "create_table",
  133962. /* 156 */ "create_table_args",
  133963. /* 157 */ "createkw",
  133964. /* 158 */ "temp",
  133965. /* 159 */ "ifnotexists",
  133966. /* 160 */ "dbnm",
  133967. /* 161 */ "columnlist",
  133968. /* 162 */ "conslist_opt",
  133969. /* 163 */ "table_options",
  133970. /* 164 */ "select",
  133971. /* 165 */ "columnname",
  133972. /* 166 */ "carglist",
  133973. /* 167 */ "typetoken",
  133974. /* 168 */ "typename",
  133975. /* 169 */ "signed",
  133976. /* 170 */ "plus_num",
  133977. /* 171 */ "minus_num",
  133978. /* 172 */ "scanpt",
  133979. /* 173 */ "ccons",
  133980. /* 174 */ "term",
  133981. /* 175 */ "expr",
  133982. /* 176 */ "onconf",
  133983. /* 177 */ "sortorder",
  133984. /* 178 */ "autoinc",
  133985. /* 179 */ "eidlist_opt",
  133986. /* 180 */ "refargs",
  133987. /* 181 */ "defer_subclause",
  133988. /* 182 */ "refarg",
  133989. /* 183 */ "refact",
  133990. /* 184 */ "init_deferred_pred_opt",
  133991. /* 185 */ "conslist",
  133992. /* 186 */ "tconscomma",
  133993. /* 187 */ "tcons",
  133994. /* 188 */ "sortlist",
  133995. /* 189 */ "eidlist",
  133996. /* 190 */ "defer_subclause_opt",
  133997. /* 191 */ "orconf",
  133998. /* 192 */ "resolvetype",
  133999. /* 193 */ "raisetype",
  134000. /* 194 */ "ifexists",
  134001. /* 195 */ "fullname",
  134002. /* 196 */ "selectnowith",
  134003. /* 197 */ "oneselect",
  134004. /* 198 */ "wqlist",
  134005. /* 199 */ "multiselect_op",
  134006. /* 200 */ "distinct",
  134007. /* 201 */ "selcollist",
  134008. /* 202 */ "from",
  134009. /* 203 */ "where_opt",
  134010. /* 204 */ "groupby_opt",
  134011. /* 205 */ "having_opt",
  134012. /* 206 */ "orderby_opt",
  134013. /* 207 */ "limit_opt",
  134014. /* 208 */ "values",
  134015. /* 209 */ "nexprlist",
  134016. /* 210 */ "exprlist",
  134017. /* 211 */ "sclp",
  134018. /* 212 */ "as",
  134019. /* 213 */ "seltablist",
  134020. /* 214 */ "stl_prefix",
  134021. /* 215 */ "joinop",
  134022. /* 216 */ "indexed_opt",
  134023. /* 217 */ "on_opt",
  134024. /* 218 */ "using_opt",
  134025. /* 219 */ "xfullname",
  134026. /* 220 */ "idlist",
  134027. /* 221 */ "with",
  134028. /* 222 */ "setlist",
  134029. /* 223 */ "insert_cmd",
  134030. /* 224 */ "idlist_opt",
  134031. /* 225 */ "upsert",
  134032. /* 226 */ "likeop",
  134033. /* 227 */ "between_op",
  134034. /* 228 */ "in_op",
  134035. /* 229 */ "paren_exprlist",
  134036. /* 230 */ "case_operand",
  134037. /* 231 */ "case_exprlist",
  134038. /* 232 */ "case_else",
  134039. /* 233 */ "uniqueflag",
  134040. /* 234 */ "collate",
  134041. /* 235 */ "nmnum",
  134042. /* 236 */ "trigger_decl",
  134043. /* 237 */ "trigger_cmd_list",
  134044. /* 238 */ "trigger_time",
  134045. /* 239 */ "trigger_event",
  134046. /* 240 */ "foreach_clause",
  134047. /* 241 */ "when_clause",
  134048. /* 242 */ "trigger_cmd",
  134049. /* 243 */ "trnm",
  134050. /* 244 */ "tridxby",
  134051. /* 245 */ "database_kw_opt",
  134052. /* 246 */ "key_opt",
  134053. /* 247 */ "add_column_fullname",
  134054. /* 248 */ "kwcolumn_opt",
  134055. /* 249 */ "create_vtab",
  134056. /* 250 */ "vtabarglist",
  134057. /* 251 */ "vtabarg",
  134058. /* 252 */ "vtabargtoken",
  134059. /* 253 */ "lp",
  134060. /* 254 */ "anylist",
  134061. };
  134062. #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
  134063. #ifndef NDEBUG
  134064. /* For tracing reduce actions, the names of all rules are required.
  134065. */
  134066. static const char *const yyRuleName[] = {
  134067. /* 0 */ "explain ::= EXPLAIN",
  134068. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  134069. /* 2 */ "cmdx ::= cmd",
  134070. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  134071. /* 4 */ "transtype ::=",
  134072. /* 5 */ "transtype ::= DEFERRED",
  134073. /* 6 */ "transtype ::= IMMEDIATE",
  134074. /* 7 */ "transtype ::= EXCLUSIVE",
  134075. /* 8 */ "cmd ::= COMMIT|END trans_opt",
  134076. /* 9 */ "cmd ::= ROLLBACK trans_opt",
  134077. /* 10 */ "cmd ::= SAVEPOINT nm",
  134078. /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
  134079. /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  134080. /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  134081. /* 14 */ "createkw ::= CREATE",
  134082. /* 15 */ "ifnotexists ::=",
  134083. /* 16 */ "ifnotexists ::= IF NOT EXISTS",
  134084. /* 17 */ "temp ::= TEMP",
  134085. /* 18 */ "temp ::=",
  134086. /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  134087. /* 20 */ "create_table_args ::= AS select",
  134088. /* 21 */ "table_options ::=",
  134089. /* 22 */ "table_options ::= WITHOUT nm",
  134090. /* 23 */ "columnname ::= nm typetoken",
  134091. /* 24 */ "typetoken ::=",
  134092. /* 25 */ "typetoken ::= typename LP signed RP",
  134093. /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
  134094. /* 27 */ "typename ::= typename ID|STRING",
  134095. /* 28 */ "scanpt ::=",
  134096. /* 29 */ "ccons ::= CONSTRAINT nm",
  134097. /* 30 */ "ccons ::= DEFAULT scanpt term scanpt",
  134098. /* 31 */ "ccons ::= DEFAULT LP expr RP",
  134099. /* 32 */ "ccons ::= DEFAULT PLUS term scanpt",
  134100. /* 33 */ "ccons ::= DEFAULT MINUS term scanpt",
  134101. /* 34 */ "ccons ::= DEFAULT scanpt ID|INDEXED",
  134102. /* 35 */ "ccons ::= NOT NULL onconf",
  134103. /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  134104. /* 37 */ "ccons ::= UNIQUE onconf",
  134105. /* 38 */ "ccons ::= CHECK LP expr RP",
  134106. /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  134107. /* 40 */ "ccons ::= defer_subclause",
  134108. /* 41 */ "ccons ::= COLLATE ID|STRING",
  134109. /* 42 */ "autoinc ::=",
  134110. /* 43 */ "autoinc ::= AUTOINCR",
  134111. /* 44 */ "refargs ::=",
  134112. /* 45 */ "refargs ::= refargs refarg",
  134113. /* 46 */ "refarg ::= MATCH nm",
  134114. /* 47 */ "refarg ::= ON INSERT refact",
  134115. /* 48 */ "refarg ::= ON DELETE refact",
  134116. /* 49 */ "refarg ::= ON UPDATE refact",
  134117. /* 50 */ "refact ::= SET NULL",
  134118. /* 51 */ "refact ::= SET DEFAULT",
  134119. /* 52 */ "refact ::= CASCADE",
  134120. /* 53 */ "refact ::= RESTRICT",
  134121. /* 54 */ "refact ::= NO ACTION",
  134122. /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  134123. /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  134124. /* 57 */ "init_deferred_pred_opt ::=",
  134125. /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  134126. /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  134127. /* 60 */ "conslist_opt ::=",
  134128. /* 61 */ "tconscomma ::= COMMA",
  134129. /* 62 */ "tcons ::= CONSTRAINT nm",
  134130. /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  134131. /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  134132. /* 65 */ "tcons ::= CHECK LP expr RP onconf",
  134133. /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  134134. /* 67 */ "defer_subclause_opt ::=",
  134135. /* 68 */ "onconf ::=",
  134136. /* 69 */ "onconf ::= ON CONFLICT resolvetype",
  134137. /* 70 */ "orconf ::=",
  134138. /* 71 */ "orconf ::= OR resolvetype",
  134139. /* 72 */ "resolvetype ::= IGNORE",
  134140. /* 73 */ "resolvetype ::= REPLACE",
  134141. /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
  134142. /* 75 */ "ifexists ::= IF EXISTS",
  134143. /* 76 */ "ifexists ::=",
  134144. /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  134145. /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
  134146. /* 79 */ "cmd ::= select",
  134147. /* 80 */ "select ::= WITH wqlist selectnowith",
  134148. /* 81 */ "select ::= WITH RECURSIVE wqlist selectnowith",
  134149. /* 82 */ "select ::= selectnowith",
  134150. /* 83 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  134151. /* 84 */ "multiselect_op ::= UNION",
  134152. /* 85 */ "multiselect_op ::= UNION ALL",
  134153. /* 86 */ "multiselect_op ::= EXCEPT|INTERSECT",
  134154. /* 87 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  134155. /* 88 */ "values ::= VALUES LP nexprlist RP",
  134156. /* 89 */ "values ::= values COMMA LP exprlist RP",
  134157. /* 90 */ "distinct ::= DISTINCT",
  134158. /* 91 */ "distinct ::= ALL",
  134159. /* 92 */ "distinct ::=",
  134160. /* 93 */ "sclp ::=",
  134161. /* 94 */ "selcollist ::= sclp scanpt expr scanpt as",
  134162. /* 95 */ "selcollist ::= sclp scanpt STAR",
  134163. /* 96 */ "selcollist ::= sclp scanpt nm DOT STAR",
  134164. /* 97 */ "as ::= AS nm",
  134165. /* 98 */ "as ::=",
  134166. /* 99 */ "from ::=",
  134167. /* 100 */ "from ::= FROM seltablist",
  134168. /* 101 */ "stl_prefix ::= seltablist joinop",
  134169. /* 102 */ "stl_prefix ::=",
  134170. /* 103 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  134171. /* 104 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  134172. /* 105 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  134173. /* 106 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  134174. /* 107 */ "dbnm ::=",
  134175. /* 108 */ "dbnm ::= DOT nm",
  134176. /* 109 */ "fullname ::= nm",
  134177. /* 110 */ "fullname ::= nm DOT nm",
  134178. /* 111 */ "xfullname ::= nm",
  134179. /* 112 */ "xfullname ::= nm DOT nm",
  134180. /* 113 */ "xfullname ::= nm DOT nm AS nm",
  134181. /* 114 */ "xfullname ::= nm AS nm",
  134182. /* 115 */ "joinop ::= COMMA|JOIN",
  134183. /* 116 */ "joinop ::= JOIN_KW JOIN",
  134184. /* 117 */ "joinop ::= JOIN_KW nm JOIN",
  134185. /* 118 */ "joinop ::= JOIN_KW nm nm JOIN",
  134186. /* 119 */ "on_opt ::= ON expr",
  134187. /* 120 */ "on_opt ::=",
  134188. /* 121 */ "indexed_opt ::=",
  134189. /* 122 */ "indexed_opt ::= INDEXED BY nm",
  134190. /* 123 */ "indexed_opt ::= NOT INDEXED",
  134191. /* 124 */ "using_opt ::= USING LP idlist RP",
  134192. /* 125 */ "using_opt ::=",
  134193. /* 126 */ "orderby_opt ::=",
  134194. /* 127 */ "orderby_opt ::= ORDER BY sortlist",
  134195. /* 128 */ "sortlist ::= sortlist COMMA expr sortorder",
  134196. /* 129 */ "sortlist ::= expr sortorder",
  134197. /* 130 */ "sortorder ::= ASC",
  134198. /* 131 */ "sortorder ::= DESC",
  134199. /* 132 */ "sortorder ::=",
  134200. /* 133 */ "groupby_opt ::=",
  134201. /* 134 */ "groupby_opt ::= GROUP BY nexprlist",
  134202. /* 135 */ "having_opt ::=",
  134203. /* 136 */ "having_opt ::= HAVING expr",
  134204. /* 137 */ "limit_opt ::=",
  134205. /* 138 */ "limit_opt ::= LIMIT expr",
  134206. /* 139 */ "limit_opt ::= LIMIT expr OFFSET expr",
  134207. /* 140 */ "limit_opt ::= LIMIT expr COMMA expr",
  134208. /* 141 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt",
  134209. /* 142 */ "where_opt ::=",
  134210. /* 143 */ "where_opt ::= WHERE expr",
  134211. /* 144 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt",
  134212. /* 145 */ "setlist ::= setlist COMMA nm EQ expr",
  134213. /* 146 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  134214. /* 147 */ "setlist ::= nm EQ expr",
  134215. /* 148 */ "setlist ::= LP idlist RP EQ expr",
  134216. /* 149 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
  134217. /* 150 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
  134218. /* 151 */ "upsert ::=",
  134219. /* 152 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
  134220. /* 153 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
  134221. /* 154 */ "upsert ::= ON CONFLICT DO NOTHING",
  134222. /* 155 */ "insert_cmd ::= INSERT orconf",
  134223. /* 156 */ "insert_cmd ::= REPLACE",
  134224. /* 157 */ "idlist_opt ::=",
  134225. /* 158 */ "idlist_opt ::= LP idlist RP",
  134226. /* 159 */ "idlist ::= idlist COMMA nm",
  134227. /* 160 */ "idlist ::= nm",
  134228. /* 161 */ "expr ::= LP expr RP",
  134229. /* 162 */ "expr ::= ID|INDEXED",
  134230. /* 163 */ "expr ::= JOIN_KW",
  134231. /* 164 */ "expr ::= nm DOT nm",
  134232. /* 165 */ "expr ::= nm DOT nm DOT nm",
  134233. /* 166 */ "term ::= NULL|FLOAT|BLOB",
  134234. /* 167 */ "term ::= STRING",
  134235. /* 168 */ "term ::= INTEGER",
  134236. /* 169 */ "expr ::= VARIABLE",
  134237. /* 170 */ "expr ::= expr COLLATE ID|STRING",
  134238. /* 171 */ "expr ::= CAST LP expr AS typetoken RP",
  134239. /* 172 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  134240. /* 173 */ "expr ::= ID|INDEXED LP STAR RP",
  134241. /* 174 */ "term ::= CTIME_KW",
  134242. /* 175 */ "expr ::= LP nexprlist COMMA expr RP",
  134243. /* 176 */ "expr ::= expr AND expr",
  134244. /* 177 */ "expr ::= expr OR expr",
  134245. /* 178 */ "expr ::= expr LT|GT|GE|LE expr",
  134246. /* 179 */ "expr ::= expr EQ|NE expr",
  134247. /* 180 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  134248. /* 181 */ "expr ::= expr PLUS|MINUS expr",
  134249. /* 182 */ "expr ::= expr STAR|SLASH|REM expr",
  134250. /* 183 */ "expr ::= expr CONCAT expr",
  134251. /* 184 */ "likeop ::= NOT LIKE_KW|MATCH",
  134252. /* 185 */ "expr ::= expr likeop expr",
  134253. /* 186 */ "expr ::= expr likeop expr ESCAPE expr",
  134254. /* 187 */ "expr ::= expr ISNULL|NOTNULL",
  134255. /* 188 */ "expr ::= expr NOT NULL",
  134256. /* 189 */ "expr ::= expr IS expr",
  134257. /* 190 */ "expr ::= expr IS NOT expr",
  134258. /* 191 */ "expr ::= NOT expr",
  134259. /* 192 */ "expr ::= BITNOT expr",
  134260. /* 193 */ "expr ::= MINUS expr",
  134261. /* 194 */ "expr ::= PLUS expr",
  134262. /* 195 */ "between_op ::= BETWEEN",
  134263. /* 196 */ "between_op ::= NOT BETWEEN",
  134264. /* 197 */ "expr ::= expr between_op expr AND expr",
  134265. /* 198 */ "in_op ::= IN",
  134266. /* 199 */ "in_op ::= NOT IN",
  134267. /* 200 */ "expr ::= expr in_op LP exprlist RP",
  134268. /* 201 */ "expr ::= LP select RP",
  134269. /* 202 */ "expr ::= expr in_op LP select RP",
  134270. /* 203 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  134271. /* 204 */ "expr ::= EXISTS LP select RP",
  134272. /* 205 */ "expr ::= CASE case_operand case_exprlist case_else END",
  134273. /* 206 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  134274. /* 207 */ "case_exprlist ::= WHEN expr THEN expr",
  134275. /* 208 */ "case_else ::= ELSE expr",
  134276. /* 209 */ "case_else ::=",
  134277. /* 210 */ "case_operand ::= expr",
  134278. /* 211 */ "case_operand ::=",
  134279. /* 212 */ "exprlist ::=",
  134280. /* 213 */ "nexprlist ::= nexprlist COMMA expr",
  134281. /* 214 */ "nexprlist ::= expr",
  134282. /* 215 */ "paren_exprlist ::=",
  134283. /* 216 */ "paren_exprlist ::= LP exprlist RP",
  134284. /* 217 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  134285. /* 218 */ "uniqueflag ::= UNIQUE",
  134286. /* 219 */ "uniqueflag ::=",
  134287. /* 220 */ "eidlist_opt ::=",
  134288. /* 221 */ "eidlist_opt ::= LP eidlist RP",
  134289. /* 222 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  134290. /* 223 */ "eidlist ::= nm collate sortorder",
  134291. /* 224 */ "collate ::=",
  134292. /* 225 */ "collate ::= COLLATE ID|STRING",
  134293. /* 226 */ "cmd ::= DROP INDEX ifexists fullname",
  134294. /* 227 */ "cmd ::= VACUUM",
  134295. /* 228 */ "cmd ::= VACUUM nm",
  134296. /* 229 */ "cmd ::= PRAGMA nm dbnm",
  134297. /* 230 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  134298. /* 231 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  134299. /* 232 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  134300. /* 233 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  134301. /* 234 */ "plus_num ::= PLUS INTEGER|FLOAT",
  134302. /* 235 */ "minus_num ::= MINUS INTEGER|FLOAT",
  134303. /* 236 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  134304. /* 237 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  134305. /* 238 */ "trigger_time ::= BEFORE|AFTER",
  134306. /* 239 */ "trigger_time ::= INSTEAD OF",
  134307. /* 240 */ "trigger_time ::=",
  134308. /* 241 */ "trigger_event ::= DELETE|INSERT",
  134309. /* 242 */ "trigger_event ::= UPDATE",
  134310. /* 243 */ "trigger_event ::= UPDATE OF idlist",
  134311. /* 244 */ "when_clause ::=",
  134312. /* 245 */ "when_clause ::= WHEN expr",
  134313. /* 246 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  134314. /* 247 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  134315. /* 248 */ "trnm ::= nm DOT nm",
  134316. /* 249 */ "tridxby ::= INDEXED BY nm",
  134317. /* 250 */ "tridxby ::= NOT INDEXED",
  134318. /* 251 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
  134319. /* 252 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
  134320. /* 253 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
  134321. /* 254 */ "trigger_cmd ::= scanpt select scanpt",
  134322. /* 255 */ "expr ::= RAISE LP IGNORE RP",
  134323. /* 256 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  134324. /* 257 */ "raisetype ::= ROLLBACK",
  134325. /* 258 */ "raisetype ::= ABORT",
  134326. /* 259 */ "raisetype ::= FAIL",
  134327. /* 260 */ "cmd ::= DROP TRIGGER ifexists fullname",
  134328. /* 261 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  134329. /* 262 */ "cmd ::= DETACH database_kw_opt expr",
  134330. /* 263 */ "key_opt ::=",
  134331. /* 264 */ "key_opt ::= KEY expr",
  134332. /* 265 */ "cmd ::= REINDEX",
  134333. /* 266 */ "cmd ::= REINDEX nm dbnm",
  134334. /* 267 */ "cmd ::= ANALYZE",
  134335. /* 268 */ "cmd ::= ANALYZE nm dbnm",
  134336. /* 269 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  134337. /* 270 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  134338. /* 271 */ "add_column_fullname ::= fullname",
  134339. /* 272 */ "cmd ::= create_vtab",
  134340. /* 273 */ "cmd ::= create_vtab LP vtabarglist RP",
  134341. /* 274 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  134342. /* 275 */ "vtabarg ::=",
  134343. /* 276 */ "vtabargtoken ::= ANY",
  134344. /* 277 */ "vtabargtoken ::= lp anylist RP",
  134345. /* 278 */ "lp ::= LP",
  134346. /* 279 */ "with ::= WITH wqlist",
  134347. /* 280 */ "with ::= WITH RECURSIVE wqlist",
  134348. /* 281 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  134349. /* 282 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  134350. /* 283 */ "input ::= cmdlist",
  134351. /* 284 */ "cmdlist ::= cmdlist ecmd",
  134352. /* 285 */ "cmdlist ::= ecmd",
  134353. /* 286 */ "ecmd ::= SEMI",
  134354. /* 287 */ "ecmd ::= cmdx SEMI",
  134355. /* 288 */ "ecmd ::= explain cmdx",
  134356. /* 289 */ "trans_opt ::=",
  134357. /* 290 */ "trans_opt ::= TRANSACTION",
  134358. /* 291 */ "trans_opt ::= TRANSACTION nm",
  134359. /* 292 */ "savepoint_opt ::= SAVEPOINT",
  134360. /* 293 */ "savepoint_opt ::=",
  134361. /* 294 */ "cmd ::= create_table create_table_args",
  134362. /* 295 */ "columnlist ::= columnlist COMMA columnname carglist",
  134363. /* 296 */ "columnlist ::= columnname carglist",
  134364. /* 297 */ "nm ::= ID|INDEXED",
  134365. /* 298 */ "nm ::= STRING",
  134366. /* 299 */ "nm ::= JOIN_KW",
  134367. /* 300 */ "typetoken ::= typename",
  134368. /* 301 */ "typename ::= ID|STRING",
  134369. /* 302 */ "signed ::= plus_num",
  134370. /* 303 */ "signed ::= minus_num",
  134371. /* 304 */ "carglist ::= carglist ccons",
  134372. /* 305 */ "carglist ::=",
  134373. /* 306 */ "ccons ::= NULL onconf",
  134374. /* 307 */ "conslist_opt ::= COMMA conslist",
  134375. /* 308 */ "conslist ::= conslist tconscomma tcons",
  134376. /* 309 */ "conslist ::= tcons",
  134377. /* 310 */ "tconscomma ::=",
  134378. /* 311 */ "defer_subclause_opt ::= defer_subclause",
  134379. /* 312 */ "resolvetype ::= raisetype",
  134380. /* 313 */ "selectnowith ::= oneselect",
  134381. /* 314 */ "oneselect ::= values",
  134382. /* 315 */ "sclp ::= selcollist COMMA",
  134383. /* 316 */ "as ::= ID|STRING",
  134384. /* 317 */ "expr ::= term",
  134385. /* 318 */ "likeop ::= LIKE_KW|MATCH",
  134386. /* 319 */ "exprlist ::= nexprlist",
  134387. /* 320 */ "nmnum ::= plus_num",
  134388. /* 321 */ "nmnum ::= nm",
  134389. /* 322 */ "nmnum ::= ON",
  134390. /* 323 */ "nmnum ::= DELETE",
  134391. /* 324 */ "nmnum ::= DEFAULT",
  134392. /* 325 */ "plus_num ::= INTEGER|FLOAT",
  134393. /* 326 */ "foreach_clause ::=",
  134394. /* 327 */ "foreach_clause ::= FOR EACH ROW",
  134395. /* 328 */ "trnm ::= nm",
  134396. /* 329 */ "tridxby ::=",
  134397. /* 330 */ "database_kw_opt ::= DATABASE",
  134398. /* 331 */ "database_kw_opt ::=",
  134399. /* 332 */ "kwcolumn_opt ::=",
  134400. /* 333 */ "kwcolumn_opt ::= COLUMNKW",
  134401. /* 334 */ "vtabarglist ::= vtabarg",
  134402. /* 335 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  134403. /* 336 */ "vtabarg ::= vtabarg vtabargtoken",
  134404. /* 337 */ "anylist ::=",
  134405. /* 338 */ "anylist ::= anylist LP anylist RP",
  134406. /* 339 */ "anylist ::= anylist ANY",
  134407. /* 340 */ "with ::=",
  134408. };
  134409. #endif /* NDEBUG */
  134410. #if YYSTACKDEPTH<=0
  134411. /*
  134412. ** Try to increase the size of the parser stack. Return the number
  134413. ** of errors. Return 0 on success.
  134414. */
  134415. static int yyGrowStack(yyParser *p){
  134416. int newSize;
  134417. int idx;
  134418. yyStackEntry *pNew;
  134419. newSize = p->yystksz*2 + 100;
  134420. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  134421. if( p->yystack==&p->yystk0 ){
  134422. pNew = malloc(newSize*sizeof(pNew[0]));
  134423. if( pNew ) pNew[0] = p->yystk0;
  134424. }else{
  134425. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  134426. }
  134427. if( pNew ){
  134428. p->yystack = pNew;
  134429. p->yytos = &p->yystack[idx];
  134430. #ifndef NDEBUG
  134431. if( yyTraceFILE ){
  134432. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  134433. yyTracePrompt, p->yystksz, newSize);
  134434. }
  134435. #endif
  134436. p->yystksz = newSize;
  134437. }
  134438. return pNew==0;
  134439. }
  134440. #endif
  134441. /* Datatype of the argument to the memory allocated passed as the
  134442. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  134443. ** putting an appropriate #define in the %include section of the input
  134444. ** grammar.
  134445. */
  134446. #ifndef YYMALLOCARGTYPE
  134447. # define YYMALLOCARGTYPE size_t
  134448. #endif
  134449. /* Initialize a new parser that has already been allocated.
  134450. */
  134451. SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
  134452. yyParser *yypParser = (yyParser*)yypRawParser;
  134453. sqlite3ParserCTX_STORE
  134454. #ifdef YYTRACKMAXSTACKDEPTH
  134455. yypParser->yyhwm = 0;
  134456. #endif
  134457. #if YYSTACKDEPTH<=0
  134458. yypParser->yytos = NULL;
  134459. yypParser->yystack = NULL;
  134460. yypParser->yystksz = 0;
  134461. if( yyGrowStack(yypParser) ){
  134462. yypParser->yystack = &yypParser->yystk0;
  134463. yypParser->yystksz = 1;
  134464. }
  134465. #endif
  134466. #ifndef YYNOERRORRECOVERY
  134467. yypParser->yyerrcnt = -1;
  134468. #endif
  134469. yypParser->yytos = yypParser->yystack;
  134470. yypParser->yystack[0].stateno = 0;
  134471. yypParser->yystack[0].major = 0;
  134472. #if YYSTACKDEPTH>0
  134473. yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
  134474. #endif
  134475. }
  134476. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  134477. /*
  134478. ** This function allocates a new parser.
  134479. ** The only argument is a pointer to a function which works like
  134480. ** malloc.
  134481. **
  134482. ** Inputs:
  134483. ** A pointer to the function used to allocate memory.
  134484. **
  134485. ** Outputs:
  134486. ** A pointer to a parser. This pointer is used in subsequent calls
  134487. ** to sqlite3Parser and sqlite3ParserFree.
  134488. */
  134489. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
  134490. yyParser *yypParser;
  134491. yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  134492. if( yypParser ){
  134493. sqlite3ParserCTX_STORE
  134494. sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
  134495. }
  134496. return (void*)yypParser;
  134497. }
  134498. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  134499. /* The following function deletes the "minor type" or semantic value
  134500. ** associated with a symbol. The symbol can be either a terminal
  134501. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  134502. ** a pointer to the value to be deleted. The code used to do the
  134503. ** deletions is derived from the %destructor and/or %token_destructor
  134504. ** directives of the input grammar.
  134505. */
  134506. static void yy_destructor(
  134507. yyParser *yypParser, /* The parser */
  134508. YYCODETYPE yymajor, /* Type code for object to destroy */
  134509. YYMINORTYPE *yypminor /* The object to be destroyed */
  134510. ){
  134511. sqlite3ParserARG_FETCH
  134512. sqlite3ParserCTX_FETCH
  134513. switch( yymajor ){
  134514. /* Here is inserted the actions which take place when a
  134515. ** terminal or non-terminal is destroyed. This can happen
  134516. ** when the symbol is popped from the stack during a
  134517. ** reduce or during error processing or when a parser is
  134518. ** being destroyed before it is finished parsing.
  134519. **
  134520. ** Note: during a reduce, the only symbols destroyed are those
  134521. ** which appear on the RHS of the rule, but which are *not* used
  134522. ** inside the C code.
  134523. */
  134524. /********* Begin destructor definitions ***************************************/
  134525. case 164: /* select */
  134526. case 196: /* selectnowith */
  134527. case 197: /* oneselect */
  134528. case 208: /* values */
  134529. {
  134530. sqlite3SelectDelete(pParse->db, (yypminor->yy399));
  134531. }
  134532. break;
  134533. case 174: /* term */
  134534. case 175: /* expr */
  134535. case 203: /* where_opt */
  134536. case 205: /* having_opt */
  134537. case 217: /* on_opt */
  134538. case 230: /* case_operand */
  134539. case 232: /* case_else */
  134540. case 241: /* when_clause */
  134541. case 246: /* key_opt */
  134542. {
  134543. sqlite3ExprDelete(pParse->db, (yypminor->yy182));
  134544. }
  134545. break;
  134546. case 179: /* eidlist_opt */
  134547. case 188: /* sortlist */
  134548. case 189: /* eidlist */
  134549. case 201: /* selcollist */
  134550. case 204: /* groupby_opt */
  134551. case 206: /* orderby_opt */
  134552. case 209: /* nexprlist */
  134553. case 210: /* exprlist */
  134554. case 211: /* sclp */
  134555. case 222: /* setlist */
  134556. case 229: /* paren_exprlist */
  134557. case 231: /* case_exprlist */
  134558. {
  134559. sqlite3ExprListDelete(pParse->db, (yypminor->yy232));
  134560. }
  134561. break;
  134562. case 195: /* fullname */
  134563. case 202: /* from */
  134564. case 213: /* seltablist */
  134565. case 214: /* stl_prefix */
  134566. case 219: /* xfullname */
  134567. {
  134568. sqlite3SrcListDelete(pParse->db, (yypminor->yy427));
  134569. }
  134570. break;
  134571. case 198: /* wqlist */
  134572. {
  134573. sqlite3WithDelete(pParse->db, (yypminor->yy91));
  134574. }
  134575. break;
  134576. case 218: /* using_opt */
  134577. case 220: /* idlist */
  134578. case 224: /* idlist_opt */
  134579. {
  134580. sqlite3IdListDelete(pParse->db, (yypminor->yy510));
  134581. }
  134582. break;
  134583. case 237: /* trigger_cmd_list */
  134584. case 242: /* trigger_cmd */
  134585. {
  134586. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy47));
  134587. }
  134588. break;
  134589. case 239: /* trigger_event */
  134590. {
  134591. sqlite3IdListDelete(pParse->db, (yypminor->yy300).b);
  134592. }
  134593. break;
  134594. /********* End destructor definitions *****************************************/
  134595. default: break; /* If no destructor action specified: do nothing */
  134596. }
  134597. }
  134598. /*
  134599. ** Pop the parser's stack once.
  134600. **
  134601. ** If there is a destructor routine associated with the token which
  134602. ** is popped from the stack, then call it.
  134603. */
  134604. static void yy_pop_parser_stack(yyParser *pParser){
  134605. yyStackEntry *yytos;
  134606. assert( pParser->yytos!=0 );
  134607. assert( pParser->yytos > pParser->yystack );
  134608. yytos = pParser->yytos--;
  134609. #ifndef NDEBUG
  134610. if( yyTraceFILE ){
  134611. fprintf(yyTraceFILE,"%sPopping %s\n",
  134612. yyTracePrompt,
  134613. yyTokenName[yytos->major]);
  134614. }
  134615. #endif
  134616. yy_destructor(pParser, yytos->major, &yytos->minor);
  134617. }
  134618. /*
  134619. ** Clear all secondary memory allocations from the parser
  134620. */
  134621. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  134622. yyParser *pParser = (yyParser*)p;
  134623. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  134624. #if YYSTACKDEPTH<=0
  134625. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  134626. #endif
  134627. }
  134628. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  134629. /*
  134630. ** Deallocate and destroy a parser. Destructors are called for
  134631. ** all stack elements before shutting the parser down.
  134632. **
  134633. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  134634. ** is defined in a %include section of the input grammar) then it is
  134635. ** assumed that the input pointer is never NULL.
  134636. */
  134637. SQLITE_PRIVATE void sqlite3ParserFree(
  134638. void *p, /* The parser to be deleted */
  134639. void (*freeProc)(void*) /* Function used to reclaim memory */
  134640. ){
  134641. #ifndef YYPARSEFREENEVERNULL
  134642. if( p==0 ) return;
  134643. #endif
  134644. sqlite3ParserFinalize(p);
  134645. (*freeProc)(p);
  134646. }
  134647. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  134648. /*
  134649. ** Return the peak depth of the stack for a parser.
  134650. */
  134651. #ifdef YYTRACKMAXSTACKDEPTH
  134652. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  134653. yyParser *pParser = (yyParser*)p;
  134654. return pParser->yyhwm;
  134655. }
  134656. #endif
  134657. /* This array of booleans keeps track of the parser statement
  134658. ** coverage. The element yycoverage[X][Y] is set when the parser
  134659. ** is in state X and has a lookahead token Y. In a well-tested
  134660. ** systems, every element of this matrix should end up being set.
  134661. */
  134662. #if defined(YYCOVERAGE)
  134663. static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
  134664. #endif
  134665. /*
  134666. ** Write into out a description of every state/lookahead combination that
  134667. **
  134668. ** (1) has not been used by the parser, and
  134669. ** (2) is not a syntax error.
  134670. **
  134671. ** Return the number of missed state/lookahead combinations.
  134672. */
  134673. #if defined(YYCOVERAGE)
  134674. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
  134675. int stateno, iLookAhead, i;
  134676. int nMissed = 0;
  134677. for(stateno=0; stateno<YYNSTATE; stateno++){
  134678. i = yy_shift_ofst[stateno];
  134679. for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
  134680. if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  134681. if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  134682. if( out ){
  134683. fprintf(out,"State %d lookahead %s %s\n", stateno,
  134684. yyTokenName[iLookAhead],
  134685. yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  134686. }
  134687. }
  134688. }
  134689. return nMissed;
  134690. }
  134691. #endif
  134692. /*
  134693. ** Find the appropriate action for a parser given the terminal
  134694. ** look-ahead token iLookAhead.
  134695. */
  134696. static YYACTIONTYPE yy_find_shift_action(
  134697. YYCODETYPE iLookAhead, /* The look-ahead token */
  134698. YYACTIONTYPE stateno /* Current state number */
  134699. ){
  134700. int i;
  134701. if( stateno>YY_MAX_SHIFT ) return stateno;
  134702. assert( stateno <= YY_SHIFT_COUNT );
  134703. #if defined(YYCOVERAGE)
  134704. yycoverage[stateno][iLookAhead] = 1;
  134705. #endif
  134706. do{
  134707. i = yy_shift_ofst[stateno];
  134708. assert( i>=0 );
  134709. assert( i+YYNTOKEN<=(int)sizeof(yy_lookahead)/sizeof(yy_lookahead[0]) );
  134710. assert( iLookAhead!=YYNOCODE );
  134711. assert( iLookAhead < YYNTOKEN );
  134712. i += iLookAhead;
  134713. if( yy_lookahead[i]!=iLookAhead ){
  134714. #ifdef YYFALLBACK
  134715. YYCODETYPE iFallback; /* Fallback token */
  134716. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  134717. && (iFallback = yyFallback[iLookAhead])!=0 ){
  134718. #ifndef NDEBUG
  134719. if( yyTraceFILE ){
  134720. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  134721. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  134722. }
  134723. #endif
  134724. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  134725. iLookAhead = iFallback;
  134726. continue;
  134727. }
  134728. #endif
  134729. #ifdef YYWILDCARD
  134730. {
  134731. int j = i - iLookAhead + YYWILDCARD;
  134732. if(
  134733. #if YY_SHIFT_MIN+YYWILDCARD<0
  134734. j>=0 &&
  134735. #endif
  134736. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  134737. j<YY_ACTTAB_COUNT &&
  134738. #endif
  134739. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  134740. ){
  134741. #ifndef NDEBUG
  134742. if( yyTraceFILE ){
  134743. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  134744. yyTracePrompt, yyTokenName[iLookAhead],
  134745. yyTokenName[YYWILDCARD]);
  134746. }
  134747. #endif /* NDEBUG */
  134748. return yy_action[j];
  134749. }
  134750. }
  134751. #endif /* YYWILDCARD */
  134752. return yy_default[stateno];
  134753. }else{
  134754. return yy_action[i];
  134755. }
  134756. }while(1);
  134757. }
  134758. /*
  134759. ** Find the appropriate action for a parser given the non-terminal
  134760. ** look-ahead token iLookAhead.
  134761. */
  134762. static int yy_find_reduce_action(
  134763. YYACTIONTYPE stateno, /* Current state number */
  134764. YYCODETYPE iLookAhead /* The look-ahead token */
  134765. ){
  134766. int i;
  134767. #ifdef YYERRORSYMBOL
  134768. if( stateno>YY_REDUCE_COUNT ){
  134769. return yy_default[stateno];
  134770. }
  134771. #else
  134772. assert( stateno<=YY_REDUCE_COUNT );
  134773. #endif
  134774. i = yy_reduce_ofst[stateno];
  134775. assert( iLookAhead!=YYNOCODE );
  134776. i += iLookAhead;
  134777. #ifdef YYERRORSYMBOL
  134778. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  134779. return yy_default[stateno];
  134780. }
  134781. #else
  134782. assert( i>=0 && i<YY_ACTTAB_COUNT );
  134783. assert( yy_lookahead[i]==iLookAhead );
  134784. #endif
  134785. return yy_action[i];
  134786. }
  134787. /*
  134788. ** The following routine is called if the stack overflows.
  134789. */
  134790. static void yyStackOverflow(yyParser *yypParser){
  134791. sqlite3ParserARG_FETCH
  134792. sqlite3ParserCTX_FETCH
  134793. #ifndef NDEBUG
  134794. if( yyTraceFILE ){
  134795. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  134796. }
  134797. #endif
  134798. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  134799. /* Here code is inserted which will execute if the parser
  134800. ** stack every overflows */
  134801. /******** Begin %stack_overflow code ******************************************/
  134802. sqlite3ErrorMsg(pParse, "parser stack overflow");
  134803. /******** End %stack_overflow code ********************************************/
  134804. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  134805. sqlite3ParserCTX_STORE
  134806. }
  134807. /*
  134808. ** Print tracing information for a SHIFT action
  134809. */
  134810. #ifndef NDEBUG
  134811. static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
  134812. if( yyTraceFILE ){
  134813. if( yyNewState<YYNSTATE ){
  134814. fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
  134815. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  134816. yyNewState);
  134817. }else{
  134818. fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  134819. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  134820. yyNewState - YY_MIN_REDUCE);
  134821. }
  134822. }
  134823. }
  134824. #else
  134825. # define yyTraceShift(X,Y,Z)
  134826. #endif
  134827. /*
  134828. ** Perform a shift action.
  134829. */
  134830. static void yy_shift(
  134831. yyParser *yypParser, /* The parser to be shifted */
  134832. YYACTIONTYPE yyNewState, /* The new state to shift in */
  134833. YYCODETYPE yyMajor, /* The major token to shift in */
  134834. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  134835. ){
  134836. yyStackEntry *yytos;
  134837. yypParser->yytos++;
  134838. #ifdef YYTRACKMAXSTACKDEPTH
  134839. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  134840. yypParser->yyhwm++;
  134841. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  134842. }
  134843. #endif
  134844. #if YYSTACKDEPTH>0
  134845. if( yypParser->yytos>yypParser->yystackEnd ){
  134846. yypParser->yytos--;
  134847. yyStackOverflow(yypParser);
  134848. return;
  134849. }
  134850. #else
  134851. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  134852. if( yyGrowStack(yypParser) ){
  134853. yypParser->yytos--;
  134854. yyStackOverflow(yypParser);
  134855. return;
  134856. }
  134857. }
  134858. #endif
  134859. if( yyNewState > YY_MAX_SHIFT ){
  134860. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  134861. }
  134862. yytos = yypParser->yytos;
  134863. yytos->stateno = yyNewState;
  134864. yytos->major = yyMajor;
  134865. yytos->minor.yy0 = yyMinor;
  134866. yyTraceShift(yypParser, yyNewState, "Shift");
  134867. }
  134868. /* The following table contains information about every rule that
  134869. ** is used during the reduce.
  134870. */
  134871. static const struct {
  134872. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  134873. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  134874. } yyRuleInfo[] = {
  134875. { 149, -1 }, /* (0) explain ::= EXPLAIN */
  134876. { 149, -3 }, /* (1) explain ::= EXPLAIN QUERY PLAN */
  134877. { 148, -1 }, /* (2) cmdx ::= cmd */
  134878. { 150, -3 }, /* (3) cmd ::= BEGIN transtype trans_opt */
  134879. { 151, 0 }, /* (4) transtype ::= */
  134880. { 151, -1 }, /* (5) transtype ::= DEFERRED */
  134881. { 151, -1 }, /* (6) transtype ::= IMMEDIATE */
  134882. { 151, -1 }, /* (7) transtype ::= EXCLUSIVE */
  134883. { 150, -2 }, /* (8) cmd ::= COMMIT|END trans_opt */
  134884. { 150, -2 }, /* (9) cmd ::= ROLLBACK trans_opt */
  134885. { 150, -2 }, /* (10) cmd ::= SAVEPOINT nm */
  134886. { 150, -3 }, /* (11) cmd ::= RELEASE savepoint_opt nm */
  134887. { 150, -5 }, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  134888. { 155, -6 }, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  134889. { 157, -1 }, /* (14) createkw ::= CREATE */
  134890. { 159, 0 }, /* (15) ifnotexists ::= */
  134891. { 159, -3 }, /* (16) ifnotexists ::= IF NOT EXISTS */
  134892. { 158, -1 }, /* (17) temp ::= TEMP */
  134893. { 158, 0 }, /* (18) temp ::= */
  134894. { 156, -5 }, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  134895. { 156, -2 }, /* (20) create_table_args ::= AS select */
  134896. { 163, 0 }, /* (21) table_options ::= */
  134897. { 163, -2 }, /* (22) table_options ::= WITHOUT nm */
  134898. { 165, -2 }, /* (23) columnname ::= nm typetoken */
  134899. { 167, 0 }, /* (24) typetoken ::= */
  134900. { 167, -4 }, /* (25) typetoken ::= typename LP signed RP */
  134901. { 167, -6 }, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  134902. { 168, -2 }, /* (27) typename ::= typename ID|STRING */
  134903. { 172, 0 }, /* (28) scanpt ::= */
  134904. { 173, -2 }, /* (29) ccons ::= CONSTRAINT nm */
  134905. { 173, -4 }, /* (30) ccons ::= DEFAULT scanpt term scanpt */
  134906. { 173, -4 }, /* (31) ccons ::= DEFAULT LP expr RP */
  134907. { 173, -4 }, /* (32) ccons ::= DEFAULT PLUS term scanpt */
  134908. { 173, -4 }, /* (33) ccons ::= DEFAULT MINUS term scanpt */
  134909. { 173, -3 }, /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
  134910. { 173, -3 }, /* (35) ccons ::= NOT NULL onconf */
  134911. { 173, -5 }, /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  134912. { 173, -2 }, /* (37) ccons ::= UNIQUE onconf */
  134913. { 173, -4 }, /* (38) ccons ::= CHECK LP expr RP */
  134914. { 173, -4 }, /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
  134915. { 173, -1 }, /* (40) ccons ::= defer_subclause */
  134916. { 173, -2 }, /* (41) ccons ::= COLLATE ID|STRING */
  134917. { 178, 0 }, /* (42) autoinc ::= */
  134918. { 178, -1 }, /* (43) autoinc ::= AUTOINCR */
  134919. { 180, 0 }, /* (44) refargs ::= */
  134920. { 180, -2 }, /* (45) refargs ::= refargs refarg */
  134921. { 182, -2 }, /* (46) refarg ::= MATCH nm */
  134922. { 182, -3 }, /* (47) refarg ::= ON INSERT refact */
  134923. { 182, -3 }, /* (48) refarg ::= ON DELETE refact */
  134924. { 182, -3 }, /* (49) refarg ::= ON UPDATE refact */
  134925. { 183, -2 }, /* (50) refact ::= SET NULL */
  134926. { 183, -2 }, /* (51) refact ::= SET DEFAULT */
  134927. { 183, -1 }, /* (52) refact ::= CASCADE */
  134928. { 183, -1 }, /* (53) refact ::= RESTRICT */
  134929. { 183, -2 }, /* (54) refact ::= NO ACTION */
  134930. { 181, -3 }, /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  134931. { 181, -2 }, /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  134932. { 184, 0 }, /* (57) init_deferred_pred_opt ::= */
  134933. { 184, -2 }, /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  134934. { 184, -2 }, /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  134935. { 162, 0 }, /* (60) conslist_opt ::= */
  134936. { 186, -1 }, /* (61) tconscomma ::= COMMA */
  134937. { 187, -2 }, /* (62) tcons ::= CONSTRAINT nm */
  134938. { 187, -7 }, /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  134939. { 187, -5 }, /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
  134940. { 187, -5 }, /* (65) tcons ::= CHECK LP expr RP onconf */
  134941. { 187, -10 }, /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  134942. { 190, 0 }, /* (67) defer_subclause_opt ::= */
  134943. { 176, 0 }, /* (68) onconf ::= */
  134944. { 176, -3 }, /* (69) onconf ::= ON CONFLICT resolvetype */
  134945. { 191, 0 }, /* (70) orconf ::= */
  134946. { 191, -2 }, /* (71) orconf ::= OR resolvetype */
  134947. { 192, -1 }, /* (72) resolvetype ::= IGNORE */
  134948. { 192, -1 }, /* (73) resolvetype ::= REPLACE */
  134949. { 150, -4 }, /* (74) cmd ::= DROP TABLE ifexists fullname */
  134950. { 194, -2 }, /* (75) ifexists ::= IF EXISTS */
  134951. { 194, 0 }, /* (76) ifexists ::= */
  134952. { 150, -9 }, /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  134953. { 150, -4 }, /* (78) cmd ::= DROP VIEW ifexists fullname */
  134954. { 150, -1 }, /* (79) cmd ::= select */
  134955. { 164, -3 }, /* (80) select ::= WITH wqlist selectnowith */
  134956. { 164, -4 }, /* (81) select ::= WITH RECURSIVE wqlist selectnowith */
  134957. { 164, -1 }, /* (82) select ::= selectnowith */
  134958. { 196, -3 }, /* (83) selectnowith ::= selectnowith multiselect_op oneselect */
  134959. { 199, -1 }, /* (84) multiselect_op ::= UNION */
  134960. { 199, -2 }, /* (85) multiselect_op ::= UNION ALL */
  134961. { 199, -1 }, /* (86) multiselect_op ::= EXCEPT|INTERSECT */
  134962. { 197, -9 }, /* (87) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  134963. { 208, -4 }, /* (88) values ::= VALUES LP nexprlist RP */
  134964. { 208, -5 }, /* (89) values ::= values COMMA LP exprlist RP */
  134965. { 200, -1 }, /* (90) distinct ::= DISTINCT */
  134966. { 200, -1 }, /* (91) distinct ::= ALL */
  134967. { 200, 0 }, /* (92) distinct ::= */
  134968. { 211, 0 }, /* (93) sclp ::= */
  134969. { 201, -5 }, /* (94) selcollist ::= sclp scanpt expr scanpt as */
  134970. { 201, -3 }, /* (95) selcollist ::= sclp scanpt STAR */
  134971. { 201, -5 }, /* (96) selcollist ::= sclp scanpt nm DOT STAR */
  134972. { 212, -2 }, /* (97) as ::= AS nm */
  134973. { 212, 0 }, /* (98) as ::= */
  134974. { 202, 0 }, /* (99) from ::= */
  134975. { 202, -2 }, /* (100) from ::= FROM seltablist */
  134976. { 214, -2 }, /* (101) stl_prefix ::= seltablist joinop */
  134977. { 214, 0 }, /* (102) stl_prefix ::= */
  134978. { 213, -7 }, /* (103) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  134979. { 213, -9 }, /* (104) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  134980. { 213, -7 }, /* (105) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  134981. { 213, -7 }, /* (106) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  134982. { 160, 0 }, /* (107) dbnm ::= */
  134983. { 160, -2 }, /* (108) dbnm ::= DOT nm */
  134984. { 195, -1 }, /* (109) fullname ::= nm */
  134985. { 195, -3 }, /* (110) fullname ::= nm DOT nm */
  134986. { 219, -1 }, /* (111) xfullname ::= nm */
  134987. { 219, -3 }, /* (112) xfullname ::= nm DOT nm */
  134988. { 219, -5 }, /* (113) xfullname ::= nm DOT nm AS nm */
  134989. { 219, -3 }, /* (114) xfullname ::= nm AS nm */
  134990. { 215, -1 }, /* (115) joinop ::= COMMA|JOIN */
  134991. { 215, -2 }, /* (116) joinop ::= JOIN_KW JOIN */
  134992. { 215, -3 }, /* (117) joinop ::= JOIN_KW nm JOIN */
  134993. { 215, -4 }, /* (118) joinop ::= JOIN_KW nm nm JOIN */
  134994. { 217, -2 }, /* (119) on_opt ::= ON expr */
  134995. { 217, 0 }, /* (120) on_opt ::= */
  134996. { 216, 0 }, /* (121) indexed_opt ::= */
  134997. { 216, -3 }, /* (122) indexed_opt ::= INDEXED BY nm */
  134998. { 216, -2 }, /* (123) indexed_opt ::= NOT INDEXED */
  134999. { 218, -4 }, /* (124) using_opt ::= USING LP idlist RP */
  135000. { 218, 0 }, /* (125) using_opt ::= */
  135001. { 206, 0 }, /* (126) orderby_opt ::= */
  135002. { 206, -3 }, /* (127) orderby_opt ::= ORDER BY sortlist */
  135003. { 188, -4 }, /* (128) sortlist ::= sortlist COMMA expr sortorder */
  135004. { 188, -2 }, /* (129) sortlist ::= expr sortorder */
  135005. { 177, -1 }, /* (130) sortorder ::= ASC */
  135006. { 177, -1 }, /* (131) sortorder ::= DESC */
  135007. { 177, 0 }, /* (132) sortorder ::= */
  135008. { 204, 0 }, /* (133) groupby_opt ::= */
  135009. { 204, -3 }, /* (134) groupby_opt ::= GROUP BY nexprlist */
  135010. { 205, 0 }, /* (135) having_opt ::= */
  135011. { 205, -2 }, /* (136) having_opt ::= HAVING expr */
  135012. { 207, 0 }, /* (137) limit_opt ::= */
  135013. { 207, -2 }, /* (138) limit_opt ::= LIMIT expr */
  135014. { 207, -4 }, /* (139) limit_opt ::= LIMIT expr OFFSET expr */
  135015. { 207, -4 }, /* (140) limit_opt ::= LIMIT expr COMMA expr */
  135016. { 150, -6 }, /* (141) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  135017. { 203, 0 }, /* (142) where_opt ::= */
  135018. { 203, -2 }, /* (143) where_opt ::= WHERE expr */
  135019. { 150, -8 }, /* (144) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  135020. { 222, -5 }, /* (145) setlist ::= setlist COMMA nm EQ expr */
  135021. { 222, -7 }, /* (146) setlist ::= setlist COMMA LP idlist RP EQ expr */
  135022. { 222, -3 }, /* (147) setlist ::= nm EQ expr */
  135023. { 222, -5 }, /* (148) setlist ::= LP idlist RP EQ expr */
  135024. { 150, -7 }, /* (149) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  135025. { 150, -7 }, /* (150) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  135026. { 225, 0 }, /* (151) upsert ::= */
  135027. { 225, -11 }, /* (152) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  135028. { 225, -8 }, /* (153) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  135029. { 225, -4 }, /* (154) upsert ::= ON CONFLICT DO NOTHING */
  135030. { 223, -2 }, /* (155) insert_cmd ::= INSERT orconf */
  135031. { 223, -1 }, /* (156) insert_cmd ::= REPLACE */
  135032. { 224, 0 }, /* (157) idlist_opt ::= */
  135033. { 224, -3 }, /* (158) idlist_opt ::= LP idlist RP */
  135034. { 220, -3 }, /* (159) idlist ::= idlist COMMA nm */
  135035. { 220, -1 }, /* (160) idlist ::= nm */
  135036. { 175, -3 }, /* (161) expr ::= LP expr RP */
  135037. { 175, -1 }, /* (162) expr ::= ID|INDEXED */
  135038. { 175, -1 }, /* (163) expr ::= JOIN_KW */
  135039. { 175, -3 }, /* (164) expr ::= nm DOT nm */
  135040. { 175, -5 }, /* (165) expr ::= nm DOT nm DOT nm */
  135041. { 174, -1 }, /* (166) term ::= NULL|FLOAT|BLOB */
  135042. { 174, -1 }, /* (167) term ::= STRING */
  135043. { 174, -1 }, /* (168) term ::= INTEGER */
  135044. { 175, -1 }, /* (169) expr ::= VARIABLE */
  135045. { 175, -3 }, /* (170) expr ::= expr COLLATE ID|STRING */
  135046. { 175, -6 }, /* (171) expr ::= CAST LP expr AS typetoken RP */
  135047. { 175, -5 }, /* (172) expr ::= ID|INDEXED LP distinct exprlist RP */
  135048. { 175, -4 }, /* (173) expr ::= ID|INDEXED LP STAR RP */
  135049. { 174, -1 }, /* (174) term ::= CTIME_KW */
  135050. { 175, -5 }, /* (175) expr ::= LP nexprlist COMMA expr RP */
  135051. { 175, -3 }, /* (176) expr ::= expr AND expr */
  135052. { 175, -3 }, /* (177) expr ::= expr OR expr */
  135053. { 175, -3 }, /* (178) expr ::= expr LT|GT|GE|LE expr */
  135054. { 175, -3 }, /* (179) expr ::= expr EQ|NE expr */
  135055. { 175, -3 }, /* (180) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  135056. { 175, -3 }, /* (181) expr ::= expr PLUS|MINUS expr */
  135057. { 175, -3 }, /* (182) expr ::= expr STAR|SLASH|REM expr */
  135058. { 175, -3 }, /* (183) expr ::= expr CONCAT expr */
  135059. { 226, -2 }, /* (184) likeop ::= NOT LIKE_KW|MATCH */
  135060. { 175, -3 }, /* (185) expr ::= expr likeop expr */
  135061. { 175, -5 }, /* (186) expr ::= expr likeop expr ESCAPE expr */
  135062. { 175, -2 }, /* (187) expr ::= expr ISNULL|NOTNULL */
  135063. { 175, -3 }, /* (188) expr ::= expr NOT NULL */
  135064. { 175, -3 }, /* (189) expr ::= expr IS expr */
  135065. { 175, -4 }, /* (190) expr ::= expr IS NOT expr */
  135066. { 175, -2 }, /* (191) expr ::= NOT expr */
  135067. { 175, -2 }, /* (192) expr ::= BITNOT expr */
  135068. { 175, -2 }, /* (193) expr ::= MINUS expr */
  135069. { 175, -2 }, /* (194) expr ::= PLUS expr */
  135070. { 227, -1 }, /* (195) between_op ::= BETWEEN */
  135071. { 227, -2 }, /* (196) between_op ::= NOT BETWEEN */
  135072. { 175, -5 }, /* (197) expr ::= expr between_op expr AND expr */
  135073. { 228, -1 }, /* (198) in_op ::= IN */
  135074. { 228, -2 }, /* (199) in_op ::= NOT IN */
  135075. { 175, -5 }, /* (200) expr ::= expr in_op LP exprlist RP */
  135076. { 175, -3 }, /* (201) expr ::= LP select RP */
  135077. { 175, -5 }, /* (202) expr ::= expr in_op LP select RP */
  135078. { 175, -5 }, /* (203) expr ::= expr in_op nm dbnm paren_exprlist */
  135079. { 175, -4 }, /* (204) expr ::= EXISTS LP select RP */
  135080. { 175, -5 }, /* (205) expr ::= CASE case_operand case_exprlist case_else END */
  135081. { 231, -5 }, /* (206) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  135082. { 231, -4 }, /* (207) case_exprlist ::= WHEN expr THEN expr */
  135083. { 232, -2 }, /* (208) case_else ::= ELSE expr */
  135084. { 232, 0 }, /* (209) case_else ::= */
  135085. { 230, -1 }, /* (210) case_operand ::= expr */
  135086. { 230, 0 }, /* (211) case_operand ::= */
  135087. { 210, 0 }, /* (212) exprlist ::= */
  135088. { 209, -3 }, /* (213) nexprlist ::= nexprlist COMMA expr */
  135089. { 209, -1 }, /* (214) nexprlist ::= expr */
  135090. { 229, 0 }, /* (215) paren_exprlist ::= */
  135091. { 229, -3 }, /* (216) paren_exprlist ::= LP exprlist RP */
  135092. { 150, -12 }, /* (217) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  135093. { 233, -1 }, /* (218) uniqueflag ::= UNIQUE */
  135094. { 233, 0 }, /* (219) uniqueflag ::= */
  135095. { 179, 0 }, /* (220) eidlist_opt ::= */
  135096. { 179, -3 }, /* (221) eidlist_opt ::= LP eidlist RP */
  135097. { 189, -5 }, /* (222) eidlist ::= eidlist COMMA nm collate sortorder */
  135098. { 189, -3 }, /* (223) eidlist ::= nm collate sortorder */
  135099. { 234, 0 }, /* (224) collate ::= */
  135100. { 234, -2 }, /* (225) collate ::= COLLATE ID|STRING */
  135101. { 150, -4 }, /* (226) cmd ::= DROP INDEX ifexists fullname */
  135102. { 150, -1 }, /* (227) cmd ::= VACUUM */
  135103. { 150, -2 }, /* (228) cmd ::= VACUUM nm */
  135104. { 150, -3 }, /* (229) cmd ::= PRAGMA nm dbnm */
  135105. { 150, -5 }, /* (230) cmd ::= PRAGMA nm dbnm EQ nmnum */
  135106. { 150, -6 }, /* (231) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  135107. { 150, -5 }, /* (232) cmd ::= PRAGMA nm dbnm EQ minus_num */
  135108. { 150, -6 }, /* (233) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  135109. { 170, -2 }, /* (234) plus_num ::= PLUS INTEGER|FLOAT */
  135110. { 171, -2 }, /* (235) minus_num ::= MINUS INTEGER|FLOAT */
  135111. { 150, -5 }, /* (236) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  135112. { 236, -11 }, /* (237) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  135113. { 238, -1 }, /* (238) trigger_time ::= BEFORE|AFTER */
  135114. { 238, -2 }, /* (239) trigger_time ::= INSTEAD OF */
  135115. { 238, 0 }, /* (240) trigger_time ::= */
  135116. { 239, -1 }, /* (241) trigger_event ::= DELETE|INSERT */
  135117. { 239, -1 }, /* (242) trigger_event ::= UPDATE */
  135118. { 239, -3 }, /* (243) trigger_event ::= UPDATE OF idlist */
  135119. { 241, 0 }, /* (244) when_clause ::= */
  135120. { 241, -2 }, /* (245) when_clause ::= WHEN expr */
  135121. { 237, -3 }, /* (246) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  135122. { 237, -2 }, /* (247) trigger_cmd_list ::= trigger_cmd SEMI */
  135123. { 243, -3 }, /* (248) trnm ::= nm DOT nm */
  135124. { 244, -3 }, /* (249) tridxby ::= INDEXED BY nm */
  135125. { 244, -2 }, /* (250) tridxby ::= NOT INDEXED */
  135126. { 242, -8 }, /* (251) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  135127. { 242, -8 }, /* (252) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  135128. { 242, -6 }, /* (253) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  135129. { 242, -3 }, /* (254) trigger_cmd ::= scanpt select scanpt */
  135130. { 175, -4 }, /* (255) expr ::= RAISE LP IGNORE RP */
  135131. { 175, -6 }, /* (256) expr ::= RAISE LP raisetype COMMA nm RP */
  135132. { 193, -1 }, /* (257) raisetype ::= ROLLBACK */
  135133. { 193, -1 }, /* (258) raisetype ::= ABORT */
  135134. { 193, -1 }, /* (259) raisetype ::= FAIL */
  135135. { 150, -4 }, /* (260) cmd ::= DROP TRIGGER ifexists fullname */
  135136. { 150, -6 }, /* (261) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  135137. { 150, -3 }, /* (262) cmd ::= DETACH database_kw_opt expr */
  135138. { 246, 0 }, /* (263) key_opt ::= */
  135139. { 246, -2 }, /* (264) key_opt ::= KEY expr */
  135140. { 150, -1 }, /* (265) cmd ::= REINDEX */
  135141. { 150, -3 }, /* (266) cmd ::= REINDEX nm dbnm */
  135142. { 150, -1 }, /* (267) cmd ::= ANALYZE */
  135143. { 150, -3 }, /* (268) cmd ::= ANALYZE nm dbnm */
  135144. { 150, -6 }, /* (269) cmd ::= ALTER TABLE fullname RENAME TO nm */
  135145. { 150, -7 }, /* (270) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  135146. { 247, -1 }, /* (271) add_column_fullname ::= fullname */
  135147. { 150, -1 }, /* (272) cmd ::= create_vtab */
  135148. { 150, -4 }, /* (273) cmd ::= create_vtab LP vtabarglist RP */
  135149. { 249, -8 }, /* (274) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  135150. { 251, 0 }, /* (275) vtabarg ::= */
  135151. { 252, -1 }, /* (276) vtabargtoken ::= ANY */
  135152. { 252, -3 }, /* (277) vtabargtoken ::= lp anylist RP */
  135153. { 253, -1 }, /* (278) lp ::= LP */
  135154. { 221, -2 }, /* (279) with ::= WITH wqlist */
  135155. { 221, -3 }, /* (280) with ::= WITH RECURSIVE wqlist */
  135156. { 198, -6 }, /* (281) wqlist ::= nm eidlist_opt AS LP select RP */
  135157. { 198, -8 }, /* (282) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  135158. { 145, -1 }, /* (283) input ::= cmdlist */
  135159. { 146, -2 }, /* (284) cmdlist ::= cmdlist ecmd */
  135160. { 146, -1 }, /* (285) cmdlist ::= ecmd */
  135161. { 147, -1 }, /* (286) ecmd ::= SEMI */
  135162. { 147, -2 }, /* (287) ecmd ::= cmdx SEMI */
  135163. { 147, -2 }, /* (288) ecmd ::= explain cmdx */
  135164. { 152, 0 }, /* (289) trans_opt ::= */
  135165. { 152, -1 }, /* (290) trans_opt ::= TRANSACTION */
  135166. { 152, -2 }, /* (291) trans_opt ::= TRANSACTION nm */
  135167. { 154, -1 }, /* (292) savepoint_opt ::= SAVEPOINT */
  135168. { 154, 0 }, /* (293) savepoint_opt ::= */
  135169. { 150, -2 }, /* (294) cmd ::= create_table create_table_args */
  135170. { 161, -4 }, /* (295) columnlist ::= columnlist COMMA columnname carglist */
  135171. { 161, -2 }, /* (296) columnlist ::= columnname carglist */
  135172. { 153, -1 }, /* (297) nm ::= ID|INDEXED */
  135173. { 153, -1 }, /* (298) nm ::= STRING */
  135174. { 153, -1 }, /* (299) nm ::= JOIN_KW */
  135175. { 167, -1 }, /* (300) typetoken ::= typename */
  135176. { 168, -1 }, /* (301) typename ::= ID|STRING */
  135177. { 169, -1 }, /* (302) signed ::= plus_num */
  135178. { 169, -1 }, /* (303) signed ::= minus_num */
  135179. { 166, -2 }, /* (304) carglist ::= carglist ccons */
  135180. { 166, 0 }, /* (305) carglist ::= */
  135181. { 173, -2 }, /* (306) ccons ::= NULL onconf */
  135182. { 162, -2 }, /* (307) conslist_opt ::= COMMA conslist */
  135183. { 185, -3 }, /* (308) conslist ::= conslist tconscomma tcons */
  135184. { 185, -1 }, /* (309) conslist ::= tcons */
  135185. { 186, 0 }, /* (310) tconscomma ::= */
  135186. { 190, -1 }, /* (311) defer_subclause_opt ::= defer_subclause */
  135187. { 192, -1 }, /* (312) resolvetype ::= raisetype */
  135188. { 196, -1 }, /* (313) selectnowith ::= oneselect */
  135189. { 197, -1 }, /* (314) oneselect ::= values */
  135190. { 211, -2 }, /* (315) sclp ::= selcollist COMMA */
  135191. { 212, -1 }, /* (316) as ::= ID|STRING */
  135192. { 175, -1 }, /* (317) expr ::= term */
  135193. { 226, -1 }, /* (318) likeop ::= LIKE_KW|MATCH */
  135194. { 210, -1 }, /* (319) exprlist ::= nexprlist */
  135195. { 235, -1 }, /* (320) nmnum ::= plus_num */
  135196. { 235, -1 }, /* (321) nmnum ::= nm */
  135197. { 235, -1 }, /* (322) nmnum ::= ON */
  135198. { 235, -1 }, /* (323) nmnum ::= DELETE */
  135199. { 235, -1 }, /* (324) nmnum ::= DEFAULT */
  135200. { 170, -1 }, /* (325) plus_num ::= INTEGER|FLOAT */
  135201. { 240, 0 }, /* (326) foreach_clause ::= */
  135202. { 240, -3 }, /* (327) foreach_clause ::= FOR EACH ROW */
  135203. { 243, -1 }, /* (328) trnm ::= nm */
  135204. { 244, 0 }, /* (329) tridxby ::= */
  135205. { 245, -1 }, /* (330) database_kw_opt ::= DATABASE */
  135206. { 245, 0 }, /* (331) database_kw_opt ::= */
  135207. { 248, 0 }, /* (332) kwcolumn_opt ::= */
  135208. { 248, -1 }, /* (333) kwcolumn_opt ::= COLUMNKW */
  135209. { 250, -1 }, /* (334) vtabarglist ::= vtabarg */
  135210. { 250, -3 }, /* (335) vtabarglist ::= vtabarglist COMMA vtabarg */
  135211. { 251, -2 }, /* (336) vtabarg ::= vtabarg vtabargtoken */
  135212. { 254, 0 }, /* (337) anylist ::= */
  135213. { 254, -4 }, /* (338) anylist ::= anylist LP anylist RP */
  135214. { 254, -2 }, /* (339) anylist ::= anylist ANY */
  135215. { 221, 0 }, /* (340) with ::= */
  135216. };
  135217. static void yy_accept(yyParser*); /* Forward Declaration */
  135218. /*
  135219. ** Perform a reduce action and the shift that must immediately
  135220. ** follow the reduce.
  135221. **
  135222. ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
  135223. ** access to the lookahead token (if any). The yyLookahead will be YYNOCODE
  135224. ** if the lookahead token has already been consumed. As this procedure is
  135225. ** only called from one place, optimizing compilers will in-line it, which
  135226. ** means that the extra parameters have no performance impact.
  135227. */
  135228. static YYACTIONTYPE yy_reduce(
  135229. yyParser *yypParser, /* The parser */
  135230. unsigned int yyruleno, /* Number of the rule by which to reduce */
  135231. int yyLookahead, /* Lookahead token, or YYNOCODE if none */
  135232. sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */
  135233. sqlite3ParserCTX_PDECL /* %extra_context */
  135234. ){
  135235. int yygoto; /* The next state */
  135236. int yyact; /* The next action */
  135237. yyStackEntry *yymsp; /* The top of the parser's stack */
  135238. int yysize; /* Amount to pop the stack */
  135239. sqlite3ParserARG_FETCH
  135240. (void)yyLookahead;
  135241. (void)yyLookaheadToken;
  135242. yymsp = yypParser->yytos;
  135243. #ifndef NDEBUG
  135244. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  135245. yysize = yyRuleInfo[yyruleno].nrhs;
  135246. if( yysize ){
  135247. fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  135248. yyTracePrompt,
  135249. yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
  135250. }else{
  135251. fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
  135252. yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
  135253. }
  135254. }
  135255. #endif /* NDEBUG */
  135256. /* Check that the stack is large enough to grow by a single entry
  135257. ** if the RHS of the rule is empty. This ensures that there is room
  135258. ** enough on the stack to push the LHS value */
  135259. if( yyRuleInfo[yyruleno].nrhs==0 ){
  135260. #ifdef YYTRACKMAXSTACKDEPTH
  135261. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  135262. yypParser->yyhwm++;
  135263. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  135264. }
  135265. #endif
  135266. #if YYSTACKDEPTH>0
  135267. if( yypParser->yytos>=yypParser->yystackEnd ){
  135268. yyStackOverflow(yypParser);
  135269. /* The call to yyStackOverflow() above pops the stack until it is
  135270. ** empty, causing the main parser loop to exit. So the return value
  135271. ** is never used and does not matter. */
  135272. return 0;
  135273. }
  135274. #else
  135275. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  135276. if( yyGrowStack(yypParser) ){
  135277. yyStackOverflow(yypParser);
  135278. /* The call to yyStackOverflow() above pops the stack until it is
  135279. ** empty, causing the main parser loop to exit. So the return value
  135280. ** is never used and does not matter. */
  135281. return 0;
  135282. }
  135283. yymsp = yypParser->yytos;
  135284. }
  135285. #endif
  135286. }
  135287. switch( yyruleno ){
  135288. /* Beginning here are the reduction cases. A typical example
  135289. ** follows:
  135290. ** case 0:
  135291. ** #line <lineno> <grammarfile>
  135292. ** { ... } // User supplied code
  135293. ** #line <lineno> <thisfile>
  135294. ** break;
  135295. */
  135296. /********** Begin reduce actions **********************************************/
  135297. YYMINORTYPE yylhsminor;
  135298. case 0: /* explain ::= EXPLAIN */
  135299. { pParse->explain = 1; }
  135300. break;
  135301. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  135302. { pParse->explain = 2; }
  135303. break;
  135304. case 2: /* cmdx ::= cmd */
  135305. { sqlite3FinishCoding(pParse); }
  135306. break;
  135307. case 3: /* cmd ::= BEGIN transtype trans_opt */
  135308. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy502);}
  135309. break;
  135310. case 4: /* transtype ::= */
  135311. {yymsp[1].minor.yy502 = TK_DEFERRED;}
  135312. break;
  135313. case 5: /* transtype ::= DEFERRED */
  135314. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  135315. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  135316. {yymsp[0].minor.yy502 = yymsp[0].major; /*A-overwrites-X*/}
  135317. break;
  135318. case 8: /* cmd ::= COMMIT|END trans_opt */
  135319. case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
  135320. {sqlite3EndTransaction(pParse,yymsp[-1].major);}
  135321. break;
  135322. case 10: /* cmd ::= SAVEPOINT nm */
  135323. {
  135324. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  135325. }
  135326. break;
  135327. case 11: /* cmd ::= RELEASE savepoint_opt nm */
  135328. {
  135329. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  135330. }
  135331. break;
  135332. case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  135333. {
  135334. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  135335. }
  135336. break;
  135337. case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  135338. {
  135339. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy502,0,0,yymsp[-2].minor.yy502);
  135340. }
  135341. break;
  135342. case 14: /* createkw ::= CREATE */
  135343. {disableLookaside(pParse);}
  135344. break;
  135345. case 15: /* ifnotexists ::= */
  135346. case 18: /* temp ::= */ yytestcase(yyruleno==18);
  135347. case 21: /* table_options ::= */ yytestcase(yyruleno==21);
  135348. case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
  135349. case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
  135350. case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
  135351. case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
  135352. case 92: /* distinct ::= */ yytestcase(yyruleno==92);
  135353. case 224: /* collate ::= */ yytestcase(yyruleno==224);
  135354. {yymsp[1].minor.yy502 = 0;}
  135355. break;
  135356. case 16: /* ifnotexists ::= IF NOT EXISTS */
  135357. {yymsp[-2].minor.yy502 = 1;}
  135358. break;
  135359. case 17: /* temp ::= TEMP */
  135360. case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
  135361. {yymsp[0].minor.yy502 = 1;}
  135362. break;
  135363. case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  135364. {
  135365. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy502,0);
  135366. }
  135367. break;
  135368. case 20: /* create_table_args ::= AS select */
  135369. {
  135370. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy399);
  135371. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy399);
  135372. }
  135373. break;
  135374. case 22: /* table_options ::= WITHOUT nm */
  135375. {
  135376. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  135377. yymsp[-1].minor.yy502 = TF_WithoutRowid | TF_NoVisibleRowid;
  135378. }else{
  135379. yymsp[-1].minor.yy502 = 0;
  135380. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  135381. }
  135382. }
  135383. break;
  135384. case 23: /* columnname ::= nm typetoken */
  135385. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  135386. break;
  135387. case 24: /* typetoken ::= */
  135388. case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
  135389. case 98: /* as ::= */ yytestcase(yyruleno==98);
  135390. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  135391. break;
  135392. case 25: /* typetoken ::= typename LP signed RP */
  135393. {
  135394. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  135395. }
  135396. break;
  135397. case 26: /* typetoken ::= typename LP signed COMMA signed RP */
  135398. {
  135399. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  135400. }
  135401. break;
  135402. case 27: /* typename ::= typename ID|STRING */
  135403. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  135404. break;
  135405. case 28: /* scanpt ::= */
  135406. {
  135407. assert( yyLookahead!=YYNOCODE );
  135408. yymsp[1].minor.yy36 = yyLookaheadToken.z;
  135409. }
  135410. break;
  135411. case 29: /* ccons ::= CONSTRAINT nm */
  135412. case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
  135413. {pParse->constraintName = yymsp[0].minor.yy0;}
  135414. break;
  135415. case 30: /* ccons ::= DEFAULT scanpt term scanpt */
  135416. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy182,yymsp[-2].minor.yy36,yymsp[0].minor.yy36);}
  135417. break;
  135418. case 31: /* ccons ::= DEFAULT LP expr RP */
  135419. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy182,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
  135420. break;
  135421. case 32: /* ccons ::= DEFAULT PLUS term scanpt */
  135422. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy182,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy36);}
  135423. break;
  135424. case 33: /* ccons ::= DEFAULT MINUS term scanpt */
  135425. {
  135426. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[-1].minor.yy182, 0);
  135427. sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy36);
  135428. }
  135429. break;
  135430. case 34: /* ccons ::= DEFAULT scanpt ID|INDEXED */
  135431. {
  135432. Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
  135433. if( p ){
  135434. sqlite3ExprIdToTrueFalse(p);
  135435. testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
  135436. }
  135437. sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
  135438. }
  135439. break;
  135440. case 35: /* ccons ::= NOT NULL onconf */
  135441. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy502);}
  135442. break;
  135443. case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  135444. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy502,yymsp[0].minor.yy502,yymsp[-2].minor.yy502);}
  135445. break;
  135446. case 37: /* ccons ::= UNIQUE onconf */
  135447. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy502,0,0,0,0,
  135448. SQLITE_IDXTYPE_UNIQUE);}
  135449. break;
  135450. case 38: /* ccons ::= CHECK LP expr RP */
  135451. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy182);}
  135452. break;
  135453. case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  135454. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy232,yymsp[0].minor.yy502);}
  135455. break;
  135456. case 40: /* ccons ::= defer_subclause */
  135457. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy502);}
  135458. break;
  135459. case 41: /* ccons ::= COLLATE ID|STRING */
  135460. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  135461. break;
  135462. case 44: /* refargs ::= */
  135463. { yymsp[1].minor.yy502 = OE_None*0x0101; /* EV: R-19803-45884 */}
  135464. break;
  135465. case 45: /* refargs ::= refargs refarg */
  135466. { yymsp[-1].minor.yy502 = (yymsp[-1].minor.yy502 & ~yymsp[0].minor.yy107.mask) | yymsp[0].minor.yy107.value; }
  135467. break;
  135468. case 46: /* refarg ::= MATCH nm */
  135469. { yymsp[-1].minor.yy107.value = 0; yymsp[-1].minor.yy107.mask = 0x000000; }
  135470. break;
  135471. case 47: /* refarg ::= ON INSERT refact */
  135472. { yymsp[-2].minor.yy107.value = 0; yymsp[-2].minor.yy107.mask = 0x000000; }
  135473. break;
  135474. case 48: /* refarg ::= ON DELETE refact */
  135475. { yymsp[-2].minor.yy107.value = yymsp[0].minor.yy502; yymsp[-2].minor.yy107.mask = 0x0000ff; }
  135476. break;
  135477. case 49: /* refarg ::= ON UPDATE refact */
  135478. { yymsp[-2].minor.yy107.value = yymsp[0].minor.yy502<<8; yymsp[-2].minor.yy107.mask = 0x00ff00; }
  135479. break;
  135480. case 50: /* refact ::= SET NULL */
  135481. { yymsp[-1].minor.yy502 = OE_SetNull; /* EV: R-33326-45252 */}
  135482. break;
  135483. case 51: /* refact ::= SET DEFAULT */
  135484. { yymsp[-1].minor.yy502 = OE_SetDflt; /* EV: R-33326-45252 */}
  135485. break;
  135486. case 52: /* refact ::= CASCADE */
  135487. { yymsp[0].minor.yy502 = OE_Cascade; /* EV: R-33326-45252 */}
  135488. break;
  135489. case 53: /* refact ::= RESTRICT */
  135490. { yymsp[0].minor.yy502 = OE_Restrict; /* EV: R-33326-45252 */}
  135491. break;
  135492. case 54: /* refact ::= NO ACTION */
  135493. { yymsp[-1].minor.yy502 = OE_None; /* EV: R-33326-45252 */}
  135494. break;
  135495. case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  135496. {yymsp[-2].minor.yy502 = 0;}
  135497. break;
  135498. case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  135499. case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
  135500. case 155: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==155);
  135501. {yymsp[-1].minor.yy502 = yymsp[0].minor.yy502;}
  135502. break;
  135503. case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  135504. case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
  135505. case 196: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==196);
  135506. case 199: /* in_op ::= NOT IN */ yytestcase(yyruleno==199);
  135507. case 225: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==225);
  135508. {yymsp[-1].minor.yy502 = 1;}
  135509. break;
  135510. case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  135511. {yymsp[-1].minor.yy502 = 0;}
  135512. break;
  135513. case 61: /* tconscomma ::= COMMA */
  135514. {pParse->constraintName.n = 0;}
  135515. break;
  135516. case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  135517. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy232,yymsp[0].minor.yy502,yymsp[-2].minor.yy502,0);}
  135518. break;
  135519. case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
  135520. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy232,yymsp[0].minor.yy502,0,0,0,0,
  135521. SQLITE_IDXTYPE_UNIQUE);}
  135522. break;
  135523. case 65: /* tcons ::= CHECK LP expr RP onconf */
  135524. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy182);}
  135525. break;
  135526. case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  135527. {
  135528. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy232, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy232, yymsp[-1].minor.yy502);
  135529. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy502);
  135530. }
  135531. break;
  135532. case 68: /* onconf ::= */
  135533. case 70: /* orconf ::= */ yytestcase(yyruleno==70);
  135534. {yymsp[1].minor.yy502 = OE_Default;}
  135535. break;
  135536. case 69: /* onconf ::= ON CONFLICT resolvetype */
  135537. {yymsp[-2].minor.yy502 = yymsp[0].minor.yy502;}
  135538. break;
  135539. case 72: /* resolvetype ::= IGNORE */
  135540. {yymsp[0].minor.yy502 = OE_Ignore;}
  135541. break;
  135542. case 73: /* resolvetype ::= REPLACE */
  135543. case 156: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==156);
  135544. {yymsp[0].minor.yy502 = OE_Replace;}
  135545. break;
  135546. case 74: /* cmd ::= DROP TABLE ifexists fullname */
  135547. {
  135548. sqlite3DropTable(pParse, yymsp[0].minor.yy427, 0, yymsp[-1].minor.yy502);
  135549. }
  135550. break;
  135551. case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  135552. {
  135553. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy232, yymsp[0].minor.yy399, yymsp[-7].minor.yy502, yymsp[-5].minor.yy502);
  135554. }
  135555. break;
  135556. case 78: /* cmd ::= DROP VIEW ifexists fullname */
  135557. {
  135558. sqlite3DropTable(pParse, yymsp[0].minor.yy427, 1, yymsp[-1].minor.yy502);
  135559. }
  135560. break;
  135561. case 79: /* cmd ::= select */
  135562. {
  135563. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  135564. sqlite3Select(pParse, yymsp[0].minor.yy399, &dest);
  135565. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy399);
  135566. }
  135567. break;
  135568. case 80: /* select ::= WITH wqlist selectnowith */
  135569. {
  135570. Select *p = yymsp[0].minor.yy399;
  135571. if( p ){
  135572. p->pWith = yymsp[-1].minor.yy91;
  135573. parserDoubleLinkSelect(pParse, p);
  135574. }else{
  135575. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy91);
  135576. }
  135577. yymsp[-2].minor.yy399 = p;
  135578. }
  135579. break;
  135580. case 81: /* select ::= WITH RECURSIVE wqlist selectnowith */
  135581. {
  135582. Select *p = yymsp[0].minor.yy399;
  135583. if( p ){
  135584. p->pWith = yymsp[-1].minor.yy91;
  135585. parserDoubleLinkSelect(pParse, p);
  135586. }else{
  135587. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy91);
  135588. }
  135589. yymsp[-3].minor.yy399 = p;
  135590. }
  135591. break;
  135592. case 82: /* select ::= selectnowith */
  135593. {
  135594. Select *p = yymsp[0].minor.yy399;
  135595. if( p ){
  135596. parserDoubleLinkSelect(pParse, p);
  135597. }
  135598. yymsp[0].minor.yy399 = p; /*A-overwrites-X*/
  135599. }
  135600. break;
  135601. case 83: /* selectnowith ::= selectnowith multiselect_op oneselect */
  135602. {
  135603. Select *pRhs = yymsp[0].minor.yy399;
  135604. Select *pLhs = yymsp[-2].minor.yy399;
  135605. if( pRhs && pRhs->pPrior ){
  135606. SrcList *pFrom;
  135607. Token x;
  135608. x.n = 0;
  135609. parserDoubleLinkSelect(pParse, pRhs);
  135610. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  135611. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
  135612. }
  135613. if( pRhs ){
  135614. pRhs->op = (u8)yymsp[-1].minor.yy502;
  135615. pRhs->pPrior = pLhs;
  135616. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  135617. pRhs->selFlags &= ~SF_MultiValue;
  135618. if( yymsp[-1].minor.yy502!=TK_ALL ) pParse->hasCompound = 1;
  135619. }else{
  135620. sqlite3SelectDelete(pParse->db, pLhs);
  135621. }
  135622. yymsp[-2].minor.yy399 = pRhs;
  135623. }
  135624. break;
  135625. case 84: /* multiselect_op ::= UNION */
  135626. case 86: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==86);
  135627. {yymsp[0].minor.yy502 = yymsp[0].major; /*A-overwrites-OP*/}
  135628. break;
  135629. case 85: /* multiselect_op ::= UNION ALL */
  135630. {yymsp[-1].minor.yy502 = TK_ALL;}
  135631. break;
  135632. case 87: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  135633. {
  135634. #if SELECTTRACE_ENABLED
  135635. Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
  135636. #endif
  135637. yymsp[-8].minor.yy399 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy232,yymsp[-5].minor.yy427,yymsp[-4].minor.yy182,yymsp[-3].minor.yy232,yymsp[-2].minor.yy182,yymsp[-1].minor.yy232,yymsp[-7].minor.yy502,yymsp[0].minor.yy182);
  135638. #if SELECTTRACE_ENABLED
  135639. /* Populate the Select.zSelName[] string that is used to help with
  135640. ** query planner debugging, to differentiate between multiple Select
  135641. ** objects in a complex query.
  135642. **
  135643. ** If the SELECT keyword is immediately followed by a C-style comment
  135644. ** then extract the first few alphanumeric characters from within that
  135645. ** comment to be the zSelName value. Otherwise, the label is #N where
  135646. ** is an integer that is incremented with each SELECT statement seen.
  135647. */
  135648. if( yymsp[-8].minor.yy399!=0 ){
  135649. const char *z = s.z+6;
  135650. int i;
  135651. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy399->zSelName), yymsp[-8].minor.yy399->zSelName,"#%d",++pParse->nSelect);
  135652. while( z[0]==' ' ) z++;
  135653. if( z[0]=='/' && z[1]=='*' ){
  135654. z += 2;
  135655. while( z[0]==' ' ) z++;
  135656. for(i=0; sqlite3Isalnum(z[i]); i++){}
  135657. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy399->zSelName), yymsp[-8].minor.yy399->zSelName, "%.*s", i, z);
  135658. }
  135659. }
  135660. #endif /* SELECTRACE_ENABLED */
  135661. }
  135662. break;
  135663. case 88: /* values ::= VALUES LP nexprlist RP */
  135664. {
  135665. yymsp[-3].minor.yy399 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy232,0,0,0,0,0,SF_Values,0);
  135666. }
  135667. break;
  135668. case 89: /* values ::= values COMMA LP exprlist RP */
  135669. {
  135670. Select *pRight, *pLeft = yymsp[-4].minor.yy399;
  135671. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy232,0,0,0,0,0,SF_Values|SF_MultiValue,0);
  135672. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  135673. if( pRight ){
  135674. pRight->op = TK_ALL;
  135675. pRight->pPrior = pLeft;
  135676. yymsp[-4].minor.yy399 = pRight;
  135677. }else{
  135678. yymsp[-4].minor.yy399 = pLeft;
  135679. }
  135680. }
  135681. break;
  135682. case 90: /* distinct ::= DISTINCT */
  135683. {yymsp[0].minor.yy502 = SF_Distinct;}
  135684. break;
  135685. case 91: /* distinct ::= ALL */
  135686. {yymsp[0].minor.yy502 = SF_All;}
  135687. break;
  135688. case 93: /* sclp ::= */
  135689. case 126: /* orderby_opt ::= */ yytestcase(yyruleno==126);
  135690. case 133: /* groupby_opt ::= */ yytestcase(yyruleno==133);
  135691. case 212: /* exprlist ::= */ yytestcase(yyruleno==212);
  135692. case 215: /* paren_exprlist ::= */ yytestcase(yyruleno==215);
  135693. case 220: /* eidlist_opt ::= */ yytestcase(yyruleno==220);
  135694. {yymsp[1].minor.yy232 = 0;}
  135695. break;
  135696. case 94: /* selcollist ::= sclp scanpt expr scanpt as */
  135697. {
  135698. yymsp[-4].minor.yy232 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy232, yymsp[-2].minor.yy182);
  135699. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy232, &yymsp[0].minor.yy0, 1);
  135700. sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy232,yymsp[-3].minor.yy36,yymsp[-1].minor.yy36);
  135701. }
  135702. break;
  135703. case 95: /* selcollist ::= sclp scanpt STAR */
  135704. {
  135705. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  135706. yymsp[-2].minor.yy232 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy232, p);
  135707. }
  135708. break;
  135709. case 96: /* selcollist ::= sclp scanpt nm DOT STAR */
  135710. {
  135711. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  135712. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  135713. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  135714. yymsp[-4].minor.yy232 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy232, pDot);
  135715. }
  135716. break;
  135717. case 97: /* as ::= AS nm */
  135718. case 108: /* dbnm ::= DOT nm */ yytestcase(yyruleno==108);
  135719. case 234: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==234);
  135720. case 235: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==235);
  135721. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  135722. break;
  135723. case 99: /* from ::= */
  135724. {yymsp[1].minor.yy427 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy427));}
  135725. break;
  135726. case 100: /* from ::= FROM seltablist */
  135727. {
  135728. yymsp[-1].minor.yy427 = yymsp[0].minor.yy427;
  135729. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy427);
  135730. }
  135731. break;
  135732. case 101: /* stl_prefix ::= seltablist joinop */
  135733. {
  135734. if( ALWAYS(yymsp[-1].minor.yy427 && yymsp[-1].minor.yy427->nSrc>0) ) yymsp[-1].minor.yy427->a[yymsp[-1].minor.yy427->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy502;
  135735. }
  135736. break;
  135737. case 102: /* stl_prefix ::= */
  135738. {yymsp[1].minor.yy427 = 0;}
  135739. break;
  135740. case 103: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  135741. {
  135742. yymsp[-6].minor.yy427 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy427,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy182,yymsp[0].minor.yy510);
  135743. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy427, &yymsp[-2].minor.yy0);
  135744. }
  135745. break;
  135746. case 104: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  135747. {
  135748. yymsp[-8].minor.yy427 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy427,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy182,yymsp[0].minor.yy510);
  135749. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy427, yymsp[-4].minor.yy232);
  135750. }
  135751. break;
  135752. case 105: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  135753. {
  135754. yymsp[-6].minor.yy427 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy427,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy399,yymsp[-1].minor.yy182,yymsp[0].minor.yy510);
  135755. }
  135756. break;
  135757. case 106: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  135758. {
  135759. if( yymsp[-6].minor.yy427==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy182==0 && yymsp[0].minor.yy510==0 ){
  135760. yymsp[-6].minor.yy427 = yymsp[-4].minor.yy427;
  135761. }else if( yymsp[-4].minor.yy427->nSrc==1 ){
  135762. yymsp[-6].minor.yy427 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy427,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy182,yymsp[0].minor.yy510);
  135763. if( yymsp[-6].minor.yy427 ){
  135764. struct SrcList_item *pNew = &yymsp[-6].minor.yy427->a[yymsp[-6].minor.yy427->nSrc-1];
  135765. struct SrcList_item *pOld = yymsp[-4].minor.yy427->a;
  135766. pNew->zName = pOld->zName;
  135767. pNew->zDatabase = pOld->zDatabase;
  135768. pNew->pSelect = pOld->pSelect;
  135769. pOld->zName = pOld->zDatabase = 0;
  135770. pOld->pSelect = 0;
  135771. }
  135772. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy427);
  135773. }else{
  135774. Select *pSubquery;
  135775. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy427);
  135776. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy427,0,0,0,0,SF_NestedFrom,0);
  135777. yymsp[-6].minor.yy427 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy427,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy182,yymsp[0].minor.yy510);
  135778. }
  135779. }
  135780. break;
  135781. case 107: /* dbnm ::= */
  135782. case 121: /* indexed_opt ::= */ yytestcase(yyruleno==121);
  135783. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  135784. break;
  135785. case 109: /* fullname ::= nm */
  135786. case 111: /* xfullname ::= nm */ yytestcase(yyruleno==111);
  135787. {yymsp[0].minor.yy427 = sqlite3SrcListAppend(pParse->db,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
  135788. break;
  135789. case 110: /* fullname ::= nm DOT nm */
  135790. case 112: /* xfullname ::= nm DOT nm */ yytestcase(yyruleno==112);
  135791. {yymsp[-2].minor.yy427 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  135792. break;
  135793. case 113: /* xfullname ::= nm DOT nm AS nm */
  135794. {
  135795. yymsp[-4].minor.yy427 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
  135796. if( yymsp[-4].minor.yy427 ) yymsp[-4].minor.yy427->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  135797. }
  135798. break;
  135799. case 114: /* xfullname ::= nm AS nm */
  135800. {
  135801. yymsp[-2].minor.yy427 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
  135802. if( yymsp[-2].minor.yy427 ) yymsp[-2].minor.yy427->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  135803. }
  135804. break;
  135805. case 115: /* joinop ::= COMMA|JOIN */
  135806. { yymsp[0].minor.yy502 = JT_INNER; }
  135807. break;
  135808. case 116: /* joinop ::= JOIN_KW JOIN */
  135809. {yymsp[-1].minor.yy502 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  135810. break;
  135811. case 117: /* joinop ::= JOIN_KW nm JOIN */
  135812. {yymsp[-2].minor.yy502 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  135813. break;
  135814. case 118: /* joinop ::= JOIN_KW nm nm JOIN */
  135815. {yymsp[-3].minor.yy502 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  135816. break;
  135817. case 119: /* on_opt ::= ON expr */
  135818. case 136: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==136);
  135819. case 143: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==143);
  135820. case 208: /* case_else ::= ELSE expr */ yytestcase(yyruleno==208);
  135821. {yymsp[-1].minor.yy182 = yymsp[0].minor.yy182;}
  135822. break;
  135823. case 120: /* on_opt ::= */
  135824. case 135: /* having_opt ::= */ yytestcase(yyruleno==135);
  135825. case 137: /* limit_opt ::= */ yytestcase(yyruleno==137);
  135826. case 142: /* where_opt ::= */ yytestcase(yyruleno==142);
  135827. case 209: /* case_else ::= */ yytestcase(yyruleno==209);
  135828. case 211: /* case_operand ::= */ yytestcase(yyruleno==211);
  135829. {yymsp[1].minor.yy182 = 0;}
  135830. break;
  135831. case 122: /* indexed_opt ::= INDEXED BY nm */
  135832. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  135833. break;
  135834. case 123: /* indexed_opt ::= NOT INDEXED */
  135835. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  135836. break;
  135837. case 124: /* using_opt ::= USING LP idlist RP */
  135838. {yymsp[-3].minor.yy510 = yymsp[-1].minor.yy510;}
  135839. break;
  135840. case 125: /* using_opt ::= */
  135841. case 157: /* idlist_opt ::= */ yytestcase(yyruleno==157);
  135842. {yymsp[1].minor.yy510 = 0;}
  135843. break;
  135844. case 127: /* orderby_opt ::= ORDER BY sortlist */
  135845. case 134: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==134);
  135846. {yymsp[-2].minor.yy232 = yymsp[0].minor.yy232;}
  135847. break;
  135848. case 128: /* sortlist ::= sortlist COMMA expr sortorder */
  135849. {
  135850. yymsp[-3].minor.yy232 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy232,yymsp[-1].minor.yy182);
  135851. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy232,yymsp[0].minor.yy502);
  135852. }
  135853. break;
  135854. case 129: /* sortlist ::= expr sortorder */
  135855. {
  135856. yymsp[-1].minor.yy232 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy182); /*A-overwrites-Y*/
  135857. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy232,yymsp[0].minor.yy502);
  135858. }
  135859. break;
  135860. case 130: /* sortorder ::= ASC */
  135861. {yymsp[0].minor.yy502 = SQLITE_SO_ASC;}
  135862. break;
  135863. case 131: /* sortorder ::= DESC */
  135864. {yymsp[0].minor.yy502 = SQLITE_SO_DESC;}
  135865. break;
  135866. case 132: /* sortorder ::= */
  135867. {yymsp[1].minor.yy502 = SQLITE_SO_UNDEFINED;}
  135868. break;
  135869. case 138: /* limit_opt ::= LIMIT expr */
  135870. {yymsp[-1].minor.yy182 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy182,0);}
  135871. break;
  135872. case 139: /* limit_opt ::= LIMIT expr OFFSET expr */
  135873. {yymsp[-3].minor.yy182 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy182,yymsp[0].minor.yy182);}
  135874. break;
  135875. case 140: /* limit_opt ::= LIMIT expr COMMA expr */
  135876. {yymsp[-3].minor.yy182 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy182,yymsp[-2].minor.yy182);}
  135877. break;
  135878. case 141: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  135879. {
  135880. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy427, &yymsp[-1].minor.yy0);
  135881. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy427,yymsp[0].minor.yy182,0,0);
  135882. }
  135883. break;
  135884. case 144: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  135885. {
  135886. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy427, &yymsp[-3].minor.yy0);
  135887. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy232,"set list");
  135888. sqlite3Update(pParse,yymsp[-4].minor.yy427,yymsp[-1].minor.yy232,yymsp[0].minor.yy182,yymsp[-5].minor.yy502,0,0,0);
  135889. }
  135890. break;
  135891. case 145: /* setlist ::= setlist COMMA nm EQ expr */
  135892. {
  135893. yymsp[-4].minor.yy232 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy232, yymsp[0].minor.yy182);
  135894. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy232, &yymsp[-2].minor.yy0, 1);
  135895. }
  135896. break;
  135897. case 146: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  135898. {
  135899. yymsp[-6].minor.yy232 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy232, yymsp[-3].minor.yy510, yymsp[0].minor.yy182);
  135900. }
  135901. break;
  135902. case 147: /* setlist ::= nm EQ expr */
  135903. {
  135904. yylhsminor.yy232 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy182);
  135905. sqlite3ExprListSetName(pParse, yylhsminor.yy232, &yymsp[-2].minor.yy0, 1);
  135906. }
  135907. yymsp[-2].minor.yy232 = yylhsminor.yy232;
  135908. break;
  135909. case 148: /* setlist ::= LP idlist RP EQ expr */
  135910. {
  135911. yymsp[-4].minor.yy232 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy510, yymsp[0].minor.yy182);
  135912. }
  135913. break;
  135914. case 149: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  135915. {
  135916. sqlite3Insert(pParse, yymsp[-3].minor.yy427, yymsp[-1].minor.yy399, yymsp[-2].minor.yy510, yymsp[-5].minor.yy502, yymsp[0].minor.yy198);
  135917. }
  135918. break;
  135919. case 150: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  135920. {
  135921. sqlite3Insert(pParse, yymsp[-3].minor.yy427, 0, yymsp[-2].minor.yy510, yymsp[-5].minor.yy502, 0);
  135922. }
  135923. break;
  135924. case 151: /* upsert ::= */
  135925. { yymsp[1].minor.yy198 = 0; }
  135926. break;
  135927. case 152: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  135928. { yymsp[-10].minor.yy198 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy232,yymsp[-5].minor.yy182,yymsp[-1].minor.yy232,yymsp[0].minor.yy182);}
  135929. break;
  135930. case 153: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  135931. { yymsp[-7].minor.yy198 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy232,yymsp[-2].minor.yy182,0,0); }
  135932. break;
  135933. case 154: /* upsert ::= ON CONFLICT DO NOTHING */
  135934. { yymsp[-3].minor.yy198 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
  135935. break;
  135936. case 158: /* idlist_opt ::= LP idlist RP */
  135937. {yymsp[-2].minor.yy510 = yymsp[-1].minor.yy510;}
  135938. break;
  135939. case 159: /* idlist ::= idlist COMMA nm */
  135940. {yymsp[-2].minor.yy510 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy510,&yymsp[0].minor.yy0);}
  135941. break;
  135942. case 160: /* idlist ::= nm */
  135943. {yymsp[0].minor.yy510 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  135944. break;
  135945. case 161: /* expr ::= LP expr RP */
  135946. {yymsp[-2].minor.yy182 = yymsp[-1].minor.yy182;}
  135947. break;
  135948. case 162: /* expr ::= ID|INDEXED */
  135949. case 163: /* expr ::= JOIN_KW */ yytestcase(yyruleno==163);
  135950. {yymsp[0].minor.yy182=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  135951. break;
  135952. case 164: /* expr ::= nm DOT nm */
  135953. {
  135954. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  135955. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  135956. yylhsminor.yy182 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  135957. }
  135958. yymsp[-2].minor.yy182 = yylhsminor.yy182;
  135959. break;
  135960. case 165: /* expr ::= nm DOT nm DOT nm */
  135961. {
  135962. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  135963. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  135964. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  135965. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  135966. yylhsminor.yy182 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  135967. }
  135968. yymsp[-4].minor.yy182 = yylhsminor.yy182;
  135969. break;
  135970. case 166: /* term ::= NULL|FLOAT|BLOB */
  135971. case 167: /* term ::= STRING */ yytestcase(yyruleno==167);
  135972. {yymsp[0].minor.yy182=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  135973. break;
  135974. case 168: /* term ::= INTEGER */
  135975. {
  135976. yylhsminor.yy182 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  135977. }
  135978. yymsp[0].minor.yy182 = yylhsminor.yy182;
  135979. break;
  135980. case 169: /* expr ::= VARIABLE */
  135981. {
  135982. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  135983. u32 n = yymsp[0].minor.yy0.n;
  135984. yymsp[0].minor.yy182 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  135985. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy182, n);
  135986. }else{
  135987. /* When doing a nested parse, one can include terms in an expression
  135988. ** that look like this: #1 #2 ... These terms refer to registers
  135989. ** in the virtual machine. #N is the N-th register. */
  135990. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  135991. assert( t.n>=2 );
  135992. if( pParse->nested==0 ){
  135993. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  135994. yymsp[0].minor.yy182 = 0;
  135995. }else{
  135996. yymsp[0].minor.yy182 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  135997. if( yymsp[0].minor.yy182 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy182->iTable);
  135998. }
  135999. }
  136000. }
  136001. break;
  136002. case 170: /* expr ::= expr COLLATE ID|STRING */
  136003. {
  136004. yymsp[-2].minor.yy182 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy182, &yymsp[0].minor.yy0, 1);
  136005. }
  136006. break;
  136007. case 171: /* expr ::= CAST LP expr AS typetoken RP */
  136008. {
  136009. yymsp[-5].minor.yy182 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  136010. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy182, yymsp[-3].minor.yy182, 0);
  136011. }
  136012. break;
  136013. case 172: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  136014. {
  136015. if( yymsp[-1].minor.yy232 && yymsp[-1].minor.yy232->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  136016. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  136017. }
  136018. yylhsminor.yy182 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy232, &yymsp[-4].minor.yy0);
  136019. if( yymsp[-2].minor.yy502==SF_Distinct && yylhsminor.yy182 ){
  136020. yylhsminor.yy182->flags |= EP_Distinct;
  136021. }
  136022. }
  136023. yymsp[-4].minor.yy182 = yylhsminor.yy182;
  136024. break;
  136025. case 173: /* expr ::= ID|INDEXED LP STAR RP */
  136026. {
  136027. yylhsminor.yy182 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  136028. }
  136029. yymsp[-3].minor.yy182 = yylhsminor.yy182;
  136030. break;
  136031. case 174: /* term ::= CTIME_KW */
  136032. {
  136033. yylhsminor.yy182 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  136034. }
  136035. yymsp[0].minor.yy182 = yylhsminor.yy182;
  136036. break;
  136037. case 175: /* expr ::= LP nexprlist COMMA expr RP */
  136038. {
  136039. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy232, yymsp[-1].minor.yy182);
  136040. yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  136041. if( yymsp[-4].minor.yy182 ){
  136042. yymsp[-4].minor.yy182->x.pList = pList;
  136043. }else{
  136044. sqlite3ExprListDelete(pParse->db, pList);
  136045. }
  136046. }
  136047. break;
  136048. case 176: /* expr ::= expr AND expr */
  136049. case 177: /* expr ::= expr OR expr */ yytestcase(yyruleno==177);
  136050. case 178: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==178);
  136051. case 179: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==179);
  136052. case 180: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==180);
  136053. case 181: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==181);
  136054. case 182: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==182);
  136055. case 183: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==183);
  136056. {yymsp[-2].minor.yy182=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy182,yymsp[0].minor.yy182);}
  136057. break;
  136058. case 184: /* likeop ::= NOT LIKE_KW|MATCH */
  136059. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  136060. break;
  136061. case 185: /* expr ::= expr likeop expr */
  136062. {
  136063. ExprList *pList;
  136064. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  136065. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  136066. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy182);
  136067. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy182);
  136068. yymsp[-2].minor.yy182 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
  136069. if( bNot ) yymsp[-2].minor.yy182 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy182, 0);
  136070. if( yymsp[-2].minor.yy182 ) yymsp[-2].minor.yy182->flags |= EP_InfixFunc;
  136071. }
  136072. break;
  136073. case 186: /* expr ::= expr likeop expr ESCAPE expr */
  136074. {
  136075. ExprList *pList;
  136076. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  136077. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  136078. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy182);
  136079. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy182);
  136080. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy182);
  136081. yymsp[-4].minor.yy182 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
  136082. if( bNot ) yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy182, 0);
  136083. if( yymsp[-4].minor.yy182 ) yymsp[-4].minor.yy182->flags |= EP_InfixFunc;
  136084. }
  136085. break;
  136086. case 187: /* expr ::= expr ISNULL|NOTNULL */
  136087. {yymsp[-1].minor.yy182 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy182,0);}
  136088. break;
  136089. case 188: /* expr ::= expr NOT NULL */
  136090. {yymsp[-2].minor.yy182 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy182,0);}
  136091. break;
  136092. case 189: /* expr ::= expr IS expr */
  136093. {
  136094. yymsp[-2].minor.yy182 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy182,yymsp[0].minor.yy182);
  136095. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy182, yymsp[-2].minor.yy182, TK_ISNULL);
  136096. }
  136097. break;
  136098. case 190: /* expr ::= expr IS NOT expr */
  136099. {
  136100. yymsp[-3].minor.yy182 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy182,yymsp[0].minor.yy182);
  136101. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy182, yymsp[-3].minor.yy182, TK_NOTNULL);
  136102. }
  136103. break;
  136104. case 191: /* expr ::= NOT expr */
  136105. case 192: /* expr ::= BITNOT expr */ yytestcase(yyruleno==192);
  136106. {yymsp[-1].minor.yy182 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy182, 0);/*A-overwrites-B*/}
  136107. break;
  136108. case 193: /* expr ::= MINUS expr */
  136109. {yymsp[-1].minor.yy182 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy182, 0);}
  136110. break;
  136111. case 194: /* expr ::= PLUS expr */
  136112. {yymsp[-1].minor.yy182 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy182, 0);}
  136113. break;
  136114. case 195: /* between_op ::= BETWEEN */
  136115. case 198: /* in_op ::= IN */ yytestcase(yyruleno==198);
  136116. {yymsp[0].minor.yy502 = 0;}
  136117. break;
  136118. case 197: /* expr ::= expr between_op expr AND expr */
  136119. {
  136120. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy182);
  136121. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy182);
  136122. yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy182, 0);
  136123. if( yymsp[-4].minor.yy182 ){
  136124. yymsp[-4].minor.yy182->x.pList = pList;
  136125. }else{
  136126. sqlite3ExprListDelete(pParse->db, pList);
  136127. }
  136128. if( yymsp[-3].minor.yy502 ) yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy182, 0);
  136129. }
  136130. break;
  136131. case 200: /* expr ::= expr in_op LP exprlist RP */
  136132. {
  136133. if( yymsp[-1].minor.yy232==0 ){
  136134. /* Expressions of the form
  136135. **
  136136. ** expr1 IN ()
  136137. ** expr1 NOT IN ()
  136138. **
  136139. ** simplify to constants 0 (false) and 1 (true), respectively,
  136140. ** regardless of the value of expr1.
  136141. */
  136142. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy182);
  136143. yymsp[-4].minor.yy182 = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy502],1);
  136144. }else if( yymsp[-1].minor.yy232->nExpr==1 ){
  136145. /* Expressions of the form:
  136146. **
  136147. ** expr1 IN (?1)
  136148. ** expr1 NOT IN (?2)
  136149. **
  136150. ** with exactly one value on the RHS can be simplified to something
  136151. ** like this:
  136152. **
  136153. ** expr1 == ?1
  136154. ** expr1 <> ?2
  136155. **
  136156. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  136157. ** so that it may not contribute to the computation of comparison
  136158. ** affinity or the collating sequence to use for comparison. Otherwise,
  136159. ** the semantics would be subtly different from IN or NOT IN.
  136160. */
  136161. Expr *pRHS = yymsp[-1].minor.yy232->a[0].pExpr;
  136162. yymsp[-1].minor.yy232->a[0].pExpr = 0;
  136163. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy232);
  136164. /* pRHS cannot be NULL because a malloc error would have been detected
  136165. ** before now and control would have never reached this point */
  136166. if( ALWAYS(pRHS) ){
  136167. pRHS->flags &= ~EP_Collate;
  136168. pRHS->flags |= EP_Generic;
  136169. }
  136170. yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, yymsp[-3].minor.yy502 ? TK_NE : TK_EQ, yymsp[-4].minor.yy182, pRHS);
  136171. }else{
  136172. yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy182, 0);
  136173. if( yymsp[-4].minor.yy182 ){
  136174. yymsp[-4].minor.yy182->x.pList = yymsp[-1].minor.yy232;
  136175. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy182);
  136176. }else{
  136177. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy232);
  136178. }
  136179. if( yymsp[-3].minor.yy502 ) yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy182, 0);
  136180. }
  136181. }
  136182. break;
  136183. case 201: /* expr ::= LP select RP */
  136184. {
  136185. yymsp[-2].minor.yy182 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  136186. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy182, yymsp[-1].minor.yy399);
  136187. }
  136188. break;
  136189. case 202: /* expr ::= expr in_op LP select RP */
  136190. {
  136191. yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy182, 0);
  136192. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy182, yymsp[-1].minor.yy399);
  136193. if( yymsp[-3].minor.yy502 ) yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy182, 0);
  136194. }
  136195. break;
  136196. case 203: /* expr ::= expr in_op nm dbnm paren_exprlist */
  136197. {
  136198. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  136199. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
  136200. if( yymsp[0].minor.yy232 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy232);
  136201. yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy182, 0);
  136202. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy182, pSelect);
  136203. if( yymsp[-3].minor.yy502 ) yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy182, 0);
  136204. }
  136205. break;
  136206. case 204: /* expr ::= EXISTS LP select RP */
  136207. {
  136208. Expr *p;
  136209. p = yymsp[-3].minor.yy182 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  136210. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy399);
  136211. }
  136212. break;
  136213. case 205: /* expr ::= CASE case_operand case_exprlist case_else END */
  136214. {
  136215. yymsp[-4].minor.yy182 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy182, 0);
  136216. if( yymsp[-4].minor.yy182 ){
  136217. yymsp[-4].minor.yy182->x.pList = yymsp[-1].minor.yy182 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy232,yymsp[-1].minor.yy182) : yymsp[-2].minor.yy232;
  136218. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy182);
  136219. }else{
  136220. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy232);
  136221. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy182);
  136222. }
  136223. }
  136224. break;
  136225. case 206: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  136226. {
  136227. yymsp[-4].minor.yy232 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy232, yymsp[-2].minor.yy182);
  136228. yymsp[-4].minor.yy232 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy232, yymsp[0].minor.yy182);
  136229. }
  136230. break;
  136231. case 207: /* case_exprlist ::= WHEN expr THEN expr */
  136232. {
  136233. yymsp[-3].minor.yy232 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy182);
  136234. yymsp[-3].minor.yy232 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy232, yymsp[0].minor.yy182);
  136235. }
  136236. break;
  136237. case 210: /* case_operand ::= expr */
  136238. {yymsp[0].minor.yy182 = yymsp[0].minor.yy182; /*A-overwrites-X*/}
  136239. break;
  136240. case 213: /* nexprlist ::= nexprlist COMMA expr */
  136241. {yymsp[-2].minor.yy232 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy232,yymsp[0].minor.yy182);}
  136242. break;
  136243. case 214: /* nexprlist ::= expr */
  136244. {yymsp[0].minor.yy232 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy182); /*A-overwrites-Y*/}
  136245. break;
  136246. case 216: /* paren_exprlist ::= LP exprlist RP */
  136247. case 221: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==221);
  136248. {yymsp[-2].minor.yy232 = yymsp[-1].minor.yy232;}
  136249. break;
  136250. case 217: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  136251. {
  136252. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  136253. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy232, yymsp[-10].minor.yy502,
  136254. &yymsp[-11].minor.yy0, yymsp[0].minor.yy182, SQLITE_SO_ASC, yymsp[-8].minor.yy502, SQLITE_IDXTYPE_APPDEF);
  136255. }
  136256. break;
  136257. case 218: /* uniqueflag ::= UNIQUE */
  136258. case 258: /* raisetype ::= ABORT */ yytestcase(yyruleno==258);
  136259. {yymsp[0].minor.yy502 = OE_Abort;}
  136260. break;
  136261. case 219: /* uniqueflag ::= */
  136262. {yymsp[1].minor.yy502 = OE_None;}
  136263. break;
  136264. case 222: /* eidlist ::= eidlist COMMA nm collate sortorder */
  136265. {
  136266. yymsp[-4].minor.yy232 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy232, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy502, yymsp[0].minor.yy502);
  136267. }
  136268. break;
  136269. case 223: /* eidlist ::= nm collate sortorder */
  136270. {
  136271. yymsp[-2].minor.yy232 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy502, yymsp[0].minor.yy502); /*A-overwrites-Y*/
  136272. }
  136273. break;
  136274. case 226: /* cmd ::= DROP INDEX ifexists fullname */
  136275. {sqlite3DropIndex(pParse, yymsp[0].minor.yy427, yymsp[-1].minor.yy502);}
  136276. break;
  136277. case 227: /* cmd ::= VACUUM */
  136278. {sqlite3Vacuum(pParse,0);}
  136279. break;
  136280. case 228: /* cmd ::= VACUUM nm */
  136281. {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
  136282. break;
  136283. case 229: /* cmd ::= PRAGMA nm dbnm */
  136284. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  136285. break;
  136286. case 230: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  136287. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  136288. break;
  136289. case 231: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  136290. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  136291. break;
  136292. case 232: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  136293. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  136294. break;
  136295. case 233: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  136296. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  136297. break;
  136298. case 236: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  136299. {
  136300. Token all;
  136301. all.z = yymsp[-3].minor.yy0.z;
  136302. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  136303. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy47, &all);
  136304. }
  136305. break;
  136306. case 237: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  136307. {
  136308. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy502, yymsp[-4].minor.yy300.a, yymsp[-4].minor.yy300.b, yymsp[-2].minor.yy427, yymsp[0].minor.yy182, yymsp[-10].minor.yy502, yymsp[-8].minor.yy502);
  136309. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  136310. }
  136311. break;
  136312. case 238: /* trigger_time ::= BEFORE|AFTER */
  136313. { yymsp[0].minor.yy502 = yymsp[0].major; /*A-overwrites-X*/ }
  136314. break;
  136315. case 239: /* trigger_time ::= INSTEAD OF */
  136316. { yymsp[-1].minor.yy502 = TK_INSTEAD;}
  136317. break;
  136318. case 240: /* trigger_time ::= */
  136319. { yymsp[1].minor.yy502 = TK_BEFORE; }
  136320. break;
  136321. case 241: /* trigger_event ::= DELETE|INSERT */
  136322. case 242: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==242);
  136323. {yymsp[0].minor.yy300.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy300.b = 0;}
  136324. break;
  136325. case 243: /* trigger_event ::= UPDATE OF idlist */
  136326. {yymsp[-2].minor.yy300.a = TK_UPDATE; yymsp[-2].minor.yy300.b = yymsp[0].minor.yy510;}
  136327. break;
  136328. case 244: /* when_clause ::= */
  136329. case 263: /* key_opt ::= */ yytestcase(yyruleno==263);
  136330. { yymsp[1].minor.yy182 = 0; }
  136331. break;
  136332. case 245: /* when_clause ::= WHEN expr */
  136333. case 264: /* key_opt ::= KEY expr */ yytestcase(yyruleno==264);
  136334. { yymsp[-1].minor.yy182 = yymsp[0].minor.yy182; }
  136335. break;
  136336. case 246: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  136337. {
  136338. assert( yymsp[-2].minor.yy47!=0 );
  136339. yymsp[-2].minor.yy47->pLast->pNext = yymsp[-1].minor.yy47;
  136340. yymsp[-2].minor.yy47->pLast = yymsp[-1].minor.yy47;
  136341. }
  136342. break;
  136343. case 247: /* trigger_cmd_list ::= trigger_cmd SEMI */
  136344. {
  136345. assert( yymsp[-1].minor.yy47!=0 );
  136346. yymsp[-1].minor.yy47->pLast = yymsp[-1].minor.yy47;
  136347. }
  136348. break;
  136349. case 248: /* trnm ::= nm DOT nm */
  136350. {
  136351. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  136352. sqlite3ErrorMsg(pParse,
  136353. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  136354. "statements within triggers");
  136355. }
  136356. break;
  136357. case 249: /* tridxby ::= INDEXED BY nm */
  136358. {
  136359. sqlite3ErrorMsg(pParse,
  136360. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  136361. "within triggers");
  136362. }
  136363. break;
  136364. case 250: /* tridxby ::= NOT INDEXED */
  136365. {
  136366. sqlite3ErrorMsg(pParse,
  136367. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  136368. "within triggers");
  136369. }
  136370. break;
  136371. case 251: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  136372. {yylhsminor.yy47 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy232, yymsp[-1].minor.yy182, yymsp[-6].minor.yy502, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy36);}
  136373. yymsp[-7].minor.yy47 = yylhsminor.yy47;
  136374. break;
  136375. case 252: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  136376. {
  136377. yylhsminor.yy47 = sqlite3TriggerInsertStep(pParse->db,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy510,yymsp[-2].minor.yy399,yymsp[-6].minor.yy502,yymsp[-1].minor.yy198,yymsp[-7].minor.yy36,yymsp[0].minor.yy36);/*yylhsminor.yy47-overwrites-yymsp[-6].minor.yy502*/
  136378. }
  136379. yymsp[-7].minor.yy47 = yylhsminor.yy47;
  136380. break;
  136381. case 253: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  136382. {yylhsminor.yy47 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy182, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy36);}
  136383. yymsp[-5].minor.yy47 = yylhsminor.yy47;
  136384. break;
  136385. case 254: /* trigger_cmd ::= scanpt select scanpt */
  136386. {yylhsminor.yy47 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy399, yymsp[-2].minor.yy36, yymsp[0].minor.yy36); /*yylhsminor.yy47-overwrites-yymsp[-1].minor.yy399*/}
  136387. yymsp[-2].minor.yy47 = yylhsminor.yy47;
  136388. break;
  136389. case 255: /* expr ::= RAISE LP IGNORE RP */
  136390. {
  136391. yymsp[-3].minor.yy182 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  136392. if( yymsp[-3].minor.yy182 ){
  136393. yymsp[-3].minor.yy182->affinity = OE_Ignore;
  136394. }
  136395. }
  136396. break;
  136397. case 256: /* expr ::= RAISE LP raisetype COMMA nm RP */
  136398. {
  136399. yymsp[-5].minor.yy182 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  136400. if( yymsp[-5].minor.yy182 ) {
  136401. yymsp[-5].minor.yy182->affinity = (char)yymsp[-3].minor.yy502;
  136402. }
  136403. }
  136404. break;
  136405. case 257: /* raisetype ::= ROLLBACK */
  136406. {yymsp[0].minor.yy502 = OE_Rollback;}
  136407. break;
  136408. case 259: /* raisetype ::= FAIL */
  136409. {yymsp[0].minor.yy502 = OE_Fail;}
  136410. break;
  136411. case 260: /* cmd ::= DROP TRIGGER ifexists fullname */
  136412. {
  136413. sqlite3DropTrigger(pParse,yymsp[0].minor.yy427,yymsp[-1].minor.yy502);
  136414. }
  136415. break;
  136416. case 261: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  136417. {
  136418. sqlite3Attach(pParse, yymsp[-3].minor.yy182, yymsp[-1].minor.yy182, yymsp[0].minor.yy182);
  136419. }
  136420. break;
  136421. case 262: /* cmd ::= DETACH database_kw_opt expr */
  136422. {
  136423. sqlite3Detach(pParse, yymsp[0].minor.yy182);
  136424. }
  136425. break;
  136426. case 265: /* cmd ::= REINDEX */
  136427. {sqlite3Reindex(pParse, 0, 0);}
  136428. break;
  136429. case 266: /* cmd ::= REINDEX nm dbnm */
  136430. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  136431. break;
  136432. case 267: /* cmd ::= ANALYZE */
  136433. {sqlite3Analyze(pParse, 0, 0);}
  136434. break;
  136435. case 268: /* cmd ::= ANALYZE nm dbnm */
  136436. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  136437. break;
  136438. case 269: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  136439. {
  136440. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy427,&yymsp[0].minor.yy0);
  136441. }
  136442. break;
  136443. case 270: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  136444. {
  136445. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  136446. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  136447. }
  136448. break;
  136449. case 271: /* add_column_fullname ::= fullname */
  136450. {
  136451. disableLookaside(pParse);
  136452. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy427);
  136453. }
  136454. break;
  136455. case 272: /* cmd ::= create_vtab */
  136456. {sqlite3VtabFinishParse(pParse,0);}
  136457. break;
  136458. case 273: /* cmd ::= create_vtab LP vtabarglist RP */
  136459. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  136460. break;
  136461. case 274: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  136462. {
  136463. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy502);
  136464. }
  136465. break;
  136466. case 275: /* vtabarg ::= */
  136467. {sqlite3VtabArgInit(pParse);}
  136468. break;
  136469. case 276: /* vtabargtoken ::= ANY */
  136470. case 277: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==277);
  136471. case 278: /* lp ::= LP */ yytestcase(yyruleno==278);
  136472. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  136473. break;
  136474. case 279: /* with ::= WITH wqlist */
  136475. case 280: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==280);
  136476. { sqlite3WithPush(pParse, yymsp[0].minor.yy91, 1); }
  136477. break;
  136478. case 281: /* wqlist ::= nm eidlist_opt AS LP select RP */
  136479. {
  136480. yymsp[-5].minor.yy91 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy232, yymsp[-1].minor.yy399); /*A-overwrites-X*/
  136481. }
  136482. break;
  136483. case 282: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  136484. {
  136485. yymsp[-7].minor.yy91 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy91, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy232, yymsp[-1].minor.yy399);
  136486. }
  136487. break;
  136488. default:
  136489. /* (283) input ::= cmdlist */ yytestcase(yyruleno==283);
  136490. /* (284) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==284);
  136491. /* (285) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=285);
  136492. /* (286) ecmd ::= SEMI */ yytestcase(yyruleno==286);
  136493. /* (287) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==287);
  136494. /* (288) ecmd ::= explain cmdx */ yytestcase(yyruleno==288);
  136495. /* (289) trans_opt ::= */ yytestcase(yyruleno==289);
  136496. /* (290) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==290);
  136497. /* (291) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==291);
  136498. /* (292) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==292);
  136499. /* (293) savepoint_opt ::= */ yytestcase(yyruleno==293);
  136500. /* (294) cmd ::= create_table create_table_args */ yytestcase(yyruleno==294);
  136501. /* (295) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==295);
  136502. /* (296) columnlist ::= columnname carglist */ yytestcase(yyruleno==296);
  136503. /* (297) nm ::= ID|INDEXED */ yytestcase(yyruleno==297);
  136504. /* (298) nm ::= STRING */ yytestcase(yyruleno==298);
  136505. /* (299) nm ::= JOIN_KW */ yytestcase(yyruleno==299);
  136506. /* (300) typetoken ::= typename */ yytestcase(yyruleno==300);
  136507. /* (301) typename ::= ID|STRING */ yytestcase(yyruleno==301);
  136508. /* (302) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=302);
  136509. /* (303) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=303);
  136510. /* (304) carglist ::= carglist ccons */ yytestcase(yyruleno==304);
  136511. /* (305) carglist ::= */ yytestcase(yyruleno==305);
  136512. /* (306) ccons ::= NULL onconf */ yytestcase(yyruleno==306);
  136513. /* (307) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==307);
  136514. /* (308) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==308);
  136515. /* (309) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=309);
  136516. /* (310) tconscomma ::= */ yytestcase(yyruleno==310);
  136517. /* (311) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=311);
  136518. /* (312) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=312);
  136519. /* (313) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=313);
  136520. /* (314) oneselect ::= values */ yytestcase(yyruleno==314);
  136521. /* (315) sclp ::= selcollist COMMA */ yytestcase(yyruleno==315);
  136522. /* (316) as ::= ID|STRING */ yytestcase(yyruleno==316);
  136523. /* (317) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=317);
  136524. /* (318) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==318);
  136525. /* (319) exprlist ::= nexprlist */ yytestcase(yyruleno==319);
  136526. /* (320) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=320);
  136527. /* (321) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=321);
  136528. /* (322) nmnum ::= ON */ yytestcase(yyruleno==322);
  136529. /* (323) nmnum ::= DELETE */ yytestcase(yyruleno==323);
  136530. /* (324) nmnum ::= DEFAULT */ yytestcase(yyruleno==324);
  136531. /* (325) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==325);
  136532. /* (326) foreach_clause ::= */ yytestcase(yyruleno==326);
  136533. /* (327) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==327);
  136534. /* (328) trnm ::= nm */ yytestcase(yyruleno==328);
  136535. /* (329) tridxby ::= */ yytestcase(yyruleno==329);
  136536. /* (330) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==330);
  136537. /* (331) database_kw_opt ::= */ yytestcase(yyruleno==331);
  136538. /* (332) kwcolumn_opt ::= */ yytestcase(yyruleno==332);
  136539. /* (333) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==333);
  136540. /* (334) vtabarglist ::= vtabarg */ yytestcase(yyruleno==334);
  136541. /* (335) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==335);
  136542. /* (336) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==336);
  136543. /* (337) anylist ::= */ yytestcase(yyruleno==337);
  136544. /* (338) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==338);
  136545. /* (339) anylist ::= anylist ANY */ yytestcase(yyruleno==339);
  136546. /* (340) with ::= */ yytestcase(yyruleno==340);
  136547. break;
  136548. /********** End reduce actions ************************************************/
  136549. };
  136550. assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  136551. yygoto = yyRuleInfo[yyruleno].lhs;
  136552. yysize = yyRuleInfo[yyruleno].nrhs;
  136553. yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
  136554. /* There are no SHIFTREDUCE actions on nonterminals because the table
  136555. ** generator has simplified them to pure REDUCE actions. */
  136556. assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
  136557. /* It is not possible for a REDUCE to be followed by an error */
  136558. assert( yyact!=YY_ERROR_ACTION );
  136559. yymsp += yysize+1;
  136560. yypParser->yytos = yymsp;
  136561. yymsp->stateno = (YYACTIONTYPE)yyact;
  136562. yymsp->major = (YYCODETYPE)yygoto;
  136563. yyTraceShift(yypParser, yyact, "... then shift");
  136564. return yyact;
  136565. }
  136566. /*
  136567. ** The following code executes when the parse fails
  136568. */
  136569. #ifndef YYNOERRORRECOVERY
  136570. static void yy_parse_failed(
  136571. yyParser *yypParser /* The parser */
  136572. ){
  136573. sqlite3ParserARG_FETCH
  136574. sqlite3ParserCTX_FETCH
  136575. #ifndef NDEBUG
  136576. if( yyTraceFILE ){
  136577. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  136578. }
  136579. #endif
  136580. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  136581. /* Here code is inserted which will be executed whenever the
  136582. ** parser fails */
  136583. /************ Begin %parse_failure code ***************************************/
  136584. /************ End %parse_failure code *****************************************/
  136585. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  136586. sqlite3ParserCTX_STORE
  136587. }
  136588. #endif /* YYNOERRORRECOVERY */
  136589. /*
  136590. ** The following code executes when a syntax error first occurs.
  136591. */
  136592. static void yy_syntax_error(
  136593. yyParser *yypParser, /* The parser */
  136594. int yymajor, /* The major type of the error token */
  136595. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  136596. ){
  136597. sqlite3ParserARG_FETCH
  136598. sqlite3ParserCTX_FETCH
  136599. #define TOKEN yyminor
  136600. /************ Begin %syntax_error code ****************************************/
  136601. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  136602. if( TOKEN.z[0] ){
  136603. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  136604. }else{
  136605. sqlite3ErrorMsg(pParse, "incomplete input");
  136606. }
  136607. /************ End %syntax_error code ******************************************/
  136608. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  136609. sqlite3ParserCTX_STORE
  136610. }
  136611. /*
  136612. ** The following is executed when the parser accepts
  136613. */
  136614. static void yy_accept(
  136615. yyParser *yypParser /* The parser */
  136616. ){
  136617. sqlite3ParserARG_FETCH
  136618. sqlite3ParserCTX_FETCH
  136619. #ifndef NDEBUG
  136620. if( yyTraceFILE ){
  136621. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  136622. }
  136623. #endif
  136624. #ifndef YYNOERRORRECOVERY
  136625. yypParser->yyerrcnt = -1;
  136626. #endif
  136627. assert( yypParser->yytos==yypParser->yystack );
  136628. /* Here code is inserted which will be executed whenever the
  136629. ** parser accepts */
  136630. /*********** Begin %parse_accept code *****************************************/
  136631. /*********** End %parse_accept code *******************************************/
  136632. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  136633. sqlite3ParserCTX_STORE
  136634. }
  136635. /* The main parser program.
  136636. ** The first argument is a pointer to a structure obtained from
  136637. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  136638. ** The second argument is the major token number. The third is
  136639. ** the minor token. The fourth optional argument is whatever the
  136640. ** user wants (and specified in the grammar) and is available for
  136641. ** use by the action routines.
  136642. **
  136643. ** Inputs:
  136644. ** <ul>
  136645. ** <li> A pointer to the parser (an opaque structure.)
  136646. ** <li> The major token number.
  136647. ** <li> The minor token number.
  136648. ** <li> An option argument of a grammar-specified type.
  136649. ** </ul>
  136650. **
  136651. ** Outputs:
  136652. ** None.
  136653. */
  136654. SQLITE_PRIVATE void sqlite3Parser(
  136655. void *yyp, /* The parser */
  136656. int yymajor, /* The major token code number */
  136657. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  136658. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  136659. ){
  136660. YYMINORTYPE yyminorunion;
  136661. YYACTIONTYPE yyact; /* The parser action. */
  136662. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  136663. int yyendofinput; /* True if we are at the end of input */
  136664. #endif
  136665. #ifdef YYERRORSYMBOL
  136666. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  136667. #endif
  136668. yyParser *yypParser = (yyParser*)yyp; /* The parser */
  136669. sqlite3ParserCTX_FETCH
  136670. sqlite3ParserARG_STORE
  136671. assert( yypParser->yytos!=0 );
  136672. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  136673. yyendofinput = (yymajor==0);
  136674. #endif
  136675. yyact = yypParser->yytos->stateno;
  136676. #ifndef NDEBUG
  136677. if( yyTraceFILE ){
  136678. if( yyact < YY_MIN_REDUCE ){
  136679. fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
  136680. yyTracePrompt,yyTokenName[yymajor],yyact);
  136681. }else{
  136682. fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  136683. yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
  136684. }
  136685. }
  136686. #endif
  136687. do{
  136688. assert( yyact==yypParser->yytos->stateno );
  136689. yyact = yy_find_shift_action(yymajor,yyact);
  136690. if( yyact >= YY_MIN_REDUCE ){
  136691. yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,
  136692. yyminor sqlite3ParserCTX_PARAM);
  136693. }else if( yyact <= YY_MAX_SHIFTREDUCE ){
  136694. yy_shift(yypParser,yyact,yymajor,yyminor);
  136695. #ifndef YYNOERRORRECOVERY
  136696. yypParser->yyerrcnt--;
  136697. #endif
  136698. break;
  136699. }else if( yyact==YY_ACCEPT_ACTION ){
  136700. yypParser->yytos--;
  136701. yy_accept(yypParser);
  136702. return;
  136703. }else{
  136704. assert( yyact == YY_ERROR_ACTION );
  136705. yyminorunion.yy0 = yyminor;
  136706. #ifdef YYERRORSYMBOL
  136707. int yymx;
  136708. #endif
  136709. #ifndef NDEBUG
  136710. if( yyTraceFILE ){
  136711. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  136712. }
  136713. #endif
  136714. #ifdef YYERRORSYMBOL
  136715. /* A syntax error has occurred.
  136716. ** The response to an error depends upon whether or not the
  136717. ** grammar defines an error token "ERROR".
  136718. **
  136719. ** This is what we do if the grammar does define ERROR:
  136720. **
  136721. ** * Call the %syntax_error function.
  136722. **
  136723. ** * Begin popping the stack until we enter a state where
  136724. ** it is legal to shift the error symbol, then shift
  136725. ** the error symbol.
  136726. **
  136727. ** * Set the error count to three.
  136728. **
  136729. ** * Begin accepting and shifting new tokens. No new error
  136730. ** processing will occur until three tokens have been
  136731. ** shifted successfully.
  136732. **
  136733. */
  136734. if( yypParser->yyerrcnt<0 ){
  136735. yy_syntax_error(yypParser,yymajor,yyminor);
  136736. }
  136737. yymx = yypParser->yytos->major;
  136738. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  136739. #ifndef NDEBUG
  136740. if( yyTraceFILE ){
  136741. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  136742. yyTracePrompt,yyTokenName[yymajor]);
  136743. }
  136744. #endif
  136745. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  136746. yymajor = YYNOCODE;
  136747. }else{
  136748. while( yypParser->yytos >= yypParser->yystack
  136749. && yymx != YYERRORSYMBOL
  136750. && (yyact = yy_find_reduce_action(
  136751. yypParser->yytos->stateno,
  136752. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  136753. ){
  136754. yy_pop_parser_stack(yypParser);
  136755. }
  136756. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  136757. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  136758. yy_parse_failed(yypParser);
  136759. #ifndef YYNOERRORRECOVERY
  136760. yypParser->yyerrcnt = -1;
  136761. #endif
  136762. yymajor = YYNOCODE;
  136763. }else if( yymx!=YYERRORSYMBOL ){
  136764. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  136765. }
  136766. }
  136767. yypParser->yyerrcnt = 3;
  136768. yyerrorhit = 1;
  136769. if( yymajor==YYNOCODE ) break;
  136770. yyact = yypParser->yytos->stateno;
  136771. #elif defined(YYNOERRORRECOVERY)
  136772. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  136773. ** do any kind of error recovery. Instead, simply invoke the syntax
  136774. ** error routine and continue going as if nothing had happened.
  136775. **
  136776. ** Applications can set this macro (for example inside %include) if
  136777. ** they intend to abandon the parse upon the first syntax error seen.
  136778. */
  136779. yy_syntax_error(yypParser,yymajor, yyminor);
  136780. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  136781. break;
  136782. #else /* YYERRORSYMBOL is not defined */
  136783. /* This is what we do if the grammar does not define ERROR:
  136784. **
  136785. ** * Report an error message, and throw away the input token.
  136786. **
  136787. ** * If the input token is $, then fail the parse.
  136788. **
  136789. ** As before, subsequent error messages are suppressed until
  136790. ** three input tokens have been successfully shifted.
  136791. */
  136792. if( yypParser->yyerrcnt<=0 ){
  136793. yy_syntax_error(yypParser,yymajor, yyminor);
  136794. }
  136795. yypParser->yyerrcnt = 3;
  136796. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  136797. if( yyendofinput ){
  136798. yy_parse_failed(yypParser);
  136799. #ifndef YYNOERRORRECOVERY
  136800. yypParser->yyerrcnt = -1;
  136801. #endif
  136802. }
  136803. break;
  136804. #endif
  136805. }
  136806. }while( yypParser->yytos>yypParser->yystack );
  136807. #ifndef NDEBUG
  136808. if( yyTraceFILE ){
  136809. yyStackEntry *i;
  136810. char cDiv = '[';
  136811. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  136812. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  136813. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  136814. cDiv = ' ';
  136815. }
  136816. fprintf(yyTraceFILE,"]\n");
  136817. }
  136818. #endif
  136819. return;
  136820. }
  136821. /************** End of parse.c ***********************************************/
  136822. /************** Begin file tokenize.c ****************************************/
  136823. /*
  136824. ** 2001 September 15
  136825. **
  136826. ** The author disclaims copyright to this source code. In place of
  136827. ** a legal notice, here is a blessing:
  136828. **
  136829. ** May you do good and not evil.
  136830. ** May you find forgiveness for yourself and forgive others.
  136831. ** May you share freely, never taking more than you give.
  136832. **
  136833. *************************************************************************
  136834. ** An tokenizer for SQL
  136835. **
  136836. ** This file contains C code that splits an SQL input string up into
  136837. ** individual tokens and sends those tokens one-by-one over to the
  136838. ** parser for analysis.
  136839. */
  136840. /* #include "sqliteInt.h" */
  136841. /* #include <stdlib.h> */
  136842. /* Character classes for tokenizing
  136843. **
  136844. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  136845. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  136846. ** The lookup table is much faster. To maximize speed, and to ensure that
  136847. ** a lookup table is used, all of the classes need to be small integers and
  136848. ** all of them need to be used within the switch.
  136849. */
  136850. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  136851. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  136852. #define CC_ID 2 /* unicode characters usable in IDs */
  136853. #define CC_DIGIT 3 /* Digits */
  136854. #define CC_DOLLAR 4 /* '$' */
  136855. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  136856. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  136857. #define CC_SPACE 7 /* Space characters */
  136858. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  136859. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  136860. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  136861. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  136862. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  136863. #define CC_GT 13 /* '>'. Part of > or >= */
  136864. #define CC_EQ 14 /* '='. Part of = or == */
  136865. #define CC_BANG 15 /* '!'. Part of != */
  136866. #define CC_SLASH 16 /* '/'. / or c-style comment */
  136867. #define CC_LP 17 /* '(' */
  136868. #define CC_RP 18 /* ')' */
  136869. #define CC_SEMI 19 /* ';' */
  136870. #define CC_PLUS 20 /* '+' */
  136871. #define CC_STAR 21 /* '*' */
  136872. #define CC_PERCENT 22 /* '%' */
  136873. #define CC_COMMA 23 /* ',' */
  136874. #define CC_AND 24 /* '&' */
  136875. #define CC_TILDA 25 /* '~' */
  136876. #define CC_DOT 26 /* '.' */
  136877. #define CC_ILLEGAL 27 /* Illegal character */
  136878. static const unsigned char aiClass[] = {
  136879. #ifdef SQLITE_ASCII
  136880. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  136881. /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  136882. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  136883. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  136884. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  136885. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  136886. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  136887. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  136888. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  136889. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  136890. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  136891. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  136892. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  136893. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  136894. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  136895. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  136896. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  136897. #endif
  136898. #ifdef SQLITE_EBCDIC
  136899. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  136900. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  136901. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  136902. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  136903. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  136904. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  136905. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  136906. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  136907. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  136908. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  136909. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  136910. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  136911. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  136912. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  136913. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  136914. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  136915. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  136916. #endif
  136917. };
  136918. /*
  136919. ** The charMap() macro maps alphabetic characters (only) into their
  136920. ** lower-case ASCII equivalent. On ASCII machines, this is just
  136921. ** an upper-to-lower case map. On EBCDIC machines we also need
  136922. ** to adjust the encoding. The mapping is only valid for alphabetics
  136923. ** which are the only characters for which this feature is used.
  136924. **
  136925. ** Used by keywordhash.h
  136926. */
  136927. #ifdef SQLITE_ASCII
  136928. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  136929. #endif
  136930. #ifdef SQLITE_EBCDIC
  136931. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  136932. const unsigned char ebcdicToAscii[] = {
  136933. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  136942. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  136943. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  136944. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  136946. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  136947. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  136948. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  136950. };
  136951. #endif
  136952. /*
  136953. ** The sqlite3KeywordCode function looks up an identifier to determine if
  136954. ** it is a keyword. If it is a keyword, the token code of that keyword is
  136955. ** returned. If the input is not a keyword, TK_ID is returned.
  136956. **
  136957. ** The implementation of this routine was generated by a program,
  136958. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  136959. ** The output of the mkkeywordhash.c program is written into a file
  136960. ** named keywordhash.h and then included into this source file by
  136961. ** the #include below.
  136962. */
  136963. /************** Include keywordhash.h in the middle of tokenize.c ************/
  136964. /************** Begin file keywordhash.h *************************************/
  136965. /***** This file contains automatically generated code ******
  136966. **
  136967. ** The code in this file has been automatically generated by
  136968. **
  136969. ** sqlite/tool/mkkeywordhash.c
  136970. **
  136971. ** The code in this file implements a function that determines whether
  136972. ** or not a given identifier is really an SQL keyword. The same thing
  136973. ** might be implemented more directly using a hand-written hash table.
  136974. ** But by using this automatically generated code, the size of the code
  136975. ** is substantially reduced. This is important for embedded applications
  136976. ** on platforms with limited memory.
  136977. */
  136978. /* Hash score: 185 */
  136979. /* zKWText[] encodes 845 bytes of keyword text in 561 bytes */
  136980. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  136981. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  136982. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  136983. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  136984. /* BETWEENOTHINGLOBYCASCADELETECASECOLLATECREATECURRENT_DATE */
  136985. /* DETACHIMMEDIATEJOINSERTLIKEMATCHPLANALYZEPRAGMABORTVALUES */
  136986. /* VIRTUALIMITWHENOTNULLWHERENAMEAFTEREPLACEANDEFAULT */
  136987. /* AUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSSCURRENT_TIMESTAMP */
  136988. /* RIMARYDEFERREDISTINCTDORDERESTRICTDROPFAILFROMFULLIFISNULL */
  136989. /* RIGHTROLLBACKROWUNIONUSINGVACUUMVIEWINITIALLY */
  136990. static const char zKWText[560] = {
  136991. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  136992. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  136993. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  136994. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  136995. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  136996. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  136997. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  136998. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  136999. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  137000. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  137001. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  137002. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  137003. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  137004. 'B','E','T','W','E','E','N','O','T','H','I','N','G','L','O','B','Y','C',
  137005. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  137006. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  137007. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  137008. 'J','O','I','N','S','E','R','T','L','I','K','E','M','A','T','C','H','P',
  137009. 'L','A','N','A','L','Y','Z','E','P','R','A','G','M','A','B','O','R','T',
  137010. 'V','A','L','U','E','S','V','I','R','T','U','A','L','I','M','I','T','W',
  137011. 'H','E','N','O','T','N','U','L','L','W','H','E','R','E','N','A','M','E',
  137012. 'A','F','T','E','R','E','P','L','A','C','E','A','N','D','E','F','A','U',
  137013. 'L','T','A','U','T','O','I','N','C','R','E','M','E','N','T','C','A','S',
  137014. 'T','C','O','L','U','M','N','C','O','M','M','I','T','C','O','N','F','L',
  137015. 'I','C','T','C','R','O','S','S','C','U','R','R','E','N','T','_','T','I',
  137016. 'M','E','S','T','A','M','P','R','I','M','A','R','Y','D','E','F','E','R',
  137017. 'R','E','D','I','S','T','I','N','C','T','D','O','R','D','E','R','E','S',
  137018. 'T','R','I','C','T','D','R','O','P','F','A','I','L','F','R','O','M','F',
  137019. 'U','L','L','I','F','I','S','N','U','L','L','R','I','G','H','T','R','O',
  137020. 'L','L','B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N',
  137021. 'G','V','A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L',
  137022. 'L','Y',
  137023. };
  137024. /* aKWHash[i] is the hash value for the i-th keyword */
  137025. static const unsigned char aKWHash[127] = {
  137026. 74, 108, 119, 72, 0, 45, 0, 0, 81, 0, 76, 61, 0,
  137027. 42, 12, 77, 15, 0, 118, 84, 54, 116, 0, 19, 0, 0,
  137028. 123, 0, 121, 111, 0, 22, 96, 0, 9, 0, 0, 68, 69,
  137029. 0, 67, 6, 0, 48, 93, 105, 0, 120, 104, 0, 0, 44,
  137030. 0, 106, 24, 0, 17, 0, 124, 53, 23, 0, 5, 62, 25,
  137031. 99, 0, 0, 126, 112, 60, 125, 57, 28, 55, 0, 94, 0,
  137032. 103, 26, 0, 102, 0, 0, 0, 98, 95, 100, 91, 115, 14,
  137033. 39, 114, 0, 80, 0, 109, 92, 90, 32, 0, 122, 79, 117,
  137034. 86, 46, 83, 0, 0, 97, 40, 59, 110, 0, 36, 0, 0,
  137035. 29, 0, 89, 87, 88, 0, 20, 85, 0, 56,
  137036. };
  137037. /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
  137038. ** then the i-th keyword has no more hash collisions. Otherwise,
  137039. ** the next keyword with the same hash is aKWHash[i]-1. */
  137040. static const unsigned char aKWNext[126] = {
  137041. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  137043. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  137045. 0, 43, 3, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 1, 64, 0, 0, 65, 0, 41, 0, 38, 0, 0, 0,
  137047. 0, 0, 49, 75, 0, 0, 30, 0, 58, 0, 0, 63, 31,
  137048. 52, 16, 34, 10, 0, 0, 0, 0, 0, 0, 0, 11, 70,
  137049. 78, 0, 8, 0, 18, 51, 0, 107, 101, 0, 113, 0, 73,
  137050. 27, 37, 71, 82, 0, 35, 66, 0, 0,
  137051. };
  137052. /* aKWLen[i] is the length (in bytes) of the i-th keyword */
  137053. static const unsigned char aKWLen[126] = {
  137054. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  137055. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  137056. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  137057. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  137058. 6, 6, 5, 6, 5, 5, 9, 7, 7, 4, 2, 7, 3,
  137059. 6, 4, 7, 6, 12, 6, 9, 4, 6, 4, 5, 4, 7,
  137060. 6, 5, 6, 7, 5, 4, 7, 3, 2, 4, 5, 6, 5,
  137061. 7, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5, 17, 12,
  137062. 7, 8, 8, 2, 2, 5, 8, 4, 4, 4, 4, 2, 6,
  137063. 5, 8, 3, 5, 5, 6, 4, 9, 3,
  137064. };
  137065. /* aKWOffset[i] is the index into zKWText[] of the start of
  137066. ** the text for the i-th keyword. */
  137067. static const unsigned short int aKWOffset[126] = {
  137068. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  137069. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  137070. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  137071. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  137072. 199, 204, 209, 212, 218, 221, 225, 234, 240, 246, 249, 251, 252,
  137073. 256, 262, 266, 273, 279, 291, 297, 306, 308, 314, 318, 323, 325,
  137074. 332, 337, 342, 348, 354, 359, 362, 362, 362, 365, 369, 372, 378,
  137075. 382, 389, 391, 398, 400, 402, 411, 415, 421, 427, 435, 440, 440,
  137076. 456, 463, 470, 471, 478, 479, 483, 491, 495, 499, 503, 507, 509,
  137077. 515, 520, 528, 531, 536, 541, 547, 551, 556,
  137078. };
  137079. /* aKWCode[i] is the parser symbol code for the i-th keyword */
  137080. static const unsigned char aKWCode[126] = {
  137081. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  137082. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  137083. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  137084. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  137085. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  137086. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  137087. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  137088. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  137089. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  137090. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  137091. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  137092. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  137093. TK_NOTHING, TK_LIKE_KW, TK_BY, TK_CASCADE, TK_ASC,
  137094. TK_DELETE, TK_CASE, TK_COLLATE, TK_CREATE, TK_CTIME_KW,
  137095. TK_DETACH, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_LIKE_KW,
  137096. TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT,
  137097. TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, TK_NOTNULL,
  137098. TK_NOT, TK_NO, TK_NULL, TK_WHERE, TK_RENAME,
  137099. TK_AFTER, TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR,
  137100. TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT,
  137101. TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY,
  137102. TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DO, TK_ORDER,
  137103. TK_RESTRICT, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  137104. TK_IF, TK_ISNULL, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  137105. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  137106. TK_ALL,
  137107. };
  137108. /* Check to see if z[0..n-1] is a keyword. If it is, write the
  137109. ** parser symbol code for that keyword into *pType. Always
  137110. ** return the integer n (the length of the token). */
  137111. static int keywordCode(const char *z, int n, int *pType){
  137112. int i, j;
  137113. const char *zKW;
  137114. if( n>=2 ){
  137115. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  137116. for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
  137117. if( aKWLen[i]!=n ) continue;
  137118. j = 0;
  137119. zKW = &zKWText[aKWOffset[i]];
  137120. #ifdef SQLITE_ASCII
  137121. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  137122. #endif
  137123. #ifdef SQLITE_EBCDIC
  137124. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  137125. #endif
  137126. if( j<n ) continue;
  137127. testcase( i==0 ); /* REINDEX */
  137128. testcase( i==1 ); /* INDEXED */
  137129. testcase( i==2 ); /* INDEX */
  137130. testcase( i==3 ); /* DESC */
  137131. testcase( i==4 ); /* ESCAPE */
  137132. testcase( i==5 ); /* EACH */
  137133. testcase( i==6 ); /* CHECK */
  137134. testcase( i==7 ); /* KEY */
  137135. testcase( i==8 ); /* BEFORE */
  137136. testcase( i==9 ); /* FOREIGN */
  137137. testcase( i==10 ); /* FOR */
  137138. testcase( i==11 ); /* IGNORE */
  137139. testcase( i==12 ); /* REGEXP */
  137140. testcase( i==13 ); /* EXPLAIN */
  137141. testcase( i==14 ); /* INSTEAD */
  137142. testcase( i==15 ); /* ADD */
  137143. testcase( i==16 ); /* DATABASE */
  137144. testcase( i==17 ); /* AS */
  137145. testcase( i==18 ); /* SELECT */
  137146. testcase( i==19 ); /* TABLE */
  137147. testcase( i==20 ); /* LEFT */
  137148. testcase( i==21 ); /* THEN */
  137149. testcase( i==22 ); /* END */
  137150. testcase( i==23 ); /* DEFERRABLE */
  137151. testcase( i==24 ); /* ELSE */
  137152. testcase( i==25 ); /* EXCEPT */
  137153. testcase( i==26 ); /* TRANSACTION */
  137154. testcase( i==27 ); /* ACTION */
  137155. testcase( i==28 ); /* ON */
  137156. testcase( i==29 ); /* NATURAL */
  137157. testcase( i==30 ); /* ALTER */
  137158. testcase( i==31 ); /* RAISE */
  137159. testcase( i==32 ); /* EXCLUSIVE */
  137160. testcase( i==33 ); /* EXISTS */
  137161. testcase( i==34 ); /* SAVEPOINT */
  137162. testcase( i==35 ); /* INTERSECT */
  137163. testcase( i==36 ); /* TRIGGER */
  137164. testcase( i==37 ); /* REFERENCES */
  137165. testcase( i==38 ); /* CONSTRAINT */
  137166. testcase( i==39 ); /* INTO */
  137167. testcase( i==40 ); /* OFFSET */
  137168. testcase( i==41 ); /* OF */
  137169. testcase( i==42 ); /* SET */
  137170. testcase( i==43 ); /* TEMPORARY */
  137171. testcase( i==44 ); /* TEMP */
  137172. testcase( i==45 ); /* OR */
  137173. testcase( i==46 ); /* UNIQUE */
  137174. testcase( i==47 ); /* QUERY */
  137175. testcase( i==48 ); /* WITHOUT */
  137176. testcase( i==49 ); /* WITH */
  137177. testcase( i==50 ); /* OUTER */
  137178. testcase( i==51 ); /* RELEASE */
  137179. testcase( i==52 ); /* ATTACH */
  137180. testcase( i==53 ); /* HAVING */
  137181. testcase( i==54 ); /* GROUP */
  137182. testcase( i==55 ); /* UPDATE */
  137183. testcase( i==56 ); /* BEGIN */
  137184. testcase( i==57 ); /* INNER */
  137185. testcase( i==58 ); /* RECURSIVE */
  137186. testcase( i==59 ); /* BETWEEN */
  137187. testcase( i==60 ); /* NOTHING */
  137188. testcase( i==61 ); /* GLOB */
  137189. testcase( i==62 ); /* BY */
  137190. testcase( i==63 ); /* CASCADE */
  137191. testcase( i==64 ); /* ASC */
  137192. testcase( i==65 ); /* DELETE */
  137193. testcase( i==66 ); /* CASE */
  137194. testcase( i==67 ); /* COLLATE */
  137195. testcase( i==68 ); /* CREATE */
  137196. testcase( i==69 ); /* CURRENT_DATE */
  137197. testcase( i==70 ); /* DETACH */
  137198. testcase( i==71 ); /* IMMEDIATE */
  137199. testcase( i==72 ); /* JOIN */
  137200. testcase( i==73 ); /* INSERT */
  137201. testcase( i==74 ); /* LIKE */
  137202. testcase( i==75 ); /* MATCH */
  137203. testcase( i==76 ); /* PLAN */
  137204. testcase( i==77 ); /* ANALYZE */
  137205. testcase( i==78 ); /* PRAGMA */
  137206. testcase( i==79 ); /* ABORT */
  137207. testcase( i==80 ); /* VALUES */
  137208. testcase( i==81 ); /* VIRTUAL */
  137209. testcase( i==82 ); /* LIMIT */
  137210. testcase( i==83 ); /* WHEN */
  137211. testcase( i==84 ); /* NOTNULL */
  137212. testcase( i==85 ); /* NOT */
  137213. testcase( i==86 ); /* NO */
  137214. testcase( i==87 ); /* NULL */
  137215. testcase( i==88 ); /* WHERE */
  137216. testcase( i==89 ); /* RENAME */
  137217. testcase( i==90 ); /* AFTER */
  137218. testcase( i==91 ); /* REPLACE */
  137219. testcase( i==92 ); /* AND */
  137220. testcase( i==93 ); /* DEFAULT */
  137221. testcase( i==94 ); /* AUTOINCREMENT */
  137222. testcase( i==95 ); /* TO */
  137223. testcase( i==96 ); /* IN */
  137224. testcase( i==97 ); /* CAST */
  137225. testcase( i==98 ); /* COLUMN */
  137226. testcase( i==99 ); /* COMMIT */
  137227. testcase( i==100 ); /* CONFLICT */
  137228. testcase( i==101 ); /* CROSS */
  137229. testcase( i==102 ); /* CURRENT_TIMESTAMP */
  137230. testcase( i==103 ); /* CURRENT_TIME */
  137231. testcase( i==104 ); /* PRIMARY */
  137232. testcase( i==105 ); /* DEFERRED */
  137233. testcase( i==106 ); /* DISTINCT */
  137234. testcase( i==107 ); /* IS */
  137235. testcase( i==108 ); /* DO */
  137236. testcase( i==109 ); /* ORDER */
  137237. testcase( i==110 ); /* RESTRICT */
  137238. testcase( i==111 ); /* DROP */
  137239. testcase( i==112 ); /* FAIL */
  137240. testcase( i==113 ); /* FROM */
  137241. testcase( i==114 ); /* FULL */
  137242. testcase( i==115 ); /* IF */
  137243. testcase( i==116 ); /* ISNULL */
  137244. testcase( i==117 ); /* RIGHT */
  137245. testcase( i==118 ); /* ROLLBACK */
  137246. testcase( i==119 ); /* ROW */
  137247. testcase( i==120 ); /* UNION */
  137248. testcase( i==121 ); /* USING */
  137249. testcase( i==122 ); /* VACUUM */
  137250. testcase( i==123 ); /* VIEW */
  137251. testcase( i==124 ); /* INITIALLY */
  137252. testcase( i==125 ); /* ALL */
  137253. *pType = aKWCode[i];
  137254. break;
  137255. }
  137256. }
  137257. return n;
  137258. }
  137259. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  137260. int id = TK_ID;
  137261. keywordCode((char*)z, n, &id);
  137262. return id;
  137263. }
  137264. #define SQLITE_N_KEYWORD 126
  137265. SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
  137266. if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
  137267. *pzName = zKWText + aKWOffset[i];
  137268. *pnName = aKWLen[i];
  137269. return SQLITE_OK;
  137270. }
  137271. SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
  137272. SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
  137273. return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
  137274. }
  137275. /************** End of keywordhash.h *****************************************/
  137276. /************** Continuing where we left off in tokenize.c *******************/
  137277. /*
  137278. ** If X is a character that can be used in an identifier then
  137279. ** IdChar(X) will be true. Otherwise it is false.
  137280. **
  137281. ** For ASCII, any character with the high-order bit set is
  137282. ** allowed in an identifier. For 7-bit characters,
  137283. ** sqlite3IsIdChar[X] must be 1.
  137284. **
  137285. ** For EBCDIC, the rules are more complex but have the same
  137286. ** end result.
  137287. **
  137288. ** Ticket #1066. the SQL standard does not allow '$' in the
  137289. ** middle of identifiers. But many SQL implementations do.
  137290. ** SQLite will allow '$' in identifiers for compatibility.
  137291. ** But the feature is undocumented.
  137292. */
  137293. #ifdef SQLITE_ASCII
  137294. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  137295. #endif
  137296. #ifdef SQLITE_EBCDIC
  137297. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  137298. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  137299. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  137300. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  137301. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  137302. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  137303. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  137304. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  137305. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  137307. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  137308. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  137309. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  137310. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  137311. };
  137312. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  137313. #endif
  137314. /* Make the IdChar function accessible from ctime.c */
  137315. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  137316. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  137317. #endif
  137318. /*
  137319. ** Return the length (in bytes) of the token that begins at z[0].
  137320. ** Store the token type in *tokenType before returning.
  137321. */
  137322. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  137323. int i, c;
  137324. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  137325. ** of the token. See the comment on the CC_ defines
  137326. ** above. */
  137327. case CC_SPACE: {
  137328. testcase( z[0]==' ' );
  137329. testcase( z[0]=='\t' );
  137330. testcase( z[0]=='\n' );
  137331. testcase( z[0]=='\f' );
  137332. testcase( z[0]=='\r' );
  137333. for(i=1; sqlite3Isspace(z[i]); i++){}
  137334. *tokenType = TK_SPACE;
  137335. return i;
  137336. }
  137337. case CC_MINUS: {
  137338. if( z[1]=='-' ){
  137339. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  137340. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  137341. return i;
  137342. }
  137343. *tokenType = TK_MINUS;
  137344. return 1;
  137345. }
  137346. case CC_LP: {
  137347. *tokenType = TK_LP;
  137348. return 1;
  137349. }
  137350. case CC_RP: {
  137351. *tokenType = TK_RP;
  137352. return 1;
  137353. }
  137354. case CC_SEMI: {
  137355. *tokenType = TK_SEMI;
  137356. return 1;
  137357. }
  137358. case CC_PLUS: {
  137359. *tokenType = TK_PLUS;
  137360. return 1;
  137361. }
  137362. case CC_STAR: {
  137363. *tokenType = TK_STAR;
  137364. return 1;
  137365. }
  137366. case CC_SLASH: {
  137367. if( z[1]!='*' || z[2]==0 ){
  137368. *tokenType = TK_SLASH;
  137369. return 1;
  137370. }
  137371. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  137372. if( c ) i++;
  137373. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  137374. return i;
  137375. }
  137376. case CC_PERCENT: {
  137377. *tokenType = TK_REM;
  137378. return 1;
  137379. }
  137380. case CC_EQ: {
  137381. *tokenType = TK_EQ;
  137382. return 1 + (z[1]=='=');
  137383. }
  137384. case CC_LT: {
  137385. if( (c=z[1])=='=' ){
  137386. *tokenType = TK_LE;
  137387. return 2;
  137388. }else if( c=='>' ){
  137389. *tokenType = TK_NE;
  137390. return 2;
  137391. }else if( c=='<' ){
  137392. *tokenType = TK_LSHIFT;
  137393. return 2;
  137394. }else{
  137395. *tokenType = TK_LT;
  137396. return 1;
  137397. }
  137398. }
  137399. case CC_GT: {
  137400. if( (c=z[1])=='=' ){
  137401. *tokenType = TK_GE;
  137402. return 2;
  137403. }else if( c=='>' ){
  137404. *tokenType = TK_RSHIFT;
  137405. return 2;
  137406. }else{
  137407. *tokenType = TK_GT;
  137408. return 1;
  137409. }
  137410. }
  137411. case CC_BANG: {
  137412. if( z[1]!='=' ){
  137413. *tokenType = TK_ILLEGAL;
  137414. return 1;
  137415. }else{
  137416. *tokenType = TK_NE;
  137417. return 2;
  137418. }
  137419. }
  137420. case CC_PIPE: {
  137421. if( z[1]!='|' ){
  137422. *tokenType = TK_BITOR;
  137423. return 1;
  137424. }else{
  137425. *tokenType = TK_CONCAT;
  137426. return 2;
  137427. }
  137428. }
  137429. case CC_COMMA: {
  137430. *tokenType = TK_COMMA;
  137431. return 1;
  137432. }
  137433. case CC_AND: {
  137434. *tokenType = TK_BITAND;
  137435. return 1;
  137436. }
  137437. case CC_TILDA: {
  137438. *tokenType = TK_BITNOT;
  137439. return 1;
  137440. }
  137441. case CC_QUOTE: {
  137442. int delim = z[0];
  137443. testcase( delim=='`' );
  137444. testcase( delim=='\'' );
  137445. testcase( delim=='"' );
  137446. for(i=1; (c=z[i])!=0; i++){
  137447. if( c==delim ){
  137448. if( z[i+1]==delim ){
  137449. i++;
  137450. }else{
  137451. break;
  137452. }
  137453. }
  137454. }
  137455. if( c=='\'' ){
  137456. *tokenType = TK_STRING;
  137457. return i+1;
  137458. }else if( c!=0 ){
  137459. *tokenType = TK_ID;
  137460. return i+1;
  137461. }else{
  137462. *tokenType = TK_ILLEGAL;
  137463. return i;
  137464. }
  137465. }
  137466. case CC_DOT: {
  137467. #ifndef SQLITE_OMIT_FLOATING_POINT
  137468. if( !sqlite3Isdigit(z[1]) )
  137469. #endif
  137470. {
  137471. *tokenType = TK_DOT;
  137472. return 1;
  137473. }
  137474. /* If the next character is a digit, this is a floating point
  137475. ** number that begins with ".". Fall thru into the next case */
  137476. }
  137477. case CC_DIGIT: {
  137478. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  137479. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  137480. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  137481. testcase( z[0]=='9' );
  137482. *tokenType = TK_INTEGER;
  137483. #ifndef SQLITE_OMIT_HEX_INTEGER
  137484. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  137485. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  137486. return i;
  137487. }
  137488. #endif
  137489. for(i=0; sqlite3Isdigit(z[i]); i++){}
  137490. #ifndef SQLITE_OMIT_FLOATING_POINT
  137491. if( z[i]=='.' ){
  137492. i++;
  137493. while( sqlite3Isdigit(z[i]) ){ i++; }
  137494. *tokenType = TK_FLOAT;
  137495. }
  137496. if( (z[i]=='e' || z[i]=='E') &&
  137497. ( sqlite3Isdigit(z[i+1])
  137498. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  137499. )
  137500. ){
  137501. i += 2;
  137502. while( sqlite3Isdigit(z[i]) ){ i++; }
  137503. *tokenType = TK_FLOAT;
  137504. }
  137505. #endif
  137506. while( IdChar(z[i]) ){
  137507. *tokenType = TK_ILLEGAL;
  137508. i++;
  137509. }
  137510. return i;
  137511. }
  137512. case CC_QUOTE2: {
  137513. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  137514. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  137515. return i;
  137516. }
  137517. case CC_VARNUM: {
  137518. *tokenType = TK_VARIABLE;
  137519. for(i=1; sqlite3Isdigit(z[i]); i++){}
  137520. return i;
  137521. }
  137522. case CC_DOLLAR:
  137523. case CC_VARALPHA: {
  137524. int n = 0;
  137525. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  137526. testcase( z[0]==':' ); testcase( z[0]=='#' );
  137527. *tokenType = TK_VARIABLE;
  137528. for(i=1; (c=z[i])!=0; i++){
  137529. if( IdChar(c) ){
  137530. n++;
  137531. #ifndef SQLITE_OMIT_TCL_VARIABLE
  137532. }else if( c=='(' && n>0 ){
  137533. do{
  137534. i++;
  137535. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  137536. if( c==')' ){
  137537. i++;
  137538. }else{
  137539. *tokenType = TK_ILLEGAL;
  137540. }
  137541. break;
  137542. }else if( c==':' && z[i+1]==':' ){
  137543. i++;
  137544. #endif
  137545. }else{
  137546. break;
  137547. }
  137548. }
  137549. if( n==0 ) *tokenType = TK_ILLEGAL;
  137550. return i;
  137551. }
  137552. case CC_KYWD: {
  137553. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  137554. if( IdChar(z[i]) ){
  137555. /* This token started out using characters that can appear in keywords,
  137556. ** but z[i] is a character not allowed within keywords, so this must
  137557. ** be an identifier instead */
  137558. i++;
  137559. break;
  137560. }
  137561. *tokenType = TK_ID;
  137562. return keywordCode((char*)z, i, tokenType);
  137563. }
  137564. case CC_X: {
  137565. #ifndef SQLITE_OMIT_BLOB_LITERAL
  137566. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  137567. if( z[1]=='\'' ){
  137568. *tokenType = TK_BLOB;
  137569. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  137570. if( z[i]!='\'' || i%2 ){
  137571. *tokenType = TK_ILLEGAL;
  137572. while( z[i] && z[i]!='\'' ){ i++; }
  137573. }
  137574. if( z[i] ) i++;
  137575. return i;
  137576. }
  137577. #endif
  137578. /* If it is not a BLOB literal, then it must be an ID, since no
  137579. ** SQL keywords start with the letter 'x'. Fall through */
  137580. }
  137581. case CC_ID: {
  137582. i = 1;
  137583. break;
  137584. }
  137585. default: {
  137586. *tokenType = TK_ILLEGAL;
  137587. return 1;
  137588. }
  137589. }
  137590. while( IdChar(z[i]) ){ i++; }
  137591. *tokenType = TK_ID;
  137592. return i;
  137593. }
  137594. /*
  137595. ** Run the parser on the given SQL string. The parser structure is
  137596. ** passed in. An SQLITE_ status code is returned. If an error occurs
  137597. ** then an and attempt is made to write an error message into
  137598. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  137599. ** error message.
  137600. */
  137601. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  137602. int nErr = 0; /* Number of errors encountered */
  137603. void *pEngine; /* The LEMON-generated LALR(1) parser */
  137604. int n = 0; /* Length of the next token token */
  137605. int tokenType; /* type of the next token */
  137606. int lastTokenParsed = -1; /* type of the previous token */
  137607. sqlite3 *db = pParse->db; /* The database connection */
  137608. int mxSqlLen; /* Max length of an SQL string */
  137609. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  137610. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  137611. #endif
  137612. assert( zSql!=0 );
  137613. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  137614. if( db->nVdbeActive==0 ){
  137615. db->u1.isInterrupted = 0;
  137616. }
  137617. pParse->rc = SQLITE_OK;
  137618. pParse->zTail = zSql;
  137619. assert( pzErrMsg!=0 );
  137620. /* sqlite3ParserTrace(stdout, "parser: "); */
  137621. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  137622. pEngine = &sEngine;
  137623. sqlite3ParserInit(pEngine, pParse);
  137624. #else
  137625. pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
  137626. if( pEngine==0 ){
  137627. sqlite3OomFault(db);
  137628. return SQLITE_NOMEM_BKPT;
  137629. }
  137630. #endif
  137631. assert( pParse->pNewTable==0 );
  137632. assert( pParse->pNewTrigger==0 );
  137633. assert( pParse->nVar==0 );
  137634. assert( pParse->pVList==0 );
  137635. while( 1 ){
  137636. if( zSql[0]!=0 ){
  137637. n = sqlite3GetToken((u8*)zSql, &tokenType);
  137638. mxSqlLen -= n;
  137639. if( mxSqlLen<0 ){
  137640. pParse->rc = SQLITE_TOOBIG;
  137641. break;
  137642. }
  137643. }else{
  137644. /* Upon reaching the end of input, call the parser two more times
  137645. ** with tokens TK_SEMI and 0, in that order. */
  137646. if( lastTokenParsed==TK_SEMI ){
  137647. tokenType = 0;
  137648. }else if( lastTokenParsed==0 ){
  137649. break;
  137650. }else{
  137651. tokenType = TK_SEMI;
  137652. }
  137653. n = 0;
  137654. }
  137655. if( tokenType>=TK_SPACE ){
  137656. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  137657. if( db->u1.isInterrupted ){
  137658. pParse->rc = SQLITE_INTERRUPT;
  137659. break;
  137660. }
  137661. if( tokenType==TK_ILLEGAL ){
  137662. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  137663. break;
  137664. }
  137665. zSql += n;
  137666. }else{
  137667. pParse->sLastToken.z = zSql;
  137668. pParse->sLastToken.n = n;
  137669. sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
  137670. lastTokenParsed = tokenType;
  137671. zSql += n;
  137672. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  137673. }
  137674. }
  137675. assert( nErr==0 );
  137676. pParse->zTail = zSql;
  137677. #ifdef YYTRACKMAXSTACKDEPTH
  137678. sqlite3_mutex_enter(sqlite3MallocMutex());
  137679. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  137680. sqlite3ParserStackPeak(pEngine)
  137681. );
  137682. sqlite3_mutex_leave(sqlite3MallocMutex());
  137683. #endif /* YYDEBUG */
  137684. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  137685. sqlite3ParserFinalize(pEngine);
  137686. #else
  137687. sqlite3ParserFree(pEngine, sqlite3_free);
  137688. #endif
  137689. if( db->mallocFailed ){
  137690. pParse->rc = SQLITE_NOMEM_BKPT;
  137691. }
  137692. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  137693. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  137694. }
  137695. assert( pzErrMsg!=0 );
  137696. if( pParse->zErrMsg ){
  137697. *pzErrMsg = pParse->zErrMsg;
  137698. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  137699. pParse->zErrMsg = 0;
  137700. nErr++;
  137701. }
  137702. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  137703. sqlite3VdbeDelete(pParse->pVdbe);
  137704. pParse->pVdbe = 0;
  137705. }
  137706. #ifndef SQLITE_OMIT_SHARED_CACHE
  137707. if( pParse->nested==0 ){
  137708. sqlite3DbFree(db, pParse->aTableLock);
  137709. pParse->aTableLock = 0;
  137710. pParse->nTableLock = 0;
  137711. }
  137712. #endif
  137713. #ifndef SQLITE_OMIT_VIRTUALTABLE
  137714. sqlite3_free(pParse->apVtabLock);
  137715. #endif
  137716. if( !IN_DECLARE_VTAB ){
  137717. /* If the pParse->declareVtab flag is set, do not delete any table
  137718. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  137719. ** will take responsibility for freeing the Table structure.
  137720. */
  137721. sqlite3DeleteTable(db, pParse->pNewTable);
  137722. }
  137723. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  137724. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  137725. sqlite3DbFree(db, pParse->pVList);
  137726. while( pParse->pAinc ){
  137727. AutoincInfo *p = pParse->pAinc;
  137728. pParse->pAinc = p->pNext;
  137729. sqlite3DbFreeNN(db, p);
  137730. }
  137731. while( pParse->pZombieTab ){
  137732. Table *p = pParse->pZombieTab;
  137733. pParse->pZombieTab = p->pNextZombie;
  137734. sqlite3DeleteTable(db, p);
  137735. }
  137736. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  137737. return nErr;
  137738. }
  137739. /************** End of tokenize.c ********************************************/
  137740. /************** Begin file complete.c ****************************************/
  137741. /*
  137742. ** 2001 September 15
  137743. **
  137744. ** The author disclaims copyright to this source code. In place of
  137745. ** a legal notice, here is a blessing:
  137746. **
  137747. ** May you do good and not evil.
  137748. ** May you find forgiveness for yourself and forgive others.
  137749. ** May you share freely, never taking more than you give.
  137750. **
  137751. *************************************************************************
  137752. ** An tokenizer for SQL
  137753. **
  137754. ** This file contains C code that implements the sqlite3_complete() API.
  137755. ** This code used to be part of the tokenizer.c source file. But by
  137756. ** separating it out, the code will be automatically omitted from
  137757. ** static links that do not use it.
  137758. */
  137759. /* #include "sqliteInt.h" */
  137760. #ifndef SQLITE_OMIT_COMPLETE
  137761. /*
  137762. ** This is defined in tokenize.c. We just have to import the definition.
  137763. */
  137764. #ifndef SQLITE_AMALGAMATION
  137765. #ifdef SQLITE_ASCII
  137766. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  137767. #endif
  137768. #ifdef SQLITE_EBCDIC
  137769. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  137770. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  137771. #endif
  137772. #endif /* SQLITE_AMALGAMATION */
  137773. /*
  137774. ** Token types used by the sqlite3_complete() routine. See the header
  137775. ** comments on that procedure for additional information.
  137776. */
  137777. #define tkSEMI 0
  137778. #define tkWS 1
  137779. #define tkOTHER 2
  137780. #ifndef SQLITE_OMIT_TRIGGER
  137781. #define tkEXPLAIN 3
  137782. #define tkCREATE 4
  137783. #define tkTEMP 5
  137784. #define tkTRIGGER 6
  137785. #define tkEND 7
  137786. #endif
  137787. /*
  137788. ** Return TRUE if the given SQL string ends in a semicolon.
  137789. **
  137790. ** Special handling is require for CREATE TRIGGER statements.
  137791. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  137792. ** must end with ";END;".
  137793. **
  137794. ** This implementation uses a state machine with 8 states:
  137795. **
  137796. ** (0) INVALID We have not yet seen a non-whitespace character.
  137797. **
  137798. ** (1) START At the beginning or end of an SQL statement. This routine
  137799. ** returns 1 if it ends in the START state and 0 if it ends
  137800. ** in any other state.
  137801. **
  137802. ** (2) NORMAL We are in the middle of statement which ends with a single
  137803. ** semicolon.
  137804. **
  137805. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  137806. ** a statement.
  137807. **
  137808. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  137809. ** statement, possibly preceded by EXPLAIN and/or followed by
  137810. ** TEMP or TEMPORARY
  137811. **
  137812. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  137813. ** ended by a semicolon, the keyword END, and another semicolon.
  137814. **
  137815. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  137816. ** the end of a trigger definition.
  137817. **
  137818. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  137819. ** of a trigger definition.
  137820. **
  137821. ** Transitions between states above are determined by tokens extracted
  137822. ** from the input. The following tokens are significant:
  137823. **
  137824. ** (0) tkSEMI A semicolon.
  137825. ** (1) tkWS Whitespace.
  137826. ** (2) tkOTHER Any other SQL token.
  137827. ** (3) tkEXPLAIN The "explain" keyword.
  137828. ** (4) tkCREATE The "create" keyword.
  137829. ** (5) tkTEMP The "temp" or "temporary" keyword.
  137830. ** (6) tkTRIGGER The "trigger" keyword.
  137831. ** (7) tkEND The "end" keyword.
  137832. **
  137833. ** Whitespace never causes a state transition and is always ignored.
  137834. ** This means that a SQL string of all whitespace is invalid.
  137835. **
  137836. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  137837. ** to recognize the end of a trigger can be omitted. All we have to do
  137838. ** is look for a semicolon that is not part of an string or comment.
  137839. */
  137840. SQLITE_API int sqlite3_complete(const char *zSql){
  137841. u8 state = 0; /* Current state, using numbers defined in header comment */
  137842. u8 token; /* Value of the next token */
  137843. #ifndef SQLITE_OMIT_TRIGGER
  137844. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  137845. ** statement. This is the normal case.
  137846. */
  137847. static const u8 trans[8][8] = {
  137848. /* Token: */
  137849. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  137850. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  137851. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  137852. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  137853. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  137854. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  137855. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  137856. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  137857. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  137858. };
  137859. #else
  137860. /* If triggers are not supported by this compile then the statement machine
  137861. ** used to detect the end of a statement is much simpler
  137862. */
  137863. static const u8 trans[3][3] = {
  137864. /* Token: */
  137865. /* State: ** SEMI WS OTHER */
  137866. /* 0 INVALID: */ { 1, 0, 2, },
  137867. /* 1 START: */ { 1, 1, 2, },
  137868. /* 2 NORMAL: */ { 1, 2, 2, },
  137869. };
  137870. #endif /* SQLITE_OMIT_TRIGGER */
  137871. #ifdef SQLITE_ENABLE_API_ARMOR
  137872. if( zSql==0 ){
  137873. (void)SQLITE_MISUSE_BKPT;
  137874. return 0;
  137875. }
  137876. #endif
  137877. while( *zSql ){
  137878. switch( *zSql ){
  137879. case ';': { /* A semicolon */
  137880. token = tkSEMI;
  137881. break;
  137882. }
  137883. case ' ':
  137884. case '\r':
  137885. case '\t':
  137886. case '\n':
  137887. case '\f': { /* White space is ignored */
  137888. token = tkWS;
  137889. break;
  137890. }
  137891. case '/': { /* C-style comments */
  137892. if( zSql[1]!='*' ){
  137893. token = tkOTHER;
  137894. break;
  137895. }
  137896. zSql += 2;
  137897. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  137898. if( zSql[0]==0 ) return 0;
  137899. zSql++;
  137900. token = tkWS;
  137901. break;
  137902. }
  137903. case '-': { /* SQL-style comments from "--" to end of line */
  137904. if( zSql[1]!='-' ){
  137905. token = tkOTHER;
  137906. break;
  137907. }
  137908. while( *zSql && *zSql!='\n' ){ zSql++; }
  137909. if( *zSql==0 ) return state==1;
  137910. token = tkWS;
  137911. break;
  137912. }
  137913. case '[': { /* Microsoft-style identifiers in [...] */
  137914. zSql++;
  137915. while( *zSql && *zSql!=']' ){ zSql++; }
  137916. if( *zSql==0 ) return 0;
  137917. token = tkOTHER;
  137918. break;
  137919. }
  137920. case '`': /* Grave-accent quoted symbols used by MySQL */
  137921. case '"': /* single- and double-quoted strings */
  137922. case '\'': {
  137923. int c = *zSql;
  137924. zSql++;
  137925. while( *zSql && *zSql!=c ){ zSql++; }
  137926. if( *zSql==0 ) return 0;
  137927. token = tkOTHER;
  137928. break;
  137929. }
  137930. default: {
  137931. #ifdef SQLITE_EBCDIC
  137932. unsigned char c;
  137933. #endif
  137934. if( IdChar((u8)*zSql) ){
  137935. /* Keywords and unquoted identifiers */
  137936. int nId;
  137937. for(nId=1; IdChar(zSql[nId]); nId++){}
  137938. #ifdef SQLITE_OMIT_TRIGGER
  137939. token = tkOTHER;
  137940. #else
  137941. switch( *zSql ){
  137942. case 'c': case 'C': {
  137943. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  137944. token = tkCREATE;
  137945. }else{
  137946. token = tkOTHER;
  137947. }
  137948. break;
  137949. }
  137950. case 't': case 'T': {
  137951. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  137952. token = tkTRIGGER;
  137953. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  137954. token = tkTEMP;
  137955. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  137956. token = tkTEMP;
  137957. }else{
  137958. token = tkOTHER;
  137959. }
  137960. break;
  137961. }
  137962. case 'e': case 'E': {
  137963. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  137964. token = tkEND;
  137965. }else
  137966. #ifndef SQLITE_OMIT_EXPLAIN
  137967. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  137968. token = tkEXPLAIN;
  137969. }else
  137970. #endif
  137971. {
  137972. token = tkOTHER;
  137973. }
  137974. break;
  137975. }
  137976. default: {
  137977. token = tkOTHER;
  137978. break;
  137979. }
  137980. }
  137981. #endif /* SQLITE_OMIT_TRIGGER */
  137982. zSql += nId-1;
  137983. }else{
  137984. /* Operators and special symbols */
  137985. token = tkOTHER;
  137986. }
  137987. break;
  137988. }
  137989. }
  137990. state = trans[state][token];
  137991. zSql++;
  137992. }
  137993. return state==1;
  137994. }
  137995. #ifndef SQLITE_OMIT_UTF16
  137996. /*
  137997. ** This routine is the same as the sqlite3_complete() routine described
  137998. ** above, except that the parameter is required to be UTF-16 encoded, not
  137999. ** UTF-8.
  138000. */
  138001. SQLITE_API int sqlite3_complete16(const void *zSql){
  138002. sqlite3_value *pVal;
  138003. char const *zSql8;
  138004. int rc;
  138005. #ifndef SQLITE_OMIT_AUTOINIT
  138006. rc = sqlite3_initialize();
  138007. if( rc ) return rc;
  138008. #endif
  138009. pVal = sqlite3ValueNew(0);
  138010. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  138011. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  138012. if( zSql8 ){
  138013. rc = sqlite3_complete(zSql8);
  138014. }else{
  138015. rc = SQLITE_NOMEM_BKPT;
  138016. }
  138017. sqlite3ValueFree(pVal);
  138018. return rc & 0xff;
  138019. }
  138020. #endif /* SQLITE_OMIT_UTF16 */
  138021. #endif /* SQLITE_OMIT_COMPLETE */
  138022. /************** End of complete.c ********************************************/
  138023. /************** Begin file main.c ********************************************/
  138024. /*
  138025. ** 2001 September 15
  138026. **
  138027. ** The author disclaims copyright to this source code. In place of
  138028. ** a legal notice, here is a blessing:
  138029. **
  138030. ** May you do good and not evil.
  138031. ** May you find forgiveness for yourself and forgive others.
  138032. ** May you share freely, never taking more than you give.
  138033. **
  138034. *************************************************************************
  138035. ** Main file for the SQLite library. The routines in this file
  138036. ** implement the programmer interface to the library. Routines in
  138037. ** other files are for internal use by SQLite and should not be
  138038. ** accessed by users of the library.
  138039. */
  138040. /* #include "sqliteInt.h" */
  138041. #ifdef SQLITE_ENABLE_FTS3
  138042. /************** Include fts3.h in the middle of main.c ***********************/
  138043. /************** Begin file fts3.h ********************************************/
  138044. /*
  138045. ** 2006 Oct 10
  138046. **
  138047. ** The author disclaims copyright to this source code. In place of
  138048. ** a legal notice, here is a blessing:
  138049. **
  138050. ** May you do good and not evil.
  138051. ** May you find forgiveness for yourself and forgive others.
  138052. ** May you share freely, never taking more than you give.
  138053. **
  138054. ******************************************************************************
  138055. **
  138056. ** This header file is used by programs that want to link against the
  138057. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  138058. */
  138059. /* #include "sqlite3.h" */
  138060. #if 0
  138061. extern "C" {
  138062. #endif /* __cplusplus */
  138063. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  138064. #if 0
  138065. } /* extern "C" */
  138066. #endif /* __cplusplus */
  138067. /************** End of fts3.h ************************************************/
  138068. /************** Continuing where we left off in main.c ***********************/
  138069. #endif
  138070. #ifdef SQLITE_ENABLE_RTREE
  138071. /************** Include rtree.h in the middle of main.c **********************/
  138072. /************** Begin file rtree.h *******************************************/
  138073. /*
  138074. ** 2008 May 26
  138075. **
  138076. ** The author disclaims copyright to this source code. In place of
  138077. ** a legal notice, here is a blessing:
  138078. **
  138079. ** May you do good and not evil.
  138080. ** May you find forgiveness for yourself and forgive others.
  138081. ** May you share freely, never taking more than you give.
  138082. **
  138083. ******************************************************************************
  138084. **
  138085. ** This header file is used by programs that want to link against the
  138086. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  138087. */
  138088. /* #include "sqlite3.h" */
  138089. #ifdef SQLITE_OMIT_VIRTUALTABLE
  138090. # undef SQLITE_ENABLE_RTREE
  138091. #endif
  138092. #if 0
  138093. extern "C" {
  138094. #endif /* __cplusplus */
  138095. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  138096. #if 0
  138097. } /* extern "C" */
  138098. #endif /* __cplusplus */
  138099. /************** End of rtree.h ***********************************************/
  138100. /************** Continuing where we left off in main.c ***********************/
  138101. #endif
  138102. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  138103. /************** Include sqliteicu.h in the middle of main.c ******************/
  138104. /************** Begin file sqliteicu.h ***************************************/
  138105. /*
  138106. ** 2008 May 26
  138107. **
  138108. ** The author disclaims copyright to this source code. In place of
  138109. ** a legal notice, here is a blessing:
  138110. **
  138111. ** May you do good and not evil.
  138112. ** May you find forgiveness for yourself and forgive others.
  138113. ** May you share freely, never taking more than you give.
  138114. **
  138115. ******************************************************************************
  138116. **
  138117. ** This header file is used by programs that want to link against the
  138118. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  138119. */
  138120. /* #include "sqlite3.h" */
  138121. #if 0
  138122. extern "C" {
  138123. #endif /* __cplusplus */
  138124. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  138125. #if 0
  138126. } /* extern "C" */
  138127. #endif /* __cplusplus */
  138128. /************** End of sqliteicu.h *******************************************/
  138129. /************** Continuing where we left off in main.c ***********************/
  138130. #endif
  138131. #ifdef SQLITE_ENABLE_JSON1
  138132. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  138133. #endif
  138134. #ifdef SQLITE_ENABLE_STMTVTAB
  138135. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
  138136. #endif
  138137. #ifdef SQLITE_ENABLE_FTS5
  138138. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  138139. #endif
  138140. #ifndef SQLITE_AMALGAMATION
  138141. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  138142. ** contains the text of SQLITE_VERSION macro.
  138143. */
  138144. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  138145. #endif
  138146. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  138147. ** a pointer to the to the sqlite3_version[] string constant.
  138148. */
  138149. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  138150. /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
  138151. ** pointer to a string constant whose value is the same as the
  138152. ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
  138153. ** an edited copy of the amalgamation, then the last four characters of
  138154. ** the hash might be different from SQLITE_SOURCE_ID.
  138155. */
  138156. /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
  138157. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  138158. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  138159. */
  138160. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  138161. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  138162. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  138163. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  138164. */
  138165. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  138166. /*
  138167. ** When compiling the test fixture or with debugging enabled (on Win32),
  138168. ** this variable being set to non-zero will cause OSTRACE macros to emit
  138169. ** extra diagnostic information.
  138170. */
  138171. #ifdef SQLITE_HAVE_OS_TRACE
  138172. # ifndef SQLITE_DEBUG_OS_TRACE
  138173. # define SQLITE_DEBUG_OS_TRACE 0
  138174. # endif
  138175. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  138176. #endif
  138177. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  138178. /*
  138179. ** If the following function pointer is not NULL and if
  138180. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  138181. ** I/O active are written using this function. These messages
  138182. ** are intended for debugging activity only.
  138183. */
  138184. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  138185. #endif
  138186. /*
  138187. ** If the following global variable points to a string which is the
  138188. ** name of a directory, then that directory will be used to store
  138189. ** temporary files.
  138190. **
  138191. ** See also the "PRAGMA temp_store_directory" SQL command.
  138192. */
  138193. SQLITE_API char *sqlite3_temp_directory = 0;
  138194. /*
  138195. ** If the following global variable points to a string which is the
  138196. ** name of a directory, then that directory will be used to store
  138197. ** all database files specified with a relative pathname.
  138198. **
  138199. ** See also the "PRAGMA data_store_directory" SQL command.
  138200. */
  138201. SQLITE_API char *sqlite3_data_directory = 0;
  138202. /*
  138203. ** Initialize SQLite.
  138204. **
  138205. ** This routine must be called to initialize the memory allocation,
  138206. ** VFS, and mutex subsystems prior to doing any serious work with
  138207. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  138208. ** this routine will be called automatically by key routines such as
  138209. ** sqlite3_open().
  138210. **
  138211. ** This routine is a no-op except on its very first call for the process,
  138212. ** or for the first call after a call to sqlite3_shutdown.
  138213. **
  138214. ** The first thread to call this routine runs the initialization to
  138215. ** completion. If subsequent threads call this routine before the first
  138216. ** thread has finished the initialization process, then the subsequent
  138217. ** threads must block until the first thread finishes with the initialization.
  138218. **
  138219. ** The first thread might call this routine recursively. Recursive
  138220. ** calls to this routine should not block, of course. Otherwise the
  138221. ** initialization process would never complete.
  138222. **
  138223. ** Let X be the first thread to enter this routine. Let Y be some other
  138224. ** thread. Then while the initial invocation of this routine by X is
  138225. ** incomplete, it is required that:
  138226. **
  138227. ** * Calls to this routine from Y must block until the outer-most
  138228. ** call by X completes.
  138229. **
  138230. ** * Recursive calls to this routine from thread X return immediately
  138231. ** without blocking.
  138232. */
  138233. SQLITE_API int sqlite3_initialize(void){
  138234. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  138235. int rc; /* Result code */
  138236. #ifdef SQLITE_EXTRA_INIT
  138237. int bRunExtraInit = 0; /* Extra initialization needed */
  138238. #endif
  138239. #ifdef SQLITE_OMIT_WSD
  138240. rc = sqlite3_wsd_init(4096, 24);
  138241. if( rc!=SQLITE_OK ){
  138242. return rc;
  138243. }
  138244. #endif
  138245. /* If the following assert() fails on some obscure processor/compiler
  138246. ** combination, the work-around is to set the correct pointer
  138247. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  138248. assert( SQLITE_PTRSIZE==sizeof(char*) );
  138249. /* If SQLite is already completely initialized, then this call
  138250. ** to sqlite3_initialize() should be a no-op. But the initialization
  138251. ** must be complete. So isInit must not be set until the very end
  138252. ** of this routine.
  138253. */
  138254. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  138255. /* Make sure the mutex subsystem is initialized. If unable to
  138256. ** initialize the mutex subsystem, return early with the error.
  138257. ** If the system is so sick that we are unable to allocate a mutex,
  138258. ** there is not much SQLite is going to be able to do.
  138259. **
  138260. ** The mutex subsystem must take care of serializing its own
  138261. ** initialization.
  138262. */
  138263. rc = sqlite3MutexInit();
  138264. if( rc ) return rc;
  138265. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  138266. ** This operation is protected by the STATIC_MASTER mutex. Note that
  138267. ** MutexAlloc() is called for a static mutex prior to initializing the
  138268. ** malloc subsystem - this implies that the allocation of a static
  138269. ** mutex must not require support from the malloc subsystem.
  138270. */
  138271. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  138272. sqlite3_mutex_enter(pMaster);
  138273. sqlite3GlobalConfig.isMutexInit = 1;
  138274. if( !sqlite3GlobalConfig.isMallocInit ){
  138275. rc = sqlite3MallocInit();
  138276. }
  138277. if( rc==SQLITE_OK ){
  138278. sqlite3GlobalConfig.isMallocInit = 1;
  138279. if( !sqlite3GlobalConfig.pInitMutex ){
  138280. sqlite3GlobalConfig.pInitMutex =
  138281. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  138282. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  138283. rc = SQLITE_NOMEM_BKPT;
  138284. }
  138285. }
  138286. }
  138287. if( rc==SQLITE_OK ){
  138288. sqlite3GlobalConfig.nRefInitMutex++;
  138289. }
  138290. sqlite3_mutex_leave(pMaster);
  138291. /* If rc is not SQLITE_OK at this point, then either the malloc
  138292. ** subsystem could not be initialized or the system failed to allocate
  138293. ** the pInitMutex mutex. Return an error in either case. */
  138294. if( rc!=SQLITE_OK ){
  138295. return rc;
  138296. }
  138297. /* Do the rest of the initialization under the recursive mutex so
  138298. ** that we will be able to handle recursive calls into
  138299. ** sqlite3_initialize(). The recursive calls normally come through
  138300. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  138301. ** recursive calls might also be possible.
  138302. **
  138303. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  138304. ** to the xInit method, so the xInit method need not be threadsafe.
  138305. **
  138306. ** The following mutex is what serializes access to the appdef pcache xInit
  138307. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  138308. ** call to sqlite3PcacheInitialize().
  138309. */
  138310. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  138311. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  138312. sqlite3GlobalConfig.inProgress = 1;
  138313. #ifdef SQLITE_ENABLE_SQLLOG
  138314. {
  138315. extern void sqlite3_init_sqllog(void);
  138316. sqlite3_init_sqllog();
  138317. }
  138318. #endif
  138319. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  138320. sqlite3RegisterBuiltinFunctions();
  138321. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  138322. rc = sqlite3PcacheInitialize();
  138323. }
  138324. if( rc==SQLITE_OK ){
  138325. sqlite3GlobalConfig.isPCacheInit = 1;
  138326. rc = sqlite3OsInit();
  138327. }
  138328. #ifdef SQLITE_ENABLE_DESERIALIZE
  138329. if( rc==SQLITE_OK ){
  138330. rc = sqlite3MemdbInit();
  138331. }
  138332. #endif
  138333. if( rc==SQLITE_OK ){
  138334. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  138335. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  138336. sqlite3GlobalConfig.isInit = 1;
  138337. #ifdef SQLITE_EXTRA_INIT
  138338. bRunExtraInit = 1;
  138339. #endif
  138340. }
  138341. sqlite3GlobalConfig.inProgress = 0;
  138342. }
  138343. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  138344. /* Go back under the static mutex and clean up the recursive
  138345. ** mutex to prevent a resource leak.
  138346. */
  138347. sqlite3_mutex_enter(pMaster);
  138348. sqlite3GlobalConfig.nRefInitMutex--;
  138349. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  138350. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  138351. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  138352. sqlite3GlobalConfig.pInitMutex = 0;
  138353. }
  138354. sqlite3_mutex_leave(pMaster);
  138355. /* The following is just a sanity check to make sure SQLite has
  138356. ** been compiled correctly. It is important to run this code, but
  138357. ** we don't want to run it too often and soak up CPU cycles for no
  138358. ** reason. So we run it once during initialization.
  138359. */
  138360. #ifndef NDEBUG
  138361. #ifndef SQLITE_OMIT_FLOATING_POINT
  138362. /* This section of code's only "output" is via assert() statements. */
  138363. if( rc==SQLITE_OK ){
  138364. u64 x = (((u64)1)<<63)-1;
  138365. double y;
  138366. assert(sizeof(x)==8);
  138367. assert(sizeof(x)==sizeof(y));
  138368. memcpy(&y, &x, 8);
  138369. assert( sqlite3IsNaN(y) );
  138370. }
  138371. #endif
  138372. #endif
  138373. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  138374. ** compile-time option.
  138375. */
  138376. #ifdef SQLITE_EXTRA_INIT
  138377. if( bRunExtraInit ){
  138378. int SQLITE_EXTRA_INIT(const char*);
  138379. rc = SQLITE_EXTRA_INIT(0);
  138380. }
  138381. #endif
  138382. return rc;
  138383. }
  138384. /*
  138385. ** Undo the effects of sqlite3_initialize(). Must not be called while
  138386. ** there are outstanding database connections or memory allocations or
  138387. ** while any part of SQLite is otherwise in use in any thread. This
  138388. ** routine is not threadsafe. But it is safe to invoke this routine
  138389. ** on when SQLite is already shut down. If SQLite is already shut down
  138390. ** when this routine is invoked, then this routine is a harmless no-op.
  138391. */
  138392. SQLITE_API int sqlite3_shutdown(void){
  138393. #ifdef SQLITE_OMIT_WSD
  138394. int rc = sqlite3_wsd_init(4096, 24);
  138395. if( rc!=SQLITE_OK ){
  138396. return rc;
  138397. }
  138398. #endif
  138399. if( sqlite3GlobalConfig.isInit ){
  138400. #ifdef SQLITE_EXTRA_SHUTDOWN
  138401. void SQLITE_EXTRA_SHUTDOWN(void);
  138402. SQLITE_EXTRA_SHUTDOWN();
  138403. #endif
  138404. sqlite3_os_end();
  138405. sqlite3_reset_auto_extension();
  138406. sqlite3GlobalConfig.isInit = 0;
  138407. }
  138408. if( sqlite3GlobalConfig.isPCacheInit ){
  138409. sqlite3PcacheShutdown();
  138410. sqlite3GlobalConfig.isPCacheInit = 0;
  138411. }
  138412. if( sqlite3GlobalConfig.isMallocInit ){
  138413. sqlite3MallocEnd();
  138414. sqlite3GlobalConfig.isMallocInit = 0;
  138415. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  138416. /* The heap subsystem has now been shutdown and these values are supposed
  138417. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  138418. ** which would rely on that heap subsystem; therefore, make sure these
  138419. ** values cannot refer to heap memory that was just invalidated when the
  138420. ** heap subsystem was shutdown. This is only done if the current call to
  138421. ** this function resulted in the heap subsystem actually being shutdown.
  138422. */
  138423. sqlite3_data_directory = 0;
  138424. sqlite3_temp_directory = 0;
  138425. #endif
  138426. }
  138427. if( sqlite3GlobalConfig.isMutexInit ){
  138428. sqlite3MutexEnd();
  138429. sqlite3GlobalConfig.isMutexInit = 0;
  138430. }
  138431. return SQLITE_OK;
  138432. }
  138433. /*
  138434. ** This API allows applications to modify the global configuration of
  138435. ** the SQLite library at run-time.
  138436. **
  138437. ** This routine should only be called when there are no outstanding
  138438. ** database connections or memory allocations. This routine is not
  138439. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  138440. ** behavior.
  138441. */
  138442. SQLITE_API int sqlite3_config(int op, ...){
  138443. va_list ap;
  138444. int rc = SQLITE_OK;
  138445. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  138446. ** the SQLite library is in use. */
  138447. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  138448. va_start(ap, op);
  138449. switch( op ){
  138450. /* Mutex configuration options are only available in a threadsafe
  138451. ** compile.
  138452. */
  138453. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  138454. case SQLITE_CONFIG_SINGLETHREAD: {
  138455. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  138456. ** Single-thread. */
  138457. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  138458. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  138459. break;
  138460. }
  138461. #endif
  138462. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  138463. case SQLITE_CONFIG_MULTITHREAD: {
  138464. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  138465. ** Multi-thread. */
  138466. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  138467. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  138468. break;
  138469. }
  138470. #endif
  138471. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  138472. case SQLITE_CONFIG_SERIALIZED: {
  138473. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  138474. ** Serialized. */
  138475. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  138476. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  138477. break;
  138478. }
  138479. #endif
  138480. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  138481. case SQLITE_CONFIG_MUTEX: {
  138482. /* Specify an alternative mutex implementation */
  138483. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  138484. break;
  138485. }
  138486. #endif
  138487. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  138488. case SQLITE_CONFIG_GETMUTEX: {
  138489. /* Retrieve the current mutex implementation */
  138490. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  138491. break;
  138492. }
  138493. #endif
  138494. case SQLITE_CONFIG_MALLOC: {
  138495. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  138496. ** single argument which is a pointer to an instance of the
  138497. ** sqlite3_mem_methods structure. The argument specifies alternative
  138498. ** low-level memory allocation routines to be used in place of the memory
  138499. ** allocation routines built into SQLite. */
  138500. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  138501. break;
  138502. }
  138503. case SQLITE_CONFIG_GETMALLOC: {
  138504. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  138505. ** single argument which is a pointer to an instance of the
  138506. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  138507. ** filled with the currently defined memory allocation routines. */
  138508. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  138509. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  138510. break;
  138511. }
  138512. case SQLITE_CONFIG_MEMSTATUS: {
  138513. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  138514. ** single argument of type int, interpreted as a boolean, which enables
  138515. ** or disables the collection of memory allocation statistics. */
  138516. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  138517. break;
  138518. }
  138519. case SQLITE_CONFIG_SMALL_MALLOC: {
  138520. sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
  138521. break;
  138522. }
  138523. case SQLITE_CONFIG_PAGECACHE: {
  138524. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  138525. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  138526. ** the size of each page cache line (sz), and the number of cache lines
  138527. ** (N). */
  138528. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  138529. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  138530. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  138531. break;
  138532. }
  138533. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  138534. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  138535. ** a single parameter which is a pointer to an integer and writes into
  138536. ** that integer the number of extra bytes per page required for each page
  138537. ** in SQLITE_CONFIG_PAGECACHE. */
  138538. *va_arg(ap, int*) =
  138539. sqlite3HeaderSizeBtree() +
  138540. sqlite3HeaderSizePcache() +
  138541. sqlite3HeaderSizePcache1();
  138542. break;
  138543. }
  138544. case SQLITE_CONFIG_PCACHE: {
  138545. /* no-op */
  138546. break;
  138547. }
  138548. case SQLITE_CONFIG_GETPCACHE: {
  138549. /* now an error */
  138550. rc = SQLITE_ERROR;
  138551. break;
  138552. }
  138553. case SQLITE_CONFIG_PCACHE2: {
  138554. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  138555. ** single argument which is a pointer to an sqlite3_pcache_methods2
  138556. ** object. This object specifies the interface to a custom page cache
  138557. ** implementation. */
  138558. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  138559. break;
  138560. }
  138561. case SQLITE_CONFIG_GETPCACHE2: {
  138562. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  138563. ** single argument which is a pointer to an sqlite3_pcache_methods2
  138564. ** object. SQLite copies of the current page cache implementation into
  138565. ** that object. */
  138566. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  138567. sqlite3PCacheSetDefault();
  138568. }
  138569. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  138570. break;
  138571. }
  138572. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  138573. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  138574. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  138575. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  138576. case SQLITE_CONFIG_HEAP: {
  138577. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  138578. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  138579. ** number of bytes in the memory buffer, and the minimum allocation size.
  138580. */
  138581. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  138582. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  138583. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  138584. if( sqlite3GlobalConfig.mnReq<1 ){
  138585. sqlite3GlobalConfig.mnReq = 1;
  138586. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  138587. /* cap min request size at 2^12 */
  138588. sqlite3GlobalConfig.mnReq = (1<<12);
  138589. }
  138590. if( sqlite3GlobalConfig.pHeap==0 ){
  138591. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  138592. ** is NULL, then SQLite reverts to using its default memory allocator
  138593. ** (the system malloc() implementation), undoing any prior invocation of
  138594. ** SQLITE_CONFIG_MALLOC.
  138595. **
  138596. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  138597. ** revert to its default implementation when sqlite3_initialize() is run
  138598. */
  138599. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  138600. }else{
  138601. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  138602. ** alternative memory allocator is engaged to handle all of SQLites
  138603. ** memory allocation needs. */
  138604. #ifdef SQLITE_ENABLE_MEMSYS3
  138605. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  138606. #endif
  138607. #ifdef SQLITE_ENABLE_MEMSYS5
  138608. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  138609. #endif
  138610. }
  138611. break;
  138612. }
  138613. #endif
  138614. case SQLITE_CONFIG_LOOKASIDE: {
  138615. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  138616. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  138617. break;
  138618. }
  138619. /* Record a pointer to the logger function and its first argument.
  138620. ** The default is NULL. Logging is disabled if the function pointer is
  138621. ** NULL.
  138622. */
  138623. case SQLITE_CONFIG_LOG: {
  138624. /* MSVC is picky about pulling func ptrs from va lists.
  138625. ** http://support.microsoft.com/kb/47961
  138626. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  138627. */
  138628. typedef void(*LOGFUNC_t)(void*,int,const char*);
  138629. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  138630. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  138631. break;
  138632. }
  138633. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  138634. ** can be changed at start-time using the
  138635. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  138636. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  138637. */
  138638. case SQLITE_CONFIG_URI: {
  138639. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  138640. ** argument of type int. If non-zero, then URI handling is globally
  138641. ** enabled. If the parameter is zero, then URI handling is globally
  138642. ** disabled. */
  138643. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  138644. break;
  138645. }
  138646. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  138647. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  138648. ** option takes a single integer argument which is interpreted as a
  138649. ** boolean in order to enable or disable the use of covering indices for
  138650. ** full table scans in the query optimizer. */
  138651. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  138652. break;
  138653. }
  138654. #ifdef SQLITE_ENABLE_SQLLOG
  138655. case SQLITE_CONFIG_SQLLOG: {
  138656. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  138657. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  138658. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  138659. break;
  138660. }
  138661. #endif
  138662. case SQLITE_CONFIG_MMAP_SIZE: {
  138663. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  138664. ** integer (sqlite3_int64) values that are the default mmap size limit
  138665. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  138666. ** mmap size limit. */
  138667. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  138668. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  138669. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  138670. ** negative, then that argument is changed to its compile-time default.
  138671. **
  138672. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  138673. ** silently truncated if necessary so that it does not exceed the
  138674. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  138675. ** compile-time option.
  138676. */
  138677. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  138678. mxMmap = SQLITE_MAX_MMAP_SIZE;
  138679. }
  138680. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  138681. if( szMmap>mxMmap) szMmap = mxMmap;
  138682. sqlite3GlobalConfig.mxMmap = mxMmap;
  138683. sqlite3GlobalConfig.szMmap = szMmap;
  138684. break;
  138685. }
  138686. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  138687. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  138688. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  138689. ** unsigned integer value that specifies the maximum size of the created
  138690. ** heap. */
  138691. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  138692. break;
  138693. }
  138694. #endif
  138695. case SQLITE_CONFIG_PMASZ: {
  138696. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  138697. break;
  138698. }
  138699. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  138700. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  138701. break;
  138702. }
  138703. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  138704. case SQLITE_CONFIG_SORTERREF_SIZE: {
  138705. int iVal = va_arg(ap, int);
  138706. if( iVal<0 ){
  138707. iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
  138708. }
  138709. sqlite3GlobalConfig.szSorterRef = (u32)iVal;
  138710. break;
  138711. }
  138712. #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
  138713. default: {
  138714. rc = SQLITE_ERROR;
  138715. break;
  138716. }
  138717. }
  138718. va_end(ap);
  138719. return rc;
  138720. }
  138721. /*
  138722. ** Set up the lookaside buffers for a database connection.
  138723. ** Return SQLITE_OK on success.
  138724. ** If lookaside is already active, return SQLITE_BUSY.
  138725. **
  138726. ** The sz parameter is the number of bytes in each lookaside slot.
  138727. ** The cnt parameter is the number of slots. If pStart is NULL the
  138728. ** space for the lookaside memory is obtained from sqlite3_malloc().
  138729. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  138730. ** the lookaside memory.
  138731. */
  138732. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  138733. #ifndef SQLITE_OMIT_LOOKASIDE
  138734. void *pStart;
  138735. if( sqlite3LookasideUsed(db,0)>0 ){
  138736. return SQLITE_BUSY;
  138737. }
  138738. /* Free any existing lookaside buffer for this handle before
  138739. ** allocating a new one so we don't have to have space for
  138740. ** both at the same time.
  138741. */
  138742. if( db->lookaside.bMalloced ){
  138743. sqlite3_free(db->lookaside.pStart);
  138744. }
  138745. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  138746. ** than a pointer to be useful.
  138747. */
  138748. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  138749. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  138750. if( cnt<0 ) cnt = 0;
  138751. if( sz==0 || cnt==0 ){
  138752. sz = 0;
  138753. pStart = 0;
  138754. }else if( pBuf==0 ){
  138755. sqlite3BeginBenignMalloc();
  138756. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  138757. sqlite3EndBenignMalloc();
  138758. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  138759. }else{
  138760. pStart = pBuf;
  138761. }
  138762. db->lookaside.pStart = pStart;
  138763. db->lookaside.pInit = 0;
  138764. db->lookaside.pFree = 0;
  138765. db->lookaside.sz = (u16)sz;
  138766. if( pStart ){
  138767. int i;
  138768. LookasideSlot *p;
  138769. assert( sz > (int)sizeof(LookasideSlot*) );
  138770. db->lookaside.nSlot = cnt;
  138771. p = (LookasideSlot*)pStart;
  138772. for(i=cnt-1; i>=0; i--){
  138773. p->pNext = db->lookaside.pInit;
  138774. db->lookaside.pInit = p;
  138775. p = (LookasideSlot*)&((u8*)p)[sz];
  138776. }
  138777. db->lookaside.pEnd = p;
  138778. db->lookaside.bDisable = 0;
  138779. db->lookaside.bMalloced = pBuf==0 ?1:0;
  138780. }else{
  138781. db->lookaside.pStart = db;
  138782. db->lookaside.pEnd = db;
  138783. db->lookaside.bDisable = 1;
  138784. db->lookaside.bMalloced = 0;
  138785. db->lookaside.nSlot = 0;
  138786. }
  138787. #endif /* SQLITE_OMIT_LOOKASIDE */
  138788. return SQLITE_OK;
  138789. }
  138790. /*
  138791. ** Return the mutex associated with a database connection.
  138792. */
  138793. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  138794. #ifdef SQLITE_ENABLE_API_ARMOR
  138795. if( !sqlite3SafetyCheckOk(db) ){
  138796. (void)SQLITE_MISUSE_BKPT;
  138797. return 0;
  138798. }
  138799. #endif
  138800. return db->mutex;
  138801. }
  138802. /*
  138803. ** Free up as much memory as we can from the given database
  138804. ** connection.
  138805. */
  138806. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  138807. int i;
  138808. #ifdef SQLITE_ENABLE_API_ARMOR
  138809. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  138810. #endif
  138811. sqlite3_mutex_enter(db->mutex);
  138812. sqlite3BtreeEnterAll(db);
  138813. for(i=0; i<db->nDb; i++){
  138814. Btree *pBt = db->aDb[i].pBt;
  138815. if( pBt ){
  138816. Pager *pPager = sqlite3BtreePager(pBt);
  138817. sqlite3PagerShrink(pPager);
  138818. }
  138819. }
  138820. sqlite3BtreeLeaveAll(db);
  138821. sqlite3_mutex_leave(db->mutex);
  138822. return SQLITE_OK;
  138823. }
  138824. /*
  138825. ** Flush any dirty pages in the pager-cache for any attached database
  138826. ** to disk.
  138827. */
  138828. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  138829. int i;
  138830. int rc = SQLITE_OK;
  138831. int bSeenBusy = 0;
  138832. #ifdef SQLITE_ENABLE_API_ARMOR
  138833. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  138834. #endif
  138835. sqlite3_mutex_enter(db->mutex);
  138836. sqlite3BtreeEnterAll(db);
  138837. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  138838. Btree *pBt = db->aDb[i].pBt;
  138839. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  138840. Pager *pPager = sqlite3BtreePager(pBt);
  138841. rc = sqlite3PagerFlush(pPager);
  138842. if( rc==SQLITE_BUSY ){
  138843. bSeenBusy = 1;
  138844. rc = SQLITE_OK;
  138845. }
  138846. }
  138847. }
  138848. sqlite3BtreeLeaveAll(db);
  138849. sqlite3_mutex_leave(db->mutex);
  138850. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  138851. }
  138852. /*
  138853. ** Configuration settings for an individual database connection
  138854. */
  138855. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  138856. va_list ap;
  138857. int rc;
  138858. va_start(ap, op);
  138859. switch( op ){
  138860. case SQLITE_DBCONFIG_MAINDBNAME: {
  138861. /* IMP: R-06824-28531 */
  138862. /* IMP: R-36257-52125 */
  138863. db->aDb[0].zDbSName = va_arg(ap,char*);
  138864. rc = SQLITE_OK;
  138865. break;
  138866. }
  138867. case SQLITE_DBCONFIG_LOOKASIDE: {
  138868. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  138869. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  138870. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  138871. rc = setupLookaside(db, pBuf, sz, cnt);
  138872. break;
  138873. }
  138874. default: {
  138875. static const struct {
  138876. int op; /* The opcode */
  138877. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  138878. } aFlagOp[] = {
  138879. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  138880. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  138881. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  138882. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  138883. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  138884. { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
  138885. { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
  138886. { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
  138887. };
  138888. unsigned int i;
  138889. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  138890. for(i=0; i<ArraySize(aFlagOp); i++){
  138891. if( aFlagOp[i].op==op ){
  138892. int onoff = va_arg(ap, int);
  138893. int *pRes = va_arg(ap, int*);
  138894. u32 oldFlags = db->flags;
  138895. if( onoff>0 ){
  138896. db->flags |= aFlagOp[i].mask;
  138897. }else if( onoff==0 ){
  138898. db->flags &= ~aFlagOp[i].mask;
  138899. }
  138900. if( oldFlags!=db->flags ){
  138901. sqlite3ExpirePreparedStatements(db);
  138902. }
  138903. if( pRes ){
  138904. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  138905. }
  138906. rc = SQLITE_OK;
  138907. break;
  138908. }
  138909. }
  138910. break;
  138911. }
  138912. }
  138913. va_end(ap);
  138914. return rc;
  138915. }
  138916. /*
  138917. ** Return true if the buffer z[0..n-1] contains all spaces.
  138918. */
  138919. static int allSpaces(const char *z, int n){
  138920. while( n>0 && z[n-1]==' ' ){ n--; }
  138921. return n==0;
  138922. }
  138923. /*
  138924. ** This is the default collating function named "BINARY" which is always
  138925. ** available.
  138926. **
  138927. ** If the padFlag argument is not NULL then space padding at the end
  138928. ** of strings is ignored. This implements the RTRIM collation.
  138929. */
  138930. static int binCollFunc(
  138931. void *padFlag,
  138932. int nKey1, const void *pKey1,
  138933. int nKey2, const void *pKey2
  138934. ){
  138935. int rc, n;
  138936. n = nKey1<nKey2 ? nKey1 : nKey2;
  138937. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  138938. ** strings byte by byte using the memcmp() function from the standard C
  138939. ** library. */
  138940. assert( pKey1 && pKey2 );
  138941. rc = memcmp(pKey1, pKey2, n);
  138942. if( rc==0 ){
  138943. if( padFlag
  138944. && allSpaces(((char*)pKey1)+n, nKey1-n)
  138945. && allSpaces(((char*)pKey2)+n, nKey2-n)
  138946. ){
  138947. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  138948. ** spaces at the end of either string do not change the result. In other
  138949. ** words, strings will compare equal to one another as long as they
  138950. ** differ only in the number of spaces at the end.
  138951. */
  138952. }else{
  138953. rc = nKey1 - nKey2;
  138954. }
  138955. }
  138956. return rc;
  138957. }
  138958. /*
  138959. ** Another built-in collating sequence: NOCASE.
  138960. **
  138961. ** This collating sequence is intended to be used for "case independent
  138962. ** comparison". SQLite's knowledge of upper and lower case equivalents
  138963. ** extends only to the 26 characters used in the English language.
  138964. **
  138965. ** At the moment there is only a UTF-8 implementation.
  138966. */
  138967. static int nocaseCollatingFunc(
  138968. void *NotUsed,
  138969. int nKey1, const void *pKey1,
  138970. int nKey2, const void *pKey2
  138971. ){
  138972. int r = sqlite3StrNICmp(
  138973. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  138974. UNUSED_PARAMETER(NotUsed);
  138975. if( 0==r ){
  138976. r = nKey1-nKey2;
  138977. }
  138978. return r;
  138979. }
  138980. /*
  138981. ** Return the ROWID of the most recent insert
  138982. */
  138983. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  138984. #ifdef SQLITE_ENABLE_API_ARMOR
  138985. if( !sqlite3SafetyCheckOk(db) ){
  138986. (void)SQLITE_MISUSE_BKPT;
  138987. return 0;
  138988. }
  138989. #endif
  138990. return db->lastRowid;
  138991. }
  138992. /*
  138993. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  138994. */
  138995. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  138996. #ifdef SQLITE_ENABLE_API_ARMOR
  138997. if( !sqlite3SafetyCheckOk(db) ){
  138998. (void)SQLITE_MISUSE_BKPT;
  138999. return;
  139000. }
  139001. #endif
  139002. sqlite3_mutex_enter(db->mutex);
  139003. db->lastRowid = iRowid;
  139004. sqlite3_mutex_leave(db->mutex);
  139005. }
  139006. /*
  139007. ** Return the number of changes in the most recent call to sqlite3_exec().
  139008. */
  139009. SQLITE_API int sqlite3_changes(sqlite3 *db){
  139010. #ifdef SQLITE_ENABLE_API_ARMOR
  139011. if( !sqlite3SafetyCheckOk(db) ){
  139012. (void)SQLITE_MISUSE_BKPT;
  139013. return 0;
  139014. }
  139015. #endif
  139016. return db->nChange;
  139017. }
  139018. /*
  139019. ** Return the number of changes since the database handle was opened.
  139020. */
  139021. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  139022. #ifdef SQLITE_ENABLE_API_ARMOR
  139023. if( !sqlite3SafetyCheckOk(db) ){
  139024. (void)SQLITE_MISUSE_BKPT;
  139025. return 0;
  139026. }
  139027. #endif
  139028. return db->nTotalChange;
  139029. }
  139030. /*
  139031. ** Close all open savepoints. This function only manipulates fields of the
  139032. ** database handle object, it does not close any savepoints that may be open
  139033. ** at the b-tree/pager level.
  139034. */
  139035. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  139036. while( db->pSavepoint ){
  139037. Savepoint *pTmp = db->pSavepoint;
  139038. db->pSavepoint = pTmp->pNext;
  139039. sqlite3DbFree(db, pTmp);
  139040. }
  139041. db->nSavepoint = 0;
  139042. db->nStatement = 0;
  139043. db->isTransactionSavepoint = 0;
  139044. }
  139045. /*
  139046. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  139047. ** if this is not the last copy of the function, do not invoke it. Multiple
  139048. ** copies of a single function are created when create_function() is called
  139049. ** with SQLITE_ANY as the encoding.
  139050. */
  139051. static void functionDestroy(sqlite3 *db, FuncDef *p){
  139052. FuncDestructor *pDestructor = p->u.pDestructor;
  139053. if( pDestructor ){
  139054. pDestructor->nRef--;
  139055. if( pDestructor->nRef==0 ){
  139056. pDestructor->xDestroy(pDestructor->pUserData);
  139057. sqlite3DbFree(db, pDestructor);
  139058. }
  139059. }
  139060. }
  139061. /*
  139062. ** Disconnect all sqlite3_vtab objects that belong to database connection
  139063. ** db. This is called when db is being closed.
  139064. */
  139065. static void disconnectAllVtab(sqlite3 *db){
  139066. #ifndef SQLITE_OMIT_VIRTUALTABLE
  139067. int i;
  139068. HashElem *p;
  139069. sqlite3BtreeEnterAll(db);
  139070. for(i=0; i<db->nDb; i++){
  139071. Schema *pSchema = db->aDb[i].pSchema;
  139072. if( db->aDb[i].pSchema ){
  139073. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  139074. Table *pTab = (Table *)sqliteHashData(p);
  139075. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  139076. }
  139077. }
  139078. }
  139079. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  139080. Module *pMod = (Module *)sqliteHashData(p);
  139081. if( pMod->pEpoTab ){
  139082. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  139083. }
  139084. }
  139085. sqlite3VtabUnlockList(db);
  139086. sqlite3BtreeLeaveAll(db);
  139087. #else
  139088. UNUSED_PARAMETER(db);
  139089. #endif
  139090. }
  139091. /*
  139092. ** Return TRUE if database connection db has unfinalized prepared
  139093. ** statements or unfinished sqlite3_backup objects.
  139094. */
  139095. static int connectionIsBusy(sqlite3 *db){
  139096. int j;
  139097. assert( sqlite3_mutex_held(db->mutex) );
  139098. if( db->pVdbe ) return 1;
  139099. for(j=0; j<db->nDb; j++){
  139100. Btree *pBt = db->aDb[j].pBt;
  139101. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  139102. }
  139103. return 0;
  139104. }
  139105. /*
  139106. ** Close an existing SQLite database
  139107. */
  139108. static int sqlite3Close(sqlite3 *db, int forceZombie){
  139109. if( !db ){
  139110. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  139111. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  139112. return SQLITE_OK;
  139113. }
  139114. if( !sqlite3SafetyCheckSickOrOk(db) ){
  139115. return SQLITE_MISUSE_BKPT;
  139116. }
  139117. sqlite3_mutex_enter(db->mutex);
  139118. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  139119. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  139120. }
  139121. /* Force xDisconnect calls on all virtual tables */
  139122. disconnectAllVtab(db);
  139123. /* If a transaction is open, the disconnectAllVtab() call above
  139124. ** will not have called the xDisconnect() method on any virtual
  139125. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  139126. ** call will do so. We need to do this before the check for active
  139127. ** SQL statements below, as the v-table implementation may be storing
  139128. ** some prepared statements internally.
  139129. */
  139130. sqlite3VtabRollback(db);
  139131. /* Legacy behavior (sqlite3_close() behavior) is to return
  139132. ** SQLITE_BUSY if the connection can not be closed immediately.
  139133. */
  139134. if( !forceZombie && connectionIsBusy(db) ){
  139135. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  139136. "statements or unfinished backups");
  139137. sqlite3_mutex_leave(db->mutex);
  139138. return SQLITE_BUSY;
  139139. }
  139140. #ifdef SQLITE_ENABLE_SQLLOG
  139141. if( sqlite3GlobalConfig.xSqllog ){
  139142. /* Closing the handle. Fourth parameter is passed the value 2. */
  139143. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  139144. }
  139145. #endif
  139146. /* Convert the connection into a zombie and then close it.
  139147. */
  139148. db->magic = SQLITE_MAGIC_ZOMBIE;
  139149. sqlite3LeaveMutexAndCloseZombie(db);
  139150. return SQLITE_OK;
  139151. }
  139152. /*
  139153. ** Two variations on the public interface for closing a database
  139154. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  139155. ** leaves the connection option if there are unfinalized prepared
  139156. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  139157. ** version forces the connection to become a zombie if there are
  139158. ** unclosed resources, and arranges for deallocation when the last
  139159. ** prepare statement or sqlite3_backup closes.
  139160. */
  139161. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  139162. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  139163. /*
  139164. ** Close the mutex on database connection db.
  139165. **
  139166. ** Furthermore, if database connection db is a zombie (meaning that there
  139167. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  139168. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  139169. ** finished, then free all resources.
  139170. */
  139171. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  139172. HashElem *i; /* Hash table iterator */
  139173. int j;
  139174. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  139175. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  139176. ** then just leave the mutex and return.
  139177. */
  139178. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  139179. sqlite3_mutex_leave(db->mutex);
  139180. return;
  139181. }
  139182. /* If we reach this point, it means that the database connection has
  139183. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  139184. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  139185. ** go ahead and free all resources.
  139186. */
  139187. /* If a transaction is open, roll it back. This also ensures that if
  139188. ** any database schemas have been modified by an uncommitted transaction
  139189. ** they are reset. And that the required b-tree mutex is held to make
  139190. ** the pager rollback and schema reset an atomic operation. */
  139191. sqlite3RollbackAll(db, SQLITE_OK);
  139192. /* Free any outstanding Savepoint structures. */
  139193. sqlite3CloseSavepoints(db);
  139194. /* Close all database connections */
  139195. for(j=0; j<db->nDb; j++){
  139196. struct Db *pDb = &db->aDb[j];
  139197. if( pDb->pBt ){
  139198. sqlite3BtreeClose(pDb->pBt);
  139199. pDb->pBt = 0;
  139200. if( j!=1 ){
  139201. pDb->pSchema = 0;
  139202. }
  139203. }
  139204. }
  139205. /* Clear the TEMP schema separately and last */
  139206. if( db->aDb[1].pSchema ){
  139207. sqlite3SchemaClear(db->aDb[1].pSchema);
  139208. }
  139209. sqlite3VtabUnlockList(db);
  139210. /* Free up the array of auxiliary databases */
  139211. sqlite3CollapseDatabaseArray(db);
  139212. assert( db->nDb<=2 );
  139213. assert( db->aDb==db->aDbStatic );
  139214. /* Tell the code in notify.c that the connection no longer holds any
  139215. ** locks and does not require any further unlock-notify callbacks.
  139216. */
  139217. sqlite3ConnectionClosed(db);
  139218. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  139219. FuncDef *pNext, *p;
  139220. p = sqliteHashData(i);
  139221. do{
  139222. functionDestroy(db, p);
  139223. pNext = p->pNext;
  139224. sqlite3DbFree(db, p);
  139225. p = pNext;
  139226. }while( p );
  139227. }
  139228. sqlite3HashClear(&db->aFunc);
  139229. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  139230. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  139231. /* Invoke any destructors registered for collation sequence user data. */
  139232. for(j=0; j<3; j++){
  139233. if( pColl[j].xDel ){
  139234. pColl[j].xDel(pColl[j].pUser);
  139235. }
  139236. }
  139237. sqlite3DbFree(db, pColl);
  139238. }
  139239. sqlite3HashClear(&db->aCollSeq);
  139240. #ifndef SQLITE_OMIT_VIRTUALTABLE
  139241. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  139242. Module *pMod = (Module *)sqliteHashData(i);
  139243. if( pMod->xDestroy ){
  139244. pMod->xDestroy(pMod->pAux);
  139245. }
  139246. sqlite3VtabEponymousTableClear(db, pMod);
  139247. sqlite3DbFree(db, pMod);
  139248. }
  139249. sqlite3HashClear(&db->aModule);
  139250. #endif
  139251. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  139252. sqlite3ValueFree(db->pErr);
  139253. sqlite3CloseExtensions(db);
  139254. #if SQLITE_USER_AUTHENTICATION
  139255. sqlite3_free(db->auth.zAuthUser);
  139256. sqlite3_free(db->auth.zAuthPW);
  139257. #endif
  139258. db->magic = SQLITE_MAGIC_ERROR;
  139259. /* The temp-database schema is allocated differently from the other schema
  139260. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  139261. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  139262. ** the same sqliteMalloc() as the one that allocates the database
  139263. ** structure?
  139264. */
  139265. sqlite3DbFree(db, db->aDb[1].pSchema);
  139266. sqlite3_mutex_leave(db->mutex);
  139267. db->magic = SQLITE_MAGIC_CLOSED;
  139268. sqlite3_mutex_free(db->mutex);
  139269. assert( sqlite3LookasideUsed(db,0)==0 );
  139270. if( db->lookaside.bMalloced ){
  139271. sqlite3_free(db->lookaside.pStart);
  139272. }
  139273. sqlite3_free(db);
  139274. }
  139275. /*
  139276. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  139277. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  139278. ** breaker") and made to return tripCode if there are any further
  139279. ** attempts to use that cursor. Read cursors remain open and valid
  139280. ** but are "saved" in case the table pages are moved around.
  139281. */
  139282. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  139283. int i;
  139284. int inTrans = 0;
  139285. int schemaChange;
  139286. assert( sqlite3_mutex_held(db->mutex) );
  139287. sqlite3BeginBenignMalloc();
  139288. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  139289. ** This is important in case the transaction being rolled back has
  139290. ** modified the database schema. If the b-tree mutexes are not taken
  139291. ** here, then another shared-cache connection might sneak in between
  139292. ** the database rollback and schema reset, which can cause false
  139293. ** corruption reports in some cases. */
  139294. sqlite3BtreeEnterAll(db);
  139295. schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
  139296. for(i=0; i<db->nDb; i++){
  139297. Btree *p = db->aDb[i].pBt;
  139298. if( p ){
  139299. if( sqlite3BtreeIsInTrans(p) ){
  139300. inTrans = 1;
  139301. }
  139302. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  139303. }
  139304. }
  139305. sqlite3VtabRollback(db);
  139306. sqlite3EndBenignMalloc();
  139307. if( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
  139308. sqlite3ExpirePreparedStatements(db);
  139309. sqlite3ResetAllSchemasOfConnection(db);
  139310. }
  139311. sqlite3BtreeLeaveAll(db);
  139312. /* Any deferred constraint violations have now been resolved. */
  139313. db->nDeferredCons = 0;
  139314. db->nDeferredImmCons = 0;
  139315. db->flags &= ~SQLITE_DeferFKs;
  139316. /* If one has been configured, invoke the rollback-hook callback */
  139317. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  139318. db->xRollbackCallback(db->pRollbackArg);
  139319. }
  139320. }
  139321. /*
  139322. ** Return a static string containing the name corresponding to the error code
  139323. ** specified in the argument.
  139324. */
  139325. #if defined(SQLITE_NEED_ERR_NAME)
  139326. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  139327. const char *zName = 0;
  139328. int i, origRc = rc;
  139329. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  139330. switch( rc ){
  139331. case SQLITE_OK: zName = "SQLITE_OK"; break;
  139332. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  139333. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  139334. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  139335. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  139336. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  139337. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  139338. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  139339. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  139340. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  139341. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  139342. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  139343. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  139344. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  139345. case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
  139346. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  139347. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  139348. case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
  139349. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  139350. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  139351. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  139352. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  139353. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  139354. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  139355. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  139356. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  139357. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  139358. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  139359. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  139360. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  139361. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  139362. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  139363. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  139364. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  139365. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  139366. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  139367. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  139368. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  139369. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  139370. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  139371. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  139372. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  139373. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  139374. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  139375. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  139376. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  139377. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  139378. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  139379. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  139380. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  139381. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  139382. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  139383. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  139384. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  139385. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  139386. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  139387. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  139388. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  139389. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  139390. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  139391. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  139392. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  139393. case SQLITE_CONSTRAINT_FOREIGNKEY:
  139394. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  139395. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  139396. case SQLITE_CONSTRAINT_PRIMARYKEY:
  139397. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  139398. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  139399. case SQLITE_CONSTRAINT_COMMITHOOK:
  139400. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  139401. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  139402. case SQLITE_CONSTRAINT_FUNCTION:
  139403. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  139404. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  139405. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  139406. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  139407. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  139408. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  139409. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  139410. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  139411. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  139412. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  139413. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  139414. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  139415. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  139416. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  139417. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  139418. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  139419. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  139420. }
  139421. }
  139422. if( zName==0 ){
  139423. static char zBuf[50];
  139424. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  139425. zName = zBuf;
  139426. }
  139427. return zName;
  139428. }
  139429. #endif
  139430. /*
  139431. ** Return a static string that describes the kind of error specified in the
  139432. ** argument.
  139433. */
  139434. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  139435. static const char* const aMsg[] = {
  139436. /* SQLITE_OK */ "not an error",
  139437. /* SQLITE_ERROR */ "SQL logic error",
  139438. /* SQLITE_INTERNAL */ 0,
  139439. /* SQLITE_PERM */ "access permission denied",
  139440. /* SQLITE_ABORT */ "query aborted",
  139441. /* SQLITE_BUSY */ "database is locked",
  139442. /* SQLITE_LOCKED */ "database table is locked",
  139443. /* SQLITE_NOMEM */ "out of memory",
  139444. /* SQLITE_READONLY */ "attempt to write a readonly database",
  139445. /* SQLITE_INTERRUPT */ "interrupted",
  139446. /* SQLITE_IOERR */ "disk I/O error",
  139447. /* SQLITE_CORRUPT */ "database disk image is malformed",
  139448. /* SQLITE_NOTFOUND */ "unknown operation",
  139449. /* SQLITE_FULL */ "database or disk is full",
  139450. /* SQLITE_CANTOPEN */ "unable to open database file",
  139451. /* SQLITE_PROTOCOL */ "locking protocol",
  139452. /* SQLITE_EMPTY */ 0,
  139453. /* SQLITE_SCHEMA */ "database schema has changed",
  139454. /* SQLITE_TOOBIG */ "string or blob too big",
  139455. /* SQLITE_CONSTRAINT */ "constraint failed",
  139456. /* SQLITE_MISMATCH */ "datatype mismatch",
  139457. /* SQLITE_MISUSE */ "bad parameter or other API misuse",
  139458. #ifdef SQLITE_DISABLE_LFS
  139459. /* SQLITE_NOLFS */ "large file support is disabled",
  139460. #else
  139461. /* SQLITE_NOLFS */ 0,
  139462. #endif
  139463. /* SQLITE_AUTH */ "authorization denied",
  139464. /* SQLITE_FORMAT */ 0,
  139465. /* SQLITE_RANGE */ "column index out of range",
  139466. /* SQLITE_NOTADB */ "file is not a database",
  139467. /* SQLITE_NOTICE */ "notification message",
  139468. /* SQLITE_WARNING */ "warning message",
  139469. };
  139470. const char *zErr = "unknown error";
  139471. switch( rc ){
  139472. case SQLITE_ABORT_ROLLBACK: {
  139473. zErr = "abort due to ROLLBACK";
  139474. break;
  139475. }
  139476. case SQLITE_ROW: {
  139477. zErr = "another row available";
  139478. break;
  139479. }
  139480. case SQLITE_DONE: {
  139481. zErr = "no more rows available";
  139482. break;
  139483. }
  139484. default: {
  139485. rc &= 0xff;
  139486. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  139487. zErr = aMsg[rc];
  139488. }
  139489. break;
  139490. }
  139491. }
  139492. return zErr;
  139493. }
  139494. /*
  139495. ** This routine implements a busy callback that sleeps and tries
  139496. ** again until a timeout value is reached. The timeout value is
  139497. ** an integer number of milliseconds passed in as the first
  139498. ** argument.
  139499. **
  139500. ** Return non-zero to retry the lock. Return zero to stop trying
  139501. ** and cause SQLite to return SQLITE_BUSY.
  139502. */
  139503. static int sqliteDefaultBusyCallback(
  139504. void *ptr, /* Database connection */
  139505. int count, /* Number of times table has been busy */
  139506. sqlite3_file *pFile /* The file on which the lock occurred */
  139507. ){
  139508. #if SQLITE_OS_WIN || HAVE_USLEEP
  139509. /* This case is for systems that have support for sleeping for fractions of
  139510. ** a second. Examples: All windows systems, unix systems with usleep() */
  139511. static const u8 delays[] =
  139512. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  139513. static const u8 totals[] =
  139514. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  139515. # define NDELAY ArraySize(delays)
  139516. sqlite3 *db = (sqlite3 *)ptr;
  139517. int tmout = db->busyTimeout;
  139518. int delay, prior;
  139519. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  139520. if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
  139521. if( count ){
  139522. tmout = 0;
  139523. sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
  139524. return 0;
  139525. }else{
  139526. return 1;
  139527. }
  139528. }
  139529. #else
  139530. UNUSED_PARAMETER(pFile);
  139531. #endif
  139532. assert( count>=0 );
  139533. if( count < NDELAY ){
  139534. delay = delays[count];
  139535. prior = totals[count];
  139536. }else{
  139537. delay = delays[NDELAY-1];
  139538. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  139539. }
  139540. if( prior + delay > tmout ){
  139541. delay = tmout - prior;
  139542. if( delay<=0 ) return 0;
  139543. }
  139544. sqlite3OsSleep(db->pVfs, delay*1000);
  139545. return 1;
  139546. #else
  139547. /* This case for unix systems that lack usleep() support. Sleeping
  139548. ** must be done in increments of whole seconds */
  139549. sqlite3 *db = (sqlite3 *)ptr;
  139550. int tmout = ((sqlite3 *)ptr)->busyTimeout;
  139551. UNUSED_PARAMETER(pFile);
  139552. if( (count+1)*1000 > tmout ){
  139553. return 0;
  139554. }
  139555. sqlite3OsSleep(db->pVfs, 1000000);
  139556. return 1;
  139557. #endif
  139558. }
  139559. /*
  139560. ** Invoke the given busy handler.
  139561. **
  139562. ** This routine is called when an operation failed to acquire a
  139563. ** lock on VFS file pFile.
  139564. **
  139565. ** If this routine returns non-zero, the lock is retried. If it
  139566. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  139567. */
  139568. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
  139569. int rc;
  139570. if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
  139571. if( p->bExtraFileArg ){
  139572. /* Add an extra parameter with the pFile pointer to the end of the
  139573. ** callback argument list */
  139574. int (*xTra)(void*,int,sqlite3_file*);
  139575. xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
  139576. rc = xTra(p->pBusyArg, p->nBusy, pFile);
  139577. }else{
  139578. /* Legacy style busy handler callback */
  139579. rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
  139580. }
  139581. if( rc==0 ){
  139582. p->nBusy = -1;
  139583. }else{
  139584. p->nBusy++;
  139585. }
  139586. return rc;
  139587. }
  139588. /*
  139589. ** This routine sets the busy callback for an Sqlite database to the
  139590. ** given callback function with the given argument.
  139591. */
  139592. SQLITE_API int sqlite3_busy_handler(
  139593. sqlite3 *db,
  139594. int (*xBusy)(void*,int),
  139595. void *pArg
  139596. ){
  139597. #ifdef SQLITE_ENABLE_API_ARMOR
  139598. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  139599. #endif
  139600. sqlite3_mutex_enter(db->mutex);
  139601. db->busyHandler.xBusyHandler = xBusy;
  139602. db->busyHandler.pBusyArg = pArg;
  139603. db->busyHandler.nBusy = 0;
  139604. db->busyHandler.bExtraFileArg = 0;
  139605. db->busyTimeout = 0;
  139606. sqlite3_mutex_leave(db->mutex);
  139607. return SQLITE_OK;
  139608. }
  139609. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  139610. /*
  139611. ** This routine sets the progress callback for an Sqlite database to the
  139612. ** given callback function with the given argument. The progress callback will
  139613. ** be invoked every nOps opcodes.
  139614. */
  139615. SQLITE_API void sqlite3_progress_handler(
  139616. sqlite3 *db,
  139617. int nOps,
  139618. int (*xProgress)(void*),
  139619. void *pArg
  139620. ){
  139621. #ifdef SQLITE_ENABLE_API_ARMOR
  139622. if( !sqlite3SafetyCheckOk(db) ){
  139623. (void)SQLITE_MISUSE_BKPT;
  139624. return;
  139625. }
  139626. #endif
  139627. sqlite3_mutex_enter(db->mutex);
  139628. if( nOps>0 ){
  139629. db->xProgress = xProgress;
  139630. db->nProgressOps = (unsigned)nOps;
  139631. db->pProgressArg = pArg;
  139632. }else{
  139633. db->xProgress = 0;
  139634. db->nProgressOps = 0;
  139635. db->pProgressArg = 0;
  139636. }
  139637. sqlite3_mutex_leave(db->mutex);
  139638. }
  139639. #endif
  139640. /*
  139641. ** This routine installs a default busy handler that waits for the
  139642. ** specified number of milliseconds before returning 0.
  139643. */
  139644. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  139645. #ifdef SQLITE_ENABLE_API_ARMOR
  139646. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  139647. #endif
  139648. if( ms>0 ){
  139649. sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
  139650. (void*)db);
  139651. db->busyTimeout = ms;
  139652. db->busyHandler.bExtraFileArg = 1;
  139653. }else{
  139654. sqlite3_busy_handler(db, 0, 0);
  139655. }
  139656. return SQLITE_OK;
  139657. }
  139658. /*
  139659. ** Cause any pending operation to stop at its earliest opportunity.
  139660. */
  139661. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  139662. #ifdef SQLITE_ENABLE_API_ARMOR
  139663. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  139664. (void)SQLITE_MISUSE_BKPT;
  139665. return;
  139666. }
  139667. #endif
  139668. db->u1.isInterrupted = 1;
  139669. }
  139670. /*
  139671. ** This function is exactly the same as sqlite3_create_function(), except
  139672. ** that it is designed to be called by internal code. The difference is
  139673. ** that if a malloc() fails in sqlite3_create_function(), an error code
  139674. ** is returned and the mallocFailed flag cleared.
  139675. */
  139676. SQLITE_PRIVATE int sqlite3CreateFunc(
  139677. sqlite3 *db,
  139678. const char *zFunctionName,
  139679. int nArg,
  139680. int enc,
  139681. void *pUserData,
  139682. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  139683. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  139684. void (*xFinal)(sqlite3_context*),
  139685. FuncDestructor *pDestructor
  139686. ){
  139687. FuncDef *p;
  139688. int nName;
  139689. int extraFlags;
  139690. assert( sqlite3_mutex_held(db->mutex) );
  139691. if( zFunctionName==0 ||
  139692. (xSFunc && (xFinal || xStep)) ||
  139693. (!xSFunc && (xFinal && !xStep)) ||
  139694. (!xSFunc && (!xFinal && xStep)) ||
  139695. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  139696. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  139697. return SQLITE_MISUSE_BKPT;
  139698. }
  139699. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  139700. extraFlags = enc & SQLITE_DETERMINISTIC;
  139701. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  139702. #ifndef SQLITE_OMIT_UTF16
  139703. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  139704. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  139705. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  139706. **
  139707. ** If SQLITE_ANY is specified, add three versions of the function
  139708. ** to the hash table.
  139709. */
  139710. if( enc==SQLITE_UTF16 ){
  139711. enc = SQLITE_UTF16NATIVE;
  139712. }else if( enc==SQLITE_ANY ){
  139713. int rc;
  139714. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  139715. pUserData, xSFunc, xStep, xFinal, pDestructor);
  139716. if( rc==SQLITE_OK ){
  139717. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  139718. pUserData, xSFunc, xStep, xFinal, pDestructor);
  139719. }
  139720. if( rc!=SQLITE_OK ){
  139721. return rc;
  139722. }
  139723. enc = SQLITE_UTF16BE;
  139724. }
  139725. #else
  139726. enc = SQLITE_UTF8;
  139727. #endif
  139728. /* Check if an existing function is being overridden or deleted. If so,
  139729. ** and there are active VMs, then return SQLITE_BUSY. If a function
  139730. ** is being overridden/deleted but there are no active VMs, allow the
  139731. ** operation to continue but invalidate all precompiled statements.
  139732. */
  139733. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  139734. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  139735. if( db->nVdbeActive ){
  139736. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  139737. "unable to delete/modify user-function due to active statements");
  139738. assert( !db->mallocFailed );
  139739. return SQLITE_BUSY;
  139740. }else{
  139741. sqlite3ExpirePreparedStatements(db);
  139742. }
  139743. }
  139744. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  139745. assert(p || db->mallocFailed);
  139746. if( !p ){
  139747. return SQLITE_NOMEM_BKPT;
  139748. }
  139749. /* If an older version of the function with a configured destructor is
  139750. ** being replaced invoke the destructor function here. */
  139751. functionDestroy(db, p);
  139752. if( pDestructor ){
  139753. pDestructor->nRef++;
  139754. }
  139755. p->u.pDestructor = pDestructor;
  139756. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  139757. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  139758. p->xSFunc = xSFunc ? xSFunc : xStep;
  139759. p->xFinalize = xFinal;
  139760. p->pUserData = pUserData;
  139761. p->nArg = (u16)nArg;
  139762. return SQLITE_OK;
  139763. }
  139764. /*
  139765. ** Create new user functions.
  139766. */
  139767. SQLITE_API int sqlite3_create_function(
  139768. sqlite3 *db,
  139769. const char *zFunc,
  139770. int nArg,
  139771. int enc,
  139772. void *p,
  139773. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  139774. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  139775. void (*xFinal)(sqlite3_context*)
  139776. ){
  139777. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
  139778. xFinal, 0);
  139779. }
  139780. SQLITE_API int sqlite3_create_function_v2(
  139781. sqlite3 *db,
  139782. const char *zFunc,
  139783. int nArg,
  139784. int enc,
  139785. void *p,
  139786. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  139787. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  139788. void (*xFinal)(sqlite3_context*),
  139789. void (*xDestroy)(void *)
  139790. ){
  139791. int rc = SQLITE_ERROR;
  139792. FuncDestructor *pArg = 0;
  139793. #ifdef SQLITE_ENABLE_API_ARMOR
  139794. if( !sqlite3SafetyCheckOk(db) ){
  139795. return SQLITE_MISUSE_BKPT;
  139796. }
  139797. #endif
  139798. sqlite3_mutex_enter(db->mutex);
  139799. if( xDestroy ){
  139800. pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
  139801. if( !pArg ){
  139802. sqlite3OomFault(db);
  139803. xDestroy(p);
  139804. goto out;
  139805. }
  139806. pArg->nRef = 0;
  139807. pArg->xDestroy = xDestroy;
  139808. pArg->pUserData = p;
  139809. }
  139810. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
  139811. if( pArg && pArg->nRef==0 ){
  139812. assert( rc!=SQLITE_OK );
  139813. xDestroy(p);
  139814. sqlite3_free(pArg);
  139815. }
  139816. out:
  139817. rc = sqlite3ApiExit(db, rc);
  139818. sqlite3_mutex_leave(db->mutex);
  139819. return rc;
  139820. }
  139821. #ifndef SQLITE_OMIT_UTF16
  139822. SQLITE_API int sqlite3_create_function16(
  139823. sqlite3 *db,
  139824. const void *zFunctionName,
  139825. int nArg,
  139826. int eTextRep,
  139827. void *p,
  139828. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  139829. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  139830. void (*xFinal)(sqlite3_context*)
  139831. ){
  139832. int rc;
  139833. char *zFunc8;
  139834. #ifdef SQLITE_ENABLE_API_ARMOR
  139835. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  139836. #endif
  139837. sqlite3_mutex_enter(db->mutex);
  139838. assert( !db->mallocFailed );
  139839. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  139840. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
  139841. sqlite3DbFree(db, zFunc8);
  139842. rc = sqlite3ApiExit(db, rc);
  139843. sqlite3_mutex_leave(db->mutex);
  139844. return rc;
  139845. }
  139846. #endif
  139847. /*
  139848. ** The following is the implementation of an SQL function that always
  139849. ** fails with an error message stating that the function is used in the
  139850. ** wrong context. The sqlite3_overload_function() API might construct
  139851. ** SQL function that use this routine so that the functions will exist
  139852. ** for name resolution but are actually overloaded by the xFindFunction
  139853. ** method of virtual tables.
  139854. */
  139855. static void sqlite3InvalidFunction(
  139856. sqlite3_context *context, /* The function calling context */
  139857. int NotUsed, /* Number of arguments to the function */
  139858. sqlite3_value **NotUsed2 /* Value of each argument */
  139859. ){
  139860. const char *zName = (const char*)sqlite3_user_data(context);
  139861. char *zErr;
  139862. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  139863. zErr = sqlite3_mprintf(
  139864. "unable to use function %s in the requested context", zName);
  139865. sqlite3_result_error(context, zErr, -1);
  139866. sqlite3_free(zErr);
  139867. }
  139868. /*
  139869. ** Declare that a function has been overloaded by a virtual table.
  139870. **
  139871. ** If the function already exists as a regular global function, then
  139872. ** this routine is a no-op. If the function does not exist, then create
  139873. ** a new one that always throws a run-time error.
  139874. **
  139875. ** When virtual tables intend to provide an overloaded function, they
  139876. ** should call this routine to make sure the global function exists.
  139877. ** A global function must exist in order for name resolution to work
  139878. ** properly.
  139879. */
  139880. SQLITE_API int sqlite3_overload_function(
  139881. sqlite3 *db,
  139882. const char *zName,
  139883. int nArg
  139884. ){
  139885. int rc;
  139886. char *zCopy;
  139887. #ifdef SQLITE_ENABLE_API_ARMOR
  139888. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  139889. return SQLITE_MISUSE_BKPT;
  139890. }
  139891. #endif
  139892. sqlite3_mutex_enter(db->mutex);
  139893. rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
  139894. sqlite3_mutex_leave(db->mutex);
  139895. if( rc ) return SQLITE_OK;
  139896. zCopy = sqlite3_mprintf(zName);
  139897. if( zCopy==0 ) return SQLITE_NOMEM;
  139898. return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
  139899. zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
  139900. }
  139901. #ifndef SQLITE_OMIT_TRACE
  139902. /*
  139903. ** Register a trace function. The pArg from the previously registered trace
  139904. ** is returned.
  139905. **
  139906. ** A NULL trace function means that no tracing is executes. A non-NULL
  139907. ** trace is a pointer to a function that is invoked at the start of each
  139908. ** SQL statement.
  139909. */
  139910. #ifndef SQLITE_OMIT_DEPRECATED
  139911. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  139912. void *pOld;
  139913. #ifdef SQLITE_ENABLE_API_ARMOR
  139914. if( !sqlite3SafetyCheckOk(db) ){
  139915. (void)SQLITE_MISUSE_BKPT;
  139916. return 0;
  139917. }
  139918. #endif
  139919. sqlite3_mutex_enter(db->mutex);
  139920. pOld = db->pTraceArg;
  139921. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  139922. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  139923. db->pTraceArg = pArg;
  139924. sqlite3_mutex_leave(db->mutex);
  139925. return pOld;
  139926. }
  139927. #endif /* SQLITE_OMIT_DEPRECATED */
  139928. /* Register a trace callback using the version-2 interface.
  139929. */
  139930. SQLITE_API int sqlite3_trace_v2(
  139931. sqlite3 *db, /* Trace this connection */
  139932. unsigned mTrace, /* Mask of events to be traced */
  139933. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  139934. void *pArg /* Context */
  139935. ){
  139936. #ifdef SQLITE_ENABLE_API_ARMOR
  139937. if( !sqlite3SafetyCheckOk(db) ){
  139938. return SQLITE_MISUSE_BKPT;
  139939. }
  139940. #endif
  139941. sqlite3_mutex_enter(db->mutex);
  139942. if( mTrace==0 ) xTrace = 0;
  139943. if( xTrace==0 ) mTrace = 0;
  139944. db->mTrace = mTrace;
  139945. db->xTrace = xTrace;
  139946. db->pTraceArg = pArg;
  139947. sqlite3_mutex_leave(db->mutex);
  139948. return SQLITE_OK;
  139949. }
  139950. #ifndef SQLITE_OMIT_DEPRECATED
  139951. /*
  139952. ** Register a profile function. The pArg from the previously registered
  139953. ** profile function is returned.
  139954. **
  139955. ** A NULL profile function means that no profiling is executes. A non-NULL
  139956. ** profile is a pointer to a function that is invoked at the conclusion of
  139957. ** each SQL statement that is run.
  139958. */
  139959. SQLITE_API void *sqlite3_profile(
  139960. sqlite3 *db,
  139961. void (*xProfile)(void*,const char*,sqlite_uint64),
  139962. void *pArg
  139963. ){
  139964. void *pOld;
  139965. #ifdef SQLITE_ENABLE_API_ARMOR
  139966. if( !sqlite3SafetyCheckOk(db) ){
  139967. (void)SQLITE_MISUSE_BKPT;
  139968. return 0;
  139969. }
  139970. #endif
  139971. sqlite3_mutex_enter(db->mutex);
  139972. pOld = db->pProfileArg;
  139973. db->xProfile = xProfile;
  139974. db->pProfileArg = pArg;
  139975. sqlite3_mutex_leave(db->mutex);
  139976. return pOld;
  139977. }
  139978. #endif /* SQLITE_OMIT_DEPRECATED */
  139979. #endif /* SQLITE_OMIT_TRACE */
  139980. /*
  139981. ** Register a function to be invoked when a transaction commits.
  139982. ** If the invoked function returns non-zero, then the commit becomes a
  139983. ** rollback.
  139984. */
  139985. SQLITE_API void *sqlite3_commit_hook(
  139986. sqlite3 *db, /* Attach the hook to this database */
  139987. int (*xCallback)(void*), /* Function to invoke on each commit */
  139988. void *pArg /* Argument to the function */
  139989. ){
  139990. void *pOld;
  139991. #ifdef SQLITE_ENABLE_API_ARMOR
  139992. if( !sqlite3SafetyCheckOk(db) ){
  139993. (void)SQLITE_MISUSE_BKPT;
  139994. return 0;
  139995. }
  139996. #endif
  139997. sqlite3_mutex_enter(db->mutex);
  139998. pOld = db->pCommitArg;
  139999. db->xCommitCallback = xCallback;
  140000. db->pCommitArg = pArg;
  140001. sqlite3_mutex_leave(db->mutex);
  140002. return pOld;
  140003. }
  140004. /*
  140005. ** Register a callback to be invoked each time a row is updated,
  140006. ** inserted or deleted using this database connection.
  140007. */
  140008. SQLITE_API void *sqlite3_update_hook(
  140009. sqlite3 *db, /* Attach the hook to this database */
  140010. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  140011. void *pArg /* Argument to the function */
  140012. ){
  140013. void *pRet;
  140014. #ifdef SQLITE_ENABLE_API_ARMOR
  140015. if( !sqlite3SafetyCheckOk(db) ){
  140016. (void)SQLITE_MISUSE_BKPT;
  140017. return 0;
  140018. }
  140019. #endif
  140020. sqlite3_mutex_enter(db->mutex);
  140021. pRet = db->pUpdateArg;
  140022. db->xUpdateCallback = xCallback;
  140023. db->pUpdateArg = pArg;
  140024. sqlite3_mutex_leave(db->mutex);
  140025. return pRet;
  140026. }
  140027. /*
  140028. ** Register a callback to be invoked each time a transaction is rolled
  140029. ** back by this database connection.
  140030. */
  140031. SQLITE_API void *sqlite3_rollback_hook(
  140032. sqlite3 *db, /* Attach the hook to this database */
  140033. void (*xCallback)(void*), /* Callback function */
  140034. void *pArg /* Argument to the function */
  140035. ){
  140036. void *pRet;
  140037. #ifdef SQLITE_ENABLE_API_ARMOR
  140038. if( !sqlite3SafetyCheckOk(db) ){
  140039. (void)SQLITE_MISUSE_BKPT;
  140040. return 0;
  140041. }
  140042. #endif
  140043. sqlite3_mutex_enter(db->mutex);
  140044. pRet = db->pRollbackArg;
  140045. db->xRollbackCallback = xCallback;
  140046. db->pRollbackArg = pArg;
  140047. sqlite3_mutex_leave(db->mutex);
  140048. return pRet;
  140049. }
  140050. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  140051. /*
  140052. ** Register a callback to be invoked each time a row is updated,
  140053. ** inserted or deleted using this database connection.
  140054. */
  140055. SQLITE_API void *sqlite3_preupdate_hook(
  140056. sqlite3 *db, /* Attach the hook to this database */
  140057. void(*xCallback)( /* Callback function */
  140058. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  140059. void *pArg /* First callback argument */
  140060. ){
  140061. void *pRet;
  140062. sqlite3_mutex_enter(db->mutex);
  140063. pRet = db->pPreUpdateArg;
  140064. db->xPreUpdateCallback = xCallback;
  140065. db->pPreUpdateArg = pArg;
  140066. sqlite3_mutex_leave(db->mutex);
  140067. return pRet;
  140068. }
  140069. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  140070. #ifndef SQLITE_OMIT_WAL
  140071. /*
  140072. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  140073. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  140074. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  140075. ** wal_autocheckpoint()).
  140076. */
  140077. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  140078. void *pClientData, /* Argument */
  140079. sqlite3 *db, /* Connection */
  140080. const char *zDb, /* Database */
  140081. int nFrame /* Size of WAL */
  140082. ){
  140083. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  140084. sqlite3BeginBenignMalloc();
  140085. sqlite3_wal_checkpoint(db, zDb);
  140086. sqlite3EndBenignMalloc();
  140087. }
  140088. return SQLITE_OK;
  140089. }
  140090. #endif /* SQLITE_OMIT_WAL */
  140091. /*
  140092. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  140093. ** a database after committing a transaction if there are nFrame or
  140094. ** more frames in the log file. Passing zero or a negative value as the
  140095. ** nFrame parameter disables automatic checkpoints entirely.
  140096. **
  140097. ** The callback registered by this function replaces any existing callback
  140098. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  140099. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  140100. ** configured by this function.
  140101. */
  140102. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  140103. #ifdef SQLITE_OMIT_WAL
  140104. UNUSED_PARAMETER(db);
  140105. UNUSED_PARAMETER(nFrame);
  140106. #else
  140107. #ifdef SQLITE_ENABLE_API_ARMOR
  140108. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  140109. #endif
  140110. if( nFrame>0 ){
  140111. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  140112. }else{
  140113. sqlite3_wal_hook(db, 0, 0);
  140114. }
  140115. #endif
  140116. return SQLITE_OK;
  140117. }
  140118. /*
  140119. ** Register a callback to be invoked each time a transaction is written
  140120. ** into the write-ahead-log by this database connection.
  140121. */
  140122. SQLITE_API void *sqlite3_wal_hook(
  140123. sqlite3 *db, /* Attach the hook to this db handle */
  140124. int(*xCallback)(void *, sqlite3*, const char*, int),
  140125. void *pArg /* First argument passed to xCallback() */
  140126. ){
  140127. #ifndef SQLITE_OMIT_WAL
  140128. void *pRet;
  140129. #ifdef SQLITE_ENABLE_API_ARMOR
  140130. if( !sqlite3SafetyCheckOk(db) ){
  140131. (void)SQLITE_MISUSE_BKPT;
  140132. return 0;
  140133. }
  140134. #endif
  140135. sqlite3_mutex_enter(db->mutex);
  140136. pRet = db->pWalArg;
  140137. db->xWalCallback = xCallback;
  140138. db->pWalArg = pArg;
  140139. sqlite3_mutex_leave(db->mutex);
  140140. return pRet;
  140141. #else
  140142. return 0;
  140143. #endif
  140144. }
  140145. /*
  140146. ** Checkpoint database zDb.
  140147. */
  140148. SQLITE_API int sqlite3_wal_checkpoint_v2(
  140149. sqlite3 *db, /* Database handle */
  140150. const char *zDb, /* Name of attached database (or NULL) */
  140151. int eMode, /* SQLITE_CHECKPOINT_* value */
  140152. int *pnLog, /* OUT: Size of WAL log in frames */
  140153. int *pnCkpt /* OUT: Total number of frames checkpointed */
  140154. ){
  140155. #ifdef SQLITE_OMIT_WAL
  140156. return SQLITE_OK;
  140157. #else
  140158. int rc; /* Return code */
  140159. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  140160. #ifdef SQLITE_ENABLE_API_ARMOR
  140161. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  140162. #endif
  140163. /* Initialize the output variables to -1 in case an error occurs. */
  140164. if( pnLog ) *pnLog = -1;
  140165. if( pnCkpt ) *pnCkpt = -1;
  140166. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  140167. assert( SQLITE_CHECKPOINT_FULL==1 );
  140168. assert( SQLITE_CHECKPOINT_RESTART==2 );
  140169. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  140170. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  140171. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  140172. ** mode: */
  140173. return SQLITE_MISUSE;
  140174. }
  140175. sqlite3_mutex_enter(db->mutex);
  140176. if( zDb && zDb[0] ){
  140177. iDb = sqlite3FindDbName(db, zDb);
  140178. }
  140179. if( iDb<0 ){
  140180. rc = SQLITE_ERROR;
  140181. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  140182. }else{
  140183. db->busyHandler.nBusy = 0;
  140184. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  140185. sqlite3Error(db, rc);
  140186. }
  140187. rc = sqlite3ApiExit(db, rc);
  140188. /* If there are no active statements, clear the interrupt flag at this
  140189. ** point. */
  140190. if( db->nVdbeActive==0 ){
  140191. db->u1.isInterrupted = 0;
  140192. }
  140193. sqlite3_mutex_leave(db->mutex);
  140194. return rc;
  140195. #endif
  140196. }
  140197. /*
  140198. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  140199. ** to contains a zero-length string, all attached databases are
  140200. ** checkpointed.
  140201. */
  140202. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  140203. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  140204. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  140205. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  140206. }
  140207. #ifndef SQLITE_OMIT_WAL
  140208. /*
  140209. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  140210. ** not currently open in WAL mode.
  140211. **
  140212. ** If a transaction is open on the database being checkpointed, this
  140213. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  140214. ** an error occurs while running the checkpoint, an SQLite error code is
  140215. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  140216. **
  140217. ** The mutex on database handle db should be held by the caller. The mutex
  140218. ** associated with the specific b-tree being checkpointed is taken by
  140219. ** this function while the checkpoint is running.
  140220. **
  140221. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  140222. ** checkpointed. If an error is encountered it is returned immediately -
  140223. ** no attempt is made to checkpoint any remaining databases.
  140224. **
  140225. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
  140226. ** or TRUNCATE.
  140227. */
  140228. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  140229. int rc = SQLITE_OK; /* Return code */
  140230. int i; /* Used to iterate through attached dbs */
  140231. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  140232. assert( sqlite3_mutex_held(db->mutex) );
  140233. assert( !pnLog || *pnLog==-1 );
  140234. assert( !pnCkpt || *pnCkpt==-1 );
  140235. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  140236. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  140237. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  140238. pnLog = 0;
  140239. pnCkpt = 0;
  140240. if( rc==SQLITE_BUSY ){
  140241. bBusy = 1;
  140242. rc = SQLITE_OK;
  140243. }
  140244. }
  140245. }
  140246. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  140247. }
  140248. #endif /* SQLITE_OMIT_WAL */
  140249. /*
  140250. ** This function returns true if main-memory should be used instead of
  140251. ** a temporary file for transient pager files and statement journals.
  140252. ** The value returned depends on the value of db->temp_store (runtime
  140253. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  140254. ** following table describes the relationship between these two values
  140255. ** and this functions return value.
  140256. **
  140257. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  140258. ** ----------------- -------------- ------------------------------
  140259. ** 0 any file (return 0)
  140260. ** 1 1 file (return 0)
  140261. ** 1 2 memory (return 1)
  140262. ** 1 0 file (return 0)
  140263. ** 2 1 file (return 0)
  140264. ** 2 2 memory (return 1)
  140265. ** 2 0 memory (return 1)
  140266. ** 3 any memory (return 1)
  140267. */
  140268. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  140269. #if SQLITE_TEMP_STORE==1
  140270. return ( db->temp_store==2 );
  140271. #endif
  140272. #if SQLITE_TEMP_STORE==2
  140273. return ( db->temp_store!=1 );
  140274. #endif
  140275. #if SQLITE_TEMP_STORE==3
  140276. UNUSED_PARAMETER(db);
  140277. return 1;
  140278. #endif
  140279. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  140280. UNUSED_PARAMETER(db);
  140281. return 0;
  140282. #endif
  140283. }
  140284. /*
  140285. ** Return UTF-8 encoded English language explanation of the most recent
  140286. ** error.
  140287. */
  140288. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  140289. const char *z;
  140290. if( !db ){
  140291. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  140292. }
  140293. if( !sqlite3SafetyCheckSickOrOk(db) ){
  140294. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  140295. }
  140296. sqlite3_mutex_enter(db->mutex);
  140297. if( db->mallocFailed ){
  140298. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  140299. }else{
  140300. testcase( db->pErr==0 );
  140301. z = (char*)sqlite3_value_text(db->pErr);
  140302. assert( !db->mallocFailed );
  140303. if( z==0 ){
  140304. z = sqlite3ErrStr(db->errCode);
  140305. }
  140306. }
  140307. sqlite3_mutex_leave(db->mutex);
  140308. return z;
  140309. }
  140310. #ifndef SQLITE_OMIT_UTF16
  140311. /*
  140312. ** Return UTF-16 encoded English language explanation of the most recent
  140313. ** error.
  140314. */
  140315. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  140316. static const u16 outOfMem[] = {
  140317. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  140318. };
  140319. static const u16 misuse[] = {
  140320. 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
  140321. 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
  140322. 'm', 'i', 's', 'u', 's', 'e', 0
  140323. };
  140324. const void *z;
  140325. if( !db ){
  140326. return (void *)outOfMem;
  140327. }
  140328. if( !sqlite3SafetyCheckSickOrOk(db) ){
  140329. return (void *)misuse;
  140330. }
  140331. sqlite3_mutex_enter(db->mutex);
  140332. if( db->mallocFailed ){
  140333. z = (void *)outOfMem;
  140334. }else{
  140335. z = sqlite3_value_text16(db->pErr);
  140336. if( z==0 ){
  140337. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  140338. z = sqlite3_value_text16(db->pErr);
  140339. }
  140340. /* A malloc() may have failed within the call to sqlite3_value_text16()
  140341. ** above. If this is the case, then the db->mallocFailed flag needs to
  140342. ** be cleared before returning. Do this directly, instead of via
  140343. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  140344. */
  140345. sqlite3OomClear(db);
  140346. }
  140347. sqlite3_mutex_leave(db->mutex);
  140348. return z;
  140349. }
  140350. #endif /* SQLITE_OMIT_UTF16 */
  140351. /*
  140352. ** Return the most recent error code generated by an SQLite routine. If NULL is
  140353. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  140354. */
  140355. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  140356. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  140357. return SQLITE_MISUSE_BKPT;
  140358. }
  140359. if( !db || db->mallocFailed ){
  140360. return SQLITE_NOMEM_BKPT;
  140361. }
  140362. return db->errCode & db->errMask;
  140363. }
  140364. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  140365. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  140366. return SQLITE_MISUSE_BKPT;
  140367. }
  140368. if( !db || db->mallocFailed ){
  140369. return SQLITE_NOMEM_BKPT;
  140370. }
  140371. return db->errCode;
  140372. }
  140373. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  140374. return db ? db->iSysErrno : 0;
  140375. }
  140376. /*
  140377. ** Return a string that describes the kind of error specified in the
  140378. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  140379. ** function.
  140380. */
  140381. SQLITE_API const char *sqlite3_errstr(int rc){
  140382. return sqlite3ErrStr(rc);
  140383. }
  140384. /*
  140385. ** Create a new collating function for database "db". The name is zName
  140386. ** and the encoding is enc.
  140387. */
  140388. static int createCollation(
  140389. sqlite3* db,
  140390. const char *zName,
  140391. u8 enc,
  140392. void* pCtx,
  140393. int(*xCompare)(void*,int,const void*,int,const void*),
  140394. void(*xDel)(void*)
  140395. ){
  140396. CollSeq *pColl;
  140397. int enc2;
  140398. assert( sqlite3_mutex_held(db->mutex) );
  140399. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  140400. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  140401. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  140402. */
  140403. enc2 = enc;
  140404. testcase( enc2==SQLITE_UTF16 );
  140405. testcase( enc2==SQLITE_UTF16_ALIGNED );
  140406. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  140407. enc2 = SQLITE_UTF16NATIVE;
  140408. }
  140409. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  140410. return SQLITE_MISUSE_BKPT;
  140411. }
  140412. /* Check if this call is removing or replacing an existing collation
  140413. ** sequence. If so, and there are active VMs, return busy. If there
  140414. ** are no active VMs, invalidate any pre-compiled statements.
  140415. */
  140416. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  140417. if( pColl && pColl->xCmp ){
  140418. if( db->nVdbeActive ){
  140419. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  140420. "unable to delete/modify collation sequence due to active statements");
  140421. return SQLITE_BUSY;
  140422. }
  140423. sqlite3ExpirePreparedStatements(db);
  140424. /* If collation sequence pColl was created directly by a call to
  140425. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  140426. ** then any copies made by synthCollSeq() need to be invalidated.
  140427. ** Also, collation destructor - CollSeq.xDel() - function may need
  140428. ** to be called.
  140429. */
  140430. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  140431. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  140432. int j;
  140433. for(j=0; j<3; j++){
  140434. CollSeq *p = &aColl[j];
  140435. if( p->enc==pColl->enc ){
  140436. if( p->xDel ){
  140437. p->xDel(p->pUser);
  140438. }
  140439. p->xCmp = 0;
  140440. }
  140441. }
  140442. }
  140443. }
  140444. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  140445. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  140446. pColl->xCmp = xCompare;
  140447. pColl->pUser = pCtx;
  140448. pColl->xDel = xDel;
  140449. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  140450. sqlite3Error(db, SQLITE_OK);
  140451. return SQLITE_OK;
  140452. }
  140453. /*
  140454. ** This array defines hard upper bounds on limit values. The
  140455. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  140456. ** #defines in sqlite3.h.
  140457. */
  140458. static const int aHardLimit[] = {
  140459. SQLITE_MAX_LENGTH,
  140460. SQLITE_MAX_SQL_LENGTH,
  140461. SQLITE_MAX_COLUMN,
  140462. SQLITE_MAX_EXPR_DEPTH,
  140463. SQLITE_MAX_COMPOUND_SELECT,
  140464. SQLITE_MAX_VDBE_OP,
  140465. SQLITE_MAX_FUNCTION_ARG,
  140466. SQLITE_MAX_ATTACHED,
  140467. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  140468. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  140469. SQLITE_MAX_TRIGGER_DEPTH,
  140470. SQLITE_MAX_WORKER_THREADS,
  140471. };
  140472. /*
  140473. ** Make sure the hard limits are set to reasonable values
  140474. */
  140475. #if SQLITE_MAX_LENGTH<100
  140476. # error SQLITE_MAX_LENGTH must be at least 100
  140477. #endif
  140478. #if SQLITE_MAX_SQL_LENGTH<100
  140479. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  140480. #endif
  140481. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  140482. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  140483. #endif
  140484. #if SQLITE_MAX_COMPOUND_SELECT<2
  140485. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  140486. #endif
  140487. #if SQLITE_MAX_VDBE_OP<40
  140488. # error SQLITE_MAX_VDBE_OP must be at least 40
  140489. #endif
  140490. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  140491. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  140492. #endif
  140493. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  140494. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  140495. #endif
  140496. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  140497. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  140498. #endif
  140499. #if SQLITE_MAX_COLUMN>32767
  140500. # error SQLITE_MAX_COLUMN must not exceed 32767
  140501. #endif
  140502. #if SQLITE_MAX_TRIGGER_DEPTH<1
  140503. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  140504. #endif
  140505. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  140506. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  140507. #endif
  140508. /*
  140509. ** Change the value of a limit. Report the old value.
  140510. ** If an invalid limit index is supplied, report -1.
  140511. ** Make no changes but still report the old value if the
  140512. ** new limit is negative.
  140513. **
  140514. ** A new lower limit does not shrink existing constructs.
  140515. ** It merely prevents new constructs that exceed the limit
  140516. ** from forming.
  140517. */
  140518. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  140519. int oldLimit;
  140520. #ifdef SQLITE_ENABLE_API_ARMOR
  140521. if( !sqlite3SafetyCheckOk(db) ){
  140522. (void)SQLITE_MISUSE_BKPT;
  140523. return -1;
  140524. }
  140525. #endif
  140526. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  140527. ** there is a hard upper bound set at compile-time by a C preprocessor
  140528. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  140529. ** "_MAX_".)
  140530. */
  140531. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  140532. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  140533. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  140534. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  140535. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  140536. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  140537. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  140538. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  140539. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  140540. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  140541. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  140542. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  140543. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  140544. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  140545. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  140546. return -1;
  140547. }
  140548. oldLimit = db->aLimit[limitId];
  140549. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  140550. if( newLimit>aHardLimit[limitId] ){
  140551. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  140552. }
  140553. db->aLimit[limitId] = newLimit;
  140554. }
  140555. return oldLimit; /* IMP: R-53341-35419 */
  140556. }
  140557. /*
  140558. ** This function is used to parse both URIs and non-URI filenames passed by the
  140559. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  140560. ** URIs specified as part of ATTACH statements.
  140561. **
  140562. ** The first argument to this function is the name of the VFS to use (or
  140563. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  140564. ** query parameter. The second argument contains the URI (or non-URI filename)
  140565. ** itself. When this function is called the *pFlags variable should contain
  140566. ** the default flags to open the database handle with. The value stored in
  140567. ** *pFlags may be updated before returning if the URI filename contains
  140568. ** "cache=xxx" or "mode=xxx" query parameters.
  140569. **
  140570. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  140571. ** the VFS that should be used to open the database file. *pzFile is set to
  140572. ** point to a buffer containing the name of the file to open. It is the
  140573. ** responsibility of the caller to eventually call sqlite3_free() to release
  140574. ** this buffer.
  140575. **
  140576. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  140577. ** may be set to point to a buffer containing an English language error
  140578. ** message. It is the responsibility of the caller to eventually release
  140579. ** this buffer by calling sqlite3_free().
  140580. */
  140581. SQLITE_PRIVATE int sqlite3ParseUri(
  140582. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  140583. const char *zUri, /* Nul-terminated URI to parse */
  140584. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  140585. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  140586. char **pzFile, /* OUT: Filename component of URI */
  140587. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  140588. ){
  140589. int rc = SQLITE_OK;
  140590. unsigned int flags = *pFlags;
  140591. const char *zVfs = zDefaultVfs;
  140592. char *zFile;
  140593. char c;
  140594. int nUri = sqlite3Strlen30(zUri);
  140595. assert( *pzErrMsg==0 );
  140596. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  140597. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  140598. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  140599. ){
  140600. char *zOpt;
  140601. int eState; /* Parser state when parsing URI */
  140602. int iIn; /* Input character index */
  140603. int iOut = 0; /* Output character index */
  140604. u64 nByte = nUri+2; /* Bytes of space to allocate */
  140605. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  140606. ** method that there may be extra parameters following the file-name. */
  140607. flags |= SQLITE_OPEN_URI;
  140608. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  140609. zFile = sqlite3_malloc64(nByte);
  140610. if( !zFile ) return SQLITE_NOMEM_BKPT;
  140611. iIn = 5;
  140612. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  140613. if( strncmp(zUri+5, "///", 3)==0 ){
  140614. iIn = 7;
  140615. /* The following condition causes URIs with five leading / characters
  140616. ** like file://///host/path to be converted into UNCs like //host/path.
  140617. ** The correct URI for that UNC has only two or four leading / characters
  140618. ** file://host/path or file:////host/path. But 5 leading slashes is a
  140619. ** common error, we are told, so we handle it as a special case. */
  140620. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  140621. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  140622. iIn = 16;
  140623. }
  140624. #else
  140625. /* Discard the scheme and authority segments of the URI. */
  140626. if( zUri[5]=='/' && zUri[6]=='/' ){
  140627. iIn = 7;
  140628. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  140629. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  140630. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  140631. iIn-7, &zUri[7]);
  140632. rc = SQLITE_ERROR;
  140633. goto parse_uri_out;
  140634. }
  140635. }
  140636. #endif
  140637. /* Copy the filename and any query parameters into the zFile buffer.
  140638. ** Decode %HH escape codes along the way.
  140639. **
  140640. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  140641. ** on the parsing context. As follows:
  140642. **
  140643. ** 0: Parsing file-name.
  140644. ** 1: Parsing name section of a name=value query parameter.
  140645. ** 2: Parsing value section of a name=value query parameter.
  140646. */
  140647. eState = 0;
  140648. while( (c = zUri[iIn])!=0 && c!='#' ){
  140649. iIn++;
  140650. if( c=='%'
  140651. && sqlite3Isxdigit(zUri[iIn])
  140652. && sqlite3Isxdigit(zUri[iIn+1])
  140653. ){
  140654. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  140655. octet += sqlite3HexToInt(zUri[iIn++]);
  140656. assert( octet>=0 && octet<256 );
  140657. if( octet==0 ){
  140658. #ifndef SQLITE_ENABLE_URI_00_ERROR
  140659. /* This branch is taken when "%00" appears within the URI. In this
  140660. ** case we ignore all text in the remainder of the path, name or
  140661. ** value currently being parsed. So ignore the current character
  140662. ** and skip to the next "?", "=" or "&", as appropriate. */
  140663. while( (c = zUri[iIn])!=0 && c!='#'
  140664. && (eState!=0 || c!='?')
  140665. && (eState!=1 || (c!='=' && c!='&'))
  140666. && (eState!=2 || c!='&')
  140667. ){
  140668. iIn++;
  140669. }
  140670. continue;
  140671. #else
  140672. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  140673. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  140674. rc = SQLITE_ERROR;
  140675. goto parse_uri_out;
  140676. #endif
  140677. }
  140678. c = octet;
  140679. }else if( eState==1 && (c=='&' || c=='=') ){
  140680. if( zFile[iOut-1]==0 ){
  140681. /* An empty option name. Ignore this option altogether. */
  140682. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  140683. continue;
  140684. }
  140685. if( c=='&' ){
  140686. zFile[iOut++] = '\0';
  140687. }else{
  140688. eState = 2;
  140689. }
  140690. c = 0;
  140691. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  140692. c = 0;
  140693. eState = 1;
  140694. }
  140695. zFile[iOut++] = c;
  140696. }
  140697. if( eState==1 ) zFile[iOut++] = '\0';
  140698. zFile[iOut++] = '\0';
  140699. zFile[iOut++] = '\0';
  140700. /* Check if there were any options specified that should be interpreted
  140701. ** here. Options that are interpreted here include "vfs" and those that
  140702. ** correspond to flags that may be passed to the sqlite3_open_v2()
  140703. ** method. */
  140704. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  140705. while( zOpt[0] ){
  140706. int nOpt = sqlite3Strlen30(zOpt);
  140707. char *zVal = &zOpt[nOpt+1];
  140708. int nVal = sqlite3Strlen30(zVal);
  140709. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  140710. zVfs = zVal;
  140711. }else{
  140712. struct OpenMode {
  140713. const char *z;
  140714. int mode;
  140715. } *aMode = 0;
  140716. char *zModeType = 0;
  140717. int mask = 0;
  140718. int limit = 0;
  140719. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  140720. static struct OpenMode aCacheMode[] = {
  140721. { "shared", SQLITE_OPEN_SHAREDCACHE },
  140722. { "private", SQLITE_OPEN_PRIVATECACHE },
  140723. { 0, 0 }
  140724. };
  140725. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  140726. aMode = aCacheMode;
  140727. limit = mask;
  140728. zModeType = "cache";
  140729. }
  140730. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  140731. static struct OpenMode aOpenMode[] = {
  140732. { "ro", SQLITE_OPEN_READONLY },
  140733. { "rw", SQLITE_OPEN_READWRITE },
  140734. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  140735. { "memory", SQLITE_OPEN_MEMORY },
  140736. { 0, 0 }
  140737. };
  140738. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  140739. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  140740. aMode = aOpenMode;
  140741. limit = mask & flags;
  140742. zModeType = "access";
  140743. }
  140744. if( aMode ){
  140745. int i;
  140746. int mode = 0;
  140747. for(i=0; aMode[i].z; i++){
  140748. const char *z = aMode[i].z;
  140749. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  140750. mode = aMode[i].mode;
  140751. break;
  140752. }
  140753. }
  140754. if( mode==0 ){
  140755. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  140756. rc = SQLITE_ERROR;
  140757. goto parse_uri_out;
  140758. }
  140759. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  140760. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  140761. zModeType, zVal);
  140762. rc = SQLITE_PERM;
  140763. goto parse_uri_out;
  140764. }
  140765. flags = (flags & ~mask) | mode;
  140766. }
  140767. }
  140768. zOpt = &zVal[nVal+1];
  140769. }
  140770. }else{
  140771. zFile = sqlite3_malloc64(nUri+2);
  140772. if( !zFile ) return SQLITE_NOMEM_BKPT;
  140773. if( nUri ){
  140774. memcpy(zFile, zUri, nUri);
  140775. }
  140776. zFile[nUri] = '\0';
  140777. zFile[nUri+1] = '\0';
  140778. flags &= ~SQLITE_OPEN_URI;
  140779. }
  140780. *ppVfs = sqlite3_vfs_find(zVfs);
  140781. if( *ppVfs==0 ){
  140782. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  140783. rc = SQLITE_ERROR;
  140784. }
  140785. parse_uri_out:
  140786. if( rc!=SQLITE_OK ){
  140787. sqlite3_free(zFile);
  140788. zFile = 0;
  140789. }
  140790. *pFlags = flags;
  140791. *pzFile = zFile;
  140792. return rc;
  140793. }
  140794. /*
  140795. ** This routine does the work of opening a database on behalf of
  140796. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  140797. ** is UTF-8 encoded.
  140798. */
  140799. static int openDatabase(
  140800. const char *zFilename, /* Database filename UTF-8 encoded */
  140801. sqlite3 **ppDb, /* OUT: Returned database handle */
  140802. unsigned int flags, /* Operational flags */
  140803. const char *zVfs /* Name of the VFS to use */
  140804. ){
  140805. sqlite3 *db; /* Store allocated handle here */
  140806. int rc; /* Return code */
  140807. int isThreadsafe; /* True for threadsafe connections */
  140808. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  140809. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  140810. #ifdef SQLITE_ENABLE_API_ARMOR
  140811. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  140812. #endif
  140813. *ppDb = 0;
  140814. #ifndef SQLITE_OMIT_AUTOINIT
  140815. rc = sqlite3_initialize();
  140816. if( rc ) return rc;
  140817. #endif
  140818. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  140819. isThreadsafe = 0;
  140820. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  140821. isThreadsafe = 0;
  140822. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  140823. isThreadsafe = 1;
  140824. }else{
  140825. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  140826. }
  140827. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  140828. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  140829. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  140830. flags |= SQLITE_OPEN_SHAREDCACHE;
  140831. }
  140832. /* Remove harmful bits from the flags parameter
  140833. **
  140834. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  140835. ** dealt with in the previous code block. Besides these, the only
  140836. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  140837. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  140838. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  140839. ** off all other flags.
  140840. */
  140841. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  140842. SQLITE_OPEN_EXCLUSIVE |
  140843. SQLITE_OPEN_MAIN_DB |
  140844. SQLITE_OPEN_TEMP_DB |
  140845. SQLITE_OPEN_TRANSIENT_DB |
  140846. SQLITE_OPEN_MAIN_JOURNAL |
  140847. SQLITE_OPEN_TEMP_JOURNAL |
  140848. SQLITE_OPEN_SUBJOURNAL |
  140849. SQLITE_OPEN_MASTER_JOURNAL |
  140850. SQLITE_OPEN_NOMUTEX |
  140851. SQLITE_OPEN_FULLMUTEX |
  140852. SQLITE_OPEN_WAL
  140853. );
  140854. /* Allocate the sqlite data structure */
  140855. db = sqlite3MallocZero( sizeof(sqlite3) );
  140856. if( db==0 ) goto opendb_out;
  140857. if( isThreadsafe
  140858. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  140859. || sqlite3GlobalConfig.bCoreMutex
  140860. #endif
  140861. ){
  140862. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  140863. if( db->mutex==0 ){
  140864. sqlite3_free(db);
  140865. db = 0;
  140866. goto opendb_out;
  140867. }
  140868. if( isThreadsafe==0 ){
  140869. sqlite3MutexWarnOnContention(db->mutex);
  140870. }
  140871. }
  140872. sqlite3_mutex_enter(db->mutex);
  140873. db->errMask = 0xff;
  140874. db->nDb = 2;
  140875. db->magic = SQLITE_MAGIC_BUSY;
  140876. db->aDb = db->aDbStatic;
  140877. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  140878. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  140879. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  140880. db->autoCommit = 1;
  140881. db->nextAutovac = -1;
  140882. db->szMmap = sqlite3GlobalConfig.szMmap;
  140883. db->nextPagesize = 0;
  140884. db->nMaxSorterMmap = 0x7FFFFFFF;
  140885. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  140886. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  140887. | SQLITE_AutoIndex
  140888. #endif
  140889. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  140890. | SQLITE_CkptFullFSync
  140891. #endif
  140892. #if SQLITE_DEFAULT_FILE_FORMAT<4
  140893. | SQLITE_LegacyFileFmt
  140894. #endif
  140895. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  140896. | SQLITE_LoadExtension
  140897. #endif
  140898. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  140899. | SQLITE_RecTriggers
  140900. #endif
  140901. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  140902. | SQLITE_ForeignKeys
  140903. #endif
  140904. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  140905. | SQLITE_ReverseOrder
  140906. #endif
  140907. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  140908. | SQLITE_CellSizeCk
  140909. #endif
  140910. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  140911. | SQLITE_Fts3Tokenizer
  140912. #endif
  140913. #if defined(SQLITE_ENABLE_QPSG)
  140914. | SQLITE_EnableQPSG
  140915. #endif
  140916. ;
  140917. sqlite3HashInit(&db->aCollSeq);
  140918. #ifndef SQLITE_OMIT_VIRTUALTABLE
  140919. sqlite3HashInit(&db->aModule);
  140920. #endif
  140921. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  140922. ** and UTF-16, so add a version for each to avoid any unnecessary
  140923. ** conversions. The only error that can occur here is a malloc() failure.
  140924. **
  140925. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  140926. ** functions:
  140927. */
  140928. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  140929. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  140930. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  140931. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  140932. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  140933. if( db->mallocFailed ){
  140934. goto opendb_out;
  140935. }
  140936. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  140937. ** strings is BINARY.
  140938. */
  140939. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  140940. assert( db->pDfltColl!=0 );
  140941. /* Parse the filename/URI argument
  140942. **
  140943. ** Only allow sensible combinations of bits in the flags argument.
  140944. ** Throw an error if any non-sense combination is used. If we
  140945. ** do not block illegal combinations here, it could trigger
  140946. ** assert() statements in deeper layers. Sensible combinations
  140947. ** are:
  140948. **
  140949. ** 1: SQLITE_OPEN_READONLY
  140950. ** 2: SQLITE_OPEN_READWRITE
  140951. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  140952. */
  140953. db->openFlags = flags;
  140954. assert( SQLITE_OPEN_READONLY == 0x01 );
  140955. assert( SQLITE_OPEN_READWRITE == 0x02 );
  140956. assert( SQLITE_OPEN_CREATE == 0x04 );
  140957. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  140958. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  140959. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  140960. if( ((1<<(flags&7)) & 0x46)==0 ){
  140961. rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  140962. }else{
  140963. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  140964. }
  140965. if( rc!=SQLITE_OK ){
  140966. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  140967. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  140968. sqlite3_free(zErrMsg);
  140969. goto opendb_out;
  140970. }
  140971. /* Open the backend database driver */
  140972. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  140973. flags | SQLITE_OPEN_MAIN_DB);
  140974. if( rc!=SQLITE_OK ){
  140975. if( rc==SQLITE_IOERR_NOMEM ){
  140976. rc = SQLITE_NOMEM_BKPT;
  140977. }
  140978. sqlite3Error(db, rc);
  140979. goto opendb_out;
  140980. }
  140981. sqlite3BtreeEnter(db->aDb[0].pBt);
  140982. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  140983. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  140984. sqlite3BtreeLeave(db->aDb[0].pBt);
  140985. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  140986. /* The default safety_level for the main database is FULL; for the temp
  140987. ** database it is OFF. This matches the pager layer defaults.
  140988. */
  140989. db->aDb[0].zDbSName = "main";
  140990. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  140991. db->aDb[1].zDbSName = "temp";
  140992. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  140993. db->magic = SQLITE_MAGIC_OPEN;
  140994. if( db->mallocFailed ){
  140995. goto opendb_out;
  140996. }
  140997. /* Register all built-in functions, but do not attempt to read the
  140998. ** database schema yet. This is delayed until the first time the database
  140999. ** is accessed.
  141000. */
  141001. sqlite3Error(db, SQLITE_OK);
  141002. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  141003. rc = sqlite3_errcode(db);
  141004. #ifdef SQLITE_ENABLE_FTS5
  141005. /* Register any built-in FTS5 module before loading the automatic
  141006. ** extensions. This allows automatic extensions to register FTS5
  141007. ** tokenizers and auxiliary functions. */
  141008. if( !db->mallocFailed && rc==SQLITE_OK ){
  141009. rc = sqlite3Fts5Init(db);
  141010. }
  141011. #endif
  141012. /* Load automatic extensions - extensions that have been registered
  141013. ** using the sqlite3_automatic_extension() API.
  141014. */
  141015. if( rc==SQLITE_OK ){
  141016. sqlite3AutoLoadExtensions(db);
  141017. rc = sqlite3_errcode(db);
  141018. if( rc!=SQLITE_OK ){
  141019. goto opendb_out;
  141020. }
  141021. }
  141022. #ifdef SQLITE_ENABLE_FTS1
  141023. if( !db->mallocFailed ){
  141024. extern int sqlite3Fts1Init(sqlite3*);
  141025. rc = sqlite3Fts1Init(db);
  141026. }
  141027. #endif
  141028. #ifdef SQLITE_ENABLE_FTS2
  141029. if( !db->mallocFailed && rc==SQLITE_OK ){
  141030. extern int sqlite3Fts2Init(sqlite3*);
  141031. rc = sqlite3Fts2Init(db);
  141032. }
  141033. #endif
  141034. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  141035. if( !db->mallocFailed && rc==SQLITE_OK ){
  141036. rc = sqlite3Fts3Init(db);
  141037. }
  141038. #endif
  141039. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  141040. if( !db->mallocFailed && rc==SQLITE_OK ){
  141041. rc = sqlite3IcuInit(db);
  141042. }
  141043. #endif
  141044. #ifdef SQLITE_ENABLE_RTREE
  141045. if( !db->mallocFailed && rc==SQLITE_OK){
  141046. rc = sqlite3RtreeInit(db);
  141047. }
  141048. #endif
  141049. #ifdef SQLITE_ENABLE_DBPAGE_VTAB
  141050. if( !db->mallocFailed && rc==SQLITE_OK){
  141051. rc = sqlite3DbpageRegister(db);
  141052. }
  141053. #endif
  141054. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  141055. if( !db->mallocFailed && rc==SQLITE_OK){
  141056. rc = sqlite3DbstatRegister(db);
  141057. }
  141058. #endif
  141059. #ifdef SQLITE_ENABLE_JSON1
  141060. if( !db->mallocFailed && rc==SQLITE_OK){
  141061. rc = sqlite3Json1Init(db);
  141062. }
  141063. #endif
  141064. #ifdef SQLITE_ENABLE_STMTVTAB
  141065. if( !db->mallocFailed && rc==SQLITE_OK){
  141066. rc = sqlite3StmtVtabInit(db);
  141067. }
  141068. #endif
  141069. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  141070. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  141071. ** mode. Doing nothing at all also makes NORMAL the default.
  141072. */
  141073. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  141074. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  141075. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  141076. SQLITE_DEFAULT_LOCKING_MODE);
  141077. #endif
  141078. if( rc ) sqlite3Error(db, rc);
  141079. /* Enable the lookaside-malloc subsystem */
  141080. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  141081. sqlite3GlobalConfig.nLookaside);
  141082. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  141083. opendb_out:
  141084. if( db ){
  141085. assert( db->mutex!=0 || isThreadsafe==0
  141086. || sqlite3GlobalConfig.bFullMutex==0 );
  141087. sqlite3_mutex_leave(db->mutex);
  141088. }
  141089. rc = sqlite3_errcode(db);
  141090. assert( db!=0 || rc==SQLITE_NOMEM );
  141091. if( rc==SQLITE_NOMEM ){
  141092. sqlite3_close(db);
  141093. db = 0;
  141094. }else if( rc!=SQLITE_OK ){
  141095. db->magic = SQLITE_MAGIC_SICK;
  141096. }
  141097. *ppDb = db;
  141098. #ifdef SQLITE_ENABLE_SQLLOG
  141099. if( sqlite3GlobalConfig.xSqllog ){
  141100. /* Opening a db handle. Fourth parameter is passed 0. */
  141101. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  141102. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  141103. }
  141104. #endif
  141105. #if defined(SQLITE_HAS_CODEC)
  141106. if( rc==SQLITE_OK ){
  141107. const char *zKey;
  141108. if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
  141109. u8 iByte;
  141110. int i;
  141111. char zDecoded[40];
  141112. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  141113. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  141114. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  141115. }
  141116. sqlite3_key_v2(db, 0, zDecoded, i/2);
  141117. }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
  141118. sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
  141119. }
  141120. }
  141121. #endif
  141122. sqlite3_free(zOpen);
  141123. return rc & 0xff;
  141124. }
  141125. /*
  141126. ** Open a new database handle.
  141127. */
  141128. SQLITE_API int sqlite3_open(
  141129. const char *zFilename,
  141130. sqlite3 **ppDb
  141131. ){
  141132. return openDatabase(zFilename, ppDb,
  141133. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  141134. }
  141135. SQLITE_API int sqlite3_open_v2(
  141136. const char *filename, /* Database filename (UTF-8) */
  141137. sqlite3 **ppDb, /* OUT: SQLite db handle */
  141138. int flags, /* Flags */
  141139. const char *zVfs /* Name of VFS module to use */
  141140. ){
  141141. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  141142. }
  141143. #ifndef SQLITE_OMIT_UTF16
  141144. /*
  141145. ** Open a new database handle.
  141146. */
  141147. SQLITE_API int sqlite3_open16(
  141148. const void *zFilename,
  141149. sqlite3 **ppDb
  141150. ){
  141151. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  141152. sqlite3_value *pVal;
  141153. int rc;
  141154. #ifdef SQLITE_ENABLE_API_ARMOR
  141155. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  141156. #endif
  141157. *ppDb = 0;
  141158. #ifndef SQLITE_OMIT_AUTOINIT
  141159. rc = sqlite3_initialize();
  141160. if( rc ) return rc;
  141161. #endif
  141162. if( zFilename==0 ) zFilename = "\000\000";
  141163. pVal = sqlite3ValueNew(0);
  141164. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  141165. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  141166. if( zFilename8 ){
  141167. rc = openDatabase(zFilename8, ppDb,
  141168. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  141169. assert( *ppDb || rc==SQLITE_NOMEM );
  141170. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  141171. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  141172. }
  141173. }else{
  141174. rc = SQLITE_NOMEM_BKPT;
  141175. }
  141176. sqlite3ValueFree(pVal);
  141177. return rc & 0xff;
  141178. }
  141179. #endif /* SQLITE_OMIT_UTF16 */
  141180. /*
  141181. ** Register a new collation sequence with the database handle db.
  141182. */
  141183. SQLITE_API int sqlite3_create_collation(
  141184. sqlite3* db,
  141185. const char *zName,
  141186. int enc,
  141187. void* pCtx,
  141188. int(*xCompare)(void*,int,const void*,int,const void*)
  141189. ){
  141190. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  141191. }
  141192. /*
  141193. ** Register a new collation sequence with the database handle db.
  141194. */
  141195. SQLITE_API int sqlite3_create_collation_v2(
  141196. sqlite3* db,
  141197. const char *zName,
  141198. int enc,
  141199. void* pCtx,
  141200. int(*xCompare)(void*,int,const void*,int,const void*),
  141201. void(*xDel)(void*)
  141202. ){
  141203. int rc;
  141204. #ifdef SQLITE_ENABLE_API_ARMOR
  141205. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  141206. #endif
  141207. sqlite3_mutex_enter(db->mutex);
  141208. assert( !db->mallocFailed );
  141209. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  141210. rc = sqlite3ApiExit(db, rc);
  141211. sqlite3_mutex_leave(db->mutex);
  141212. return rc;
  141213. }
  141214. #ifndef SQLITE_OMIT_UTF16
  141215. /*
  141216. ** Register a new collation sequence with the database handle db.
  141217. */
  141218. SQLITE_API int sqlite3_create_collation16(
  141219. sqlite3* db,
  141220. const void *zName,
  141221. int enc,
  141222. void* pCtx,
  141223. int(*xCompare)(void*,int,const void*,int,const void*)
  141224. ){
  141225. int rc = SQLITE_OK;
  141226. char *zName8;
  141227. #ifdef SQLITE_ENABLE_API_ARMOR
  141228. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  141229. #endif
  141230. sqlite3_mutex_enter(db->mutex);
  141231. assert( !db->mallocFailed );
  141232. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  141233. if( zName8 ){
  141234. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  141235. sqlite3DbFree(db, zName8);
  141236. }
  141237. rc = sqlite3ApiExit(db, rc);
  141238. sqlite3_mutex_leave(db->mutex);
  141239. return rc;
  141240. }
  141241. #endif /* SQLITE_OMIT_UTF16 */
  141242. /*
  141243. ** Register a collation sequence factory callback with the database handle
  141244. ** db. Replace any previously installed collation sequence factory.
  141245. */
  141246. SQLITE_API int sqlite3_collation_needed(
  141247. sqlite3 *db,
  141248. void *pCollNeededArg,
  141249. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  141250. ){
  141251. #ifdef SQLITE_ENABLE_API_ARMOR
  141252. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  141253. #endif
  141254. sqlite3_mutex_enter(db->mutex);
  141255. db->xCollNeeded = xCollNeeded;
  141256. db->xCollNeeded16 = 0;
  141257. db->pCollNeededArg = pCollNeededArg;
  141258. sqlite3_mutex_leave(db->mutex);
  141259. return SQLITE_OK;
  141260. }
  141261. #ifndef SQLITE_OMIT_UTF16
  141262. /*
  141263. ** Register a collation sequence factory callback with the database handle
  141264. ** db. Replace any previously installed collation sequence factory.
  141265. */
  141266. SQLITE_API int sqlite3_collation_needed16(
  141267. sqlite3 *db,
  141268. void *pCollNeededArg,
  141269. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  141270. ){
  141271. #ifdef SQLITE_ENABLE_API_ARMOR
  141272. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  141273. #endif
  141274. sqlite3_mutex_enter(db->mutex);
  141275. db->xCollNeeded = 0;
  141276. db->xCollNeeded16 = xCollNeeded16;
  141277. db->pCollNeededArg = pCollNeededArg;
  141278. sqlite3_mutex_leave(db->mutex);
  141279. return SQLITE_OK;
  141280. }
  141281. #endif /* SQLITE_OMIT_UTF16 */
  141282. #ifndef SQLITE_OMIT_DEPRECATED
  141283. /*
  141284. ** This function is now an anachronism. It used to be used to recover from a
  141285. ** malloc() failure, but SQLite now does this automatically.
  141286. */
  141287. SQLITE_API int sqlite3_global_recover(void){
  141288. return SQLITE_OK;
  141289. }
  141290. #endif
  141291. /*
  141292. ** Test to see whether or not the database connection is in autocommit
  141293. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  141294. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  141295. ** by the next COMMIT or ROLLBACK.
  141296. */
  141297. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  141298. #ifdef SQLITE_ENABLE_API_ARMOR
  141299. if( !sqlite3SafetyCheckOk(db) ){
  141300. (void)SQLITE_MISUSE_BKPT;
  141301. return 0;
  141302. }
  141303. #endif
  141304. return db->autoCommit;
  141305. }
  141306. /*
  141307. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  141308. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  141309. ** constants. They serve two purposes:
  141310. **
  141311. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  141312. ** to detect when version error conditions occurs.
  141313. **
  141314. ** 2. Invoke sqlite3_log() to provide the source code location where
  141315. ** a low-level error is first detected.
  141316. */
  141317. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
  141318. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  141319. zType, lineno, 20+sqlite3_sourceid());
  141320. return iErr;
  141321. }
  141322. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  141323. testcase( sqlite3GlobalConfig.xLog!=0 );
  141324. return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
  141325. }
  141326. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  141327. testcase( sqlite3GlobalConfig.xLog!=0 );
  141328. return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
  141329. }
  141330. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  141331. testcase( sqlite3GlobalConfig.xLog!=0 );
  141332. return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  141333. }
  141334. #ifdef SQLITE_DEBUG
  141335. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
  141336. char zMsg[100];
  141337. sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
  141338. testcase( sqlite3GlobalConfig.xLog!=0 );
  141339. return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  141340. }
  141341. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  141342. testcase( sqlite3GlobalConfig.xLog!=0 );
  141343. return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
  141344. }
  141345. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  141346. testcase( sqlite3GlobalConfig.xLog!=0 );
  141347. return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  141348. }
  141349. #endif
  141350. #ifndef SQLITE_OMIT_DEPRECATED
  141351. /*
  141352. ** This is a convenience routine that makes sure that all thread-specific
  141353. ** data for this thread has been deallocated.
  141354. **
  141355. ** SQLite no longer uses thread-specific data so this routine is now a
  141356. ** no-op. It is retained for historical compatibility.
  141357. */
  141358. SQLITE_API void sqlite3_thread_cleanup(void){
  141359. }
  141360. #endif
  141361. /*
  141362. ** Return meta information about a specific column of a database table.
  141363. ** See comment in sqlite3.h (sqlite.h.in) for details.
  141364. */
  141365. SQLITE_API int sqlite3_table_column_metadata(
  141366. sqlite3 *db, /* Connection handle */
  141367. const char *zDbName, /* Database name or NULL */
  141368. const char *zTableName, /* Table name */
  141369. const char *zColumnName, /* Column name */
  141370. char const **pzDataType, /* OUTPUT: Declared data type */
  141371. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  141372. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  141373. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  141374. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  141375. ){
  141376. int rc;
  141377. char *zErrMsg = 0;
  141378. Table *pTab = 0;
  141379. Column *pCol = 0;
  141380. int iCol = 0;
  141381. char const *zDataType = 0;
  141382. char const *zCollSeq = 0;
  141383. int notnull = 0;
  141384. int primarykey = 0;
  141385. int autoinc = 0;
  141386. #ifdef SQLITE_ENABLE_API_ARMOR
  141387. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  141388. return SQLITE_MISUSE_BKPT;
  141389. }
  141390. #endif
  141391. /* Ensure the database schema has been loaded */
  141392. sqlite3_mutex_enter(db->mutex);
  141393. sqlite3BtreeEnterAll(db);
  141394. rc = sqlite3Init(db, &zErrMsg);
  141395. if( SQLITE_OK!=rc ){
  141396. goto error_out;
  141397. }
  141398. /* Locate the table in question */
  141399. pTab = sqlite3FindTable(db, zTableName, zDbName);
  141400. if( !pTab || pTab->pSelect ){
  141401. pTab = 0;
  141402. goto error_out;
  141403. }
  141404. /* Find the column for which info is requested */
  141405. if( zColumnName==0 ){
  141406. /* Query for existance of table only */
  141407. }else{
  141408. for(iCol=0; iCol<pTab->nCol; iCol++){
  141409. pCol = &pTab->aCol[iCol];
  141410. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  141411. break;
  141412. }
  141413. }
  141414. if( iCol==pTab->nCol ){
  141415. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  141416. iCol = pTab->iPKey;
  141417. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  141418. }else{
  141419. pTab = 0;
  141420. goto error_out;
  141421. }
  141422. }
  141423. }
  141424. /* The following block stores the meta information that will be returned
  141425. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  141426. ** and autoinc. At this point there are two possibilities:
  141427. **
  141428. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  141429. ** and there is no explicitly declared IPK column.
  141430. **
  141431. ** 2. The table is not a view and the column name identified an
  141432. ** explicitly declared column. Copy meta information from *pCol.
  141433. */
  141434. if( pCol ){
  141435. zDataType = sqlite3ColumnType(pCol,0);
  141436. zCollSeq = pCol->zColl;
  141437. notnull = pCol->notNull!=0;
  141438. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  141439. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  141440. }else{
  141441. zDataType = "INTEGER";
  141442. primarykey = 1;
  141443. }
  141444. if( !zCollSeq ){
  141445. zCollSeq = sqlite3StrBINARY;
  141446. }
  141447. error_out:
  141448. sqlite3BtreeLeaveAll(db);
  141449. /* Whether the function call succeeded or failed, set the output parameters
  141450. ** to whatever their local counterparts contain. If an error did occur,
  141451. ** this has the effect of zeroing all output parameters.
  141452. */
  141453. if( pzDataType ) *pzDataType = zDataType;
  141454. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  141455. if( pNotNull ) *pNotNull = notnull;
  141456. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  141457. if( pAutoinc ) *pAutoinc = autoinc;
  141458. if( SQLITE_OK==rc && !pTab ){
  141459. sqlite3DbFree(db, zErrMsg);
  141460. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  141461. zColumnName);
  141462. rc = SQLITE_ERROR;
  141463. }
  141464. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  141465. sqlite3DbFree(db, zErrMsg);
  141466. rc = sqlite3ApiExit(db, rc);
  141467. sqlite3_mutex_leave(db->mutex);
  141468. return rc;
  141469. }
  141470. /*
  141471. ** Sleep for a little while. Return the amount of time slept.
  141472. */
  141473. SQLITE_API int sqlite3_sleep(int ms){
  141474. sqlite3_vfs *pVfs;
  141475. int rc;
  141476. pVfs = sqlite3_vfs_find(0);
  141477. if( pVfs==0 ) return 0;
  141478. /* This function works in milliseconds, but the underlying OsSleep()
  141479. ** API uses microseconds. Hence the 1000's.
  141480. */
  141481. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  141482. return rc;
  141483. }
  141484. /*
  141485. ** Enable or disable the extended result codes.
  141486. */
  141487. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  141488. #ifdef SQLITE_ENABLE_API_ARMOR
  141489. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  141490. #endif
  141491. sqlite3_mutex_enter(db->mutex);
  141492. db->errMask = onoff ? 0xffffffff : 0xff;
  141493. sqlite3_mutex_leave(db->mutex);
  141494. return SQLITE_OK;
  141495. }
  141496. /*
  141497. ** Invoke the xFileControl method on a particular database.
  141498. */
  141499. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  141500. int rc = SQLITE_ERROR;
  141501. Btree *pBtree;
  141502. #ifdef SQLITE_ENABLE_API_ARMOR
  141503. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  141504. #endif
  141505. sqlite3_mutex_enter(db->mutex);
  141506. pBtree = sqlite3DbNameToBtree(db, zDbName);
  141507. if( pBtree ){
  141508. Pager *pPager;
  141509. sqlite3_file *fd;
  141510. sqlite3BtreeEnter(pBtree);
  141511. pPager = sqlite3BtreePager(pBtree);
  141512. assert( pPager!=0 );
  141513. fd = sqlite3PagerFile(pPager);
  141514. assert( fd!=0 );
  141515. if( op==SQLITE_FCNTL_FILE_POINTER ){
  141516. *(sqlite3_file**)pArg = fd;
  141517. rc = SQLITE_OK;
  141518. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  141519. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  141520. rc = SQLITE_OK;
  141521. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  141522. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  141523. rc = SQLITE_OK;
  141524. }else{
  141525. rc = sqlite3OsFileControl(fd, op, pArg);
  141526. }
  141527. sqlite3BtreeLeave(pBtree);
  141528. }
  141529. sqlite3_mutex_leave(db->mutex);
  141530. return rc;
  141531. }
  141532. /*
  141533. ** Interface to the testing logic.
  141534. */
  141535. SQLITE_API int sqlite3_test_control(int op, ...){
  141536. int rc = 0;
  141537. #ifdef SQLITE_UNTESTABLE
  141538. UNUSED_PARAMETER(op);
  141539. #else
  141540. va_list ap;
  141541. va_start(ap, op);
  141542. switch( op ){
  141543. /*
  141544. ** Save the current state of the PRNG.
  141545. */
  141546. case SQLITE_TESTCTRL_PRNG_SAVE: {
  141547. sqlite3PrngSaveState();
  141548. break;
  141549. }
  141550. /*
  141551. ** Restore the state of the PRNG to the last state saved using
  141552. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  141553. ** this verb acts like PRNG_RESET.
  141554. */
  141555. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  141556. sqlite3PrngRestoreState();
  141557. break;
  141558. }
  141559. /*
  141560. ** Reset the PRNG back to its uninitialized state. The next call
  141561. ** to sqlite3_randomness() will reseed the PRNG using a single call
  141562. ** to the xRandomness method of the default VFS.
  141563. */
  141564. case SQLITE_TESTCTRL_PRNG_RESET: {
  141565. sqlite3_randomness(0,0);
  141566. break;
  141567. }
  141568. /*
  141569. ** sqlite3_test_control(BITVEC_TEST, size, program)
  141570. **
  141571. ** Run a test against a Bitvec object of size. The program argument
  141572. ** is an array of integers that defines the test. Return -1 on a
  141573. ** memory allocation error, 0 on success, or non-zero for an error.
  141574. ** See the sqlite3BitvecBuiltinTest() for additional information.
  141575. */
  141576. case SQLITE_TESTCTRL_BITVEC_TEST: {
  141577. int sz = va_arg(ap, int);
  141578. int *aProg = va_arg(ap, int*);
  141579. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  141580. break;
  141581. }
  141582. /*
  141583. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  141584. **
  141585. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  141586. ** if xCallback is not NULL.
  141587. **
  141588. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  141589. ** is called immediately after installing the new callback and the return
  141590. ** value from sqlite3FaultSim(0) becomes the return from
  141591. ** sqlite3_test_control().
  141592. */
  141593. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  141594. /* MSVC is picky about pulling func ptrs from va lists.
  141595. ** http://support.microsoft.com/kb/47961
  141596. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  141597. */
  141598. typedef int(*TESTCALLBACKFUNC_t)(int);
  141599. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  141600. rc = sqlite3FaultSim(0);
  141601. break;
  141602. }
  141603. /*
  141604. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  141605. **
  141606. ** Register hooks to call to indicate which malloc() failures
  141607. ** are benign.
  141608. */
  141609. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  141610. typedef void (*void_function)(void);
  141611. void_function xBenignBegin;
  141612. void_function xBenignEnd;
  141613. xBenignBegin = va_arg(ap, void_function);
  141614. xBenignEnd = va_arg(ap, void_function);
  141615. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  141616. break;
  141617. }
  141618. /*
  141619. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  141620. **
  141621. ** Set the PENDING byte to the value in the argument, if X>0.
  141622. ** Make no changes if X==0. Return the value of the pending byte
  141623. ** as it existing before this routine was called.
  141624. **
  141625. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  141626. ** an incompatible database file format. Changing the PENDING byte
  141627. ** while any database connection is open results in undefined and
  141628. ** deleterious behavior.
  141629. */
  141630. case SQLITE_TESTCTRL_PENDING_BYTE: {
  141631. rc = PENDING_BYTE;
  141632. #ifndef SQLITE_OMIT_WSD
  141633. {
  141634. unsigned int newVal = va_arg(ap, unsigned int);
  141635. if( newVal ) sqlite3PendingByte = newVal;
  141636. }
  141637. #endif
  141638. break;
  141639. }
  141640. /*
  141641. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  141642. **
  141643. ** This action provides a run-time test to see whether or not
  141644. ** assert() was enabled at compile-time. If X is true and assert()
  141645. ** is enabled, then the return value is true. If X is true and
  141646. ** assert() is disabled, then the return value is zero. If X is
  141647. ** false and assert() is enabled, then the assertion fires and the
  141648. ** process aborts. If X is false and assert() is disabled, then the
  141649. ** return value is zero.
  141650. */
  141651. case SQLITE_TESTCTRL_ASSERT: {
  141652. volatile int x = 0;
  141653. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  141654. rc = x;
  141655. break;
  141656. }
  141657. /*
  141658. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  141659. **
  141660. ** This action provides a run-time test to see how the ALWAYS and
  141661. ** NEVER macros were defined at compile-time.
  141662. **
  141663. ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
  141664. **
  141665. ** The recommended test is X==2. If the return value is 2, that means
  141666. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  141667. ** default setting. If the return value is 1, then ALWAYS() is either
  141668. ** hard-coded to true or else it asserts if its argument is false.
  141669. ** The first behavior (hard-coded to true) is the case if
  141670. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  141671. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  141672. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  141673. **
  141674. ** The run-time test procedure might look something like this:
  141675. **
  141676. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  141677. ** // ALWAYS() and NEVER() are no-op pass-through macros
  141678. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  141679. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  141680. ** }else{
  141681. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  141682. ** }
  141683. */
  141684. case SQLITE_TESTCTRL_ALWAYS: {
  141685. int x = va_arg(ap,int);
  141686. rc = x ? ALWAYS(x) : 0;
  141687. break;
  141688. }
  141689. /*
  141690. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  141691. **
  141692. ** The integer returned reveals the byte-order of the computer on which
  141693. ** SQLite is running:
  141694. **
  141695. ** 1 big-endian, determined at run-time
  141696. ** 10 little-endian, determined at run-time
  141697. ** 432101 big-endian, determined at compile-time
  141698. ** 123410 little-endian, determined at compile-time
  141699. */
  141700. case SQLITE_TESTCTRL_BYTEORDER: {
  141701. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  141702. break;
  141703. }
  141704. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  141705. **
  141706. ** Set the nReserve size to N for the main database on the database
  141707. ** connection db.
  141708. */
  141709. case SQLITE_TESTCTRL_RESERVE: {
  141710. sqlite3 *db = va_arg(ap, sqlite3*);
  141711. int x = va_arg(ap,int);
  141712. sqlite3_mutex_enter(db->mutex);
  141713. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  141714. sqlite3_mutex_leave(db->mutex);
  141715. break;
  141716. }
  141717. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  141718. **
  141719. ** Enable or disable various optimizations for testing purposes. The
  141720. ** argument N is a bitmask of optimizations to be disabled. For normal
  141721. ** operation N should be 0. The idea is that a test program (like the
  141722. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  141723. ** with various optimizations disabled to verify that the same answer
  141724. ** is obtained in every case.
  141725. */
  141726. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  141727. sqlite3 *db = va_arg(ap, sqlite3*);
  141728. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  141729. break;
  141730. }
  141731. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  141732. **
  141733. ** If parameter onoff is non-zero, configure the wrappers so that all
  141734. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  141735. ** undo this setting.
  141736. */
  141737. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  141738. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  141739. break;
  141740. }
  141741. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  141742. **
  141743. ** Set or clear a flag that indicates that the database file is always well-
  141744. ** formed and never corrupt. This flag is clear by default, indicating that
  141745. ** database files might have arbitrary corruption. Setting the flag during
  141746. ** testing causes certain assert() statements in the code to be activated
  141747. ** that demonstrat invariants on well-formed database files.
  141748. */
  141749. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  141750. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  141751. break;
  141752. }
  141753. /* Set the threshold at which OP_Once counters reset back to zero.
  141754. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  141755. ** too big to test in a reasonable amount of time, so this control is
  141756. ** provided to set a small and easily reachable reset value.
  141757. */
  141758. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  141759. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  141760. break;
  141761. }
  141762. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  141763. **
  141764. ** Set the VDBE coverage callback function to xCallback with context
  141765. ** pointer ptr.
  141766. */
  141767. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  141768. #ifdef SQLITE_VDBE_COVERAGE
  141769. typedef void (*branch_callback)(void*,int,u8,u8);
  141770. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  141771. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  141772. #endif
  141773. break;
  141774. }
  141775. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  141776. case SQLITE_TESTCTRL_SORTER_MMAP: {
  141777. sqlite3 *db = va_arg(ap, sqlite3*);
  141778. db->nMaxSorterMmap = va_arg(ap, int);
  141779. break;
  141780. }
  141781. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  141782. **
  141783. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  141784. ** not.
  141785. */
  141786. case SQLITE_TESTCTRL_ISINIT: {
  141787. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  141788. break;
  141789. }
  141790. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  141791. **
  141792. ** This test control is used to create imposter tables. "db" is a pointer
  141793. ** to the database connection. dbName is the database name (ex: "main" or
  141794. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  141795. ** or off. "tnum" is the root page of the b-tree to which the imposter
  141796. ** table should connect.
  141797. **
  141798. ** Enable imposter mode only when the schema has already been parsed. Then
  141799. ** run a single CREATE TABLE statement to construct the imposter table in
  141800. ** the parsed schema. Then turn imposter mode back off again.
  141801. **
  141802. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  141803. ** the schema to be reparsed the next time it is needed. This has the
  141804. ** effect of erasing all imposter tables.
  141805. */
  141806. case SQLITE_TESTCTRL_IMPOSTER: {
  141807. sqlite3 *db = va_arg(ap, sqlite3*);
  141808. sqlite3_mutex_enter(db->mutex);
  141809. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  141810. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  141811. db->init.newTnum = va_arg(ap,int);
  141812. if( db->init.busy==0 && db->init.newTnum>0 ){
  141813. sqlite3ResetAllSchemasOfConnection(db);
  141814. }
  141815. sqlite3_mutex_leave(db->mutex);
  141816. break;
  141817. }
  141818. #if defined(YYCOVERAGE)
  141819. /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
  141820. **
  141821. ** This test control (only available when SQLite is compiled with
  141822. ** -DYYCOVERAGE) writes a report onto "out" that shows all
  141823. ** state/lookahead combinations in the parser state machine
  141824. ** which are never exercised. If any state is missed, make the
  141825. ** return code SQLITE_ERROR.
  141826. */
  141827. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  141828. FILE *out = va_arg(ap, FILE*);
  141829. if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
  141830. break;
  141831. }
  141832. #endif /* defined(YYCOVERAGE) */
  141833. }
  141834. va_end(ap);
  141835. #endif /* SQLITE_UNTESTABLE */
  141836. return rc;
  141837. }
  141838. /*
  141839. ** This is a utility routine, useful to VFS implementations, that checks
  141840. ** to see if a database file was a URI that contained a specific query
  141841. ** parameter, and if so obtains the value of the query parameter.
  141842. **
  141843. ** The zFilename argument is the filename pointer passed into the xOpen()
  141844. ** method of a VFS implementation. The zParam argument is the name of the
  141845. ** query parameter we seek. This routine returns the value of the zParam
  141846. ** parameter if it exists. If the parameter does not exist, this routine
  141847. ** returns a NULL pointer.
  141848. */
  141849. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  141850. if( zFilename==0 || zParam==0 ) return 0;
  141851. zFilename += sqlite3Strlen30(zFilename) + 1;
  141852. while( zFilename[0] ){
  141853. int x = strcmp(zFilename, zParam);
  141854. zFilename += sqlite3Strlen30(zFilename) + 1;
  141855. if( x==0 ) return zFilename;
  141856. zFilename += sqlite3Strlen30(zFilename) + 1;
  141857. }
  141858. return 0;
  141859. }
  141860. /*
  141861. ** Return a boolean value for a query parameter.
  141862. */
  141863. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  141864. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  141865. bDflt = bDflt!=0;
  141866. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  141867. }
  141868. /*
  141869. ** Return a 64-bit integer value for a query parameter.
  141870. */
  141871. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  141872. const char *zFilename, /* Filename as passed to xOpen */
  141873. const char *zParam, /* URI parameter sought */
  141874. sqlite3_int64 bDflt /* return if parameter is missing */
  141875. ){
  141876. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  141877. sqlite3_int64 v;
  141878. if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
  141879. bDflt = v;
  141880. }
  141881. return bDflt;
  141882. }
  141883. /*
  141884. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  141885. */
  141886. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  141887. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  141888. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  141889. }
  141890. /*
  141891. ** Return the filename of the database associated with a database
  141892. ** connection.
  141893. */
  141894. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  141895. Btree *pBt;
  141896. #ifdef SQLITE_ENABLE_API_ARMOR
  141897. if( !sqlite3SafetyCheckOk(db) ){
  141898. (void)SQLITE_MISUSE_BKPT;
  141899. return 0;
  141900. }
  141901. #endif
  141902. pBt = sqlite3DbNameToBtree(db, zDbName);
  141903. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  141904. }
  141905. /*
  141906. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  141907. ** no such database exists.
  141908. */
  141909. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  141910. Btree *pBt;
  141911. #ifdef SQLITE_ENABLE_API_ARMOR
  141912. if( !sqlite3SafetyCheckOk(db) ){
  141913. (void)SQLITE_MISUSE_BKPT;
  141914. return -1;
  141915. }
  141916. #endif
  141917. pBt = sqlite3DbNameToBtree(db, zDbName);
  141918. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  141919. }
  141920. #ifdef SQLITE_ENABLE_SNAPSHOT
  141921. /*
  141922. ** Obtain a snapshot handle for the snapshot of database zDb currently
  141923. ** being read by handle db.
  141924. */
  141925. SQLITE_API int sqlite3_snapshot_get(
  141926. sqlite3 *db,
  141927. const char *zDb,
  141928. sqlite3_snapshot **ppSnapshot
  141929. ){
  141930. int rc = SQLITE_ERROR;
  141931. #ifndef SQLITE_OMIT_WAL
  141932. #ifdef SQLITE_ENABLE_API_ARMOR
  141933. if( !sqlite3SafetyCheckOk(db) ){
  141934. return SQLITE_MISUSE_BKPT;
  141935. }
  141936. #endif
  141937. sqlite3_mutex_enter(db->mutex);
  141938. if( db->autoCommit==0 ){
  141939. int iDb = sqlite3FindDbName(db, zDb);
  141940. if( iDb==0 || iDb>1 ){
  141941. Btree *pBt = db->aDb[iDb].pBt;
  141942. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  141943. rc = sqlite3BtreeBeginTrans(pBt, 0);
  141944. if( rc==SQLITE_OK ){
  141945. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  141946. }
  141947. }
  141948. }
  141949. }
  141950. sqlite3_mutex_leave(db->mutex);
  141951. #endif /* SQLITE_OMIT_WAL */
  141952. return rc;
  141953. }
  141954. /*
  141955. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  141956. */
  141957. SQLITE_API int sqlite3_snapshot_open(
  141958. sqlite3 *db,
  141959. const char *zDb,
  141960. sqlite3_snapshot *pSnapshot
  141961. ){
  141962. int rc = SQLITE_ERROR;
  141963. #ifndef SQLITE_OMIT_WAL
  141964. #ifdef SQLITE_ENABLE_API_ARMOR
  141965. if( !sqlite3SafetyCheckOk(db) ){
  141966. return SQLITE_MISUSE_BKPT;
  141967. }
  141968. #endif
  141969. sqlite3_mutex_enter(db->mutex);
  141970. if( db->autoCommit==0 ){
  141971. int iDb;
  141972. iDb = sqlite3FindDbName(db, zDb);
  141973. if( iDb==0 || iDb>1 ){
  141974. Btree *pBt = db->aDb[iDb].pBt;
  141975. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  141976. rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
  141977. if( rc==SQLITE_OK ){
  141978. rc = sqlite3BtreeBeginTrans(pBt, 0);
  141979. sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
  141980. }
  141981. }
  141982. }
  141983. }
  141984. sqlite3_mutex_leave(db->mutex);
  141985. #endif /* SQLITE_OMIT_WAL */
  141986. return rc;
  141987. }
  141988. /*
  141989. ** Recover as many snapshots as possible from the wal file associated with
  141990. ** schema zDb of database db.
  141991. */
  141992. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  141993. int rc = SQLITE_ERROR;
  141994. int iDb;
  141995. #ifndef SQLITE_OMIT_WAL
  141996. #ifdef SQLITE_ENABLE_API_ARMOR
  141997. if( !sqlite3SafetyCheckOk(db) ){
  141998. return SQLITE_MISUSE_BKPT;
  141999. }
  142000. #endif
  142001. sqlite3_mutex_enter(db->mutex);
  142002. iDb = sqlite3FindDbName(db, zDb);
  142003. if( iDb==0 || iDb>1 ){
  142004. Btree *pBt = db->aDb[iDb].pBt;
  142005. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  142006. rc = sqlite3BtreeBeginTrans(pBt, 0);
  142007. if( rc==SQLITE_OK ){
  142008. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  142009. sqlite3BtreeCommit(pBt);
  142010. }
  142011. }
  142012. }
  142013. sqlite3_mutex_leave(db->mutex);
  142014. #endif /* SQLITE_OMIT_WAL */
  142015. return rc;
  142016. }
  142017. /*
  142018. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  142019. */
  142020. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  142021. sqlite3_free(pSnapshot);
  142022. }
  142023. #endif /* SQLITE_ENABLE_SNAPSHOT */
  142024. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  142025. /*
  142026. ** Given the name of a compile-time option, return true if that option
  142027. ** was used and false if not.
  142028. **
  142029. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  142030. ** is not required for a match.
  142031. */
  142032. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  142033. int i, n;
  142034. int nOpt;
  142035. const char **azCompileOpt;
  142036. #if SQLITE_ENABLE_API_ARMOR
  142037. if( zOptName==0 ){
  142038. (void)SQLITE_MISUSE_BKPT;
  142039. return 0;
  142040. }
  142041. #endif
  142042. azCompileOpt = sqlite3CompileOptions(&nOpt);
  142043. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  142044. n = sqlite3Strlen30(zOptName);
  142045. /* Since nOpt is normally in single digits, a linear search is
  142046. ** adequate. No need for a binary search. */
  142047. for(i=0; i<nOpt; i++){
  142048. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  142049. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  142050. ){
  142051. return 1;
  142052. }
  142053. }
  142054. return 0;
  142055. }
  142056. /*
  142057. ** Return the N-th compile-time option string. If N is out of range,
  142058. ** return a NULL pointer.
  142059. */
  142060. SQLITE_API const char *sqlite3_compileoption_get(int N){
  142061. int nOpt;
  142062. const char **azCompileOpt;
  142063. azCompileOpt = sqlite3CompileOptions(&nOpt);
  142064. if( N>=0 && N<nOpt ){
  142065. return azCompileOpt[N];
  142066. }
  142067. return 0;
  142068. }
  142069. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  142070. /************** End of main.c ************************************************/
  142071. /************** Begin file notify.c ******************************************/
  142072. /*
  142073. ** 2009 March 3
  142074. **
  142075. ** The author disclaims copyright to this source code. In place of
  142076. ** a legal notice, here is a blessing:
  142077. **
  142078. ** May you do good and not evil.
  142079. ** May you find forgiveness for yourself and forgive others.
  142080. ** May you share freely, never taking more than you give.
  142081. **
  142082. *************************************************************************
  142083. **
  142084. ** This file contains the implementation of the sqlite3_unlock_notify()
  142085. ** API method and its associated functionality.
  142086. */
  142087. /* #include "sqliteInt.h" */
  142088. /* #include "btreeInt.h" */
  142089. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  142090. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  142091. /*
  142092. ** Public interfaces:
  142093. **
  142094. ** sqlite3ConnectionBlocked()
  142095. ** sqlite3ConnectionUnlocked()
  142096. ** sqlite3ConnectionClosed()
  142097. ** sqlite3_unlock_notify()
  142098. */
  142099. #define assertMutexHeld() \
  142100. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  142101. /*
  142102. ** Head of a linked list of all sqlite3 objects created by this process
  142103. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  142104. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  142105. ** mutex is held.
  142106. */
  142107. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  142108. #ifndef NDEBUG
  142109. /*
  142110. ** This function is a complex assert() that verifies the following
  142111. ** properties of the blocked connections list:
  142112. **
  142113. ** 1) Each entry in the list has a non-NULL value for either
  142114. ** pUnlockConnection or pBlockingConnection, or both.
  142115. **
  142116. ** 2) All entries in the list that share a common value for
  142117. ** xUnlockNotify are grouped together.
  142118. **
  142119. ** 3) If the argument db is not NULL, then none of the entries in the
  142120. ** blocked connections list have pUnlockConnection or pBlockingConnection
  142121. ** set to db. This is used when closing connection db.
  142122. */
  142123. static void checkListProperties(sqlite3 *db){
  142124. sqlite3 *p;
  142125. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  142126. int seen = 0;
  142127. sqlite3 *p2;
  142128. /* Verify property (1) */
  142129. assert( p->pUnlockConnection || p->pBlockingConnection );
  142130. /* Verify property (2) */
  142131. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  142132. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  142133. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  142134. assert( db==0 || p->pUnlockConnection!=db );
  142135. assert( db==0 || p->pBlockingConnection!=db );
  142136. }
  142137. }
  142138. }
  142139. #else
  142140. # define checkListProperties(x)
  142141. #endif
  142142. /*
  142143. ** Remove connection db from the blocked connections list. If connection
  142144. ** db is not currently a part of the list, this function is a no-op.
  142145. */
  142146. static void removeFromBlockedList(sqlite3 *db){
  142147. sqlite3 **pp;
  142148. assertMutexHeld();
  142149. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  142150. if( *pp==db ){
  142151. *pp = (*pp)->pNextBlocked;
  142152. break;
  142153. }
  142154. }
  142155. }
  142156. /*
  142157. ** Add connection db to the blocked connections list. It is assumed
  142158. ** that it is not already a part of the list.
  142159. */
  142160. static void addToBlockedList(sqlite3 *db){
  142161. sqlite3 **pp;
  142162. assertMutexHeld();
  142163. for(
  142164. pp=&sqlite3BlockedList;
  142165. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  142166. pp=&(*pp)->pNextBlocked
  142167. );
  142168. db->pNextBlocked = *pp;
  142169. *pp = db;
  142170. }
  142171. /*
  142172. ** Obtain the STATIC_MASTER mutex.
  142173. */
  142174. static void enterMutex(void){
  142175. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  142176. checkListProperties(0);
  142177. }
  142178. /*
  142179. ** Release the STATIC_MASTER mutex.
  142180. */
  142181. static void leaveMutex(void){
  142182. assertMutexHeld();
  142183. checkListProperties(0);
  142184. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  142185. }
  142186. /*
  142187. ** Register an unlock-notify callback.
  142188. **
  142189. ** This is called after connection "db" has attempted some operation
  142190. ** but has received an SQLITE_LOCKED error because another connection
  142191. ** (call it pOther) in the same process was busy using the same shared
  142192. ** cache. pOther is found by looking at db->pBlockingConnection.
  142193. **
  142194. ** If there is no blocking connection, the callback is invoked immediately,
  142195. ** before this routine returns.
  142196. **
  142197. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  142198. ** a deadlock.
  142199. **
  142200. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  142201. ** its locks.
  142202. **
  142203. ** Each call to this routine overrides any prior callbacks registered
  142204. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  142205. ** cancelled.
  142206. */
  142207. SQLITE_API int sqlite3_unlock_notify(
  142208. sqlite3 *db,
  142209. void (*xNotify)(void **, int),
  142210. void *pArg
  142211. ){
  142212. int rc = SQLITE_OK;
  142213. sqlite3_mutex_enter(db->mutex);
  142214. enterMutex();
  142215. if( xNotify==0 ){
  142216. removeFromBlockedList(db);
  142217. db->pBlockingConnection = 0;
  142218. db->pUnlockConnection = 0;
  142219. db->xUnlockNotify = 0;
  142220. db->pUnlockArg = 0;
  142221. }else if( 0==db->pBlockingConnection ){
  142222. /* The blocking transaction has been concluded. Or there never was a
  142223. ** blocking transaction. In either case, invoke the notify callback
  142224. ** immediately.
  142225. */
  142226. xNotify(&pArg, 1);
  142227. }else{
  142228. sqlite3 *p;
  142229. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  142230. if( p ){
  142231. rc = SQLITE_LOCKED; /* Deadlock detected. */
  142232. }else{
  142233. db->pUnlockConnection = db->pBlockingConnection;
  142234. db->xUnlockNotify = xNotify;
  142235. db->pUnlockArg = pArg;
  142236. removeFromBlockedList(db);
  142237. addToBlockedList(db);
  142238. }
  142239. }
  142240. leaveMutex();
  142241. assert( !db->mallocFailed );
  142242. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  142243. sqlite3_mutex_leave(db->mutex);
  142244. return rc;
  142245. }
  142246. /*
  142247. ** This function is called while stepping or preparing a statement
  142248. ** associated with connection db. The operation will return SQLITE_LOCKED
  142249. ** to the user because it requires a lock that will not be available
  142250. ** until connection pBlocker concludes its current transaction.
  142251. */
  142252. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  142253. enterMutex();
  142254. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  142255. addToBlockedList(db);
  142256. }
  142257. db->pBlockingConnection = pBlocker;
  142258. leaveMutex();
  142259. }
  142260. /*
  142261. ** This function is called when
  142262. ** the transaction opened by database db has just finished. Locks held
  142263. ** by database connection db have been released.
  142264. **
  142265. ** This function loops through each entry in the blocked connections
  142266. ** list and does the following:
  142267. **
  142268. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  142269. ** set to db, then set pBlockingConnection=0.
  142270. **
  142271. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  142272. ** set to db, then invoke the configured unlock-notify callback and
  142273. ** set pUnlockConnection=0.
  142274. **
  142275. ** 3) If the two steps above mean that pBlockingConnection==0 and
  142276. ** pUnlockConnection==0, remove the entry from the blocked connections
  142277. ** list.
  142278. */
  142279. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  142280. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  142281. int nArg = 0; /* Number of entries in aArg[] */
  142282. sqlite3 **pp; /* Iterator variable */
  142283. void **aArg; /* Arguments to the unlock callback */
  142284. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  142285. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  142286. aArg = aStatic;
  142287. enterMutex(); /* Enter STATIC_MASTER mutex */
  142288. /* This loop runs once for each entry in the blocked-connections list. */
  142289. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  142290. sqlite3 *p = *pp;
  142291. /* Step 1. */
  142292. if( p->pBlockingConnection==db ){
  142293. p->pBlockingConnection = 0;
  142294. }
  142295. /* Step 2. */
  142296. if( p->pUnlockConnection==db ){
  142297. assert( p->xUnlockNotify );
  142298. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  142299. xUnlockNotify(aArg, nArg);
  142300. nArg = 0;
  142301. }
  142302. sqlite3BeginBenignMalloc();
  142303. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  142304. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  142305. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  142306. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  142307. ){
  142308. /* The aArg[] array needs to grow. */
  142309. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  142310. if( pNew ){
  142311. memcpy(pNew, aArg, nArg*sizeof(void *));
  142312. sqlite3_free(aDyn);
  142313. aDyn = aArg = pNew;
  142314. }else{
  142315. /* This occurs when the array of context pointers that need to
  142316. ** be passed to the unlock-notify callback is larger than the
  142317. ** aStatic[] array allocated on the stack and the attempt to
  142318. ** allocate a larger array from the heap has failed.
  142319. **
  142320. ** This is a difficult situation to handle. Returning an error
  142321. ** code to the caller is insufficient, as even if an error code
  142322. ** is returned the transaction on connection db will still be
  142323. ** closed and the unlock-notify callbacks on blocked connections
  142324. ** will go unissued. This might cause the application to wait
  142325. ** indefinitely for an unlock-notify callback that will never
  142326. ** arrive.
  142327. **
  142328. ** Instead, invoke the unlock-notify callback with the context
  142329. ** array already accumulated. We can then clear the array and
  142330. ** begin accumulating any further context pointers without
  142331. ** requiring any dynamic allocation. This is sub-optimal because
  142332. ** it means that instead of one callback with a large array of
  142333. ** context pointers the application will receive two or more
  142334. ** callbacks with smaller arrays of context pointers, which will
  142335. ** reduce the applications ability to prioritize multiple
  142336. ** connections. But it is the best that can be done under the
  142337. ** circumstances.
  142338. */
  142339. xUnlockNotify(aArg, nArg);
  142340. nArg = 0;
  142341. }
  142342. }
  142343. sqlite3EndBenignMalloc();
  142344. aArg[nArg++] = p->pUnlockArg;
  142345. xUnlockNotify = p->xUnlockNotify;
  142346. p->pUnlockConnection = 0;
  142347. p->xUnlockNotify = 0;
  142348. p->pUnlockArg = 0;
  142349. }
  142350. /* Step 3. */
  142351. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  142352. /* Remove connection p from the blocked connections list. */
  142353. *pp = p->pNextBlocked;
  142354. p->pNextBlocked = 0;
  142355. }else{
  142356. pp = &p->pNextBlocked;
  142357. }
  142358. }
  142359. if( nArg!=0 ){
  142360. xUnlockNotify(aArg, nArg);
  142361. }
  142362. sqlite3_free(aDyn);
  142363. leaveMutex(); /* Leave STATIC_MASTER mutex */
  142364. }
  142365. /*
  142366. ** This is called when the database connection passed as an argument is
  142367. ** being closed. The connection is removed from the blocked list.
  142368. */
  142369. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  142370. sqlite3ConnectionUnlocked(db);
  142371. enterMutex();
  142372. removeFromBlockedList(db);
  142373. checkListProperties(db);
  142374. leaveMutex();
  142375. }
  142376. #endif
  142377. /************** End of notify.c **********************************************/
  142378. /************** Begin file fts3.c ********************************************/
  142379. /*
  142380. ** 2006 Oct 10
  142381. **
  142382. ** The author disclaims copyright to this source code. In place of
  142383. ** a legal notice, here is a blessing:
  142384. **
  142385. ** May you do good and not evil.
  142386. ** May you find forgiveness for yourself and forgive others.
  142387. ** May you share freely, never taking more than you give.
  142388. **
  142389. ******************************************************************************
  142390. **
  142391. ** This is an SQLite module implementing full-text search.
  142392. */
  142393. /*
  142394. ** The code in this file is only compiled if:
  142395. **
  142396. ** * The FTS3 module is being built as an extension
  142397. ** (in which case SQLITE_CORE is not defined), or
  142398. **
  142399. ** * The FTS3 module is being built into the core of
  142400. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  142401. */
  142402. /* The full-text index is stored in a series of b+tree (-like)
  142403. ** structures called segments which map terms to doclists. The
  142404. ** structures are like b+trees in layout, but are constructed from the
  142405. ** bottom up in optimal fashion and are not updatable. Since trees
  142406. ** are built from the bottom up, things will be described from the
  142407. ** bottom up.
  142408. **
  142409. **
  142410. **** Varints ****
  142411. ** The basic unit of encoding is a variable-length integer called a
  142412. ** varint. We encode variable-length integers in little-endian order
  142413. ** using seven bits * per byte as follows:
  142414. **
  142415. ** KEY:
  142416. ** A = 0xxxxxxx 7 bits of data and one flag bit
  142417. ** B = 1xxxxxxx 7 bits of data and one flag bit
  142418. **
  142419. ** 7 bits - A
  142420. ** 14 bits - BA
  142421. ** 21 bits - BBA
  142422. ** and so on.
  142423. **
  142424. ** This is similar in concept to how sqlite encodes "varints" but
  142425. ** the encoding is not the same. SQLite varints are big-endian
  142426. ** are are limited to 9 bytes in length whereas FTS3 varints are
  142427. ** little-endian and can be up to 10 bytes in length (in theory).
  142428. **
  142429. ** Example encodings:
  142430. **
  142431. ** 1: 0x01
  142432. ** 127: 0x7f
  142433. ** 128: 0x81 0x00
  142434. **
  142435. **
  142436. **** Document lists ****
  142437. ** A doclist (document list) holds a docid-sorted list of hits for a
  142438. ** given term. Doclists hold docids and associated token positions.
  142439. ** A docid is the unique integer identifier for a single document.
  142440. ** A position is the index of a word within the document. The first
  142441. ** word of the document has a position of 0.
  142442. **
  142443. ** FTS3 used to optionally store character offsets using a compile-time
  142444. ** option. But that functionality is no longer supported.
  142445. **
  142446. ** A doclist is stored like this:
  142447. **
  142448. ** array {
  142449. ** varint docid; (delta from previous doclist)
  142450. ** array { (position list for column 0)
  142451. ** varint position; (2 more than the delta from previous position)
  142452. ** }
  142453. ** array {
  142454. ** varint POS_COLUMN; (marks start of position list for new column)
  142455. ** varint column; (index of new column)
  142456. ** array {
  142457. ** varint position; (2 more than the delta from previous position)
  142458. ** }
  142459. ** }
  142460. ** varint POS_END; (marks end of positions for this document.
  142461. ** }
  142462. **
  142463. ** Here, array { X } means zero or more occurrences of X, adjacent in
  142464. ** memory. A "position" is an index of a token in the token stream
  142465. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  142466. ** in the same logical place as the position element, and act as sentinals
  142467. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  142468. ** The positions numbers are not stored literally but rather as two more
  142469. ** than the difference from the prior position, or the just the position plus
  142470. ** 2 for the first position. Example:
  142471. **
  142472. ** label: A B C D E F G H I J K
  142473. ** value: 123 5 9 1 1 14 35 0 234 72 0
  142474. **
  142475. ** The 123 value is the first docid. For column zero in this document
  142476. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  142477. ** at D signals the start of a new column; the 1 at E indicates that the
  142478. ** new column is column number 1. There are two positions at 12 and 45
  142479. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  142480. ** 234 at I is the delta to next docid (357). It has one position 70
  142481. ** (72-2) and then terminates with the 0 at K.
  142482. **
  142483. ** A "position-list" is the list of positions for multiple columns for
  142484. ** a single docid. A "column-list" is the set of positions for a single
  142485. ** column. Hence, a position-list consists of one or more column-lists,
  142486. ** a document record consists of a docid followed by a position-list and
  142487. ** a doclist consists of one or more document records.
  142488. **
  142489. ** A bare doclist omits the position information, becoming an
  142490. ** array of varint-encoded docids.
  142491. **
  142492. **** Segment leaf nodes ****
  142493. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  142494. ** nodes are written using LeafWriter, and read using LeafReader (to
  142495. ** iterate through a single leaf node's data) and LeavesReader (to
  142496. ** iterate through a segment's entire leaf layer). Leaf nodes have
  142497. ** the format:
  142498. **
  142499. ** varint iHeight; (height from leaf level, always 0)
  142500. ** varint nTerm; (length of first term)
  142501. ** char pTerm[nTerm]; (content of first term)
  142502. ** varint nDoclist; (length of term's associated doclist)
  142503. ** char pDoclist[nDoclist]; (content of doclist)
  142504. ** array {
  142505. ** (further terms are delta-encoded)
  142506. ** varint nPrefix; (length of prefix shared with previous term)
  142507. ** varint nSuffix; (length of unshared suffix)
  142508. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  142509. ** varint nDoclist; (length of term's associated doclist)
  142510. ** char pDoclist[nDoclist]; (content of doclist)
  142511. ** }
  142512. **
  142513. ** Here, array { X } means zero or more occurrences of X, adjacent in
  142514. ** memory.
  142515. **
  142516. ** Leaf nodes are broken into blocks which are stored contiguously in
  142517. ** the %_segments table in sorted order. This means that when the end
  142518. ** of a node is reached, the next term is in the node with the next
  142519. ** greater node id.
  142520. **
  142521. ** New data is spilled to a new leaf node when the current node
  142522. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  142523. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  142524. ** node (a leaf node with a single term and doclist). The goal of
  142525. ** these settings is to pack together groups of small doclists while
  142526. ** making it efficient to directly access large doclists. The
  142527. ** assumption is that large doclists represent terms which are more
  142528. ** likely to be query targets.
  142529. **
  142530. ** TODO(shess) It may be useful for blocking decisions to be more
  142531. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  142532. ** node rather than splitting into 2k and .5k nodes. My intuition is
  142533. ** that this might extend through 2x or 4x the pagesize.
  142534. **
  142535. **
  142536. **** Segment interior nodes ****
  142537. ** Segment interior nodes store blockids for subtree nodes and terms
  142538. ** to describe what data is stored by the each subtree. Interior
  142539. ** nodes are written using InteriorWriter, and read using
  142540. ** InteriorReader. InteriorWriters are created as needed when
  142541. ** SegmentWriter creates new leaf nodes, or when an interior node
  142542. ** itself grows too big and must be split. The format of interior
  142543. ** nodes:
  142544. **
  142545. ** varint iHeight; (height from leaf level, always >0)
  142546. ** varint iBlockid; (block id of node's leftmost subtree)
  142547. ** optional {
  142548. ** varint nTerm; (length of first term)
  142549. ** char pTerm[nTerm]; (content of first term)
  142550. ** array {
  142551. ** (further terms are delta-encoded)
  142552. ** varint nPrefix; (length of shared prefix with previous term)
  142553. ** varint nSuffix; (length of unshared suffix)
  142554. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  142555. ** }
  142556. ** }
  142557. **
  142558. ** Here, optional { X } means an optional element, while array { X }
  142559. ** means zero or more occurrences of X, adjacent in memory.
  142560. **
  142561. ** An interior node encodes n terms separating n+1 subtrees. The
  142562. ** subtree blocks are contiguous, so only the first subtree's blockid
  142563. ** is encoded. The subtree at iBlockid will contain all terms less
  142564. ** than the first term encoded (or all terms if no term is encoded).
  142565. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  142566. ** than pTerm[i+1], the subtree for that term will be rooted at
  142567. ** iBlockid+i. Interior nodes only store enough term data to
  142568. ** distinguish adjacent children (if the rightmost term of the left
  142569. ** child is "something", and the leftmost term of the right child is
  142570. ** "wicked", only "w" is stored).
  142571. **
  142572. ** New data is spilled to a new interior node at the same height when
  142573. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  142574. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  142575. ** interior nodes and making the tree too skinny. The interior nodes
  142576. ** at a given height are naturally tracked by interior nodes at
  142577. ** height+1, and so on.
  142578. **
  142579. **
  142580. **** Segment directory ****
  142581. ** The segment directory in table %_segdir stores meta-information for
  142582. ** merging and deleting segments, and also the root node of the
  142583. ** segment's tree.
  142584. **
  142585. ** The root node is the top node of the segment's tree after encoding
  142586. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  142587. ** This could be either a leaf node or an interior node. If the top
  142588. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  142589. ** and a new root interior node is generated (which should always fit
  142590. ** within ROOT_MAX because it only needs space for 2 varints, the
  142591. ** height and the blockid of the previous root).
  142592. **
  142593. ** The meta-information in the segment directory is:
  142594. ** level - segment level (see below)
  142595. ** idx - index within level
  142596. ** - (level,idx uniquely identify a segment)
  142597. ** start_block - first leaf node
  142598. ** leaves_end_block - last leaf node
  142599. ** end_block - last block (including interior nodes)
  142600. ** root - contents of root node
  142601. **
  142602. ** If the root node is a leaf node, then start_block,
  142603. ** leaves_end_block, and end_block are all 0.
  142604. **
  142605. **
  142606. **** Segment merging ****
  142607. ** To amortize update costs, segments are grouped into levels and
  142608. ** merged in batches. Each increase in level represents exponentially
  142609. ** more documents.
  142610. **
  142611. ** New documents (actually, document updates) are tokenized and
  142612. ** written individually (using LeafWriter) to a level 0 segment, with
  142613. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  142614. ** level 0 segments are merged into a single level 1 segment. Level 1
  142615. ** is populated like level 0, and eventually MERGE_COUNT level 1
  142616. ** segments are merged to a single level 2 segment (representing
  142617. ** MERGE_COUNT^2 updates), and so on.
  142618. **
  142619. ** A segment merge traverses all segments at a given level in
  142620. ** parallel, performing a straightforward sorted merge. Since segment
  142621. ** leaf nodes are written in to the %_segments table in order, this
  142622. ** merge traverses the underlying sqlite disk structures efficiently.
  142623. ** After the merge, all segment blocks from the merged level are
  142624. ** deleted.
  142625. **
  142626. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  142627. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  142628. ** very similar performance numbers to 16 on insertion, though they're
  142629. ** a tiny bit slower (perhaps due to more overhead in merge-time
  142630. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  142631. ** 16, 2 about 66% slower than 16.
  142632. **
  142633. ** At query time, high MERGE_COUNT increases the number of segments
  142634. ** which need to be scanned and merged. For instance, with 100k docs
  142635. ** inserted:
  142636. **
  142637. ** MERGE_COUNT segments
  142638. ** 16 25
  142639. ** 8 12
  142640. ** 4 10
  142641. ** 2 6
  142642. **
  142643. ** This appears to have only a moderate impact on queries for very
  142644. ** frequent terms (which are somewhat dominated by segment merge
  142645. ** costs), and infrequent and non-existent terms still seem to be fast
  142646. ** even with many segments.
  142647. **
  142648. ** TODO(shess) That said, it would be nice to have a better query-side
  142649. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  142650. ** optimizations to things like doclist merging will swing the sweet
  142651. ** spot around.
  142652. **
  142653. **
  142654. **
  142655. **** Handling of deletions and updates ****
  142656. ** Since we're using a segmented structure, with no docid-oriented
  142657. ** index into the term index, we clearly cannot simply update the term
  142658. ** index when a document is deleted or updated. For deletions, we
  142659. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  142660. ** we simply write the new doclist. Segment merges overwrite older
  142661. ** data for a particular docid with newer data, so deletes or updates
  142662. ** will eventually overtake the earlier data and knock it out. The
  142663. ** query logic likewise merges doclists so that newer data knocks out
  142664. ** older data.
  142665. */
  142666. /************** Include fts3Int.h in the middle of fts3.c ********************/
  142667. /************** Begin file fts3Int.h *****************************************/
  142668. /*
  142669. ** 2009 Nov 12
  142670. **
  142671. ** The author disclaims copyright to this source code. In place of
  142672. ** a legal notice, here is a blessing:
  142673. **
  142674. ** May you do good and not evil.
  142675. ** May you find forgiveness for yourself and forgive others.
  142676. ** May you share freely, never taking more than you give.
  142677. **
  142678. ******************************************************************************
  142679. **
  142680. */
  142681. #ifndef _FTSINT_H
  142682. #define _FTSINT_H
  142683. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  142684. # define NDEBUG 1
  142685. #endif
  142686. /* FTS3/FTS4 require virtual tables */
  142687. #ifdef SQLITE_OMIT_VIRTUALTABLE
  142688. # undef SQLITE_ENABLE_FTS3
  142689. # undef SQLITE_ENABLE_FTS4
  142690. #endif
  142691. /*
  142692. ** FTS4 is really an extension for FTS3. It is enabled using the
  142693. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  142694. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  142695. */
  142696. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  142697. # define SQLITE_ENABLE_FTS3
  142698. #endif
  142699. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  142700. /* If not building as part of the core, include sqlite3ext.h. */
  142701. #ifndef SQLITE_CORE
  142702. /* # include "sqlite3ext.h" */
  142703. SQLITE_EXTENSION_INIT3
  142704. #endif
  142705. /* #include "sqlite3.h" */
  142706. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  142707. /************** Begin file fts3_tokenizer.h **********************************/
  142708. /*
  142709. ** 2006 July 10
  142710. **
  142711. ** The author disclaims copyright to this source code.
  142712. **
  142713. *************************************************************************
  142714. ** Defines the interface to tokenizers used by fulltext-search. There
  142715. ** are three basic components:
  142716. **
  142717. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  142718. ** interface functions. This is essentially the class structure for
  142719. ** tokenizers.
  142720. **
  142721. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  142722. ** including customization information defined at creation time.
  142723. **
  142724. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  142725. ** tokens from a particular input.
  142726. */
  142727. #ifndef _FTS3_TOKENIZER_H_
  142728. #define _FTS3_TOKENIZER_H_
  142729. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  142730. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  142731. ** we will need a way to register the API consistently.
  142732. */
  142733. /* #include "sqlite3.h" */
  142734. /*
  142735. ** Structures used by the tokenizer interface. When a new tokenizer
  142736. ** implementation is registered, the caller provides a pointer to
  142737. ** an sqlite3_tokenizer_module containing pointers to the callback
  142738. ** functions that make up an implementation.
  142739. **
  142740. ** When an fts3 table is created, it passes any arguments passed to
  142741. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  142742. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  142743. ** implementation. The xCreate() function in turn returns an
  142744. ** sqlite3_tokenizer structure representing the specific tokenizer to
  142745. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  142746. **
  142747. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  142748. ** method is called. It returns an sqlite3_tokenizer_cursor object
  142749. ** that may be used to tokenize a specific input buffer based on
  142750. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  142751. ** object.
  142752. */
  142753. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  142754. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  142755. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  142756. struct sqlite3_tokenizer_module {
  142757. /*
  142758. ** Structure version. Should always be set to 0 or 1.
  142759. */
  142760. int iVersion;
  142761. /*
  142762. ** Create a new tokenizer. The values in the argv[] array are the
  142763. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  142764. ** TABLE statement that created the fts3 table. For example, if
  142765. ** the following SQL is executed:
  142766. **
  142767. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  142768. **
  142769. ** then argc is set to 2, and the argv[] array contains pointers
  142770. ** to the strings "arg1" and "arg2".
  142771. **
  142772. ** This method should return either SQLITE_OK (0), or an SQLite error
  142773. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  142774. ** to point at the newly created tokenizer structure. The generic
  142775. ** sqlite3_tokenizer.pModule variable should not be initialized by
  142776. ** this callback. The caller will do so.
  142777. */
  142778. int (*xCreate)(
  142779. int argc, /* Size of argv array */
  142780. const char *const*argv, /* Tokenizer argument strings */
  142781. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  142782. );
  142783. /*
  142784. ** Destroy an existing tokenizer. The fts3 module calls this method
  142785. ** exactly once for each successful call to xCreate().
  142786. */
  142787. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  142788. /*
  142789. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  142790. ** is responsible for ensuring that the input buffer remains valid
  142791. ** until the cursor is closed (using the xClose() method).
  142792. */
  142793. int (*xOpen)(
  142794. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  142795. const char *pInput, int nBytes, /* Input buffer */
  142796. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  142797. );
  142798. /*
  142799. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  142800. ** method exactly once for each successful call to xOpen().
  142801. */
  142802. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  142803. /*
  142804. ** Retrieve the next token from the tokenizer cursor pCursor. This
  142805. ** method should either return SQLITE_OK and set the values of the
  142806. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  142807. ** the end of the buffer has been reached, or an SQLite error code.
  142808. **
  142809. ** *ppToken should be set to point at a buffer containing the
  142810. ** normalized version of the token (i.e. after any case-folding and/or
  142811. ** stemming has been performed). *pnBytes should be set to the length
  142812. ** of this buffer in bytes. The input text that generated the token is
  142813. ** identified by the byte offsets returned in *piStartOffset and
  142814. ** *piEndOffset. *piStartOffset should be set to the index of the first
  142815. ** byte of the token in the input buffer. *piEndOffset should be set
  142816. ** to the index of the first byte just past the end of the token in
  142817. ** the input buffer.
  142818. **
  142819. ** The buffer *ppToken is set to point at is managed by the tokenizer
  142820. ** implementation. It is only required to be valid until the next call
  142821. ** to xNext() or xClose().
  142822. */
  142823. /* TODO(shess) current implementation requires pInput to be
  142824. ** nul-terminated. This should either be fixed, or pInput/nBytes
  142825. ** should be converted to zInput.
  142826. */
  142827. int (*xNext)(
  142828. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  142829. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  142830. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  142831. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  142832. int *piPosition /* OUT: Number of tokens returned before this one */
  142833. );
  142834. /***********************************************************************
  142835. ** Methods below this point are only available if iVersion>=1.
  142836. */
  142837. /*
  142838. ** Configure the language id of a tokenizer cursor.
  142839. */
  142840. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  142841. };
  142842. struct sqlite3_tokenizer {
  142843. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  142844. /* Tokenizer implementations will typically add additional fields */
  142845. };
  142846. struct sqlite3_tokenizer_cursor {
  142847. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  142848. /* Tokenizer implementations will typically add additional fields */
  142849. };
  142850. int fts3_global_term_cnt(int iTerm, int iCol);
  142851. int fts3_term_cnt(int iTerm, int iCol);
  142852. #endif /* _FTS3_TOKENIZER_H_ */
  142853. /************** End of fts3_tokenizer.h **************************************/
  142854. /************** Continuing where we left off in fts3Int.h ********************/
  142855. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  142856. /************** Begin file fts3_hash.h ***************************************/
  142857. /*
  142858. ** 2001 September 22
  142859. **
  142860. ** The author disclaims copyright to this source code. In place of
  142861. ** a legal notice, here is a blessing:
  142862. **
  142863. ** May you do good and not evil.
  142864. ** May you find forgiveness for yourself and forgive others.
  142865. ** May you share freely, never taking more than you give.
  142866. **
  142867. *************************************************************************
  142868. ** This is the header file for the generic hash-table implementation
  142869. ** used in SQLite. We've modified it slightly to serve as a standalone
  142870. ** hash table implementation for the full-text indexing module.
  142871. **
  142872. */
  142873. #ifndef _FTS3_HASH_H_
  142874. #define _FTS3_HASH_H_
  142875. /* Forward declarations of structures. */
  142876. typedef struct Fts3Hash Fts3Hash;
  142877. typedef struct Fts3HashElem Fts3HashElem;
  142878. /* A complete hash table is an instance of the following structure.
  142879. ** The internals of this structure are intended to be opaque -- client
  142880. ** code should not attempt to access or modify the fields of this structure
  142881. ** directly. Change this structure only by using the routines below.
  142882. ** However, many of the "procedures" and "functions" for modifying and
  142883. ** accessing this structure are really macros, so we can't really make
  142884. ** this structure opaque.
  142885. */
  142886. struct Fts3Hash {
  142887. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  142888. char copyKey; /* True if copy of key made on insert */
  142889. int count; /* Number of entries in this table */
  142890. Fts3HashElem *first; /* The first element of the array */
  142891. int htsize; /* Number of buckets in the hash table */
  142892. struct _fts3ht { /* the hash table */
  142893. int count; /* Number of entries with this hash */
  142894. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  142895. } *ht;
  142896. };
  142897. /* Each element in the hash table is an instance of the following
  142898. ** structure. All elements are stored on a single doubly-linked list.
  142899. **
  142900. ** Again, this structure is intended to be opaque, but it can't really
  142901. ** be opaque because it is used by macros.
  142902. */
  142903. struct Fts3HashElem {
  142904. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  142905. void *data; /* Data associated with this element */
  142906. void *pKey; int nKey; /* Key associated with this element */
  142907. };
  142908. /*
  142909. ** There are 2 different modes of operation for a hash table:
  142910. **
  142911. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  142912. ** (including the null-terminator, if any). Case
  142913. ** is respected in comparisons.
  142914. **
  142915. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  142916. ** memcmp() is used to compare keys.
  142917. **
  142918. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  142919. */
  142920. #define FTS3_HASH_STRING 1
  142921. #define FTS3_HASH_BINARY 2
  142922. /*
  142923. ** Access routines. To delete, insert a NULL pointer.
  142924. */
  142925. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  142926. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  142927. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  142928. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  142929. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  142930. /*
  142931. ** Shorthand for the functions above
  142932. */
  142933. #define fts3HashInit sqlite3Fts3HashInit
  142934. #define fts3HashInsert sqlite3Fts3HashInsert
  142935. #define fts3HashFind sqlite3Fts3HashFind
  142936. #define fts3HashClear sqlite3Fts3HashClear
  142937. #define fts3HashFindElem sqlite3Fts3HashFindElem
  142938. /*
  142939. ** Macros for looping over all elements of a hash table. The idiom is
  142940. ** like this:
  142941. **
  142942. ** Fts3Hash h;
  142943. ** Fts3HashElem *p;
  142944. ** ...
  142945. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  142946. ** SomeStructure *pData = fts3HashData(p);
  142947. ** // do something with pData
  142948. ** }
  142949. */
  142950. #define fts3HashFirst(H) ((H)->first)
  142951. #define fts3HashNext(E) ((E)->next)
  142952. #define fts3HashData(E) ((E)->data)
  142953. #define fts3HashKey(E) ((E)->pKey)
  142954. #define fts3HashKeysize(E) ((E)->nKey)
  142955. /*
  142956. ** Number of entries in a hash table
  142957. */
  142958. #define fts3HashCount(H) ((H)->count)
  142959. #endif /* _FTS3_HASH_H_ */
  142960. /************** End of fts3_hash.h *******************************************/
  142961. /************** Continuing where we left off in fts3Int.h ********************/
  142962. /*
  142963. ** This constant determines the maximum depth of an FTS expression tree
  142964. ** that the library will create and use. FTS uses recursion to perform
  142965. ** various operations on the query tree, so the disadvantage of a large
  142966. ** limit is that it may allow very large queries to use large amounts
  142967. ** of stack space (perhaps causing a stack overflow).
  142968. */
  142969. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  142970. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  142971. #endif
  142972. /*
  142973. ** This constant controls how often segments are merged. Once there are
  142974. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  142975. ** segment of level N+1.
  142976. */
  142977. #define FTS3_MERGE_COUNT 16
  142978. /*
  142979. ** This is the maximum amount of data (in bytes) to store in the
  142980. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  142981. ** populated as documents are inserted/updated/deleted in a transaction
  142982. ** and used to create a new segment when the transaction is committed.
  142983. ** However if this limit is reached midway through a transaction, a new
  142984. ** segment is created and the hash table cleared immediately.
  142985. */
  142986. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  142987. /*
  142988. ** Macro to return the number of elements in an array. SQLite has a
  142989. ** similar macro called ArraySize(). Use a different name to avoid
  142990. ** a collision when building an amalgamation with built-in FTS3.
  142991. */
  142992. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  142993. #ifndef MIN
  142994. # define MIN(x,y) ((x)<(y)?(x):(y))
  142995. #endif
  142996. #ifndef MAX
  142997. # define MAX(x,y) ((x)>(y)?(x):(y))
  142998. #endif
  142999. /*
  143000. ** Maximum length of a varint encoded integer. The varint format is different
  143001. ** from that used by SQLite, so the maximum length is 10, not 9.
  143002. */
  143003. #define FTS3_VARINT_MAX 10
  143004. /*
  143005. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  143006. ** in the document set and zero or more prefix indexes. All indexes are stored
  143007. ** as one or more b+-trees in the %_segments and %_segdir tables.
  143008. **
  143009. ** It is possible to determine which index a b+-tree belongs to based on the
  143010. ** value stored in the "%_segdir.level" column. Given this value L, the index
  143011. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  143012. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  143013. ** between 1024 and 2047 to index 1, and so on.
  143014. **
  143015. ** It is considered impossible for an index to use more than 1024 levels. In
  143016. ** theory though this may happen, but only after at least
  143017. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  143018. */
  143019. #define FTS3_SEGDIR_MAXLEVEL 1024
  143020. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  143021. /*
  143022. ** The testcase() macro is only used by the amalgamation. If undefined,
  143023. ** make it a no-op.
  143024. */
  143025. #ifndef testcase
  143026. # define testcase(X)
  143027. #endif
  143028. /*
  143029. ** Terminator values for position-lists and column-lists.
  143030. */
  143031. #define POS_COLUMN (1) /* Column-list terminator */
  143032. #define POS_END (0) /* Position-list terminator */
  143033. /*
  143034. ** This section provides definitions to allow the
  143035. ** FTS3 extension to be compiled outside of the
  143036. ** amalgamation.
  143037. */
  143038. #ifndef SQLITE_AMALGAMATION
  143039. /*
  143040. ** Macros indicating that conditional expressions are always true or
  143041. ** false.
  143042. */
  143043. #ifdef SQLITE_COVERAGE_TEST
  143044. # define ALWAYS(x) (1)
  143045. # define NEVER(X) (0)
  143046. #elif defined(SQLITE_DEBUG)
  143047. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  143048. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  143049. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  143050. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  143051. #else
  143052. # define ALWAYS(x) (x)
  143053. # define NEVER(x) (x)
  143054. #endif
  143055. /*
  143056. ** Internal types used by SQLite.
  143057. */
  143058. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  143059. typedef short int i16; /* 2-byte (or larger) signed integer */
  143060. typedef unsigned int u32; /* 4-byte unsigned integer */
  143061. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  143062. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  143063. /*
  143064. ** Macro used to suppress compiler warnings for unused parameters.
  143065. */
  143066. #define UNUSED_PARAMETER(x) (void)(x)
  143067. /*
  143068. ** Activate assert() only if SQLITE_TEST is enabled.
  143069. */
  143070. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  143071. # define NDEBUG 1
  143072. #endif
  143073. /*
  143074. ** The TESTONLY macro is used to enclose variable declarations or
  143075. ** other bits of code that are needed to support the arguments
  143076. ** within testcase() and assert() macros.
  143077. */
  143078. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  143079. # define TESTONLY(X) X
  143080. #else
  143081. # define TESTONLY(X)
  143082. #endif
  143083. #endif /* SQLITE_AMALGAMATION */
  143084. #ifdef SQLITE_DEBUG
  143085. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  143086. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  143087. #else
  143088. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  143089. #endif
  143090. typedef struct Fts3Table Fts3Table;
  143091. typedef struct Fts3Cursor Fts3Cursor;
  143092. typedef struct Fts3Expr Fts3Expr;
  143093. typedef struct Fts3Phrase Fts3Phrase;
  143094. typedef struct Fts3PhraseToken Fts3PhraseToken;
  143095. typedef struct Fts3Doclist Fts3Doclist;
  143096. typedef struct Fts3SegFilter Fts3SegFilter;
  143097. typedef struct Fts3DeferredToken Fts3DeferredToken;
  143098. typedef struct Fts3SegReader Fts3SegReader;
  143099. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  143100. typedef struct MatchinfoBuffer MatchinfoBuffer;
  143101. /*
  143102. ** A connection to a fulltext index is an instance of the following
  143103. ** structure. The xCreate and xConnect methods create an instance
  143104. ** of this structure and xDestroy and xDisconnect free that instance.
  143105. ** All other methods receive a pointer to the structure as one of their
  143106. ** arguments.
  143107. */
  143108. struct Fts3Table {
  143109. sqlite3_vtab base; /* Base class used by SQLite core */
  143110. sqlite3 *db; /* The database connection */
  143111. const char *zDb; /* logical database name */
  143112. const char *zName; /* virtual table name */
  143113. int nColumn; /* number of named columns in virtual table */
  143114. char **azColumn; /* column names. malloced */
  143115. u8 *abNotindexed; /* True for 'notindexed' columns */
  143116. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  143117. char *zContentTbl; /* content=xxx option, or NULL */
  143118. char *zLanguageid; /* languageid=xxx option, or NULL */
  143119. int nAutoincrmerge; /* Value configured by 'automerge' */
  143120. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  143121. /* Precompiled statements used by the implementation. Each of these
  143122. ** statements is run and reset within a single virtual table API call.
  143123. */
  143124. sqlite3_stmt *aStmt[40];
  143125. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  143126. char *zReadExprlist;
  143127. char *zWriteExprlist;
  143128. int nNodeSize; /* Soft limit for node size */
  143129. u8 bFts4; /* True for FTS4, false for FTS3 */
  143130. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  143131. u8 bHasDocsize; /* True if %_docsize table exists */
  143132. u8 bDescIdx; /* True if doclists are in reverse order */
  143133. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  143134. int nPgsz; /* Page size for host database */
  143135. char *zSegmentsTbl; /* Name of %_segments table */
  143136. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  143137. /*
  143138. ** The following array of hash tables is used to buffer pending index
  143139. ** updates during transactions. All pending updates buffered at any one
  143140. ** time must share a common language-id (see the FTS4 langid= feature).
  143141. ** The current language id is stored in variable iPrevLangid.
  143142. **
  143143. ** A single FTS4 table may have multiple full-text indexes. For each index
  143144. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  143145. ** terms that appear in the document set. Each subsequent index in aIndex[]
  143146. ** is an index of prefixes of a specific length.
  143147. **
  143148. ** Variable nPendingData contains an estimate the memory consumed by the
  143149. ** pending data structures, including hash table overhead, but not including
  143150. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  143151. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  143152. ** recently inserted record.
  143153. */
  143154. int nIndex; /* Size of aIndex[] */
  143155. struct Fts3Index {
  143156. int nPrefix; /* Prefix length (0 for main terms index) */
  143157. Fts3Hash hPending; /* Pending terms table for this index */
  143158. } *aIndex;
  143159. int nMaxPendingData; /* Max pending data before flush to disk */
  143160. int nPendingData; /* Current bytes of pending data */
  143161. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  143162. int iPrevLangid; /* Langid of recently inserted document */
  143163. int bPrevDelete; /* True if last operation was a delete */
  143164. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  143165. /* State variables used for validating that the transaction control
  143166. ** methods of the virtual table are called at appropriate times. These
  143167. ** values do not contribute to FTS functionality; they are used for
  143168. ** verifying the operation of the SQLite core.
  143169. */
  143170. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  143171. int mxSavepoint; /* Largest valid xSavepoint integer */
  143172. #endif
  143173. #ifdef SQLITE_TEST
  143174. /* True to disable the incremental doclist optimization. This is controled
  143175. ** by special insert command 'test-no-incr-doclist'. */
  143176. int bNoIncrDoclist;
  143177. #endif
  143178. };
  143179. /*
  143180. ** When the core wants to read from the virtual table, it creates a
  143181. ** virtual table cursor (an instance of the following structure) using
  143182. ** the xOpen method. Cursors are destroyed using the xClose method.
  143183. */
  143184. struct Fts3Cursor {
  143185. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  143186. i16 eSearch; /* Search strategy (see below) */
  143187. u8 isEof; /* True if at End Of Results */
  143188. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  143189. u8 bSeekStmt; /* True if pStmt is a seek */
  143190. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  143191. Fts3Expr *pExpr; /* Parsed MATCH query string */
  143192. int iLangid; /* Language being queried for */
  143193. int nPhrase; /* Number of matchable phrases in query */
  143194. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  143195. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  143196. char *pNextId; /* Pointer into the body of aDoclist */
  143197. char *aDoclist; /* List of docids for full-text queries */
  143198. int nDoclist; /* Size of buffer at aDoclist */
  143199. u8 bDesc; /* True to sort in descending order */
  143200. int eEvalmode; /* An FTS3_EVAL_XX constant */
  143201. int nRowAvg; /* Average size of database rows, in pages */
  143202. sqlite3_int64 nDoc; /* Documents in table */
  143203. i64 iMinDocid; /* Minimum docid to return */
  143204. i64 iMaxDocid; /* Maximum docid to return */
  143205. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  143206. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  143207. };
  143208. #define FTS3_EVAL_FILTER 0
  143209. #define FTS3_EVAL_NEXT 1
  143210. #define FTS3_EVAL_MATCHINFO 2
  143211. /*
  143212. ** The Fts3Cursor.eSearch member is always set to one of the following.
  143213. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  143214. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  143215. ** of the column to be searched. For example, in
  143216. **
  143217. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  143218. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  143219. **
  143220. ** Because the LHS of the MATCH operator is 2nd column "b",
  143221. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  143222. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  143223. ** indicating that all columns should be searched,
  143224. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  143225. */
  143226. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  143227. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  143228. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  143229. /*
  143230. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  143231. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  143232. ** above. The upper 16-bits contain a combination of the following
  143233. ** bits, used to describe extra constraints on full-text searches.
  143234. */
  143235. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  143236. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  143237. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  143238. struct Fts3Doclist {
  143239. char *aAll; /* Array containing doclist (or NULL) */
  143240. int nAll; /* Size of a[] in bytes */
  143241. char *pNextDocid; /* Pointer to next docid */
  143242. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  143243. int bFreeList; /* True if pList should be sqlite3_free()d */
  143244. char *pList; /* Pointer to position list following iDocid */
  143245. int nList; /* Length of position list */
  143246. };
  143247. /*
  143248. ** A "phrase" is a sequence of one or more tokens that must match in
  143249. ** sequence. A single token is the base case and the most common case.
  143250. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  143251. ** nToken will be the number of tokens in the string.
  143252. */
  143253. struct Fts3PhraseToken {
  143254. char *z; /* Text of the token */
  143255. int n; /* Number of bytes in buffer z */
  143256. int isPrefix; /* True if token ends with a "*" character */
  143257. int bFirst; /* True if token must appear at position 0 */
  143258. /* Variables above this point are populated when the expression is
  143259. ** parsed (by code in fts3_expr.c). Below this point the variables are
  143260. ** used when evaluating the expression. */
  143261. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  143262. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  143263. };
  143264. struct Fts3Phrase {
  143265. /* Cache of doclist for this phrase. */
  143266. Fts3Doclist doclist;
  143267. int bIncr; /* True if doclist is loaded incrementally */
  143268. int iDoclistToken;
  143269. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  143270. ** OR condition. */
  143271. char *pOrPoslist;
  143272. i64 iOrDocid;
  143273. /* Variables below this point are populated by fts3_expr.c when parsing
  143274. ** a MATCH expression. Everything above is part of the evaluation phase.
  143275. */
  143276. int nToken; /* Number of tokens in the phrase */
  143277. int iColumn; /* Index of column this phrase must match */
  143278. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  143279. };
  143280. /*
  143281. ** A tree of these objects forms the RHS of a MATCH operator.
  143282. **
  143283. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  143284. ** points to a malloced buffer, size nDoclist bytes, containing the results
  143285. ** of this phrase query in FTS3 doclist format. As usual, the initial
  143286. ** "Length" field found in doclists stored on disk is omitted from this
  143287. ** buffer.
  143288. **
  143289. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  143290. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  143291. ** where nCol is the number of columns in the queried FTS table. The array
  143292. ** is populated as follows:
  143293. **
  143294. ** aMI[iCol*3 + 0] = Undefined
  143295. ** aMI[iCol*3 + 1] = Number of occurrences
  143296. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  143297. **
  143298. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  143299. ** when the expression node is.
  143300. */
  143301. struct Fts3Expr {
  143302. int eType; /* One of the FTSQUERY_XXX values defined below */
  143303. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  143304. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  143305. Fts3Expr *pLeft; /* Left operand */
  143306. Fts3Expr *pRight; /* Right operand */
  143307. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  143308. /* The following are used by the fts3_eval.c module. */
  143309. sqlite3_int64 iDocid; /* Current docid */
  143310. u8 bEof; /* True this expression is at EOF already */
  143311. u8 bStart; /* True if iDocid is valid */
  143312. u8 bDeferred; /* True if this expression is entirely deferred */
  143313. /* The following are used by the fts3_snippet.c module. */
  143314. int iPhrase; /* Index of this phrase in matchinfo() results */
  143315. u32 *aMI; /* See above */
  143316. };
  143317. /*
  143318. ** Candidate values for Fts3Query.eType. Note that the order of the first
  143319. ** four values is in order of precedence when parsing expressions. For
  143320. ** example, the following:
  143321. **
  143322. ** "a OR b AND c NOT d NEAR e"
  143323. **
  143324. ** is equivalent to:
  143325. **
  143326. ** "a OR (b AND (c NOT (d NEAR e)))"
  143327. */
  143328. #define FTSQUERY_NEAR 1
  143329. #define FTSQUERY_NOT 2
  143330. #define FTSQUERY_AND 3
  143331. #define FTSQUERY_OR 4
  143332. #define FTSQUERY_PHRASE 5
  143333. /* fts3_write.c */
  143334. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  143335. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  143336. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  143337. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  143338. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  143339. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  143340. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  143341. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  143342. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  143343. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  143344. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  143345. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  143346. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  143347. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  143348. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  143349. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  143350. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  143351. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  143352. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  143353. #else
  143354. # define sqlite3Fts3FreeDeferredTokens(x)
  143355. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  143356. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  143357. # define sqlite3Fts3FreeDeferredDoclists(x)
  143358. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  143359. #endif
  143360. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  143361. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  143362. /* Special values interpreted by sqlite3SegReaderCursor() */
  143363. #define FTS3_SEGCURSOR_PENDING -1
  143364. #define FTS3_SEGCURSOR_ALL -2
  143365. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  143366. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  143367. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  143368. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  143369. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  143370. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  143371. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  143372. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  143373. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  143374. #define FTS3_SEGMENT_PREFIX 0x00000008
  143375. #define FTS3_SEGMENT_SCAN 0x00000010
  143376. #define FTS3_SEGMENT_FIRST 0x00000020
  143377. /* Type passed as 4th argument to SegmentReaderIterate() */
  143378. struct Fts3SegFilter {
  143379. const char *zTerm;
  143380. int nTerm;
  143381. int iCol;
  143382. int flags;
  143383. };
  143384. struct Fts3MultiSegReader {
  143385. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  143386. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  143387. int nSegment; /* Size of apSegment array */
  143388. int nAdvance; /* How many seg-readers to advance */
  143389. Fts3SegFilter *pFilter; /* Pointer to filter object */
  143390. char *aBuffer; /* Buffer to merge doclists in */
  143391. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  143392. int iColFilter; /* If >=0, filter for this column */
  143393. int bRestart;
  143394. /* Used by fts3.c only. */
  143395. int nCost; /* Cost of running iterator */
  143396. int bLookup; /* True if a lookup of a single entry. */
  143397. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  143398. char *zTerm; /* Pointer to term buffer */
  143399. int nTerm; /* Size of zTerm in bytes */
  143400. char *aDoclist; /* Pointer to doclist buffer */
  143401. int nDoclist; /* Size of aDoclist[] in bytes */
  143402. };
  143403. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  143404. #define fts3GetVarint32(p, piVal) ( \
  143405. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  143406. )
  143407. /* fts3.c */
  143408. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  143409. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  143410. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  143411. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  143412. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  143413. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  143414. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  143415. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  143416. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  143417. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  143418. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  143419. /* fts3_tokenizer.c */
  143420. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  143421. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  143422. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  143423. sqlite3_tokenizer **, char **
  143424. );
  143425. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  143426. /* fts3_snippet.c */
  143427. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  143428. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  143429. const char *, const char *, int, int
  143430. );
  143431. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  143432. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  143433. /* fts3_expr.c */
  143434. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  143435. char **, int, int, int, const char *, int, Fts3Expr **, char **
  143436. );
  143437. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  143438. #ifdef SQLITE_TEST
  143439. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
  143440. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  143441. #endif
  143442. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  143443. sqlite3_tokenizer_cursor **
  143444. );
  143445. /* fts3_aux.c */
  143446. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  143447. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  143448. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  143449. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  143450. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  143451. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  143452. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  143453. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  143454. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  143455. /* fts3_tokenize_vtab.c */
  143456. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  143457. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  143458. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  143459. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  143460. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  143461. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  143462. #endif
  143463. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  143464. #endif /* _FTSINT_H */
  143465. /************** End of fts3Int.h *********************************************/
  143466. /************** Continuing where we left off in fts3.c ***********************/
  143467. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  143468. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  143469. # define SQLITE_CORE 1
  143470. #endif
  143471. /* #include <assert.h> */
  143472. /* #include <stdlib.h> */
  143473. /* #include <stddef.h> */
  143474. /* #include <stdio.h> */
  143475. /* #include <string.h> */
  143476. /* #include <stdarg.h> */
  143477. /* #include "fts3.h" */
  143478. #ifndef SQLITE_CORE
  143479. /* # include "sqlite3ext.h" */
  143480. SQLITE_EXTENSION_INIT1
  143481. #endif
  143482. static int fts3EvalNext(Fts3Cursor *pCsr);
  143483. static int fts3EvalStart(Fts3Cursor *pCsr);
  143484. static int fts3TermSegReaderCursor(
  143485. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  143486. #ifndef SQLITE_AMALGAMATION
  143487. # if defined(SQLITE_DEBUG)
  143488. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  143489. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  143490. # endif
  143491. #endif
  143492. /*
  143493. ** Write a 64-bit variable-length integer to memory starting at p[0].
  143494. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  143495. ** The number of bytes written is returned.
  143496. */
  143497. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  143498. unsigned char *q = (unsigned char *) p;
  143499. sqlite_uint64 vu = v;
  143500. do{
  143501. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  143502. vu >>= 7;
  143503. }while( vu!=0 );
  143504. q[-1] &= 0x7f; /* turn off high bit in final byte */
  143505. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  143506. return (int) (q - (unsigned char *)p);
  143507. }
  143508. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  143509. v = (v & mask1) | ( (*ptr++) << shift ); \
  143510. if( (v & mask2)==0 ){ var = v; return ret; }
  143511. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  143512. v = (*ptr++); \
  143513. if( (v & mask2)==0 ){ var = v; return ret; }
  143514. /*
  143515. ** Read a 64-bit variable-length integer from memory starting at p[0].
  143516. ** Return the number of bytes read, or 0 on error.
  143517. ** The value is stored in *v.
  143518. */
  143519. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  143520. const unsigned char *p = (const unsigned char*)pBuf;
  143521. const unsigned char *pStart = p;
  143522. u32 a;
  143523. u64 b;
  143524. int shift;
  143525. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  143526. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  143527. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  143528. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  143529. b = (a & 0x0FFFFFFF );
  143530. for(shift=28; shift<=63; shift+=7){
  143531. u64 c = *p++;
  143532. b += (c&0x7F) << shift;
  143533. if( (c & 0x80)==0 ) break;
  143534. }
  143535. *v = b;
  143536. return (int)(p - pStart);
  143537. }
  143538. /*
  143539. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  143540. ** a non-negative 32-bit integer before it is returned.
  143541. */
  143542. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  143543. u32 a;
  143544. #ifndef fts3GetVarint32
  143545. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  143546. #else
  143547. a = (*p++);
  143548. assert( a & 0x80 );
  143549. #endif
  143550. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  143551. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  143552. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  143553. a = (a & 0x0FFFFFFF );
  143554. *pi = (int)(a | ((u32)(*p & 0x07) << 28));
  143555. assert( 0==(a & 0x80000000) );
  143556. assert( *pi>=0 );
  143557. return 5;
  143558. }
  143559. /*
  143560. ** Return the number of bytes required to encode v as a varint
  143561. */
  143562. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  143563. int i = 0;
  143564. do{
  143565. i++;
  143566. v >>= 7;
  143567. }while( v!=0 );
  143568. return i;
  143569. }
  143570. /*
  143571. ** Convert an SQL-style quoted string into a normal string by removing
  143572. ** the quote characters. The conversion is done in-place. If the
  143573. ** input does not begin with a quote character, then this routine
  143574. ** is a no-op.
  143575. **
  143576. ** Examples:
  143577. **
  143578. ** "abc" becomes abc
  143579. ** 'xyz' becomes xyz
  143580. ** [pqr] becomes pqr
  143581. ** `mno` becomes mno
  143582. **
  143583. */
  143584. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  143585. char quote; /* Quote character (if any ) */
  143586. quote = z[0];
  143587. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  143588. int iIn = 1; /* Index of next byte to read from input */
  143589. int iOut = 0; /* Index of next byte to write to output */
  143590. /* If the first byte was a '[', then the close-quote character is a ']' */
  143591. if( quote=='[' ) quote = ']';
  143592. while( z[iIn] ){
  143593. if( z[iIn]==quote ){
  143594. if( z[iIn+1]!=quote ) break;
  143595. z[iOut++] = quote;
  143596. iIn += 2;
  143597. }else{
  143598. z[iOut++] = z[iIn++];
  143599. }
  143600. }
  143601. z[iOut] = '\0';
  143602. }
  143603. }
  143604. /*
  143605. ** Read a single varint from the doclist at *pp and advance *pp to point
  143606. ** to the first byte past the end of the varint. Add the value of the varint
  143607. ** to *pVal.
  143608. */
  143609. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  143610. sqlite3_int64 iVal;
  143611. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  143612. *pVal += iVal;
  143613. }
  143614. /*
  143615. ** When this function is called, *pp points to the first byte following a
  143616. ** varint that is part of a doclist (or position-list, or any other list
  143617. ** of varints). This function moves *pp to point to the start of that varint,
  143618. ** and sets *pVal by the varint value.
  143619. **
  143620. ** Argument pStart points to the first byte of the doclist that the
  143621. ** varint is part of.
  143622. */
  143623. static void fts3GetReverseVarint(
  143624. char **pp,
  143625. char *pStart,
  143626. sqlite3_int64 *pVal
  143627. ){
  143628. sqlite3_int64 iVal;
  143629. char *p;
  143630. /* Pointer p now points at the first byte past the varint we are
  143631. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  143632. ** clear on character p[-1]. */
  143633. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  143634. p++;
  143635. *pp = p;
  143636. sqlite3Fts3GetVarint(p, &iVal);
  143637. *pVal = iVal;
  143638. }
  143639. /*
  143640. ** The xDisconnect() virtual table method.
  143641. */
  143642. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  143643. Fts3Table *p = (Fts3Table *)pVtab;
  143644. int i;
  143645. assert( p->nPendingData==0 );
  143646. assert( p->pSegments==0 );
  143647. /* Free any prepared statements held */
  143648. sqlite3_finalize(p->pSeekStmt);
  143649. for(i=0; i<SizeofArray(p->aStmt); i++){
  143650. sqlite3_finalize(p->aStmt[i]);
  143651. }
  143652. sqlite3_free(p->zSegmentsTbl);
  143653. sqlite3_free(p->zReadExprlist);
  143654. sqlite3_free(p->zWriteExprlist);
  143655. sqlite3_free(p->zContentTbl);
  143656. sqlite3_free(p->zLanguageid);
  143657. /* Invoke the tokenizer destructor to free the tokenizer. */
  143658. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  143659. sqlite3_free(p);
  143660. return SQLITE_OK;
  143661. }
  143662. /*
  143663. ** Write an error message into *pzErr
  143664. */
  143665. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  143666. va_list ap;
  143667. sqlite3_free(*pzErr);
  143668. va_start(ap, zFormat);
  143669. *pzErr = sqlite3_vmprintf(zFormat, ap);
  143670. va_end(ap);
  143671. }
  143672. /*
  143673. ** Construct one or more SQL statements from the format string given
  143674. ** and then evaluate those statements. The success code is written
  143675. ** into *pRc.
  143676. **
  143677. ** If *pRc is initially non-zero then this routine is a no-op.
  143678. */
  143679. static void fts3DbExec(
  143680. int *pRc, /* Success code */
  143681. sqlite3 *db, /* Database in which to run SQL */
  143682. const char *zFormat, /* Format string for SQL */
  143683. ... /* Arguments to the format string */
  143684. ){
  143685. va_list ap;
  143686. char *zSql;
  143687. if( *pRc ) return;
  143688. va_start(ap, zFormat);
  143689. zSql = sqlite3_vmprintf(zFormat, ap);
  143690. va_end(ap);
  143691. if( zSql==0 ){
  143692. *pRc = SQLITE_NOMEM;
  143693. }else{
  143694. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  143695. sqlite3_free(zSql);
  143696. }
  143697. }
  143698. /*
  143699. ** The xDestroy() virtual table method.
  143700. */
  143701. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  143702. Fts3Table *p = (Fts3Table *)pVtab;
  143703. int rc = SQLITE_OK; /* Return code */
  143704. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  143705. sqlite3 *db = p->db; /* Database handle */
  143706. /* Drop the shadow tables */
  143707. if( p->zContentTbl==0 ){
  143708. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  143709. }
  143710. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  143711. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  143712. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  143713. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  143714. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  143715. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  143716. ** Otherwise, return an SQLite error code.
  143717. */
  143718. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  143719. }
  143720. /*
  143721. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  143722. ** passed as the first argument. This is done as part of the xConnect()
  143723. ** and xCreate() methods.
  143724. **
  143725. ** If *pRc is non-zero when this function is called, it is a no-op.
  143726. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  143727. ** before returning.
  143728. */
  143729. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  143730. if( *pRc==SQLITE_OK ){
  143731. int i; /* Iterator variable */
  143732. int rc; /* Return code */
  143733. char *zSql; /* SQL statement passed to declare_vtab() */
  143734. char *zCols; /* List of user defined columns */
  143735. const char *zLanguageid;
  143736. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  143737. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  143738. /* Create a list of user columns for the virtual table */
  143739. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  143740. for(i=1; zCols && i<p->nColumn; i++){
  143741. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  143742. }
  143743. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  143744. zSql = sqlite3_mprintf(
  143745. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  143746. zCols, p->zName, zLanguageid
  143747. );
  143748. if( !zCols || !zSql ){
  143749. rc = SQLITE_NOMEM;
  143750. }else{
  143751. rc = sqlite3_declare_vtab(p->db, zSql);
  143752. }
  143753. sqlite3_free(zSql);
  143754. sqlite3_free(zCols);
  143755. *pRc = rc;
  143756. }
  143757. }
  143758. /*
  143759. ** Create the %_stat table if it does not already exist.
  143760. */
  143761. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  143762. fts3DbExec(pRc, p->db,
  143763. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  143764. "(id INTEGER PRIMARY KEY, value BLOB);",
  143765. p->zDb, p->zName
  143766. );
  143767. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  143768. }
  143769. /*
  143770. ** Create the backing store tables (%_content, %_segments and %_segdir)
  143771. ** required by the FTS3 table passed as the only argument. This is done
  143772. ** as part of the vtab xCreate() method.
  143773. **
  143774. ** If the p->bHasDocsize boolean is true (indicating that this is an
  143775. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  143776. ** %_stat tables required by FTS4.
  143777. */
  143778. static int fts3CreateTables(Fts3Table *p){
  143779. int rc = SQLITE_OK; /* Return code */
  143780. int i; /* Iterator variable */
  143781. sqlite3 *db = p->db; /* The database connection */
  143782. if( p->zContentTbl==0 ){
  143783. const char *zLanguageid = p->zLanguageid;
  143784. char *zContentCols; /* Columns of %_content table */
  143785. /* Create a list of user columns for the content table */
  143786. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  143787. for(i=0; zContentCols && i<p->nColumn; i++){
  143788. char *z = p->azColumn[i];
  143789. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  143790. }
  143791. if( zLanguageid && zContentCols ){
  143792. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  143793. }
  143794. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  143795. /* Create the content table */
  143796. fts3DbExec(&rc, db,
  143797. "CREATE TABLE %Q.'%q_content'(%s)",
  143798. p->zDb, p->zName, zContentCols
  143799. );
  143800. sqlite3_free(zContentCols);
  143801. }
  143802. /* Create other tables */
  143803. fts3DbExec(&rc, db,
  143804. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  143805. p->zDb, p->zName
  143806. );
  143807. fts3DbExec(&rc, db,
  143808. "CREATE TABLE %Q.'%q_segdir'("
  143809. "level INTEGER,"
  143810. "idx INTEGER,"
  143811. "start_block INTEGER,"
  143812. "leaves_end_block INTEGER,"
  143813. "end_block INTEGER,"
  143814. "root BLOB,"
  143815. "PRIMARY KEY(level, idx)"
  143816. ");",
  143817. p->zDb, p->zName
  143818. );
  143819. if( p->bHasDocsize ){
  143820. fts3DbExec(&rc, db,
  143821. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  143822. p->zDb, p->zName
  143823. );
  143824. }
  143825. assert( p->bHasStat==p->bFts4 );
  143826. if( p->bHasStat ){
  143827. sqlite3Fts3CreateStatTable(&rc, p);
  143828. }
  143829. return rc;
  143830. }
  143831. /*
  143832. ** Store the current database page-size in bytes in p->nPgsz.
  143833. **
  143834. ** If *pRc is non-zero when this function is called, it is a no-op.
  143835. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  143836. ** before returning.
  143837. */
  143838. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  143839. if( *pRc==SQLITE_OK ){
  143840. int rc; /* Return code */
  143841. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  143842. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  143843. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  143844. if( !zSql ){
  143845. rc = SQLITE_NOMEM;
  143846. }else{
  143847. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  143848. if( rc==SQLITE_OK ){
  143849. sqlite3_step(pStmt);
  143850. p->nPgsz = sqlite3_column_int(pStmt, 0);
  143851. rc = sqlite3_finalize(pStmt);
  143852. }else if( rc==SQLITE_AUTH ){
  143853. p->nPgsz = 1024;
  143854. rc = SQLITE_OK;
  143855. }
  143856. }
  143857. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  143858. sqlite3_free(zSql);
  143859. *pRc = rc;
  143860. }
  143861. }
  143862. /*
  143863. ** "Special" FTS4 arguments are column specifications of the following form:
  143864. **
  143865. ** <key> = <value>
  143866. **
  143867. ** There may not be whitespace surrounding the "=" character. The <value>
  143868. ** term may be quoted, but the <key> may not.
  143869. */
  143870. static int fts3IsSpecialColumn(
  143871. const char *z,
  143872. int *pnKey,
  143873. char **pzValue
  143874. ){
  143875. char *zValue;
  143876. const char *zCsr = z;
  143877. while( *zCsr!='=' ){
  143878. if( *zCsr=='\0' ) return 0;
  143879. zCsr++;
  143880. }
  143881. *pnKey = (int)(zCsr-z);
  143882. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  143883. if( zValue ){
  143884. sqlite3Fts3Dequote(zValue);
  143885. }
  143886. *pzValue = zValue;
  143887. return 1;
  143888. }
  143889. /*
  143890. ** Append the output of a printf() style formatting to an existing string.
  143891. */
  143892. static void fts3Appendf(
  143893. int *pRc, /* IN/OUT: Error code */
  143894. char **pz, /* IN/OUT: Pointer to string buffer */
  143895. const char *zFormat, /* Printf format string to append */
  143896. ... /* Arguments for printf format string */
  143897. ){
  143898. if( *pRc==SQLITE_OK ){
  143899. va_list ap;
  143900. char *z;
  143901. va_start(ap, zFormat);
  143902. z = sqlite3_vmprintf(zFormat, ap);
  143903. va_end(ap);
  143904. if( z && *pz ){
  143905. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  143906. sqlite3_free(z);
  143907. z = z2;
  143908. }
  143909. if( z==0 ) *pRc = SQLITE_NOMEM;
  143910. sqlite3_free(*pz);
  143911. *pz = z;
  143912. }
  143913. }
  143914. /*
  143915. ** Return a copy of input string zInput enclosed in double-quotes (") and
  143916. ** with all double quote characters escaped. For example:
  143917. **
  143918. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  143919. **
  143920. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  143921. ** is the callers responsibility to call sqlite3_free() to release this
  143922. ** memory.
  143923. */
  143924. static char *fts3QuoteId(char const *zInput){
  143925. int nRet;
  143926. char *zRet;
  143927. nRet = 2 + (int)strlen(zInput)*2 + 1;
  143928. zRet = sqlite3_malloc(nRet);
  143929. if( zRet ){
  143930. int i;
  143931. char *z = zRet;
  143932. *(z++) = '"';
  143933. for(i=0; zInput[i]; i++){
  143934. if( zInput[i]=='"' ) *(z++) = '"';
  143935. *(z++) = zInput[i];
  143936. }
  143937. *(z++) = '"';
  143938. *(z++) = '\0';
  143939. }
  143940. return zRet;
  143941. }
  143942. /*
  143943. ** Return a list of comma separated SQL expressions and a FROM clause that
  143944. ** could be used in a SELECT statement such as the following:
  143945. **
  143946. ** SELECT <list of expressions> FROM %_content AS x ...
  143947. **
  143948. ** to return the docid, followed by each column of text data in order
  143949. ** from left to write. If parameter zFunc is not NULL, then instead of
  143950. ** being returned directly each column of text data is passed to an SQL
  143951. ** function named zFunc first. For example, if zFunc is "unzip" and the
  143952. ** table has the three user-defined columns "a", "b", and "c", the following
  143953. ** string is returned:
  143954. **
  143955. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  143956. **
  143957. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  143958. ** is the responsibility of the caller to eventually free it.
  143959. **
  143960. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  143961. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  143962. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  143963. ** no error occurs, *pRc is left unmodified.
  143964. */
  143965. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  143966. char *zRet = 0;
  143967. char *zFree = 0;
  143968. char *zFunction;
  143969. int i;
  143970. if( p->zContentTbl==0 ){
  143971. if( !zFunc ){
  143972. zFunction = "";
  143973. }else{
  143974. zFree = zFunction = fts3QuoteId(zFunc);
  143975. }
  143976. fts3Appendf(pRc, &zRet, "docid");
  143977. for(i=0; i<p->nColumn; i++){
  143978. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  143979. }
  143980. if( p->zLanguageid ){
  143981. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  143982. }
  143983. sqlite3_free(zFree);
  143984. }else{
  143985. fts3Appendf(pRc, &zRet, "rowid");
  143986. for(i=0; i<p->nColumn; i++){
  143987. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  143988. }
  143989. if( p->zLanguageid ){
  143990. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  143991. }
  143992. }
  143993. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  143994. p->zDb,
  143995. (p->zContentTbl ? p->zContentTbl : p->zName),
  143996. (p->zContentTbl ? "" : "_content")
  143997. );
  143998. return zRet;
  143999. }
  144000. /*
  144001. ** Return a list of N comma separated question marks, where N is the number
  144002. ** of columns in the %_content table (one for the docid plus one for each
  144003. ** user-defined text column).
  144004. **
  144005. ** If argument zFunc is not NULL, then all but the first question mark
  144006. ** is preceded by zFunc and an open bracket, and followed by a closed
  144007. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  144008. ** user-defined text columns, the following string is returned:
  144009. **
  144010. ** "?, zip(?), zip(?), zip(?)"
  144011. **
  144012. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  144013. ** is the responsibility of the caller to eventually free it.
  144014. **
  144015. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  144016. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  144017. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  144018. ** no error occurs, *pRc is left unmodified.
  144019. */
  144020. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  144021. char *zRet = 0;
  144022. char *zFree = 0;
  144023. char *zFunction;
  144024. int i;
  144025. if( !zFunc ){
  144026. zFunction = "";
  144027. }else{
  144028. zFree = zFunction = fts3QuoteId(zFunc);
  144029. }
  144030. fts3Appendf(pRc, &zRet, "?");
  144031. for(i=0; i<p->nColumn; i++){
  144032. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  144033. }
  144034. if( p->zLanguageid ){
  144035. fts3Appendf(pRc, &zRet, ", ?");
  144036. }
  144037. sqlite3_free(zFree);
  144038. return zRet;
  144039. }
  144040. /*
  144041. ** This function interprets the string at (*pp) as a non-negative integer
  144042. ** value. It reads the integer and sets *pnOut to the value read, then
  144043. ** sets *pp to point to the byte immediately following the last byte of
  144044. ** the integer value.
  144045. **
  144046. ** Only decimal digits ('0'..'9') may be part of an integer value.
  144047. **
  144048. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  144049. ** the output value undefined. Otherwise SQLITE_OK is returned.
  144050. **
  144051. ** This function is used when parsing the "prefix=" FTS4 parameter.
  144052. */
  144053. static int fts3GobbleInt(const char **pp, int *pnOut){
  144054. const int MAX_NPREFIX = 10000000;
  144055. const char *p; /* Iterator pointer */
  144056. int nInt = 0; /* Output value */
  144057. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  144058. nInt = nInt * 10 + (p[0] - '0');
  144059. if( nInt>MAX_NPREFIX ){
  144060. nInt = 0;
  144061. break;
  144062. }
  144063. }
  144064. if( p==*pp ) return SQLITE_ERROR;
  144065. *pnOut = nInt;
  144066. *pp = p;
  144067. return SQLITE_OK;
  144068. }
  144069. /*
  144070. ** This function is called to allocate an array of Fts3Index structures
  144071. ** representing the indexes maintained by the current FTS table. FTS tables
  144072. ** always maintain the main "terms" index, but may also maintain one or
  144073. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  144074. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  144075. **
  144076. ** Argument zParam is passed the value of the "prefix=" option if one was
  144077. ** specified, or NULL otherwise.
  144078. **
  144079. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  144080. ** the allocated array. *pnIndex is set to the number of elements in the
  144081. ** array. If an error does occur, an SQLite error code is returned.
  144082. **
  144083. ** Regardless of whether or not an error is returned, it is the responsibility
  144084. ** of the caller to call sqlite3_free() on the output array to free it.
  144085. */
  144086. static int fts3PrefixParameter(
  144087. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  144088. int *pnIndex, /* OUT: size of *apIndex[] array */
  144089. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  144090. ){
  144091. struct Fts3Index *aIndex; /* Allocated array */
  144092. int nIndex = 1; /* Number of entries in array */
  144093. if( zParam && zParam[0] ){
  144094. const char *p;
  144095. nIndex++;
  144096. for(p=zParam; *p; p++){
  144097. if( *p==',' ) nIndex++;
  144098. }
  144099. }
  144100. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  144101. *apIndex = aIndex;
  144102. if( !aIndex ){
  144103. return SQLITE_NOMEM;
  144104. }
  144105. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  144106. if( zParam ){
  144107. const char *p = zParam;
  144108. int i;
  144109. for(i=1; i<nIndex; i++){
  144110. int nPrefix = 0;
  144111. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  144112. assert( nPrefix>=0 );
  144113. if( nPrefix==0 ){
  144114. nIndex--;
  144115. i--;
  144116. }else{
  144117. aIndex[i].nPrefix = nPrefix;
  144118. }
  144119. p++;
  144120. }
  144121. }
  144122. *pnIndex = nIndex;
  144123. return SQLITE_OK;
  144124. }
  144125. /*
  144126. ** This function is called when initializing an FTS4 table that uses the
  144127. ** content=xxx option. It determines the number of and names of the columns
  144128. ** of the new FTS4 table.
  144129. **
  144130. ** The third argument passed to this function is the value passed to the
  144131. ** config=xxx option (i.e. "xxx"). This function queries the database for
  144132. ** a table of that name. If found, the output variables are populated
  144133. ** as follows:
  144134. **
  144135. ** *pnCol: Set to the number of columns table xxx has,
  144136. **
  144137. ** *pnStr: Set to the total amount of space required to store a copy
  144138. ** of each columns name, including the nul-terminator.
  144139. **
  144140. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  144141. ** the name of the corresponding column in table xxx. The array
  144142. ** and its contents are allocated using a single allocation. It
  144143. ** is the responsibility of the caller to free this allocation
  144144. ** by eventually passing the *pazCol value to sqlite3_free().
  144145. **
  144146. ** If the table cannot be found, an error code is returned and the output
  144147. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  144148. ** returned (and the output variables are undefined).
  144149. */
  144150. static int fts3ContentColumns(
  144151. sqlite3 *db, /* Database handle */
  144152. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  144153. const char *zTbl, /* Name of content table */
  144154. const char ***pazCol, /* OUT: Malloc'd array of column names */
  144155. int *pnCol, /* OUT: Size of array *pazCol */
  144156. int *pnStr, /* OUT: Bytes of string content */
  144157. char **pzErr /* OUT: error message */
  144158. ){
  144159. int rc = SQLITE_OK; /* Return code */
  144160. char *zSql; /* "SELECT *" statement on zTbl */
  144161. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  144162. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  144163. if( !zSql ){
  144164. rc = SQLITE_NOMEM;
  144165. }else{
  144166. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  144167. if( rc!=SQLITE_OK ){
  144168. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  144169. }
  144170. }
  144171. sqlite3_free(zSql);
  144172. if( rc==SQLITE_OK ){
  144173. const char **azCol; /* Output array */
  144174. int nStr = 0; /* Size of all column names (incl. 0x00) */
  144175. int nCol; /* Number of table columns */
  144176. int i; /* Used to iterate through columns */
  144177. /* Loop through the returned columns. Set nStr to the number of bytes of
  144178. ** space required to store a copy of each column name, including the
  144179. ** nul-terminator byte. */
  144180. nCol = sqlite3_column_count(pStmt);
  144181. for(i=0; i<nCol; i++){
  144182. const char *zCol = sqlite3_column_name(pStmt, i);
  144183. nStr += (int)strlen(zCol) + 1;
  144184. }
  144185. /* Allocate and populate the array to return. */
  144186. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  144187. if( azCol==0 ){
  144188. rc = SQLITE_NOMEM;
  144189. }else{
  144190. char *p = (char *)&azCol[nCol];
  144191. for(i=0; i<nCol; i++){
  144192. const char *zCol = sqlite3_column_name(pStmt, i);
  144193. int n = (int)strlen(zCol)+1;
  144194. memcpy(p, zCol, n);
  144195. azCol[i] = p;
  144196. p += n;
  144197. }
  144198. }
  144199. sqlite3_finalize(pStmt);
  144200. /* Set the output variables. */
  144201. *pnCol = nCol;
  144202. *pnStr = nStr;
  144203. *pazCol = azCol;
  144204. }
  144205. return rc;
  144206. }
  144207. /*
  144208. ** This function is the implementation of both the xConnect and xCreate
  144209. ** methods of the FTS3 virtual table.
  144210. **
  144211. ** The argv[] array contains the following:
  144212. **
  144213. ** argv[0] -> module name ("fts3" or "fts4")
  144214. ** argv[1] -> database name
  144215. ** argv[2] -> table name
  144216. ** argv[...] -> "column name" and other module argument fields.
  144217. */
  144218. static int fts3InitVtab(
  144219. int isCreate, /* True for xCreate, false for xConnect */
  144220. sqlite3 *db, /* The SQLite database connection */
  144221. void *pAux, /* Hash table containing tokenizers */
  144222. int argc, /* Number of elements in argv array */
  144223. const char * const *argv, /* xCreate/xConnect argument array */
  144224. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  144225. char **pzErr /* Write any error message here */
  144226. ){
  144227. Fts3Hash *pHash = (Fts3Hash *)pAux;
  144228. Fts3Table *p = 0; /* Pointer to allocated vtab */
  144229. int rc = SQLITE_OK; /* Return code */
  144230. int i; /* Iterator variable */
  144231. int nByte; /* Size of allocation used for *p */
  144232. int iCol; /* Column index */
  144233. int nString = 0; /* Bytes required to hold all column names */
  144234. int nCol = 0; /* Number of columns in the FTS table */
  144235. char *zCsr; /* Space for holding column names */
  144236. int nDb; /* Bytes required to hold database name */
  144237. int nName; /* Bytes required to hold table name */
  144238. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  144239. const char **aCol; /* Array of column names */
  144240. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  144241. int nIndex = 0; /* Size of aIndex[] array */
  144242. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  144243. /* The results of parsing supported FTS4 key=value options: */
  144244. int bNoDocsize = 0; /* True to omit %_docsize table */
  144245. int bDescIdx = 0; /* True to store descending indexes */
  144246. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  144247. char *zCompress = 0; /* compress=? parameter (or NULL) */
  144248. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  144249. char *zContent = 0; /* content=? parameter (or NULL) */
  144250. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  144251. char **azNotindexed = 0; /* The set of notindexed= columns */
  144252. int nNotindexed = 0; /* Size of azNotindexed[] array */
  144253. assert( strlen(argv[0])==4 );
  144254. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  144255. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  144256. );
  144257. nDb = (int)strlen(argv[1]) + 1;
  144258. nName = (int)strlen(argv[2]) + 1;
  144259. nByte = sizeof(const char *) * (argc-2);
  144260. aCol = (const char **)sqlite3_malloc(nByte);
  144261. if( aCol ){
  144262. memset((void*)aCol, 0, nByte);
  144263. azNotindexed = (char **)sqlite3_malloc(nByte);
  144264. }
  144265. if( azNotindexed ){
  144266. memset(azNotindexed, 0, nByte);
  144267. }
  144268. if( !aCol || !azNotindexed ){
  144269. rc = SQLITE_NOMEM;
  144270. goto fts3_init_out;
  144271. }
  144272. /* Loop through all of the arguments passed by the user to the FTS3/4
  144273. ** module (i.e. all the column names and special arguments). This loop
  144274. ** does the following:
  144275. **
  144276. ** + Figures out the number of columns the FTSX table will have, and
  144277. ** the number of bytes of space that must be allocated to store copies
  144278. ** of the column names.
  144279. **
  144280. ** + If there is a tokenizer specification included in the arguments,
  144281. ** initializes the tokenizer pTokenizer.
  144282. */
  144283. for(i=3; rc==SQLITE_OK && i<argc; i++){
  144284. char const *z = argv[i];
  144285. int nKey;
  144286. char *zVal;
  144287. /* Check if this is a tokenizer specification */
  144288. if( !pTokenizer
  144289. && strlen(z)>8
  144290. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  144291. && 0==sqlite3Fts3IsIdChar(z[8])
  144292. ){
  144293. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  144294. }
  144295. /* Check if it is an FTS4 special argument. */
  144296. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  144297. struct Fts4Option {
  144298. const char *zOpt;
  144299. int nOpt;
  144300. } aFts4Opt[] = {
  144301. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  144302. { "prefix", 6 }, /* 1 -> PREFIX */
  144303. { "compress", 8 }, /* 2 -> COMPRESS */
  144304. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  144305. { "order", 5 }, /* 4 -> ORDER */
  144306. { "content", 7 }, /* 5 -> CONTENT */
  144307. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  144308. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  144309. };
  144310. int iOpt;
  144311. if( !zVal ){
  144312. rc = SQLITE_NOMEM;
  144313. }else{
  144314. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  144315. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  144316. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  144317. break;
  144318. }
  144319. }
  144320. switch( iOpt ){
  144321. case 0: /* MATCHINFO */
  144322. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  144323. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  144324. rc = SQLITE_ERROR;
  144325. }
  144326. bNoDocsize = 1;
  144327. break;
  144328. case 1: /* PREFIX */
  144329. sqlite3_free(zPrefix);
  144330. zPrefix = zVal;
  144331. zVal = 0;
  144332. break;
  144333. case 2: /* COMPRESS */
  144334. sqlite3_free(zCompress);
  144335. zCompress = zVal;
  144336. zVal = 0;
  144337. break;
  144338. case 3: /* UNCOMPRESS */
  144339. sqlite3_free(zUncompress);
  144340. zUncompress = zVal;
  144341. zVal = 0;
  144342. break;
  144343. case 4: /* ORDER */
  144344. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  144345. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  144346. ){
  144347. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  144348. rc = SQLITE_ERROR;
  144349. }
  144350. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  144351. break;
  144352. case 5: /* CONTENT */
  144353. sqlite3_free(zContent);
  144354. zContent = zVal;
  144355. zVal = 0;
  144356. break;
  144357. case 6: /* LANGUAGEID */
  144358. assert( iOpt==6 );
  144359. sqlite3_free(zLanguageid);
  144360. zLanguageid = zVal;
  144361. zVal = 0;
  144362. break;
  144363. case 7: /* NOTINDEXED */
  144364. azNotindexed[nNotindexed++] = zVal;
  144365. zVal = 0;
  144366. break;
  144367. default:
  144368. assert( iOpt==SizeofArray(aFts4Opt) );
  144369. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  144370. rc = SQLITE_ERROR;
  144371. break;
  144372. }
  144373. sqlite3_free(zVal);
  144374. }
  144375. }
  144376. /* Otherwise, the argument is a column name. */
  144377. else {
  144378. nString += (int)(strlen(z) + 1);
  144379. aCol[nCol++] = z;
  144380. }
  144381. }
  144382. /* If a content=xxx option was specified, the following:
  144383. **
  144384. ** 1. Ignore any compress= and uncompress= options.
  144385. **
  144386. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  144387. ** TABLE statement, use all columns from the content table.
  144388. */
  144389. if( rc==SQLITE_OK && zContent ){
  144390. sqlite3_free(zCompress);
  144391. sqlite3_free(zUncompress);
  144392. zCompress = 0;
  144393. zUncompress = 0;
  144394. if( nCol==0 ){
  144395. sqlite3_free((void*)aCol);
  144396. aCol = 0;
  144397. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  144398. /* If a languageid= option was specified, remove the language id
  144399. ** column from the aCol[] array. */
  144400. if( rc==SQLITE_OK && zLanguageid ){
  144401. int j;
  144402. for(j=0; j<nCol; j++){
  144403. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  144404. int k;
  144405. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  144406. nCol--;
  144407. break;
  144408. }
  144409. }
  144410. }
  144411. }
  144412. }
  144413. if( rc!=SQLITE_OK ) goto fts3_init_out;
  144414. if( nCol==0 ){
  144415. assert( nString==0 );
  144416. aCol[0] = "content";
  144417. nString = 8;
  144418. nCol = 1;
  144419. }
  144420. if( pTokenizer==0 ){
  144421. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  144422. if( rc!=SQLITE_OK ) goto fts3_init_out;
  144423. }
  144424. assert( pTokenizer );
  144425. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  144426. if( rc==SQLITE_ERROR ){
  144427. assert( zPrefix );
  144428. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  144429. }
  144430. if( rc!=SQLITE_OK ) goto fts3_init_out;
  144431. /* Allocate and populate the Fts3Table structure. */
  144432. nByte = sizeof(Fts3Table) + /* Fts3Table */
  144433. nCol * sizeof(char *) + /* azColumn */
  144434. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  144435. nCol * sizeof(u8) + /* abNotindexed */
  144436. nName + /* zName */
  144437. nDb + /* zDb */
  144438. nString; /* Space for azColumn strings */
  144439. p = (Fts3Table*)sqlite3_malloc(nByte);
  144440. if( p==0 ){
  144441. rc = SQLITE_NOMEM;
  144442. goto fts3_init_out;
  144443. }
  144444. memset(p, 0, nByte);
  144445. p->db = db;
  144446. p->nColumn = nCol;
  144447. p->nPendingData = 0;
  144448. p->azColumn = (char **)&p[1];
  144449. p->pTokenizer = pTokenizer;
  144450. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  144451. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  144452. p->bHasStat = (u8)isFts4;
  144453. p->bFts4 = (u8)isFts4;
  144454. p->bDescIdx = (u8)bDescIdx;
  144455. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  144456. p->zContentTbl = zContent;
  144457. p->zLanguageid = zLanguageid;
  144458. zContent = 0;
  144459. zLanguageid = 0;
  144460. TESTONLY( p->inTransaction = -1 );
  144461. TESTONLY( p->mxSavepoint = -1 );
  144462. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  144463. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  144464. p->nIndex = nIndex;
  144465. for(i=0; i<nIndex; i++){
  144466. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  144467. }
  144468. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  144469. /* Fill in the zName and zDb fields of the vtab structure. */
  144470. zCsr = (char *)&p->abNotindexed[nCol];
  144471. p->zName = zCsr;
  144472. memcpy(zCsr, argv[2], nName);
  144473. zCsr += nName;
  144474. p->zDb = zCsr;
  144475. memcpy(zCsr, argv[1], nDb);
  144476. zCsr += nDb;
  144477. /* Fill in the azColumn array */
  144478. for(iCol=0; iCol<nCol; iCol++){
  144479. char *z;
  144480. int n = 0;
  144481. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  144482. if( n>0 ){
  144483. memcpy(zCsr, z, n);
  144484. }
  144485. zCsr[n] = '\0';
  144486. sqlite3Fts3Dequote(zCsr);
  144487. p->azColumn[iCol] = zCsr;
  144488. zCsr += n+1;
  144489. assert( zCsr <= &((char *)p)[nByte] );
  144490. }
  144491. /* Fill in the abNotindexed array */
  144492. for(iCol=0; iCol<nCol; iCol++){
  144493. int n = (int)strlen(p->azColumn[iCol]);
  144494. for(i=0; i<nNotindexed; i++){
  144495. char *zNot = azNotindexed[i];
  144496. if( zNot && n==(int)strlen(zNot)
  144497. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  144498. ){
  144499. p->abNotindexed[iCol] = 1;
  144500. sqlite3_free(zNot);
  144501. azNotindexed[i] = 0;
  144502. }
  144503. }
  144504. }
  144505. for(i=0; i<nNotindexed; i++){
  144506. if( azNotindexed[i] ){
  144507. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  144508. rc = SQLITE_ERROR;
  144509. }
  144510. }
  144511. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  144512. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  144513. rc = SQLITE_ERROR;
  144514. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  144515. }
  144516. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  144517. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  144518. if( rc!=SQLITE_OK ) goto fts3_init_out;
  144519. /* If this is an xCreate call, create the underlying tables in the
  144520. ** database. TODO: For xConnect(), it could verify that said tables exist.
  144521. */
  144522. if( isCreate ){
  144523. rc = fts3CreateTables(p);
  144524. }
  144525. /* Check to see if a legacy fts3 table has been "upgraded" by the
  144526. ** addition of a %_stat table so that it can use incremental merge.
  144527. */
  144528. if( !isFts4 && !isCreate ){
  144529. p->bHasStat = 2;
  144530. }
  144531. /* Figure out the page-size for the database. This is required in order to
  144532. ** estimate the cost of loading large doclists from the database. */
  144533. fts3DatabasePageSize(&rc, p);
  144534. p->nNodeSize = p->nPgsz-35;
  144535. /* Declare the table schema to SQLite. */
  144536. fts3DeclareVtab(&rc, p);
  144537. fts3_init_out:
  144538. sqlite3_free(zPrefix);
  144539. sqlite3_free(aIndex);
  144540. sqlite3_free(zCompress);
  144541. sqlite3_free(zUncompress);
  144542. sqlite3_free(zContent);
  144543. sqlite3_free(zLanguageid);
  144544. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  144545. sqlite3_free((void *)aCol);
  144546. sqlite3_free((void *)azNotindexed);
  144547. if( rc!=SQLITE_OK ){
  144548. if( p ){
  144549. fts3DisconnectMethod((sqlite3_vtab *)p);
  144550. }else if( pTokenizer ){
  144551. pTokenizer->pModule->xDestroy(pTokenizer);
  144552. }
  144553. }else{
  144554. assert( p->pSegments==0 );
  144555. *ppVTab = &p->base;
  144556. }
  144557. return rc;
  144558. }
  144559. /*
  144560. ** The xConnect() and xCreate() methods for the virtual table. All the
  144561. ** work is done in function fts3InitVtab().
  144562. */
  144563. static int fts3ConnectMethod(
  144564. sqlite3 *db, /* Database connection */
  144565. void *pAux, /* Pointer to tokenizer hash table */
  144566. int argc, /* Number of elements in argv array */
  144567. const char * const *argv, /* xCreate/xConnect argument array */
  144568. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  144569. char **pzErr /* OUT: sqlite3_malloc'd error message */
  144570. ){
  144571. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  144572. }
  144573. static int fts3CreateMethod(
  144574. sqlite3 *db, /* Database connection */
  144575. void *pAux, /* Pointer to tokenizer hash table */
  144576. int argc, /* Number of elements in argv array */
  144577. const char * const *argv, /* xCreate/xConnect argument array */
  144578. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  144579. char **pzErr /* OUT: sqlite3_malloc'd error message */
  144580. ){
  144581. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  144582. }
  144583. /*
  144584. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  144585. ** extension is currently being used by a version of SQLite too old to
  144586. ** support estimatedRows. In that case this function is a no-op.
  144587. */
  144588. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  144589. #if SQLITE_VERSION_NUMBER>=3008002
  144590. if( sqlite3_libversion_number()>=3008002 ){
  144591. pIdxInfo->estimatedRows = nRow;
  144592. }
  144593. #endif
  144594. }
  144595. /*
  144596. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  144597. ** extension is currently being used by a version of SQLite too old to
  144598. ** support index-info flags. In that case this function is a no-op.
  144599. */
  144600. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  144601. #if SQLITE_VERSION_NUMBER>=3008012
  144602. if( sqlite3_libversion_number()>=3008012 ){
  144603. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  144604. }
  144605. #endif
  144606. }
  144607. /*
  144608. ** Implementation of the xBestIndex method for FTS3 tables. There
  144609. ** are three possible strategies, in order of preference:
  144610. **
  144611. ** 1. Direct lookup by rowid or docid.
  144612. ** 2. Full-text search using a MATCH operator on a non-docid column.
  144613. ** 3. Linear scan of %_content table.
  144614. */
  144615. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  144616. Fts3Table *p = (Fts3Table *)pVTab;
  144617. int i; /* Iterator variable */
  144618. int iCons = -1; /* Index of constraint to use */
  144619. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  144620. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  144621. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  144622. int iIdx;
  144623. /* By default use a full table scan. This is an expensive option,
  144624. ** so search through the constraints to see if a more efficient
  144625. ** strategy is possible.
  144626. */
  144627. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  144628. pInfo->estimatedCost = 5000000;
  144629. for(i=0; i<pInfo->nConstraint; i++){
  144630. int bDocid; /* True if this constraint is on docid */
  144631. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  144632. if( pCons->usable==0 ){
  144633. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  144634. /* There exists an unusable MATCH constraint. This means that if
  144635. ** the planner does elect to use the results of this call as part
  144636. ** of the overall query plan the user will see an "unable to use
  144637. ** function MATCH in the requested context" error. To discourage
  144638. ** this, return a very high cost here. */
  144639. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  144640. pInfo->estimatedCost = 1e50;
  144641. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  144642. return SQLITE_OK;
  144643. }
  144644. continue;
  144645. }
  144646. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  144647. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  144648. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  144649. pInfo->idxNum = FTS3_DOCID_SEARCH;
  144650. pInfo->estimatedCost = 1.0;
  144651. iCons = i;
  144652. }
  144653. /* A MATCH constraint. Use a full-text search.
  144654. **
  144655. ** If there is more than one MATCH constraint available, use the first
  144656. ** one encountered. If there is both a MATCH constraint and a direct
  144657. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  144658. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  144659. ** it would lead to an "unable to use function MATCH in the requested
  144660. ** context" error.
  144661. */
  144662. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  144663. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  144664. ){
  144665. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  144666. pInfo->estimatedCost = 2.0;
  144667. iCons = i;
  144668. }
  144669. /* Equality constraint on the langid column */
  144670. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  144671. && pCons->iColumn==p->nColumn + 2
  144672. ){
  144673. iLangidCons = i;
  144674. }
  144675. if( bDocid ){
  144676. switch( pCons->op ){
  144677. case SQLITE_INDEX_CONSTRAINT_GE:
  144678. case SQLITE_INDEX_CONSTRAINT_GT:
  144679. iDocidGe = i;
  144680. break;
  144681. case SQLITE_INDEX_CONSTRAINT_LE:
  144682. case SQLITE_INDEX_CONSTRAINT_LT:
  144683. iDocidLe = i;
  144684. break;
  144685. }
  144686. }
  144687. }
  144688. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  144689. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  144690. iIdx = 1;
  144691. if( iCons>=0 ){
  144692. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  144693. pInfo->aConstraintUsage[iCons].omit = 1;
  144694. }
  144695. if( iLangidCons>=0 ){
  144696. pInfo->idxNum |= FTS3_HAVE_LANGID;
  144697. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  144698. }
  144699. if( iDocidGe>=0 ){
  144700. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  144701. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  144702. }
  144703. if( iDocidLe>=0 ){
  144704. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  144705. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  144706. }
  144707. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  144708. ** docid) order. Both ascending and descending are possible.
  144709. */
  144710. if( pInfo->nOrderBy==1 ){
  144711. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  144712. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  144713. if( pOrder->desc ){
  144714. pInfo->idxStr = "DESC";
  144715. }else{
  144716. pInfo->idxStr = "ASC";
  144717. }
  144718. pInfo->orderByConsumed = 1;
  144719. }
  144720. }
  144721. assert( p->pSegments==0 );
  144722. return SQLITE_OK;
  144723. }
  144724. /*
  144725. ** Implementation of xOpen method.
  144726. */
  144727. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  144728. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  144729. UNUSED_PARAMETER(pVTab);
  144730. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  144731. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  144732. ** if the allocation fails, return SQLITE_NOMEM.
  144733. */
  144734. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  144735. if( !pCsr ){
  144736. return SQLITE_NOMEM;
  144737. }
  144738. memset(pCsr, 0, sizeof(Fts3Cursor));
  144739. return SQLITE_OK;
  144740. }
  144741. /*
  144742. ** Finalize the statement handle at pCsr->pStmt.
  144743. **
  144744. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  144745. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  144746. ** pointer there instead of finalizing it.
  144747. */
  144748. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  144749. if( pCsr->bSeekStmt ){
  144750. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  144751. if( p->pSeekStmt==0 ){
  144752. p->pSeekStmt = pCsr->pStmt;
  144753. sqlite3_reset(pCsr->pStmt);
  144754. pCsr->pStmt = 0;
  144755. }
  144756. pCsr->bSeekStmt = 0;
  144757. }
  144758. sqlite3_finalize(pCsr->pStmt);
  144759. }
  144760. /*
  144761. ** Free all resources currently held by the cursor passed as the only
  144762. ** argument.
  144763. */
  144764. static void fts3ClearCursor(Fts3Cursor *pCsr){
  144765. fts3CursorFinalizeStmt(pCsr);
  144766. sqlite3Fts3FreeDeferredTokens(pCsr);
  144767. sqlite3_free(pCsr->aDoclist);
  144768. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  144769. sqlite3Fts3ExprFree(pCsr->pExpr);
  144770. memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  144771. }
  144772. /*
  144773. ** Close the cursor. For additional information see the documentation
  144774. ** on the xClose method of the virtual table interface.
  144775. */
  144776. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  144777. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  144778. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  144779. fts3ClearCursor(pCsr);
  144780. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  144781. sqlite3_free(pCsr);
  144782. return SQLITE_OK;
  144783. }
  144784. /*
  144785. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  144786. ** compose and prepare an SQL statement of the form:
  144787. **
  144788. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  144789. **
  144790. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  144791. ** it. If an error occurs, return an SQLite error code.
  144792. */
  144793. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  144794. int rc = SQLITE_OK;
  144795. if( pCsr->pStmt==0 ){
  144796. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  144797. char *zSql;
  144798. if( p->pSeekStmt ){
  144799. pCsr->pStmt = p->pSeekStmt;
  144800. p->pSeekStmt = 0;
  144801. }else{
  144802. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  144803. if( !zSql ) return SQLITE_NOMEM;
  144804. rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  144805. sqlite3_free(zSql);
  144806. }
  144807. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  144808. }
  144809. return rc;
  144810. }
  144811. /*
  144812. ** Position the pCsr->pStmt statement so that it is on the row
  144813. ** of the %_content table that contains the last match. Return
  144814. ** SQLITE_OK on success.
  144815. */
  144816. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  144817. int rc = SQLITE_OK;
  144818. if( pCsr->isRequireSeek ){
  144819. rc = fts3CursorSeekStmt(pCsr);
  144820. if( rc==SQLITE_OK ){
  144821. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  144822. pCsr->isRequireSeek = 0;
  144823. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  144824. return SQLITE_OK;
  144825. }else{
  144826. rc = sqlite3_reset(pCsr->pStmt);
  144827. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  144828. /* If no row was found and no error has occurred, then the %_content
  144829. ** table is missing a row that is present in the full-text index.
  144830. ** The data structures are corrupt. */
  144831. rc = FTS_CORRUPT_VTAB;
  144832. pCsr->isEof = 1;
  144833. }
  144834. }
  144835. }
  144836. }
  144837. if( rc!=SQLITE_OK && pContext ){
  144838. sqlite3_result_error_code(pContext, rc);
  144839. }
  144840. return rc;
  144841. }
  144842. /*
  144843. ** This function is used to process a single interior node when searching
  144844. ** a b-tree for a term or term prefix. The node data is passed to this
  144845. ** function via the zNode/nNode parameters. The term to search for is
  144846. ** passed in zTerm/nTerm.
  144847. **
  144848. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  144849. ** of the child node that heads the sub-tree that may contain the term.
  144850. **
  144851. ** If piLast is not NULL, then *piLast is set to the right-most child node
  144852. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  144853. ** a prefix.
  144854. **
  144855. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  144856. */
  144857. static int fts3ScanInteriorNode(
  144858. const char *zTerm, /* Term to select leaves for */
  144859. int nTerm, /* Size of term zTerm in bytes */
  144860. const char *zNode, /* Buffer containing segment interior node */
  144861. int nNode, /* Size of buffer at zNode */
  144862. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  144863. sqlite3_int64 *piLast /* OUT: Selected child node */
  144864. ){
  144865. int rc = SQLITE_OK; /* Return code */
  144866. const char *zCsr = zNode; /* Cursor to iterate through node */
  144867. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  144868. char *zBuffer = 0; /* Buffer to load terms into */
  144869. int nAlloc = 0; /* Size of allocated buffer */
  144870. int isFirstTerm = 1; /* True when processing first term on page */
  144871. sqlite3_int64 iChild; /* Block id of child node to descend to */
  144872. /* Skip over the 'height' varint that occurs at the start of every
  144873. ** interior node. Then load the blockid of the left-child of the b-tree
  144874. ** node into variable iChild.
  144875. **
  144876. ** Even if the data structure on disk is corrupted, this (reading two
  144877. ** varints from the buffer) does not risk an overread. If zNode is a
  144878. ** root node, then the buffer comes from a SELECT statement. SQLite does
  144879. ** not make this guarantee explicitly, but in practice there are always
  144880. ** either more than 20 bytes of allocated space following the nNode bytes of
  144881. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  144882. ** table, then there are always 20 bytes of zeroed padding following the
  144883. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  144884. */
  144885. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  144886. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  144887. if( zCsr>zEnd ){
  144888. return FTS_CORRUPT_VTAB;
  144889. }
  144890. while( zCsr<zEnd && (piFirst || piLast) ){
  144891. int cmp; /* memcmp() result */
  144892. int nSuffix; /* Size of term suffix */
  144893. int nPrefix = 0; /* Size of term prefix */
  144894. int nBuffer; /* Total term size */
  144895. /* Load the next term on the node into zBuffer. Use realloc() to expand
  144896. ** the size of zBuffer if required. */
  144897. if( !isFirstTerm ){
  144898. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  144899. }
  144900. isFirstTerm = 0;
  144901. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  144902. assert( nPrefix>=0 && nSuffix>=0 );
  144903. if( &zCsr[nSuffix]>zEnd ){
  144904. rc = FTS_CORRUPT_VTAB;
  144905. goto finish_scan;
  144906. }
  144907. if( nPrefix+nSuffix>nAlloc ){
  144908. char *zNew;
  144909. nAlloc = (nPrefix+nSuffix) * 2;
  144910. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  144911. if( !zNew ){
  144912. rc = SQLITE_NOMEM;
  144913. goto finish_scan;
  144914. }
  144915. zBuffer = zNew;
  144916. }
  144917. assert( zBuffer );
  144918. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  144919. nBuffer = nPrefix + nSuffix;
  144920. zCsr += nSuffix;
  144921. /* Compare the term we are searching for with the term just loaded from
  144922. ** the interior node. If the specified term is greater than or equal
  144923. ** to the term from the interior node, then all terms on the sub-tree
  144924. ** headed by node iChild are smaller than zTerm. No need to search
  144925. ** iChild.
  144926. **
  144927. ** If the interior node term is larger than the specified term, then
  144928. ** the tree headed by iChild may contain the specified term.
  144929. */
  144930. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  144931. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  144932. *piFirst = iChild;
  144933. piFirst = 0;
  144934. }
  144935. if( piLast && cmp<0 ){
  144936. *piLast = iChild;
  144937. piLast = 0;
  144938. }
  144939. iChild++;
  144940. };
  144941. if( piFirst ) *piFirst = iChild;
  144942. if( piLast ) *piLast = iChild;
  144943. finish_scan:
  144944. sqlite3_free(zBuffer);
  144945. return rc;
  144946. }
  144947. /*
  144948. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  144949. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  144950. ** contains a term. This function searches the sub-tree headed by the zNode
  144951. ** node for the range of leaf nodes that may contain the specified term
  144952. ** or terms for which the specified term is a prefix.
  144953. **
  144954. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  144955. ** left-most leaf node in the tree that may contain the specified term.
  144956. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  144957. ** right-most leaf node that may contain a term for which the specified
  144958. ** term is a prefix.
  144959. **
  144960. ** It is possible that the range of returned leaf nodes does not contain
  144961. ** the specified term or any terms for which it is a prefix. However, if the
  144962. ** segment does contain any such terms, they are stored within the identified
  144963. ** range. Because this function only inspects interior segment nodes (and
  144964. ** never loads leaf nodes into memory), it is not possible to be sure.
  144965. **
  144966. ** If an error occurs, an error code other than SQLITE_OK is returned.
  144967. */
  144968. static int fts3SelectLeaf(
  144969. Fts3Table *p, /* Virtual table handle */
  144970. const char *zTerm, /* Term to select leaves for */
  144971. int nTerm, /* Size of term zTerm in bytes */
  144972. const char *zNode, /* Buffer containing segment interior node */
  144973. int nNode, /* Size of buffer at zNode */
  144974. sqlite3_int64 *piLeaf, /* Selected leaf node */
  144975. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  144976. ){
  144977. int rc = SQLITE_OK; /* Return code */
  144978. int iHeight; /* Height of this node in tree */
  144979. assert( piLeaf || piLeaf2 );
  144980. fts3GetVarint32(zNode, &iHeight);
  144981. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  144982. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  144983. if( rc==SQLITE_OK && iHeight>1 ){
  144984. char *zBlob = 0; /* Blob read from %_segments table */
  144985. int nBlob = 0; /* Size of zBlob in bytes */
  144986. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  144987. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  144988. if( rc==SQLITE_OK ){
  144989. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  144990. }
  144991. sqlite3_free(zBlob);
  144992. piLeaf = 0;
  144993. zBlob = 0;
  144994. }
  144995. if( rc==SQLITE_OK ){
  144996. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  144997. }
  144998. if( rc==SQLITE_OK ){
  144999. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  145000. }
  145001. sqlite3_free(zBlob);
  145002. }
  145003. return rc;
  145004. }
  145005. /*
  145006. ** This function is used to create delta-encoded serialized lists of FTS3
  145007. ** varints. Each call to this function appends a single varint to a list.
  145008. */
  145009. static void fts3PutDeltaVarint(
  145010. char **pp, /* IN/OUT: Output pointer */
  145011. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  145012. sqlite3_int64 iVal /* Write this value to the list */
  145013. ){
  145014. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  145015. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  145016. *piPrev = iVal;
  145017. }
  145018. /*
  145019. ** When this function is called, *ppPoslist is assumed to point to the
  145020. ** start of a position-list. After it returns, *ppPoslist points to the
  145021. ** first byte after the position-list.
  145022. **
  145023. ** A position list is list of positions (delta encoded) and columns for
  145024. ** a single document record of a doclist. So, in other words, this
  145025. ** routine advances *ppPoslist so that it points to the next docid in
  145026. ** the doclist, or to the first byte past the end of the doclist.
  145027. **
  145028. ** If pp is not NULL, then the contents of the position list are copied
  145029. ** to *pp. *pp is set to point to the first byte past the last byte copied
  145030. ** before this function returns.
  145031. */
  145032. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  145033. char *pEnd = *ppPoslist;
  145034. char c = 0;
  145035. /* The end of a position list is marked by a zero encoded as an FTS3
  145036. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  145037. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  145038. ** of some other, multi-byte, value.
  145039. **
  145040. ** The following while-loop moves pEnd to point to the first byte that is not
  145041. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  145042. ** pEnd once more so that it points to the byte immediately following the
  145043. ** last byte in the position-list.
  145044. */
  145045. while( *pEnd | c ){
  145046. c = *pEnd++ & 0x80;
  145047. testcase( c!=0 && (*pEnd)==0 );
  145048. }
  145049. pEnd++; /* Advance past the POS_END terminator byte */
  145050. if( pp ){
  145051. int n = (int)(pEnd - *ppPoslist);
  145052. char *p = *pp;
  145053. memcpy(p, *ppPoslist, n);
  145054. p += n;
  145055. *pp = p;
  145056. }
  145057. *ppPoslist = pEnd;
  145058. }
  145059. /*
  145060. ** When this function is called, *ppPoslist is assumed to point to the
  145061. ** start of a column-list. After it returns, *ppPoslist points to the
  145062. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  145063. **
  145064. ** A column-list is list of delta-encoded positions for a single column
  145065. ** within a single document within a doclist.
  145066. **
  145067. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  145068. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  145069. ** the POS_COLUMN or POS_END that terminates the column-list.
  145070. **
  145071. ** If pp is not NULL, then the contents of the column-list are copied
  145072. ** to *pp. *pp is set to point to the first byte past the last byte copied
  145073. ** before this function returns. The POS_COLUMN or POS_END terminator
  145074. ** is not copied into *pp.
  145075. */
  145076. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  145077. char *pEnd = *ppPoslist;
  145078. char c = 0;
  145079. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  145080. ** not part of a multi-byte varint.
  145081. */
  145082. while( 0xFE & (*pEnd | c) ){
  145083. c = *pEnd++ & 0x80;
  145084. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  145085. }
  145086. if( pp ){
  145087. int n = (int)(pEnd - *ppPoslist);
  145088. char *p = *pp;
  145089. memcpy(p, *ppPoslist, n);
  145090. p += n;
  145091. *pp = p;
  145092. }
  145093. *ppPoslist = pEnd;
  145094. }
  145095. /*
  145096. ** Value used to signify the end of an position-list. This is safe because
  145097. ** it is not possible to have a document with 2^31 terms.
  145098. */
  145099. #define POSITION_LIST_END 0x7fffffff
  145100. /*
  145101. ** This function is used to help parse position-lists. When this function is
  145102. ** called, *pp may point to the start of the next varint in the position-list
  145103. ** being parsed, or it may point to 1 byte past the end of the position-list
  145104. ** (in which case **pp will be a terminator bytes POS_END (0) or
  145105. ** (1)).
  145106. **
  145107. ** If *pp points past the end of the current position-list, set *pi to
  145108. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  145109. ** increment the current value of *pi by the value read, and set *pp to
  145110. ** point to the next value before returning.
  145111. **
  145112. ** Before calling this routine *pi must be initialized to the value of
  145113. ** the previous position, or zero if we are reading the first position
  145114. ** in the position-list. Because positions are delta-encoded, the value
  145115. ** of the previous position is needed in order to compute the value of
  145116. ** the next position.
  145117. */
  145118. static void fts3ReadNextPos(
  145119. char **pp, /* IN/OUT: Pointer into position-list buffer */
  145120. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  145121. ){
  145122. if( (**pp)&0xFE ){
  145123. fts3GetDeltaVarint(pp, pi);
  145124. *pi -= 2;
  145125. }else{
  145126. *pi = POSITION_LIST_END;
  145127. }
  145128. }
  145129. /*
  145130. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  145131. ** the value of iCol encoded as a varint to *pp. This will start a new
  145132. ** column list.
  145133. **
  145134. ** Set *pp to point to the byte just after the last byte written before
  145135. ** returning (do not modify it if iCol==0). Return the total number of bytes
  145136. ** written (0 if iCol==0).
  145137. */
  145138. static int fts3PutColNumber(char **pp, int iCol){
  145139. int n = 0; /* Number of bytes written */
  145140. if( iCol ){
  145141. char *p = *pp; /* Output pointer */
  145142. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  145143. *p = 0x01;
  145144. *pp = &p[n];
  145145. }
  145146. return n;
  145147. }
  145148. /*
  145149. ** Compute the union of two position lists. The output written
  145150. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  145151. ** order and with any duplicates removed. All pointers are
  145152. ** updated appropriately. The caller is responsible for insuring
  145153. ** that there is enough space in *pp to hold the complete output.
  145154. */
  145155. static void fts3PoslistMerge(
  145156. char **pp, /* Output buffer */
  145157. char **pp1, /* Left input list */
  145158. char **pp2 /* Right input list */
  145159. ){
  145160. char *p = *pp;
  145161. char *p1 = *pp1;
  145162. char *p2 = *pp2;
  145163. while( *p1 || *p2 ){
  145164. int iCol1; /* The current column index in pp1 */
  145165. int iCol2; /* The current column index in pp2 */
  145166. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  145167. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  145168. else iCol1 = 0;
  145169. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  145170. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  145171. else iCol2 = 0;
  145172. if( iCol1==iCol2 ){
  145173. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  145174. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  145175. sqlite3_int64 iPrev = 0;
  145176. int n = fts3PutColNumber(&p, iCol1);
  145177. p1 += n;
  145178. p2 += n;
  145179. /* At this point, both p1 and p2 point to the start of column-lists
  145180. ** for the same column (the column with index iCol1 and iCol2).
  145181. ** A column-list is a list of non-negative delta-encoded varints, each
  145182. ** incremented by 2 before being stored. Each list is terminated by a
  145183. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  145184. ** and writes the results to buffer p. p is left pointing to the byte
  145185. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  145186. ** written to the output.
  145187. */
  145188. fts3GetDeltaVarint(&p1, &i1);
  145189. fts3GetDeltaVarint(&p2, &i2);
  145190. do {
  145191. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  145192. iPrev -= 2;
  145193. if( i1==i2 ){
  145194. fts3ReadNextPos(&p1, &i1);
  145195. fts3ReadNextPos(&p2, &i2);
  145196. }else if( i1<i2 ){
  145197. fts3ReadNextPos(&p1, &i1);
  145198. }else{
  145199. fts3ReadNextPos(&p2, &i2);
  145200. }
  145201. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  145202. }else if( iCol1<iCol2 ){
  145203. p1 += fts3PutColNumber(&p, iCol1);
  145204. fts3ColumnlistCopy(&p, &p1);
  145205. }else{
  145206. p2 += fts3PutColNumber(&p, iCol2);
  145207. fts3ColumnlistCopy(&p, &p2);
  145208. }
  145209. }
  145210. *p++ = POS_END;
  145211. *pp = p;
  145212. *pp1 = p1 + 1;
  145213. *pp2 = p2 + 1;
  145214. }
  145215. /*
  145216. ** This function is used to merge two position lists into one. When it is
  145217. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  145218. ** the part of a doclist that follows each document id. For example, if a row
  145219. ** contains:
  145220. **
  145221. ** 'a b c'|'x y z'|'a b b a'
  145222. **
  145223. ** Then the position list for this row for token 'b' would consist of:
  145224. **
  145225. ** 0x02 0x01 0x02 0x03 0x03 0x00
  145226. **
  145227. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  145228. ** byte following the 0x00 terminator of their respective position lists.
  145229. **
  145230. ** If isSaveLeft is 0, an entry is added to the output position list for
  145231. ** each position in *pp2 for which there exists one or more positions in
  145232. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  145233. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  145234. ** slots before it.
  145235. **
  145236. ** e.g. nToken==1 searches for adjacent positions.
  145237. */
  145238. static int fts3PoslistPhraseMerge(
  145239. char **pp, /* IN/OUT: Preallocated output buffer */
  145240. int nToken, /* Maximum difference in token positions */
  145241. int isSaveLeft, /* Save the left position */
  145242. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  145243. char **pp1, /* IN/OUT: Left input list */
  145244. char **pp2 /* IN/OUT: Right input list */
  145245. ){
  145246. char *p = *pp;
  145247. char *p1 = *pp1;
  145248. char *p2 = *pp2;
  145249. int iCol1 = 0;
  145250. int iCol2 = 0;
  145251. /* Never set both isSaveLeft and isExact for the same invocation. */
  145252. assert( isSaveLeft==0 || isExact==0 );
  145253. assert( p!=0 && *p1!=0 && *p2!=0 );
  145254. if( *p1==POS_COLUMN ){
  145255. p1++;
  145256. p1 += fts3GetVarint32(p1, &iCol1);
  145257. }
  145258. if( *p2==POS_COLUMN ){
  145259. p2++;
  145260. p2 += fts3GetVarint32(p2, &iCol2);
  145261. }
  145262. while( 1 ){
  145263. if( iCol1==iCol2 ){
  145264. char *pSave = p;
  145265. sqlite3_int64 iPrev = 0;
  145266. sqlite3_int64 iPos1 = 0;
  145267. sqlite3_int64 iPos2 = 0;
  145268. if( iCol1 ){
  145269. *p++ = POS_COLUMN;
  145270. p += sqlite3Fts3PutVarint(p, iCol1);
  145271. }
  145272. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  145273. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  145274. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  145275. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  145276. while( 1 ){
  145277. if( iPos2==iPos1+nToken
  145278. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  145279. ){
  145280. sqlite3_int64 iSave;
  145281. iSave = isSaveLeft ? iPos1 : iPos2;
  145282. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  145283. pSave = 0;
  145284. assert( p );
  145285. }
  145286. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  145287. if( (*p2&0xFE)==0 ) break;
  145288. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  145289. }else{
  145290. if( (*p1&0xFE)==0 ) break;
  145291. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  145292. }
  145293. }
  145294. if( pSave ){
  145295. assert( pp && p );
  145296. p = pSave;
  145297. }
  145298. fts3ColumnlistCopy(0, &p1);
  145299. fts3ColumnlistCopy(0, &p2);
  145300. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  145301. if( 0==*p1 || 0==*p2 ) break;
  145302. p1++;
  145303. p1 += fts3GetVarint32(p1, &iCol1);
  145304. p2++;
  145305. p2 += fts3GetVarint32(p2, &iCol2);
  145306. }
  145307. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  145308. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  145309. ** end of the position list, or the 0x01 that precedes the next
  145310. ** column-number in the position list.
  145311. */
  145312. else if( iCol1<iCol2 ){
  145313. fts3ColumnlistCopy(0, &p1);
  145314. if( 0==*p1 ) break;
  145315. p1++;
  145316. p1 += fts3GetVarint32(p1, &iCol1);
  145317. }else{
  145318. fts3ColumnlistCopy(0, &p2);
  145319. if( 0==*p2 ) break;
  145320. p2++;
  145321. p2 += fts3GetVarint32(p2, &iCol2);
  145322. }
  145323. }
  145324. fts3PoslistCopy(0, &p2);
  145325. fts3PoslistCopy(0, &p1);
  145326. *pp1 = p1;
  145327. *pp2 = p2;
  145328. if( *pp==p ){
  145329. return 0;
  145330. }
  145331. *p++ = 0x00;
  145332. *pp = p;
  145333. return 1;
  145334. }
  145335. /*
  145336. ** Merge two position-lists as required by the NEAR operator. The argument
  145337. ** position lists correspond to the left and right phrases of an expression
  145338. ** like:
  145339. **
  145340. ** "phrase 1" NEAR "phrase number 2"
  145341. **
  145342. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  145343. ** expression and *pp2 to the right. As usual, the indexes in the position
  145344. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  145345. ** in the example above).
  145346. **
  145347. ** The output position list - written to *pp - is a copy of *pp2 with those
  145348. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  145349. */
  145350. static int fts3PoslistNearMerge(
  145351. char **pp, /* Output buffer */
  145352. char *aTmp, /* Temporary buffer space */
  145353. int nRight, /* Maximum difference in token positions */
  145354. int nLeft, /* Maximum difference in token positions */
  145355. char **pp1, /* IN/OUT: Left input list */
  145356. char **pp2 /* IN/OUT: Right input list */
  145357. ){
  145358. char *p1 = *pp1;
  145359. char *p2 = *pp2;
  145360. char *pTmp1 = aTmp;
  145361. char *pTmp2;
  145362. char *aTmp2;
  145363. int res = 1;
  145364. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  145365. aTmp2 = pTmp2 = pTmp1;
  145366. *pp1 = p1;
  145367. *pp2 = p2;
  145368. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  145369. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  145370. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  145371. }else if( pTmp1!=aTmp ){
  145372. fts3PoslistCopy(pp, &aTmp);
  145373. }else if( pTmp2!=aTmp2 ){
  145374. fts3PoslistCopy(pp, &aTmp2);
  145375. }else{
  145376. res = 0;
  145377. }
  145378. return res;
  145379. }
  145380. /*
  145381. ** An instance of this function is used to merge together the (potentially
  145382. ** large number of) doclists for each term that matches a prefix query.
  145383. ** See function fts3TermSelectMerge() for details.
  145384. */
  145385. typedef struct TermSelect TermSelect;
  145386. struct TermSelect {
  145387. char *aaOutput[16]; /* Malloc'd output buffers */
  145388. int anOutput[16]; /* Size each output buffer in bytes */
  145389. };
  145390. /*
  145391. ** This function is used to read a single varint from a buffer. Parameter
  145392. ** pEnd points 1 byte past the end of the buffer. When this function is
  145393. ** called, if *pp points to pEnd or greater, then the end of the buffer
  145394. ** has been reached. In this case *pp is set to 0 and the function returns.
  145395. **
  145396. ** If *pp does not point to or past pEnd, then a single varint is read
  145397. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  145398. **
  145399. ** If bDescIdx is false, the value read is added to *pVal before returning.
  145400. ** If it is true, the value read is subtracted from *pVal before this
  145401. ** function returns.
  145402. */
  145403. static void fts3GetDeltaVarint3(
  145404. char **pp, /* IN/OUT: Point to read varint from */
  145405. char *pEnd, /* End of buffer */
  145406. int bDescIdx, /* True if docids are descending */
  145407. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  145408. ){
  145409. if( *pp>=pEnd ){
  145410. *pp = 0;
  145411. }else{
  145412. sqlite3_int64 iVal;
  145413. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  145414. if( bDescIdx ){
  145415. *pVal -= iVal;
  145416. }else{
  145417. *pVal += iVal;
  145418. }
  145419. }
  145420. }
  145421. /*
  145422. ** This function is used to write a single varint to a buffer. The varint
  145423. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  145424. ** end of the value written.
  145425. **
  145426. ** If *pbFirst is zero when this function is called, the value written to
  145427. ** the buffer is that of parameter iVal.
  145428. **
  145429. ** If *pbFirst is non-zero when this function is called, then the value
  145430. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  145431. ** (if bDescIdx is non-zero).
  145432. **
  145433. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  145434. ** to the value of parameter iVal.
  145435. */
  145436. static void fts3PutDeltaVarint3(
  145437. char **pp, /* IN/OUT: Output pointer */
  145438. int bDescIdx, /* True for descending docids */
  145439. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  145440. int *pbFirst, /* IN/OUT: True after first int written */
  145441. sqlite3_int64 iVal /* Write this value to the list */
  145442. ){
  145443. sqlite3_int64 iWrite;
  145444. if( bDescIdx==0 || *pbFirst==0 ){
  145445. iWrite = iVal - *piPrev;
  145446. }else{
  145447. iWrite = *piPrev - iVal;
  145448. }
  145449. assert( *pbFirst || *piPrev==0 );
  145450. assert( *pbFirst==0 || iWrite>0 );
  145451. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  145452. *piPrev = iVal;
  145453. *pbFirst = 1;
  145454. }
  145455. /*
  145456. ** This macro is used by various functions that merge doclists. The two
  145457. ** arguments are 64-bit docid values. If the value of the stack variable
  145458. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  145459. ** Otherwise, (i2-i1).
  145460. **
  145461. ** Using this makes it easier to write code that can merge doclists that are
  145462. ** sorted in either ascending or descending order.
  145463. */
  145464. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  145465. /*
  145466. ** This function does an "OR" merge of two doclists (output contains all
  145467. ** positions contained in either argument doclist). If the docids in the
  145468. ** input doclists are sorted in ascending order, parameter bDescDoclist
  145469. ** should be false. If they are sorted in ascending order, it should be
  145470. ** passed a non-zero value.
  145471. **
  145472. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  145473. ** containing the output doclist and SQLITE_OK is returned. In this case
  145474. ** *pnOut is set to the number of bytes in the output doclist.
  145475. **
  145476. ** If an error occurs, an SQLite error code is returned. The output values
  145477. ** are undefined in this case.
  145478. */
  145479. static int fts3DoclistOrMerge(
  145480. int bDescDoclist, /* True if arguments are desc */
  145481. char *a1, int n1, /* First doclist */
  145482. char *a2, int n2, /* Second doclist */
  145483. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  145484. ){
  145485. sqlite3_int64 i1 = 0;
  145486. sqlite3_int64 i2 = 0;
  145487. sqlite3_int64 iPrev = 0;
  145488. char *pEnd1 = &a1[n1];
  145489. char *pEnd2 = &a2[n2];
  145490. char *p1 = a1;
  145491. char *p2 = a2;
  145492. char *p;
  145493. char *aOut;
  145494. int bFirstOut = 0;
  145495. *paOut = 0;
  145496. *pnOut = 0;
  145497. /* Allocate space for the output. Both the input and output doclists
  145498. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  145499. ** then the first docid in each list is simply encoded as a varint. For
  145500. ** each subsequent docid, the varint stored is the difference between the
  145501. ** current and previous docid (a positive number - since the list is in
  145502. ** ascending order).
  145503. **
  145504. ** The first docid written to the output is therefore encoded using the
  145505. ** same number of bytes as it is in whichever of the input lists it is
  145506. ** read from. And each subsequent docid read from the same input list
  145507. ** consumes either the same or less bytes as it did in the input (since
  145508. ** the difference between it and the previous value in the output must
  145509. ** be a positive value less than or equal to the delta value read from
  145510. ** the input list). The same argument applies to all but the first docid
  145511. ** read from the 'other' list. And to the contents of all position lists
  145512. ** that will be copied and merged from the input to the output.
  145513. **
  145514. ** However, if the first docid copied to the output is a negative number,
  145515. ** then the encoding of the first docid from the 'other' input list may
  145516. ** be larger in the output than it was in the input (since the delta value
  145517. ** may be a larger positive integer than the actual docid).
  145518. **
  145519. ** The space required to store the output is therefore the sum of the
  145520. ** sizes of the two inputs, plus enough space for exactly one of the input
  145521. ** docids to grow.
  145522. **
  145523. ** A symetric argument may be made if the doclists are in descending
  145524. ** order.
  145525. */
  145526. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  145527. if( !aOut ) return SQLITE_NOMEM;
  145528. p = aOut;
  145529. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  145530. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  145531. while( p1 || p2 ){
  145532. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  145533. if( p2 && p1 && iDiff==0 ){
  145534. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  145535. fts3PoslistMerge(&p, &p1, &p2);
  145536. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  145537. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  145538. }else if( !p2 || (p1 && iDiff<0) ){
  145539. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  145540. fts3PoslistCopy(&p, &p1);
  145541. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  145542. }else{
  145543. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  145544. fts3PoslistCopy(&p, &p2);
  145545. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  145546. }
  145547. }
  145548. *paOut = aOut;
  145549. *pnOut = (int)(p-aOut);
  145550. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  145551. return SQLITE_OK;
  145552. }
  145553. /*
  145554. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  145555. ** the output contains a copy of each position from the right-hand input
  145556. ** doclist for which there is a position in the left-hand input doclist
  145557. ** exactly nDist tokens before it.
  145558. **
  145559. ** If the docids in the input doclists are sorted in ascending order,
  145560. ** parameter bDescDoclist should be false. If they are sorted in ascending
  145561. ** order, it should be passed a non-zero value.
  145562. **
  145563. ** The right-hand input doclist is overwritten by this function.
  145564. */
  145565. static int fts3DoclistPhraseMerge(
  145566. int bDescDoclist, /* True if arguments are desc */
  145567. int nDist, /* Distance from left to right (1=adjacent) */
  145568. char *aLeft, int nLeft, /* Left doclist */
  145569. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  145570. ){
  145571. sqlite3_int64 i1 = 0;
  145572. sqlite3_int64 i2 = 0;
  145573. sqlite3_int64 iPrev = 0;
  145574. char *aRight = *paRight;
  145575. char *pEnd1 = &aLeft[nLeft];
  145576. char *pEnd2 = &aRight[*pnRight];
  145577. char *p1 = aLeft;
  145578. char *p2 = aRight;
  145579. char *p;
  145580. int bFirstOut = 0;
  145581. char *aOut;
  145582. assert( nDist>0 );
  145583. if( bDescDoclist ){
  145584. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  145585. if( aOut==0 ) return SQLITE_NOMEM;
  145586. }else{
  145587. aOut = aRight;
  145588. }
  145589. p = aOut;
  145590. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  145591. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  145592. while( p1 && p2 ){
  145593. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  145594. if( iDiff==0 ){
  145595. char *pSave = p;
  145596. sqlite3_int64 iPrevSave = iPrev;
  145597. int bFirstOutSave = bFirstOut;
  145598. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  145599. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  145600. p = pSave;
  145601. iPrev = iPrevSave;
  145602. bFirstOut = bFirstOutSave;
  145603. }
  145604. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  145605. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  145606. }else if( iDiff<0 ){
  145607. fts3PoslistCopy(0, &p1);
  145608. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  145609. }else{
  145610. fts3PoslistCopy(0, &p2);
  145611. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  145612. }
  145613. }
  145614. *pnRight = (int)(p - aOut);
  145615. if( bDescDoclist ){
  145616. sqlite3_free(aRight);
  145617. *paRight = aOut;
  145618. }
  145619. return SQLITE_OK;
  145620. }
  145621. /*
  145622. ** Argument pList points to a position list nList bytes in size. This
  145623. ** function checks to see if the position list contains any entries for
  145624. ** a token in position 0 (of any column). If so, it writes argument iDelta
  145625. ** to the output buffer pOut, followed by a position list consisting only
  145626. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  145627. ** The value returned is the number of bytes written to pOut (if any).
  145628. */
  145629. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  145630. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  145631. char *pList, /* Position list (no 0x00 term) */
  145632. int nList, /* Size of pList in bytes */
  145633. char *pOut /* Write output here */
  145634. ){
  145635. int nOut = 0;
  145636. int bWritten = 0; /* True once iDelta has been written */
  145637. char *p = pList;
  145638. char *pEnd = &pList[nList];
  145639. if( *p!=0x01 ){
  145640. if( *p==0x02 ){
  145641. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  145642. pOut[nOut++] = 0x02;
  145643. bWritten = 1;
  145644. }
  145645. fts3ColumnlistCopy(0, &p);
  145646. }
  145647. while( p<pEnd ){
  145648. sqlite3_int64 iCol;
  145649. p++;
  145650. p += sqlite3Fts3GetVarint(p, &iCol);
  145651. if( *p==0x02 ){
  145652. if( bWritten==0 ){
  145653. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  145654. bWritten = 1;
  145655. }
  145656. pOut[nOut++] = 0x01;
  145657. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  145658. pOut[nOut++] = 0x02;
  145659. }
  145660. fts3ColumnlistCopy(0, &p);
  145661. }
  145662. if( bWritten ){
  145663. pOut[nOut++] = 0x00;
  145664. }
  145665. return nOut;
  145666. }
  145667. /*
  145668. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  145669. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  145670. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  145671. **
  145672. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  145673. ** the responsibility of the caller to free any doclists left in the
  145674. ** TermSelect.aaOutput[] array.
  145675. */
  145676. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  145677. char *aOut = 0;
  145678. int nOut = 0;
  145679. int i;
  145680. /* Loop through the doclists in the aaOutput[] array. Merge them all
  145681. ** into a single doclist.
  145682. */
  145683. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  145684. if( pTS->aaOutput[i] ){
  145685. if( !aOut ){
  145686. aOut = pTS->aaOutput[i];
  145687. nOut = pTS->anOutput[i];
  145688. pTS->aaOutput[i] = 0;
  145689. }else{
  145690. int nNew;
  145691. char *aNew;
  145692. int rc = fts3DoclistOrMerge(p->bDescIdx,
  145693. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  145694. );
  145695. if( rc!=SQLITE_OK ){
  145696. sqlite3_free(aOut);
  145697. return rc;
  145698. }
  145699. sqlite3_free(pTS->aaOutput[i]);
  145700. sqlite3_free(aOut);
  145701. pTS->aaOutput[i] = 0;
  145702. aOut = aNew;
  145703. nOut = nNew;
  145704. }
  145705. }
  145706. }
  145707. pTS->aaOutput[0] = aOut;
  145708. pTS->anOutput[0] = nOut;
  145709. return SQLITE_OK;
  145710. }
  145711. /*
  145712. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  145713. ** as the first argument. The merge is an "OR" merge (see function
  145714. ** fts3DoclistOrMerge() for details).
  145715. **
  145716. ** This function is called with the doclist for each term that matches
  145717. ** a queried prefix. It merges all these doclists into one, the doclist
  145718. ** for the specified prefix. Since there can be a very large number of
  145719. ** doclists to merge, the merging is done pair-wise using the TermSelect
  145720. ** object.
  145721. **
  145722. ** This function returns SQLITE_OK if the merge is successful, or an
  145723. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  145724. */
  145725. static int fts3TermSelectMerge(
  145726. Fts3Table *p, /* FTS table handle */
  145727. TermSelect *pTS, /* TermSelect object to merge into */
  145728. char *aDoclist, /* Pointer to doclist */
  145729. int nDoclist /* Size of aDoclist in bytes */
  145730. ){
  145731. if( pTS->aaOutput[0]==0 ){
  145732. /* If this is the first term selected, copy the doclist to the output
  145733. ** buffer using memcpy().
  145734. **
  145735. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  145736. ** allocation. This is so as to ensure that the buffer is big enough
  145737. ** to hold the current doclist AND'd with any other doclist. If the
  145738. ** doclists are stored in order=ASC order, this padding would not be
  145739. ** required (since the size of [doclistA AND doclistB] is always less
  145740. ** than or equal to the size of [doclistA] in that case). But this is
  145741. ** not true for order=DESC. For example, a doclist containing (1, -1)
  145742. ** may be smaller than (-1), as in the first example the -1 may be stored
  145743. ** as a single-byte delta, whereas in the second it must be stored as a
  145744. ** FTS3_VARINT_MAX byte varint.
  145745. **
  145746. ** Similar padding is added in the fts3DoclistOrMerge() function.
  145747. */
  145748. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  145749. pTS->anOutput[0] = nDoclist;
  145750. if( pTS->aaOutput[0] ){
  145751. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  145752. }else{
  145753. return SQLITE_NOMEM;
  145754. }
  145755. }else{
  145756. char *aMerge = aDoclist;
  145757. int nMerge = nDoclist;
  145758. int iOut;
  145759. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  145760. if( pTS->aaOutput[iOut]==0 ){
  145761. assert( iOut>0 );
  145762. pTS->aaOutput[iOut] = aMerge;
  145763. pTS->anOutput[iOut] = nMerge;
  145764. break;
  145765. }else{
  145766. char *aNew;
  145767. int nNew;
  145768. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  145769. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  145770. );
  145771. if( rc!=SQLITE_OK ){
  145772. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  145773. return rc;
  145774. }
  145775. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  145776. sqlite3_free(pTS->aaOutput[iOut]);
  145777. pTS->aaOutput[iOut] = 0;
  145778. aMerge = aNew;
  145779. nMerge = nNew;
  145780. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  145781. pTS->aaOutput[iOut] = aMerge;
  145782. pTS->anOutput[iOut] = nMerge;
  145783. }
  145784. }
  145785. }
  145786. }
  145787. return SQLITE_OK;
  145788. }
  145789. /*
  145790. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  145791. */
  145792. static int fts3SegReaderCursorAppend(
  145793. Fts3MultiSegReader *pCsr,
  145794. Fts3SegReader *pNew
  145795. ){
  145796. if( (pCsr->nSegment%16)==0 ){
  145797. Fts3SegReader **apNew;
  145798. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  145799. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  145800. if( !apNew ){
  145801. sqlite3Fts3SegReaderFree(pNew);
  145802. return SQLITE_NOMEM;
  145803. }
  145804. pCsr->apSegment = apNew;
  145805. }
  145806. pCsr->apSegment[pCsr->nSegment++] = pNew;
  145807. return SQLITE_OK;
  145808. }
  145809. /*
  145810. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  145811. ** 8th argument.
  145812. **
  145813. ** This function returns SQLITE_OK if successful, or an SQLite error code
  145814. ** otherwise.
  145815. */
  145816. static int fts3SegReaderCursor(
  145817. Fts3Table *p, /* FTS3 table handle */
  145818. int iLangid, /* Language id */
  145819. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  145820. int iLevel, /* Level of segments to scan */
  145821. const char *zTerm, /* Term to query for */
  145822. int nTerm, /* Size of zTerm in bytes */
  145823. int isPrefix, /* True for a prefix search */
  145824. int isScan, /* True to scan from zTerm to EOF */
  145825. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  145826. ){
  145827. int rc = SQLITE_OK; /* Error code */
  145828. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  145829. int rc2; /* Result of sqlite3_reset() */
  145830. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  145831. ** for the pending-terms. If this is a scan, then this call must be being
  145832. ** made by an fts4aux module, not an FTS table. In this case calling
  145833. ** Fts3SegReaderPending might segfault, as the data structures used by
  145834. ** fts4aux are not completely populated. So it's easiest to filter these
  145835. ** calls out here. */
  145836. if( iLevel<0 && p->aIndex ){
  145837. Fts3SegReader *pSeg = 0;
  145838. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  145839. if( rc==SQLITE_OK && pSeg ){
  145840. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  145841. }
  145842. }
  145843. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  145844. if( rc==SQLITE_OK ){
  145845. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  145846. }
  145847. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  145848. Fts3SegReader *pSeg = 0;
  145849. /* Read the values returned by the SELECT into local variables. */
  145850. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  145851. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  145852. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  145853. int nRoot = sqlite3_column_bytes(pStmt, 4);
  145854. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  145855. /* If zTerm is not NULL, and this segment is not stored entirely on its
  145856. ** root node, the range of leaves scanned can be reduced. Do this. */
  145857. if( iStartBlock && zTerm ){
  145858. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  145859. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  145860. if( rc!=SQLITE_OK ) goto finished;
  145861. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  145862. }
  145863. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  145864. (isPrefix==0 && isScan==0),
  145865. iStartBlock, iLeavesEndBlock,
  145866. iEndBlock, zRoot, nRoot, &pSeg
  145867. );
  145868. if( rc!=SQLITE_OK ) goto finished;
  145869. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  145870. }
  145871. }
  145872. finished:
  145873. rc2 = sqlite3_reset(pStmt);
  145874. if( rc==SQLITE_DONE ) rc = rc2;
  145875. return rc;
  145876. }
  145877. /*
  145878. ** Set up a cursor object for iterating through a full-text index or a
  145879. ** single level therein.
  145880. */
  145881. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  145882. Fts3Table *p, /* FTS3 table handle */
  145883. int iLangid, /* Language-id to search */
  145884. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  145885. int iLevel, /* Level of segments to scan */
  145886. const char *zTerm, /* Term to query for */
  145887. int nTerm, /* Size of zTerm in bytes */
  145888. int isPrefix, /* True for a prefix search */
  145889. int isScan, /* True to scan from zTerm to EOF */
  145890. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  145891. ){
  145892. assert( iIndex>=0 && iIndex<p->nIndex );
  145893. assert( iLevel==FTS3_SEGCURSOR_ALL
  145894. || iLevel==FTS3_SEGCURSOR_PENDING
  145895. || iLevel>=0
  145896. );
  145897. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  145898. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  145899. assert( isPrefix==0 || isScan==0 );
  145900. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  145901. return fts3SegReaderCursor(
  145902. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  145903. );
  145904. }
  145905. /*
  145906. ** In addition to its current configuration, have the Fts3MultiSegReader
  145907. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  145908. **
  145909. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  145910. */
  145911. static int fts3SegReaderCursorAddZero(
  145912. Fts3Table *p, /* FTS virtual table handle */
  145913. int iLangid,
  145914. const char *zTerm, /* Term to scan doclist of */
  145915. int nTerm, /* Number of bytes in zTerm */
  145916. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  145917. ){
  145918. return fts3SegReaderCursor(p,
  145919. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  145920. );
  145921. }
  145922. /*
  145923. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  145924. ** if isPrefix is true, to scan the doclist for all terms for which
  145925. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  145926. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  145927. ** an SQLite error code.
  145928. **
  145929. ** It is the responsibility of the caller to free this object by eventually
  145930. ** passing it to fts3SegReaderCursorFree()
  145931. **
  145932. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  145933. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  145934. */
  145935. static int fts3TermSegReaderCursor(
  145936. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  145937. const char *zTerm, /* Term to query for */
  145938. int nTerm, /* Size of zTerm in bytes */
  145939. int isPrefix, /* True for a prefix search */
  145940. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  145941. ){
  145942. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  145943. int rc = SQLITE_NOMEM; /* Return code */
  145944. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  145945. if( pSegcsr ){
  145946. int i;
  145947. int bFound = 0; /* True once an index has been found */
  145948. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  145949. if( isPrefix ){
  145950. for(i=1; bFound==0 && i<p->nIndex; i++){
  145951. if( p->aIndex[i].nPrefix==nTerm ){
  145952. bFound = 1;
  145953. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  145954. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  145955. );
  145956. pSegcsr->bLookup = 1;
  145957. }
  145958. }
  145959. for(i=1; bFound==0 && i<p->nIndex; i++){
  145960. if( p->aIndex[i].nPrefix==nTerm+1 ){
  145961. bFound = 1;
  145962. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  145963. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  145964. );
  145965. if( rc==SQLITE_OK ){
  145966. rc = fts3SegReaderCursorAddZero(
  145967. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  145968. );
  145969. }
  145970. }
  145971. }
  145972. }
  145973. if( bFound==0 ){
  145974. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  145975. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  145976. );
  145977. pSegcsr->bLookup = !isPrefix;
  145978. }
  145979. }
  145980. *ppSegcsr = pSegcsr;
  145981. return rc;
  145982. }
  145983. /*
  145984. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  145985. */
  145986. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  145987. sqlite3Fts3SegReaderFinish(pSegcsr);
  145988. sqlite3_free(pSegcsr);
  145989. }
  145990. /*
  145991. ** This function retrieves the doclist for the specified term (or term
  145992. ** prefix) from the database.
  145993. */
  145994. static int fts3TermSelect(
  145995. Fts3Table *p, /* Virtual table handle */
  145996. Fts3PhraseToken *pTok, /* Token to query for */
  145997. int iColumn, /* Column to query (or -ve for all columns) */
  145998. int *pnOut, /* OUT: Size of buffer at *ppOut */
  145999. char **ppOut /* OUT: Malloced result buffer */
  146000. ){
  146001. int rc; /* Return code */
  146002. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  146003. TermSelect tsc; /* Object for pair-wise doclist merging */
  146004. Fts3SegFilter filter; /* Segment term filter configuration */
  146005. pSegcsr = pTok->pSegcsr;
  146006. memset(&tsc, 0, sizeof(TermSelect));
  146007. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  146008. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  146009. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  146010. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  146011. filter.iCol = iColumn;
  146012. filter.zTerm = pTok->z;
  146013. filter.nTerm = pTok->n;
  146014. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  146015. while( SQLITE_OK==rc
  146016. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  146017. ){
  146018. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  146019. }
  146020. if( rc==SQLITE_OK ){
  146021. rc = fts3TermSelectFinishMerge(p, &tsc);
  146022. }
  146023. if( rc==SQLITE_OK ){
  146024. *ppOut = tsc.aaOutput[0];
  146025. *pnOut = tsc.anOutput[0];
  146026. }else{
  146027. int i;
  146028. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  146029. sqlite3_free(tsc.aaOutput[i]);
  146030. }
  146031. }
  146032. fts3SegReaderCursorFree(pSegcsr);
  146033. pTok->pSegcsr = 0;
  146034. return rc;
  146035. }
  146036. /*
  146037. ** This function counts the total number of docids in the doclist stored
  146038. ** in buffer aList[], size nList bytes.
  146039. **
  146040. ** If the isPoslist argument is true, then it is assumed that the doclist
  146041. ** contains a position-list following each docid. Otherwise, it is assumed
  146042. ** that the doclist is simply a list of docids stored as delta encoded
  146043. ** varints.
  146044. */
  146045. static int fts3DoclistCountDocids(char *aList, int nList){
  146046. int nDoc = 0; /* Return value */
  146047. if( aList ){
  146048. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  146049. char *p = aList; /* Cursor */
  146050. while( p<aEnd ){
  146051. nDoc++;
  146052. while( (*p++)&0x80 ); /* Skip docid varint */
  146053. fts3PoslistCopy(0, &p); /* Skip over position list */
  146054. }
  146055. }
  146056. return nDoc;
  146057. }
  146058. /*
  146059. ** Advance the cursor to the next row in the %_content table that
  146060. ** matches the search criteria. For a MATCH search, this will be
  146061. ** the next row that matches. For a full-table scan, this will be
  146062. ** simply the next row in the %_content table. For a docid lookup,
  146063. ** this routine simply sets the EOF flag.
  146064. **
  146065. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  146066. ** even if we reach end-of-file. The fts3EofMethod() will be called
  146067. ** subsequently to determine whether or not an EOF was hit.
  146068. */
  146069. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  146070. int rc;
  146071. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  146072. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  146073. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  146074. pCsr->isEof = 1;
  146075. rc = sqlite3_reset(pCsr->pStmt);
  146076. }else{
  146077. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  146078. rc = SQLITE_OK;
  146079. }
  146080. }else{
  146081. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  146082. }
  146083. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  146084. return rc;
  146085. }
  146086. /*
  146087. ** The following are copied from sqliteInt.h.
  146088. **
  146089. ** Constants for the largest and smallest possible 64-bit signed integers.
  146090. ** These macros are designed to work correctly on both 32-bit and 64-bit
  146091. ** compilers.
  146092. */
  146093. #ifndef SQLITE_AMALGAMATION
  146094. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  146095. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  146096. #endif
  146097. /*
  146098. ** If the numeric type of argument pVal is "integer", then return it
  146099. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  146100. ** the second parameter, iDefault.
  146101. */
  146102. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  146103. if( pVal ){
  146104. int eType = sqlite3_value_numeric_type(pVal);
  146105. if( eType==SQLITE_INTEGER ){
  146106. return sqlite3_value_int64(pVal);
  146107. }
  146108. }
  146109. return iDefault;
  146110. }
  146111. /*
  146112. ** This is the xFilter interface for the virtual table. See
  146113. ** the virtual table xFilter method documentation for additional
  146114. ** information.
  146115. **
  146116. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  146117. ** the %_content table.
  146118. **
  146119. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  146120. ** in the %_content table.
  146121. **
  146122. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  146123. ** column on the left-hand side of the MATCH operator is column
  146124. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  146125. ** side of the MATCH operator.
  146126. */
  146127. static int fts3FilterMethod(
  146128. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  146129. int idxNum, /* Strategy index */
  146130. const char *idxStr, /* Unused */
  146131. int nVal, /* Number of elements in apVal */
  146132. sqlite3_value **apVal /* Arguments for the indexing scheme */
  146133. ){
  146134. int rc = SQLITE_OK;
  146135. char *zSql; /* SQL statement used to access %_content */
  146136. int eSearch;
  146137. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  146138. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  146139. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  146140. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  146141. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  146142. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  146143. int iIdx;
  146144. UNUSED_PARAMETER(idxStr);
  146145. UNUSED_PARAMETER(nVal);
  146146. eSearch = (idxNum & 0x0000FFFF);
  146147. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  146148. assert( p->pSegments==0 );
  146149. /* Collect arguments into local variables */
  146150. iIdx = 0;
  146151. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  146152. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  146153. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  146154. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  146155. assert( iIdx==nVal );
  146156. /* In case the cursor has been used before, clear it now. */
  146157. fts3ClearCursor(pCsr);
  146158. /* Set the lower and upper bounds on docids to return */
  146159. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  146160. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  146161. if( idxStr ){
  146162. pCsr->bDesc = (idxStr[0]=='D');
  146163. }else{
  146164. pCsr->bDesc = p->bDescIdx;
  146165. }
  146166. pCsr->eSearch = (i16)eSearch;
  146167. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  146168. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  146169. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  146170. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  146171. return SQLITE_NOMEM;
  146172. }
  146173. pCsr->iLangid = 0;
  146174. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  146175. assert( p->base.zErrMsg==0 );
  146176. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  146177. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  146178. &p->base.zErrMsg
  146179. );
  146180. if( rc!=SQLITE_OK ){
  146181. return rc;
  146182. }
  146183. rc = fts3EvalStart(pCsr);
  146184. sqlite3Fts3SegmentsClose(p);
  146185. if( rc!=SQLITE_OK ) return rc;
  146186. pCsr->pNextId = pCsr->aDoclist;
  146187. pCsr->iPrevId = 0;
  146188. }
  146189. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  146190. ** statement loops through all rows of the %_content table. For a
  146191. ** full-text query or docid lookup, the statement retrieves a single
  146192. ** row by docid.
  146193. */
  146194. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  146195. if( pDocidGe || pDocidLe ){
  146196. zSql = sqlite3_mprintf(
  146197. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  146198. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  146199. (pCsr->bDesc ? "DESC" : "ASC")
  146200. );
  146201. }else{
  146202. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  146203. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  146204. );
  146205. }
  146206. if( zSql ){
  146207. rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  146208. sqlite3_free(zSql);
  146209. }else{
  146210. rc = SQLITE_NOMEM;
  146211. }
  146212. }else if( eSearch==FTS3_DOCID_SEARCH ){
  146213. rc = fts3CursorSeekStmt(pCsr);
  146214. if( rc==SQLITE_OK ){
  146215. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  146216. }
  146217. }
  146218. if( rc!=SQLITE_OK ) return rc;
  146219. return fts3NextMethod(pCursor);
  146220. }
  146221. /*
  146222. ** This is the xEof method of the virtual table. SQLite calls this
  146223. ** routine to find out if it has reached the end of a result set.
  146224. */
  146225. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  146226. Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
  146227. if( pCsr->isEof ){
  146228. fts3ClearCursor(pCsr);
  146229. pCsr->isEof = 1;
  146230. }
  146231. return pCsr->isEof;
  146232. }
  146233. /*
  146234. ** This is the xRowid method. The SQLite core calls this routine to
  146235. ** retrieve the rowid for the current row of the result set. fts3
  146236. ** exposes %_content.docid as the rowid for the virtual table. The
  146237. ** rowid should be written to *pRowid.
  146238. */
  146239. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  146240. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  146241. *pRowid = pCsr->iPrevId;
  146242. return SQLITE_OK;
  146243. }
  146244. /*
  146245. ** This is the xColumn method, called by SQLite to request a value from
  146246. ** the row that the supplied cursor currently points to.
  146247. **
  146248. ** If:
  146249. **
  146250. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  146251. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  146252. ** (iCol == p->nColumn+1) -> Docid column
  146253. ** (iCol == p->nColumn+2) -> Langid column
  146254. */
  146255. static int fts3ColumnMethod(
  146256. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  146257. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  146258. int iCol /* Index of column to read value from */
  146259. ){
  146260. int rc = SQLITE_OK; /* Return Code */
  146261. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  146262. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  146263. /* The column value supplied by SQLite must be in range. */
  146264. assert( iCol>=0 && iCol<=p->nColumn+2 );
  146265. switch( iCol-p->nColumn ){
  146266. case 0:
  146267. /* The special 'table-name' column */
  146268. sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
  146269. break;
  146270. case 1:
  146271. /* The docid column */
  146272. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  146273. break;
  146274. case 2:
  146275. if( pCsr->pExpr ){
  146276. sqlite3_result_int64(pCtx, pCsr->iLangid);
  146277. break;
  146278. }else if( p->zLanguageid==0 ){
  146279. sqlite3_result_int(pCtx, 0);
  146280. break;
  146281. }else{
  146282. iCol = p->nColumn;
  146283. /* fall-through */
  146284. }
  146285. default:
  146286. /* A user column. Or, if this is a full-table scan, possibly the
  146287. ** language-id column. Seek the cursor. */
  146288. rc = fts3CursorSeek(0, pCsr);
  146289. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  146290. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  146291. }
  146292. break;
  146293. }
  146294. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  146295. return rc;
  146296. }
  146297. /*
  146298. ** This function is the implementation of the xUpdate callback used by
  146299. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  146300. ** inserted, updated or deleted.
  146301. */
  146302. static int fts3UpdateMethod(
  146303. sqlite3_vtab *pVtab, /* Virtual table handle */
  146304. int nArg, /* Size of argument array */
  146305. sqlite3_value **apVal, /* Array of arguments */
  146306. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  146307. ){
  146308. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  146309. }
  146310. /*
  146311. ** Implementation of xSync() method. Flush the contents of the pending-terms
  146312. ** hash-table to the database.
  146313. */
  146314. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  146315. /* Following an incremental-merge operation, assuming that the input
  146316. ** segments are not completely consumed (the usual case), they are updated
  146317. ** in place to remove the entries that have already been merged. This
  146318. ** involves updating the leaf block that contains the smallest unmerged
  146319. ** entry and each block (if any) between the leaf and the root node. So
  146320. ** if the height of the input segment b-trees is N, and input segments
  146321. ** are merged eight at a time, updating the input segments at the end
  146322. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  146323. ** small - often between 0 and 2. So the overhead of the incremental
  146324. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  146325. ** dwarfing the actual productive work accomplished, the incremental merge
  146326. ** is only attempted if it will write at least 64 leaf blocks. Hence
  146327. ** nMinMerge.
  146328. **
  146329. ** Of course, updating the input segments also involves deleting a bunch
  146330. ** of blocks from the segments table. But this is not considered overhead
  146331. ** as it would also be required by a crisis-merge that used the same input
  146332. ** segments.
  146333. */
  146334. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  146335. Fts3Table *p = (Fts3Table*)pVtab;
  146336. int rc;
  146337. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  146338. rc = sqlite3Fts3PendingTermsFlush(p);
  146339. if( rc==SQLITE_OK
  146340. && p->nLeafAdd>(nMinMerge/16)
  146341. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  146342. ){
  146343. int mxLevel = 0; /* Maximum relative level value in db */
  146344. int A; /* Incr-merge parameter A */
  146345. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  146346. assert( rc==SQLITE_OK || mxLevel==0 );
  146347. A = p->nLeafAdd * mxLevel;
  146348. A += (A/2);
  146349. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  146350. }
  146351. sqlite3Fts3SegmentsClose(p);
  146352. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  146353. return rc;
  146354. }
  146355. /*
  146356. ** If it is currently unknown whether or not the FTS table has an %_stat
  146357. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  146358. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  146359. ** if an error occurs.
  146360. */
  146361. static int fts3SetHasStat(Fts3Table *p){
  146362. int rc = SQLITE_OK;
  146363. if( p->bHasStat==2 ){
  146364. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  146365. if( zTbl ){
  146366. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  146367. sqlite3_free(zTbl);
  146368. p->bHasStat = (res==SQLITE_OK);
  146369. }else{
  146370. rc = SQLITE_NOMEM;
  146371. }
  146372. }
  146373. return rc;
  146374. }
  146375. /*
  146376. ** Implementation of xBegin() method.
  146377. */
  146378. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  146379. Fts3Table *p = (Fts3Table*)pVtab;
  146380. UNUSED_PARAMETER(pVtab);
  146381. assert( p->pSegments==0 );
  146382. assert( p->nPendingData==0 );
  146383. assert( p->inTransaction!=1 );
  146384. TESTONLY( p->inTransaction = 1 );
  146385. TESTONLY( p->mxSavepoint = -1; );
  146386. p->nLeafAdd = 0;
  146387. return fts3SetHasStat(p);
  146388. }
  146389. /*
  146390. ** Implementation of xCommit() method. This is a no-op. The contents of
  146391. ** the pending-terms hash-table have already been flushed into the database
  146392. ** by fts3SyncMethod().
  146393. */
  146394. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  146395. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  146396. UNUSED_PARAMETER(pVtab);
  146397. assert( p->nPendingData==0 );
  146398. assert( p->inTransaction!=0 );
  146399. assert( p->pSegments==0 );
  146400. TESTONLY( p->inTransaction = 0 );
  146401. TESTONLY( p->mxSavepoint = -1; );
  146402. return SQLITE_OK;
  146403. }
  146404. /*
  146405. ** Implementation of xRollback(). Discard the contents of the pending-terms
  146406. ** hash-table. Any changes made to the database are reverted by SQLite.
  146407. */
  146408. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  146409. Fts3Table *p = (Fts3Table*)pVtab;
  146410. sqlite3Fts3PendingTermsClear(p);
  146411. assert( p->inTransaction!=0 );
  146412. TESTONLY( p->inTransaction = 0 );
  146413. TESTONLY( p->mxSavepoint = -1; );
  146414. return SQLITE_OK;
  146415. }
  146416. /*
  146417. ** When called, *ppPoslist must point to the byte immediately following the
  146418. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  146419. ** moves *ppPoslist so that it instead points to the first byte of the
  146420. ** same position list.
  146421. */
  146422. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  146423. char *p = &(*ppPoslist)[-2];
  146424. char c = 0;
  146425. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  146426. while( p>pStart && (c=*p--)==0 );
  146427. /* Search backwards for a varint with value zero (the end of the previous
  146428. ** poslist). This is an 0x00 byte preceded by some byte that does not
  146429. ** have the 0x80 bit set. */
  146430. while( p>pStart && (*p & 0x80) | c ){
  146431. c = *p--;
  146432. }
  146433. assert( p==pStart || c==0 );
  146434. /* At this point p points to that preceding byte without the 0x80 bit
  146435. ** set. So to find the start of the poslist, skip forward 2 bytes then
  146436. ** over a varint.
  146437. **
  146438. ** Normally. The other case is that p==pStart and the poslist to return
  146439. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  146440. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  146441. ** is required for cases where the first byte of a doclist and the
  146442. ** doclist is empty. For example, if the first docid is 10, a doclist
  146443. ** that begins with:
  146444. **
  146445. ** 0x0A 0x00 <next docid delta varint>
  146446. */
  146447. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  146448. while( *p++&0x80 );
  146449. *ppPoslist = p;
  146450. }
  146451. /*
  146452. ** Helper function used by the implementation of the overloaded snippet(),
  146453. ** offsets() and optimize() SQL functions.
  146454. **
  146455. ** If the value passed as the third argument is a blob of size
  146456. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  146457. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  146458. ** message is written to context pContext and SQLITE_ERROR returned. The
  146459. ** string passed via zFunc is used as part of the error message.
  146460. */
  146461. static int fts3FunctionArg(
  146462. sqlite3_context *pContext, /* SQL function call context */
  146463. const char *zFunc, /* Function name */
  146464. sqlite3_value *pVal, /* argv[0] passed to function */
  146465. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  146466. ){
  146467. int rc;
  146468. *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
  146469. if( (*ppCsr)!=0 ){
  146470. rc = SQLITE_OK;
  146471. }else{
  146472. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  146473. sqlite3_result_error(pContext, zErr, -1);
  146474. sqlite3_free(zErr);
  146475. rc = SQLITE_ERROR;
  146476. }
  146477. return rc;
  146478. }
  146479. /*
  146480. ** Implementation of the snippet() function for FTS3
  146481. */
  146482. static void fts3SnippetFunc(
  146483. sqlite3_context *pContext, /* SQLite function call context */
  146484. int nVal, /* Size of apVal[] array */
  146485. sqlite3_value **apVal /* Array of arguments */
  146486. ){
  146487. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  146488. const char *zStart = "<b>";
  146489. const char *zEnd = "</b>";
  146490. const char *zEllipsis = "<b>...</b>";
  146491. int iCol = -1;
  146492. int nToken = 15; /* Default number of tokens in snippet */
  146493. /* There must be at least one argument passed to this function (otherwise
  146494. ** the non-overloaded version would have been called instead of this one).
  146495. */
  146496. assert( nVal>=1 );
  146497. if( nVal>6 ){
  146498. sqlite3_result_error(pContext,
  146499. "wrong number of arguments to function snippet()", -1);
  146500. return;
  146501. }
  146502. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  146503. switch( nVal ){
  146504. case 6: nToken = sqlite3_value_int(apVal[5]);
  146505. case 5: iCol = sqlite3_value_int(apVal[4]);
  146506. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  146507. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  146508. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  146509. }
  146510. if( !zEllipsis || !zEnd || !zStart ){
  146511. sqlite3_result_error_nomem(pContext);
  146512. }else if( nToken==0 ){
  146513. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  146514. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  146515. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  146516. }
  146517. }
  146518. /*
  146519. ** Implementation of the offsets() function for FTS3
  146520. */
  146521. static void fts3OffsetsFunc(
  146522. sqlite3_context *pContext, /* SQLite function call context */
  146523. int nVal, /* Size of argument array */
  146524. sqlite3_value **apVal /* Array of arguments */
  146525. ){
  146526. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  146527. UNUSED_PARAMETER(nVal);
  146528. assert( nVal==1 );
  146529. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  146530. assert( pCsr );
  146531. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  146532. sqlite3Fts3Offsets(pContext, pCsr);
  146533. }
  146534. }
  146535. /*
  146536. ** Implementation of the special optimize() function for FTS3. This
  146537. ** function merges all segments in the database to a single segment.
  146538. ** Example usage is:
  146539. **
  146540. ** SELECT optimize(t) FROM t LIMIT 1;
  146541. **
  146542. ** where 't' is the name of an FTS3 table.
  146543. */
  146544. static void fts3OptimizeFunc(
  146545. sqlite3_context *pContext, /* SQLite function call context */
  146546. int nVal, /* Size of argument array */
  146547. sqlite3_value **apVal /* Array of arguments */
  146548. ){
  146549. int rc; /* Return code */
  146550. Fts3Table *p; /* Virtual table handle */
  146551. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  146552. UNUSED_PARAMETER(nVal);
  146553. assert( nVal==1 );
  146554. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  146555. p = (Fts3Table *)pCursor->base.pVtab;
  146556. assert( p );
  146557. rc = sqlite3Fts3Optimize(p);
  146558. switch( rc ){
  146559. case SQLITE_OK:
  146560. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  146561. break;
  146562. case SQLITE_DONE:
  146563. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  146564. break;
  146565. default:
  146566. sqlite3_result_error_code(pContext, rc);
  146567. break;
  146568. }
  146569. }
  146570. /*
  146571. ** Implementation of the matchinfo() function for FTS3
  146572. */
  146573. static void fts3MatchinfoFunc(
  146574. sqlite3_context *pContext, /* SQLite function call context */
  146575. int nVal, /* Size of argument array */
  146576. sqlite3_value **apVal /* Array of arguments */
  146577. ){
  146578. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  146579. assert( nVal==1 || nVal==2 );
  146580. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  146581. const char *zArg = 0;
  146582. if( nVal>1 ){
  146583. zArg = (const char *)sqlite3_value_text(apVal[1]);
  146584. }
  146585. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  146586. }
  146587. }
  146588. /*
  146589. ** This routine implements the xFindFunction method for the FTS3
  146590. ** virtual table.
  146591. */
  146592. static int fts3FindFunctionMethod(
  146593. sqlite3_vtab *pVtab, /* Virtual table handle */
  146594. int nArg, /* Number of SQL function arguments */
  146595. const char *zName, /* Name of SQL function */
  146596. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  146597. void **ppArg /* Unused */
  146598. ){
  146599. struct Overloaded {
  146600. const char *zName;
  146601. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  146602. } aOverload[] = {
  146603. { "snippet", fts3SnippetFunc },
  146604. { "offsets", fts3OffsetsFunc },
  146605. { "optimize", fts3OptimizeFunc },
  146606. { "matchinfo", fts3MatchinfoFunc },
  146607. };
  146608. int i; /* Iterator variable */
  146609. UNUSED_PARAMETER(pVtab);
  146610. UNUSED_PARAMETER(nArg);
  146611. UNUSED_PARAMETER(ppArg);
  146612. for(i=0; i<SizeofArray(aOverload); i++){
  146613. if( strcmp(zName, aOverload[i].zName)==0 ){
  146614. *pxFunc = aOverload[i].xFunc;
  146615. return 1;
  146616. }
  146617. }
  146618. /* No function of the specified name was found. Return 0. */
  146619. return 0;
  146620. }
  146621. /*
  146622. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  146623. */
  146624. static int fts3RenameMethod(
  146625. sqlite3_vtab *pVtab, /* Virtual table handle */
  146626. const char *zName /* New name of table */
  146627. ){
  146628. Fts3Table *p = (Fts3Table *)pVtab;
  146629. sqlite3 *db = p->db; /* Database connection */
  146630. int rc; /* Return Code */
  146631. /* At this point it must be known if the %_stat table exists or not.
  146632. ** So bHasStat may not be 2. */
  146633. rc = fts3SetHasStat(p);
  146634. /* As it happens, the pending terms table is always empty here. This is
  146635. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  146636. ** always opens a savepoint transaction. And the xSavepoint() method
  146637. ** flushes the pending terms table. But leave the (no-op) call to
  146638. ** PendingTermsFlush() in in case that changes.
  146639. */
  146640. assert( p->nPendingData==0 );
  146641. if( rc==SQLITE_OK ){
  146642. rc = sqlite3Fts3PendingTermsFlush(p);
  146643. }
  146644. if( p->zContentTbl==0 ){
  146645. fts3DbExec(&rc, db,
  146646. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  146647. p->zDb, p->zName, zName
  146648. );
  146649. }
  146650. if( p->bHasDocsize ){
  146651. fts3DbExec(&rc, db,
  146652. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  146653. p->zDb, p->zName, zName
  146654. );
  146655. }
  146656. if( p->bHasStat ){
  146657. fts3DbExec(&rc, db,
  146658. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  146659. p->zDb, p->zName, zName
  146660. );
  146661. }
  146662. fts3DbExec(&rc, db,
  146663. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  146664. p->zDb, p->zName, zName
  146665. );
  146666. fts3DbExec(&rc, db,
  146667. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  146668. p->zDb, p->zName, zName
  146669. );
  146670. return rc;
  146671. }
  146672. /*
  146673. ** The xSavepoint() method.
  146674. **
  146675. ** Flush the contents of the pending-terms table to disk.
  146676. */
  146677. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  146678. int rc = SQLITE_OK;
  146679. UNUSED_PARAMETER(iSavepoint);
  146680. assert( ((Fts3Table *)pVtab)->inTransaction );
  146681. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  146682. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  146683. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  146684. rc = fts3SyncMethod(pVtab);
  146685. }
  146686. return rc;
  146687. }
  146688. /*
  146689. ** The xRelease() method.
  146690. **
  146691. ** This is a no-op.
  146692. */
  146693. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  146694. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  146695. UNUSED_PARAMETER(iSavepoint);
  146696. UNUSED_PARAMETER(pVtab);
  146697. assert( p->inTransaction );
  146698. assert( p->mxSavepoint >= iSavepoint );
  146699. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  146700. return SQLITE_OK;
  146701. }
  146702. /*
  146703. ** The xRollbackTo() method.
  146704. **
  146705. ** Discard the contents of the pending terms table.
  146706. */
  146707. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  146708. Fts3Table *p = (Fts3Table*)pVtab;
  146709. UNUSED_PARAMETER(iSavepoint);
  146710. assert( p->inTransaction );
  146711. assert( p->mxSavepoint >= iSavepoint );
  146712. TESTONLY( p->mxSavepoint = iSavepoint );
  146713. sqlite3Fts3PendingTermsClear(p);
  146714. return SQLITE_OK;
  146715. }
  146716. static const sqlite3_module fts3Module = {
  146717. /* iVersion */ 2,
  146718. /* xCreate */ fts3CreateMethod,
  146719. /* xConnect */ fts3ConnectMethod,
  146720. /* xBestIndex */ fts3BestIndexMethod,
  146721. /* xDisconnect */ fts3DisconnectMethod,
  146722. /* xDestroy */ fts3DestroyMethod,
  146723. /* xOpen */ fts3OpenMethod,
  146724. /* xClose */ fts3CloseMethod,
  146725. /* xFilter */ fts3FilterMethod,
  146726. /* xNext */ fts3NextMethod,
  146727. /* xEof */ fts3EofMethod,
  146728. /* xColumn */ fts3ColumnMethod,
  146729. /* xRowid */ fts3RowidMethod,
  146730. /* xUpdate */ fts3UpdateMethod,
  146731. /* xBegin */ fts3BeginMethod,
  146732. /* xSync */ fts3SyncMethod,
  146733. /* xCommit */ fts3CommitMethod,
  146734. /* xRollback */ fts3RollbackMethod,
  146735. /* xFindFunction */ fts3FindFunctionMethod,
  146736. /* xRename */ fts3RenameMethod,
  146737. /* xSavepoint */ fts3SavepointMethod,
  146738. /* xRelease */ fts3ReleaseMethod,
  146739. /* xRollbackTo */ fts3RollbackToMethod,
  146740. };
  146741. /*
  146742. ** This function is registered as the module destructor (called when an
  146743. ** FTS3 enabled database connection is closed). It frees the memory
  146744. ** allocated for the tokenizer hash table.
  146745. */
  146746. static void hashDestroy(void *p){
  146747. Fts3Hash *pHash = (Fts3Hash *)p;
  146748. sqlite3Fts3HashClear(pHash);
  146749. sqlite3_free(pHash);
  146750. }
  146751. /*
  146752. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  146753. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  146754. ** respectively. The following three forward declarations are for functions
  146755. ** declared in these files used to retrieve the respective implementations.
  146756. **
  146757. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  146758. ** to by the argument to point to the "simple" tokenizer implementation.
  146759. ** And so on.
  146760. */
  146761. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  146762. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  146763. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  146764. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  146765. #endif
  146766. #ifdef SQLITE_ENABLE_ICU
  146767. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  146768. #endif
  146769. /*
  146770. ** Initialize the fts3 extension. If this extension is built as part
  146771. ** of the sqlite library, then this function is called directly by
  146772. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  146773. ** function is called by the sqlite3_extension_init() entry point.
  146774. */
  146775. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  146776. int rc = SQLITE_OK;
  146777. Fts3Hash *pHash = 0;
  146778. const sqlite3_tokenizer_module *pSimple = 0;
  146779. const sqlite3_tokenizer_module *pPorter = 0;
  146780. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  146781. const sqlite3_tokenizer_module *pUnicode = 0;
  146782. #endif
  146783. #ifdef SQLITE_ENABLE_ICU
  146784. const sqlite3_tokenizer_module *pIcu = 0;
  146785. sqlite3Fts3IcuTokenizerModule(&pIcu);
  146786. #endif
  146787. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  146788. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  146789. #endif
  146790. #ifdef SQLITE_TEST
  146791. rc = sqlite3Fts3InitTerm(db);
  146792. if( rc!=SQLITE_OK ) return rc;
  146793. #endif
  146794. rc = sqlite3Fts3InitAux(db);
  146795. if( rc!=SQLITE_OK ) return rc;
  146796. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  146797. sqlite3Fts3PorterTokenizerModule(&pPorter);
  146798. /* Allocate and initialize the hash-table used to store tokenizers. */
  146799. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  146800. if( !pHash ){
  146801. rc = SQLITE_NOMEM;
  146802. }else{
  146803. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  146804. }
  146805. /* Load the built-in tokenizers into the hash table */
  146806. if( rc==SQLITE_OK ){
  146807. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  146808. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  146809. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  146810. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  146811. #endif
  146812. #ifdef SQLITE_ENABLE_ICU
  146813. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  146814. #endif
  146815. ){
  146816. rc = SQLITE_NOMEM;
  146817. }
  146818. }
  146819. #ifdef SQLITE_TEST
  146820. if( rc==SQLITE_OK ){
  146821. rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
  146822. }
  146823. #endif
  146824. /* Create the virtual table wrapper around the hash-table and overload
  146825. ** the four scalar functions. If this is successful, register the
  146826. ** module with sqlite.
  146827. */
  146828. if( SQLITE_OK==rc
  146829. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  146830. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  146831. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  146832. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  146833. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  146834. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  146835. ){
  146836. rc = sqlite3_create_module_v2(
  146837. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  146838. );
  146839. if( rc==SQLITE_OK ){
  146840. rc = sqlite3_create_module_v2(
  146841. db, "fts4", &fts3Module, (void *)pHash, 0
  146842. );
  146843. }
  146844. if( rc==SQLITE_OK ){
  146845. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  146846. }
  146847. return rc;
  146848. }
  146849. /* An error has occurred. Delete the hash table and return the error code. */
  146850. assert( rc!=SQLITE_OK );
  146851. if( pHash ){
  146852. sqlite3Fts3HashClear(pHash);
  146853. sqlite3_free(pHash);
  146854. }
  146855. return rc;
  146856. }
  146857. /*
  146858. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  146859. ** by pExpr.
  146860. **
  146861. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  146862. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  146863. ** Fts3SegReader objects internally to provide an interface to seek or scan
  146864. ** within the union of all segments of a b-tree. Hence the name.
  146865. **
  146866. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  146867. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  146868. ** there exists prefix b-tree of the right length) then it may be traversed
  146869. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  146870. ** doclist and then traversed.
  146871. */
  146872. static void fts3EvalAllocateReaders(
  146873. Fts3Cursor *pCsr, /* FTS cursor handle */
  146874. Fts3Expr *pExpr, /* Allocate readers for this expression */
  146875. int *pnToken, /* OUT: Total number of tokens in phrase. */
  146876. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  146877. int *pRc /* IN/OUT: Error code */
  146878. ){
  146879. if( pExpr && SQLITE_OK==*pRc ){
  146880. if( pExpr->eType==FTSQUERY_PHRASE ){
  146881. int i;
  146882. int nToken = pExpr->pPhrase->nToken;
  146883. *pnToken += nToken;
  146884. for(i=0; i<nToken; i++){
  146885. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  146886. int rc = fts3TermSegReaderCursor(pCsr,
  146887. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  146888. );
  146889. if( rc!=SQLITE_OK ){
  146890. *pRc = rc;
  146891. return;
  146892. }
  146893. }
  146894. assert( pExpr->pPhrase->iDoclistToken==0 );
  146895. pExpr->pPhrase->iDoclistToken = -1;
  146896. }else{
  146897. *pnOr += (pExpr->eType==FTSQUERY_OR);
  146898. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  146899. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  146900. }
  146901. }
  146902. }
  146903. /*
  146904. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  146905. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  146906. **
  146907. ** This function assumes that pList points to a buffer allocated using
  146908. ** sqlite3_malloc(). This function takes responsibility for eventually
  146909. ** freeing the buffer.
  146910. **
  146911. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  146912. */
  146913. static int fts3EvalPhraseMergeToken(
  146914. Fts3Table *pTab, /* FTS Table pointer */
  146915. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  146916. int iToken, /* Token pList/nList corresponds to */
  146917. char *pList, /* Pointer to doclist */
  146918. int nList /* Number of bytes in pList */
  146919. ){
  146920. int rc = SQLITE_OK;
  146921. assert( iToken!=p->iDoclistToken );
  146922. if( pList==0 ){
  146923. sqlite3_free(p->doclist.aAll);
  146924. p->doclist.aAll = 0;
  146925. p->doclist.nAll = 0;
  146926. }
  146927. else if( p->iDoclistToken<0 ){
  146928. p->doclist.aAll = pList;
  146929. p->doclist.nAll = nList;
  146930. }
  146931. else if( p->doclist.aAll==0 ){
  146932. sqlite3_free(pList);
  146933. }
  146934. else {
  146935. char *pLeft;
  146936. char *pRight;
  146937. int nLeft;
  146938. int nRight;
  146939. int nDiff;
  146940. if( p->iDoclistToken<iToken ){
  146941. pLeft = p->doclist.aAll;
  146942. nLeft = p->doclist.nAll;
  146943. pRight = pList;
  146944. nRight = nList;
  146945. nDiff = iToken - p->iDoclistToken;
  146946. }else{
  146947. pRight = p->doclist.aAll;
  146948. nRight = p->doclist.nAll;
  146949. pLeft = pList;
  146950. nLeft = nList;
  146951. nDiff = p->iDoclistToken - iToken;
  146952. }
  146953. rc = fts3DoclistPhraseMerge(
  146954. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  146955. );
  146956. sqlite3_free(pLeft);
  146957. p->doclist.aAll = pRight;
  146958. p->doclist.nAll = nRight;
  146959. }
  146960. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  146961. return rc;
  146962. }
  146963. /*
  146964. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  146965. ** does not take deferred tokens into account.
  146966. **
  146967. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  146968. */
  146969. static int fts3EvalPhraseLoad(
  146970. Fts3Cursor *pCsr, /* FTS Cursor handle */
  146971. Fts3Phrase *p /* Phrase object */
  146972. ){
  146973. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  146974. int iToken;
  146975. int rc = SQLITE_OK;
  146976. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  146977. Fts3PhraseToken *pToken = &p->aToken[iToken];
  146978. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  146979. if( pToken->pSegcsr ){
  146980. int nThis = 0;
  146981. char *pThis = 0;
  146982. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  146983. if( rc==SQLITE_OK ){
  146984. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  146985. }
  146986. }
  146987. assert( pToken->pSegcsr==0 );
  146988. }
  146989. return rc;
  146990. }
  146991. /*
  146992. ** This function is called on each phrase after the position lists for
  146993. ** any deferred tokens have been loaded into memory. It updates the phrases
  146994. ** current position list to include only those positions that are really
  146995. ** instances of the phrase (after considering deferred tokens). If this
  146996. ** means that the phrase does not appear in the current row, doclist.pList
  146997. ** and doclist.nList are both zeroed.
  146998. **
  146999. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  147000. */
  147001. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  147002. int iToken; /* Used to iterate through phrase tokens */
  147003. char *aPoslist = 0; /* Position list for deferred tokens */
  147004. int nPoslist = 0; /* Number of bytes in aPoslist */
  147005. int iPrev = -1; /* Token number of previous deferred token */
  147006. assert( pPhrase->doclist.bFreeList==0 );
  147007. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  147008. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  147009. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  147010. if( pDeferred ){
  147011. char *pList;
  147012. int nList;
  147013. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  147014. if( rc!=SQLITE_OK ) return rc;
  147015. if( pList==0 ){
  147016. sqlite3_free(aPoslist);
  147017. pPhrase->doclist.pList = 0;
  147018. pPhrase->doclist.nList = 0;
  147019. return SQLITE_OK;
  147020. }else if( aPoslist==0 ){
  147021. aPoslist = pList;
  147022. nPoslist = nList;
  147023. }else{
  147024. char *aOut = pList;
  147025. char *p1 = aPoslist;
  147026. char *p2 = aOut;
  147027. assert( iPrev>=0 );
  147028. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  147029. sqlite3_free(aPoslist);
  147030. aPoslist = pList;
  147031. nPoslist = (int)(aOut - aPoslist);
  147032. if( nPoslist==0 ){
  147033. sqlite3_free(aPoslist);
  147034. pPhrase->doclist.pList = 0;
  147035. pPhrase->doclist.nList = 0;
  147036. return SQLITE_OK;
  147037. }
  147038. }
  147039. iPrev = iToken;
  147040. }
  147041. }
  147042. if( iPrev>=0 ){
  147043. int nMaxUndeferred = pPhrase->iDoclistToken;
  147044. if( nMaxUndeferred<0 ){
  147045. pPhrase->doclist.pList = aPoslist;
  147046. pPhrase->doclist.nList = nPoslist;
  147047. pPhrase->doclist.iDocid = pCsr->iPrevId;
  147048. pPhrase->doclist.bFreeList = 1;
  147049. }else{
  147050. int nDistance;
  147051. char *p1;
  147052. char *p2;
  147053. char *aOut;
  147054. if( nMaxUndeferred>iPrev ){
  147055. p1 = aPoslist;
  147056. p2 = pPhrase->doclist.pList;
  147057. nDistance = nMaxUndeferred - iPrev;
  147058. }else{
  147059. p1 = pPhrase->doclist.pList;
  147060. p2 = aPoslist;
  147061. nDistance = iPrev - nMaxUndeferred;
  147062. }
  147063. aOut = (char *)sqlite3_malloc(nPoslist+8);
  147064. if( !aOut ){
  147065. sqlite3_free(aPoslist);
  147066. return SQLITE_NOMEM;
  147067. }
  147068. pPhrase->doclist.pList = aOut;
  147069. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  147070. pPhrase->doclist.bFreeList = 1;
  147071. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  147072. }else{
  147073. sqlite3_free(aOut);
  147074. pPhrase->doclist.pList = 0;
  147075. pPhrase->doclist.nList = 0;
  147076. }
  147077. sqlite3_free(aPoslist);
  147078. }
  147079. }
  147080. return SQLITE_OK;
  147081. }
  147082. /*
  147083. ** Maximum number of tokens a phrase may have to be considered for the
  147084. ** incremental doclists strategy.
  147085. */
  147086. #define MAX_INCR_PHRASE_TOKENS 4
  147087. /*
  147088. ** This function is called for each Fts3Phrase in a full-text query
  147089. ** expression to initialize the mechanism for returning rows. Once this
  147090. ** function has been called successfully on an Fts3Phrase, it may be
  147091. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  147092. **
  147093. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  147094. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  147095. ** memory within this call.
  147096. **
  147097. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  147098. */
  147099. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  147100. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  147101. int rc = SQLITE_OK; /* Error code */
  147102. int i;
  147103. /* Determine if doclists may be loaded from disk incrementally. This is
  147104. ** possible if the bOptOk argument is true, the FTS doclists will be
  147105. ** scanned in forward order, and the phrase consists of
  147106. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  147107. ** tokens or prefix tokens that cannot use a prefix-index. */
  147108. int bHaveIncr = 0;
  147109. int bIncrOk = (bOptOk
  147110. && pCsr->bDesc==pTab->bDescIdx
  147111. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  147112. #ifdef SQLITE_TEST
  147113. && pTab->bNoIncrDoclist==0
  147114. #endif
  147115. );
  147116. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  147117. Fts3PhraseToken *pToken = &p->aToken[i];
  147118. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  147119. bIncrOk = 0;
  147120. }
  147121. if( pToken->pSegcsr ) bHaveIncr = 1;
  147122. }
  147123. if( bIncrOk && bHaveIncr ){
  147124. /* Use the incremental approach. */
  147125. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  147126. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  147127. Fts3PhraseToken *pToken = &p->aToken[i];
  147128. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  147129. if( pSegcsr ){
  147130. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  147131. }
  147132. }
  147133. p->bIncr = 1;
  147134. }else{
  147135. /* Load the full doclist for the phrase into memory. */
  147136. rc = fts3EvalPhraseLoad(pCsr, p);
  147137. p->bIncr = 0;
  147138. }
  147139. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  147140. return rc;
  147141. }
  147142. /*
  147143. ** This function is used to iterate backwards (from the end to start)
  147144. ** through doclists. It is used by this module to iterate through phrase
  147145. ** doclists in reverse and by the fts3_write.c module to iterate through
  147146. ** pending-terms lists when writing to databases with "order=desc".
  147147. **
  147148. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  147149. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  147150. ** function iterates from the end of the doclist to the beginning.
  147151. */
  147152. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  147153. int bDescIdx, /* True if the doclist is desc */
  147154. char *aDoclist, /* Pointer to entire doclist */
  147155. int nDoclist, /* Length of aDoclist in bytes */
  147156. char **ppIter, /* IN/OUT: Iterator pointer */
  147157. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  147158. int *pnList, /* OUT: List length pointer */
  147159. u8 *pbEof /* OUT: End-of-file flag */
  147160. ){
  147161. char *p = *ppIter;
  147162. assert( nDoclist>0 );
  147163. assert( *pbEof==0 );
  147164. assert( p || *piDocid==0 );
  147165. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  147166. if( p==0 ){
  147167. sqlite3_int64 iDocid = 0;
  147168. char *pNext = 0;
  147169. char *pDocid = aDoclist;
  147170. char *pEnd = &aDoclist[nDoclist];
  147171. int iMul = 1;
  147172. while( pDocid<pEnd ){
  147173. sqlite3_int64 iDelta;
  147174. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  147175. iDocid += (iMul * iDelta);
  147176. pNext = pDocid;
  147177. fts3PoslistCopy(0, &pDocid);
  147178. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  147179. iMul = (bDescIdx ? -1 : 1);
  147180. }
  147181. *pnList = (int)(pEnd - pNext);
  147182. *ppIter = pNext;
  147183. *piDocid = iDocid;
  147184. }else{
  147185. int iMul = (bDescIdx ? -1 : 1);
  147186. sqlite3_int64 iDelta;
  147187. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  147188. *piDocid -= (iMul * iDelta);
  147189. if( p==aDoclist ){
  147190. *pbEof = 1;
  147191. }else{
  147192. char *pSave = p;
  147193. fts3ReversePoslist(aDoclist, &p);
  147194. *pnList = (int)(pSave - p);
  147195. }
  147196. *ppIter = p;
  147197. }
  147198. }
  147199. /*
  147200. ** Iterate forwards through a doclist.
  147201. */
  147202. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  147203. int bDescIdx, /* True if the doclist is desc */
  147204. char *aDoclist, /* Pointer to entire doclist */
  147205. int nDoclist, /* Length of aDoclist in bytes */
  147206. char **ppIter, /* IN/OUT: Iterator pointer */
  147207. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  147208. u8 *pbEof /* OUT: End-of-file flag */
  147209. ){
  147210. char *p = *ppIter;
  147211. assert( nDoclist>0 );
  147212. assert( *pbEof==0 );
  147213. assert( p || *piDocid==0 );
  147214. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  147215. if( p==0 ){
  147216. p = aDoclist;
  147217. p += sqlite3Fts3GetVarint(p, piDocid);
  147218. }else{
  147219. fts3PoslistCopy(0, &p);
  147220. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  147221. if( p>=&aDoclist[nDoclist] ){
  147222. *pbEof = 1;
  147223. }else{
  147224. sqlite3_int64 iVar;
  147225. p += sqlite3Fts3GetVarint(p, &iVar);
  147226. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  147227. }
  147228. }
  147229. *ppIter = p;
  147230. }
  147231. /*
  147232. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  147233. ** to true if EOF is reached.
  147234. */
  147235. static void fts3EvalDlPhraseNext(
  147236. Fts3Table *pTab,
  147237. Fts3Doclist *pDL,
  147238. u8 *pbEof
  147239. ){
  147240. char *pIter; /* Used to iterate through aAll */
  147241. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  147242. if( pDL->pNextDocid ){
  147243. pIter = pDL->pNextDocid;
  147244. }else{
  147245. pIter = pDL->aAll;
  147246. }
  147247. if( pIter>=pEnd ){
  147248. /* We have already reached the end of this doclist. EOF. */
  147249. *pbEof = 1;
  147250. }else{
  147251. sqlite3_int64 iDelta;
  147252. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  147253. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  147254. pDL->iDocid += iDelta;
  147255. }else{
  147256. pDL->iDocid -= iDelta;
  147257. }
  147258. pDL->pList = pIter;
  147259. fts3PoslistCopy(0, &pIter);
  147260. pDL->nList = (int)(pIter - pDL->pList);
  147261. /* pIter now points just past the 0x00 that terminates the position-
  147262. ** list for document pDL->iDocid. However, if this position-list was
  147263. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  147264. ** point to the start of the next docid value. The following line deals
  147265. ** with this case by advancing pIter past the zero-padding added by
  147266. ** fts3EvalNearTrim(). */
  147267. while( pIter<pEnd && *pIter==0 ) pIter++;
  147268. pDL->pNextDocid = pIter;
  147269. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  147270. *pbEof = 0;
  147271. }
  147272. }
  147273. /*
  147274. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  147275. */
  147276. typedef struct TokenDoclist TokenDoclist;
  147277. struct TokenDoclist {
  147278. int bIgnore;
  147279. sqlite3_int64 iDocid;
  147280. char *pList;
  147281. int nList;
  147282. };
  147283. /*
  147284. ** Token pToken is an incrementally loaded token that is part of a
  147285. ** multi-token phrase. Advance it to the next matching document in the
  147286. ** database and populate output variable *p with the details of the new
  147287. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  147288. **
  147289. ** If an error occurs, return an SQLite error code. Otherwise, return
  147290. ** SQLITE_OK.
  147291. */
  147292. static int incrPhraseTokenNext(
  147293. Fts3Table *pTab, /* Virtual table handle */
  147294. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  147295. int iToken, /* Specific token to advance */
  147296. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  147297. u8 *pbEof /* OUT: True if iterator is at EOF */
  147298. ){
  147299. int rc = SQLITE_OK;
  147300. if( pPhrase->iDoclistToken==iToken ){
  147301. assert( p->bIgnore==0 );
  147302. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  147303. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  147304. p->pList = pPhrase->doclist.pList;
  147305. p->nList = pPhrase->doclist.nList;
  147306. p->iDocid = pPhrase->doclist.iDocid;
  147307. }else{
  147308. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  147309. assert( pToken->pDeferred==0 );
  147310. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  147311. if( pToken->pSegcsr ){
  147312. assert( p->bIgnore==0 );
  147313. rc = sqlite3Fts3MsrIncrNext(
  147314. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  147315. );
  147316. if( p->pList==0 ) *pbEof = 1;
  147317. }else{
  147318. p->bIgnore = 1;
  147319. }
  147320. }
  147321. return rc;
  147322. }
  147323. /*
  147324. ** The phrase iterator passed as the second argument:
  147325. **
  147326. ** * features at least one token that uses an incremental doclist, and
  147327. **
  147328. ** * does not contain any deferred tokens.
  147329. **
  147330. ** Advance it to the next matching documnent in the database and populate
  147331. ** the Fts3Doclist.pList and nList fields.
  147332. **
  147333. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  147334. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  147335. ** successfully advanced, *pbEof is set to 0.
  147336. **
  147337. ** If an error occurs, return an SQLite error code. Otherwise, return
  147338. ** SQLITE_OK.
  147339. */
  147340. static int fts3EvalIncrPhraseNext(
  147341. Fts3Cursor *pCsr, /* FTS Cursor handle */
  147342. Fts3Phrase *p, /* Phrase object to advance to next docid */
  147343. u8 *pbEof /* OUT: Set to 1 if EOF */
  147344. ){
  147345. int rc = SQLITE_OK;
  147346. Fts3Doclist *pDL = &p->doclist;
  147347. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  147348. u8 bEof = 0;
  147349. /* This is only called if it is guaranteed that the phrase has at least
  147350. ** one incremental token. In which case the bIncr flag is set. */
  147351. assert( p->bIncr==1 );
  147352. if( p->nToken==1 ){
  147353. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  147354. &pDL->iDocid, &pDL->pList, &pDL->nList
  147355. );
  147356. if( pDL->pList==0 ) bEof = 1;
  147357. }else{
  147358. int bDescDoclist = pCsr->bDesc;
  147359. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  147360. memset(a, 0, sizeof(a));
  147361. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  147362. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  147363. while( bEof==0 ){
  147364. int bMaxSet = 0;
  147365. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  147366. int i; /* Used to iterate through tokens */
  147367. /* Advance the iterator for each token in the phrase once. */
  147368. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  147369. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  147370. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  147371. iMax = a[i].iDocid;
  147372. bMaxSet = 1;
  147373. }
  147374. }
  147375. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  147376. assert( rc!=SQLITE_OK || bMaxSet );
  147377. /* Keep advancing iterators until they all point to the same document */
  147378. for(i=0; i<p->nToken; i++){
  147379. while( rc==SQLITE_OK && bEof==0
  147380. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  147381. ){
  147382. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  147383. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  147384. iMax = a[i].iDocid;
  147385. i = 0;
  147386. }
  147387. }
  147388. }
  147389. /* Check if the current entries really are a phrase match */
  147390. if( bEof==0 ){
  147391. int nList = 0;
  147392. int nByte = a[p->nToken-1].nList;
  147393. char *aDoclist = sqlite3_malloc(nByte+1);
  147394. if( !aDoclist ) return SQLITE_NOMEM;
  147395. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  147396. for(i=0; i<(p->nToken-1); i++){
  147397. if( a[i].bIgnore==0 ){
  147398. char *pL = a[i].pList;
  147399. char *pR = aDoclist;
  147400. char *pOut = aDoclist;
  147401. int nDist = p->nToken-1-i;
  147402. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  147403. if( res==0 ) break;
  147404. nList = (int)(pOut - aDoclist);
  147405. }
  147406. }
  147407. if( i==(p->nToken-1) ){
  147408. pDL->iDocid = iMax;
  147409. pDL->pList = aDoclist;
  147410. pDL->nList = nList;
  147411. pDL->bFreeList = 1;
  147412. break;
  147413. }
  147414. sqlite3_free(aDoclist);
  147415. }
  147416. }
  147417. }
  147418. *pbEof = bEof;
  147419. return rc;
  147420. }
  147421. /*
  147422. ** Attempt to move the phrase iterator to point to the next matching docid.
  147423. ** If an error occurs, return an SQLite error code. Otherwise, return
  147424. ** SQLITE_OK.
  147425. **
  147426. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  147427. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  147428. ** successfully advanced, *pbEof is set to 0.
  147429. */
  147430. static int fts3EvalPhraseNext(
  147431. Fts3Cursor *pCsr, /* FTS Cursor handle */
  147432. Fts3Phrase *p, /* Phrase object to advance to next docid */
  147433. u8 *pbEof /* OUT: Set to 1 if EOF */
  147434. ){
  147435. int rc = SQLITE_OK;
  147436. Fts3Doclist *pDL = &p->doclist;
  147437. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  147438. if( p->bIncr ){
  147439. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  147440. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  147441. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  147442. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  147443. );
  147444. pDL->pList = pDL->pNextDocid;
  147445. }else{
  147446. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  147447. }
  147448. return rc;
  147449. }
  147450. /*
  147451. **
  147452. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  147453. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  147454. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  147455. ** expressions for which all descendent tokens are deferred.
  147456. **
  147457. ** If parameter bOptOk is zero, then it is guaranteed that the
  147458. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  147459. ** each phrase in the expression (subject to deferred token processing).
  147460. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  147461. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  147462. **
  147463. ** If an error occurs within this function, *pRc is set to an SQLite error
  147464. ** code before returning.
  147465. */
  147466. static void fts3EvalStartReaders(
  147467. Fts3Cursor *pCsr, /* FTS Cursor handle */
  147468. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  147469. int *pRc /* IN/OUT: Error code */
  147470. ){
  147471. if( pExpr && SQLITE_OK==*pRc ){
  147472. if( pExpr->eType==FTSQUERY_PHRASE ){
  147473. int nToken = pExpr->pPhrase->nToken;
  147474. if( nToken ){
  147475. int i;
  147476. for(i=0; i<nToken; i++){
  147477. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  147478. }
  147479. pExpr->bDeferred = (i==nToken);
  147480. }
  147481. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  147482. }else{
  147483. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  147484. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  147485. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  147486. }
  147487. }
  147488. }
  147489. /*
  147490. ** An array of the following structures is assembled as part of the process
  147491. ** of selecting tokens to defer before the query starts executing (as part
  147492. ** of the xFilter() method). There is one element in the array for each
  147493. ** token in the FTS expression.
  147494. **
  147495. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  147496. ** to phrases that are connected only by AND and NEAR operators (not OR or
  147497. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  147498. ** separately. The root of a tokens AND/NEAR cluster is stored in
  147499. ** Fts3TokenAndCost.pRoot.
  147500. */
  147501. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  147502. struct Fts3TokenAndCost {
  147503. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  147504. int iToken; /* Position of token in phrase */
  147505. Fts3PhraseToken *pToken; /* The token itself */
  147506. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  147507. int nOvfl; /* Number of overflow pages to load doclist */
  147508. int iCol; /* The column the token must match */
  147509. };
  147510. /*
  147511. ** This function is used to populate an allocated Fts3TokenAndCost array.
  147512. **
  147513. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  147514. ** Otherwise, if an error occurs during execution, *pRc is set to an
  147515. ** SQLite error code.
  147516. */
  147517. static void fts3EvalTokenCosts(
  147518. Fts3Cursor *pCsr, /* FTS Cursor handle */
  147519. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  147520. Fts3Expr *pExpr, /* Expression to consider */
  147521. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  147522. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  147523. int *pRc /* IN/OUT: Error code */
  147524. ){
  147525. if( *pRc==SQLITE_OK ){
  147526. if( pExpr->eType==FTSQUERY_PHRASE ){
  147527. Fts3Phrase *pPhrase = pExpr->pPhrase;
  147528. int i;
  147529. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  147530. Fts3TokenAndCost *pTC = (*ppTC)++;
  147531. pTC->pPhrase = pPhrase;
  147532. pTC->iToken = i;
  147533. pTC->pRoot = pRoot;
  147534. pTC->pToken = &pPhrase->aToken[i];
  147535. pTC->iCol = pPhrase->iColumn;
  147536. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  147537. }
  147538. }else if( pExpr->eType!=FTSQUERY_NOT ){
  147539. assert( pExpr->eType==FTSQUERY_OR
  147540. || pExpr->eType==FTSQUERY_AND
  147541. || pExpr->eType==FTSQUERY_NEAR
  147542. );
  147543. assert( pExpr->pLeft && pExpr->pRight );
  147544. if( pExpr->eType==FTSQUERY_OR ){
  147545. pRoot = pExpr->pLeft;
  147546. **ppOr = pRoot;
  147547. (*ppOr)++;
  147548. }
  147549. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  147550. if( pExpr->eType==FTSQUERY_OR ){
  147551. pRoot = pExpr->pRight;
  147552. **ppOr = pRoot;
  147553. (*ppOr)++;
  147554. }
  147555. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  147556. }
  147557. }
  147558. }
  147559. /*
  147560. ** Determine the average document (row) size in pages. If successful,
  147561. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  147562. ** an SQLite error code.
  147563. **
  147564. ** The average document size in pages is calculated by first calculating
  147565. ** determining the average size in bytes, B. If B is less than the amount
  147566. ** of data that will fit on a single leaf page of an intkey table in
  147567. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  147568. ** the number of overflow pages consumed by a record B bytes in size.
  147569. */
  147570. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  147571. int rc = SQLITE_OK;
  147572. if( pCsr->nRowAvg==0 ){
  147573. /* The average document size, which is required to calculate the cost
  147574. ** of each doclist, has not yet been determined. Read the required
  147575. ** data from the %_stat table to calculate it.
  147576. **
  147577. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  147578. ** varints, where nCol is the number of columns in the FTS3 table.
  147579. ** The first varint is the number of documents currently stored in
  147580. ** the table. The following nCol varints contain the total amount of
  147581. ** data stored in all rows of each column of the table, from left
  147582. ** to right.
  147583. */
  147584. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  147585. sqlite3_stmt *pStmt;
  147586. sqlite3_int64 nDoc = 0;
  147587. sqlite3_int64 nByte = 0;
  147588. const char *pEnd;
  147589. const char *a;
  147590. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  147591. if( rc!=SQLITE_OK ) return rc;
  147592. a = sqlite3_column_blob(pStmt, 0);
  147593. assert( a );
  147594. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  147595. a += sqlite3Fts3GetVarint(a, &nDoc);
  147596. while( a<pEnd ){
  147597. a += sqlite3Fts3GetVarint(a, &nByte);
  147598. }
  147599. if( nDoc==0 || nByte==0 ){
  147600. sqlite3_reset(pStmt);
  147601. return FTS_CORRUPT_VTAB;
  147602. }
  147603. pCsr->nDoc = nDoc;
  147604. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  147605. assert( pCsr->nRowAvg>0 );
  147606. rc = sqlite3_reset(pStmt);
  147607. }
  147608. *pnPage = pCsr->nRowAvg;
  147609. return rc;
  147610. }
  147611. /*
  147612. ** This function is called to select the tokens (if any) that will be
  147613. ** deferred. The array aTC[] has already been populated when this is
  147614. ** called.
  147615. **
  147616. ** This function is called once for each AND/NEAR cluster in the
  147617. ** expression. Each invocation determines which tokens to defer within
  147618. ** the cluster with root node pRoot. See comments above the definition
  147619. ** of struct Fts3TokenAndCost for more details.
  147620. **
  147621. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  147622. ** called on each token to defer. Otherwise, an SQLite error code is
  147623. ** returned.
  147624. */
  147625. static int fts3EvalSelectDeferred(
  147626. Fts3Cursor *pCsr, /* FTS Cursor handle */
  147627. Fts3Expr *pRoot, /* Consider tokens with this root node */
  147628. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  147629. int nTC /* Number of entries in aTC[] */
  147630. ){
  147631. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  147632. int nDocSize = 0; /* Number of pages per doc loaded */
  147633. int rc = SQLITE_OK; /* Return code */
  147634. int ii; /* Iterator variable for various purposes */
  147635. int nOvfl = 0; /* Total overflow pages used by doclists */
  147636. int nToken = 0; /* Total number of tokens in cluster */
  147637. int nMinEst = 0; /* The minimum count for any phrase so far. */
  147638. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  147639. /* Tokens are never deferred for FTS tables created using the content=xxx
  147640. ** option. The reason being that it is not guaranteed that the content
  147641. ** table actually contains the same data as the index. To prevent this from
  147642. ** causing any problems, the deferred token optimization is completely
  147643. ** disabled for content=xxx tables. */
  147644. if( pTab->zContentTbl ){
  147645. return SQLITE_OK;
  147646. }
  147647. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  147648. ** associated with the tokens spill onto overflow pages, or if there is
  147649. ** only 1 token, exit early. No tokens to defer in this case. */
  147650. for(ii=0; ii<nTC; ii++){
  147651. if( aTC[ii].pRoot==pRoot ){
  147652. nOvfl += aTC[ii].nOvfl;
  147653. nToken++;
  147654. }
  147655. }
  147656. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  147657. /* Obtain the average docsize (in pages). */
  147658. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  147659. assert( rc!=SQLITE_OK || nDocSize>0 );
  147660. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  147661. ** of the number of overflow pages that will be loaded by the pager layer
  147662. ** to retrieve the entire doclist for the token from the full-text index.
  147663. ** Load the doclists for tokens that are either:
  147664. **
  147665. ** a. The cheapest token in the entire query (i.e. the one visited by the
  147666. ** first iteration of this loop), or
  147667. **
  147668. ** b. Part of a multi-token phrase.
  147669. **
  147670. ** After each token doclist is loaded, merge it with the others from the
  147671. ** same phrase and count the number of documents that the merged doclist
  147672. ** contains. Set variable "nMinEst" to the smallest number of documents in
  147673. ** any phrase doclist for which 1 or more token doclists have been loaded.
  147674. ** Let nOther be the number of other phrases for which it is certain that
  147675. ** one or more tokens will not be deferred.
  147676. **
  147677. ** Then, for each token, defer it if loading the doclist would result in
  147678. ** loading N or more overflow pages into memory, where N is computed as:
  147679. **
  147680. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  147681. */
  147682. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  147683. int iTC; /* Used to iterate through aTC[] array. */
  147684. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  147685. /* Set pTC to point to the cheapest remaining token. */
  147686. for(iTC=0; iTC<nTC; iTC++){
  147687. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  147688. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  147689. ){
  147690. pTC = &aTC[iTC];
  147691. }
  147692. }
  147693. assert( pTC );
  147694. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  147695. /* The number of overflow pages to load for this (and therefore all
  147696. ** subsequent) tokens is greater than the estimated number of pages
  147697. ** that will be loaded if all subsequent tokens are deferred.
  147698. */
  147699. Fts3PhraseToken *pToken = pTC->pToken;
  147700. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  147701. fts3SegReaderCursorFree(pToken->pSegcsr);
  147702. pToken->pSegcsr = 0;
  147703. }else{
  147704. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  147705. ** for-loop. Except, limit the value to 2^24 to prevent it from
  147706. ** overflowing the 32-bit integer it is stored in. */
  147707. if( ii<12 ) nLoad4 = nLoad4*4;
  147708. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  147709. /* Either this is the cheapest token in the entire query, or it is
  147710. ** part of a multi-token phrase. Either way, the entire doclist will
  147711. ** (eventually) be loaded into memory. It may as well be now. */
  147712. Fts3PhraseToken *pToken = pTC->pToken;
  147713. int nList = 0;
  147714. char *pList = 0;
  147715. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  147716. assert( rc==SQLITE_OK || pList==0 );
  147717. if( rc==SQLITE_OK ){
  147718. rc = fts3EvalPhraseMergeToken(
  147719. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  147720. );
  147721. }
  147722. if( rc==SQLITE_OK ){
  147723. int nCount;
  147724. nCount = fts3DoclistCountDocids(
  147725. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  147726. );
  147727. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  147728. }
  147729. }
  147730. }
  147731. pTC->pToken = 0;
  147732. }
  147733. return rc;
  147734. }
  147735. /*
  147736. ** This function is called from within the xFilter method. It initializes
  147737. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  147738. ** the results of a query, the caller does:
  147739. **
  147740. ** fts3EvalStart(pCsr);
  147741. ** while( 1 ){
  147742. ** fts3EvalNext(pCsr);
  147743. ** if( pCsr->bEof ) break;
  147744. ** ... return row pCsr->iPrevId to the caller ...
  147745. ** }
  147746. */
  147747. static int fts3EvalStart(Fts3Cursor *pCsr){
  147748. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  147749. int rc = SQLITE_OK;
  147750. int nToken = 0;
  147751. int nOr = 0;
  147752. /* Allocate a MultiSegReader for each token in the expression. */
  147753. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  147754. /* Determine which, if any, tokens in the expression should be deferred. */
  147755. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  147756. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  147757. Fts3TokenAndCost *aTC;
  147758. Fts3Expr **apOr;
  147759. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  147760. sizeof(Fts3TokenAndCost) * nToken
  147761. + sizeof(Fts3Expr *) * nOr * 2
  147762. );
  147763. apOr = (Fts3Expr **)&aTC[nToken];
  147764. if( !aTC ){
  147765. rc = SQLITE_NOMEM;
  147766. }else{
  147767. int ii;
  147768. Fts3TokenAndCost *pTC = aTC;
  147769. Fts3Expr **ppOr = apOr;
  147770. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  147771. nToken = (int)(pTC-aTC);
  147772. nOr = (int)(ppOr-apOr);
  147773. if( rc==SQLITE_OK ){
  147774. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  147775. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  147776. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  147777. }
  147778. }
  147779. sqlite3_free(aTC);
  147780. }
  147781. }
  147782. #endif
  147783. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  147784. return rc;
  147785. }
  147786. /*
  147787. ** Invalidate the current position list for phrase pPhrase.
  147788. */
  147789. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  147790. if( pPhrase->doclist.bFreeList ){
  147791. sqlite3_free(pPhrase->doclist.pList);
  147792. }
  147793. pPhrase->doclist.pList = 0;
  147794. pPhrase->doclist.nList = 0;
  147795. pPhrase->doclist.bFreeList = 0;
  147796. }
  147797. /*
  147798. ** This function is called to edit the position list associated with
  147799. ** the phrase object passed as the fifth argument according to a NEAR
  147800. ** condition. For example:
  147801. **
  147802. ** abc NEAR/5 "def ghi"
  147803. **
  147804. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  147805. ** the example above). When this function is called, *paPoslist points to
  147806. ** the position list, and *pnToken is the number of phrase tokens in, the
  147807. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  147808. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  147809. ** the position list associated with phrase "abc".
  147810. **
  147811. ** All positions in the pPhrase position list that are not sufficiently
  147812. ** close to a position in the *paPoslist position list are removed. If this
  147813. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  147814. **
  147815. ** Before returning, *paPoslist is set to point to the position lsit
  147816. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  147817. ** pPhrase.
  147818. */
  147819. static int fts3EvalNearTrim(
  147820. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  147821. char *aTmp, /* Temporary space to use */
  147822. char **paPoslist, /* IN/OUT: Position list */
  147823. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  147824. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  147825. ){
  147826. int nParam1 = nNear + pPhrase->nToken;
  147827. int nParam2 = nNear + *pnToken;
  147828. int nNew;
  147829. char *p2;
  147830. char *pOut;
  147831. int res;
  147832. assert( pPhrase->doclist.pList );
  147833. p2 = pOut = pPhrase->doclist.pList;
  147834. res = fts3PoslistNearMerge(
  147835. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  147836. );
  147837. if( res ){
  147838. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  147839. assert( pPhrase->doclist.pList[nNew]=='\0' );
  147840. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  147841. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  147842. pPhrase->doclist.nList = nNew;
  147843. *paPoslist = pPhrase->doclist.pList;
  147844. *pnToken = pPhrase->nToken;
  147845. }
  147846. return res;
  147847. }
  147848. /*
  147849. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  147850. ** Otherwise, it advances the expression passed as the second argument to
  147851. ** point to the next matching row in the database. Expressions iterate through
  147852. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  147853. ** or descending if it is non-zero.
  147854. **
  147855. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  147856. ** successful, the following variables in pExpr are set:
  147857. **
  147858. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  147859. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  147860. **
  147861. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  147862. ** at EOF, then the following variables are populated with the position list
  147863. ** for the phrase for the visited row:
  147864. **
  147865. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  147866. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  147867. **
  147868. ** It says above that this function advances the expression to the next
  147869. ** matching row. This is usually true, but there are the following exceptions:
  147870. **
  147871. ** 1. Deferred tokens are not taken into account. If a phrase consists
  147872. ** entirely of deferred tokens, it is assumed to match every row in
  147873. ** the db. In this case the position-list is not populated at all.
  147874. **
  147875. ** Or, if a phrase contains one or more deferred tokens and one or
  147876. ** more non-deferred tokens, then the expression is advanced to the
  147877. ** next possible match, considering only non-deferred tokens. In other
  147878. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  147879. ** is advanced to the next row that contains an instance of "A * C",
  147880. ** where "*" may match any single token. The position list in this case
  147881. ** is populated as for "A * C" before returning.
  147882. **
  147883. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  147884. ** advanced to point to the next row that matches "x AND y".
  147885. **
  147886. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  147887. ** really a match, taking into account deferred tokens and NEAR operators.
  147888. */
  147889. static void fts3EvalNextRow(
  147890. Fts3Cursor *pCsr, /* FTS Cursor handle */
  147891. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  147892. int *pRc /* IN/OUT: Error code */
  147893. ){
  147894. if( *pRc==SQLITE_OK ){
  147895. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  147896. assert( pExpr->bEof==0 );
  147897. pExpr->bStart = 1;
  147898. switch( pExpr->eType ){
  147899. case FTSQUERY_NEAR:
  147900. case FTSQUERY_AND: {
  147901. Fts3Expr *pLeft = pExpr->pLeft;
  147902. Fts3Expr *pRight = pExpr->pRight;
  147903. assert( !pLeft->bDeferred || !pRight->bDeferred );
  147904. if( pLeft->bDeferred ){
  147905. /* LHS is entirely deferred. So we assume it matches every row.
  147906. ** Advance the RHS iterator to find the next row visited. */
  147907. fts3EvalNextRow(pCsr, pRight, pRc);
  147908. pExpr->iDocid = pRight->iDocid;
  147909. pExpr->bEof = pRight->bEof;
  147910. }else if( pRight->bDeferred ){
  147911. /* RHS is entirely deferred. So we assume it matches every row.
  147912. ** Advance the LHS iterator to find the next row visited. */
  147913. fts3EvalNextRow(pCsr, pLeft, pRc);
  147914. pExpr->iDocid = pLeft->iDocid;
  147915. pExpr->bEof = pLeft->bEof;
  147916. }else{
  147917. /* Neither the RHS or LHS are deferred. */
  147918. fts3EvalNextRow(pCsr, pLeft, pRc);
  147919. fts3EvalNextRow(pCsr, pRight, pRc);
  147920. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  147921. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  147922. if( iDiff==0 ) break;
  147923. if( iDiff<0 ){
  147924. fts3EvalNextRow(pCsr, pLeft, pRc);
  147925. }else{
  147926. fts3EvalNextRow(pCsr, pRight, pRc);
  147927. }
  147928. }
  147929. pExpr->iDocid = pLeft->iDocid;
  147930. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  147931. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  147932. assert( pRight->eType==FTSQUERY_PHRASE );
  147933. if( pRight->pPhrase->doclist.aAll ){
  147934. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  147935. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  147936. memset(pDl->pList, 0, pDl->nList);
  147937. fts3EvalNextRow(pCsr, pRight, pRc);
  147938. }
  147939. }
  147940. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  147941. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  147942. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  147943. memset(pDl->pList, 0, pDl->nList);
  147944. fts3EvalNextRow(pCsr, pLeft, pRc);
  147945. }
  147946. }
  147947. }
  147948. }
  147949. break;
  147950. }
  147951. case FTSQUERY_OR: {
  147952. Fts3Expr *pLeft = pExpr->pLeft;
  147953. Fts3Expr *pRight = pExpr->pRight;
  147954. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  147955. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  147956. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  147957. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  147958. fts3EvalNextRow(pCsr, pLeft, pRc);
  147959. }else if( pLeft->bEof || iCmp>0 ){
  147960. fts3EvalNextRow(pCsr, pRight, pRc);
  147961. }else{
  147962. fts3EvalNextRow(pCsr, pLeft, pRc);
  147963. fts3EvalNextRow(pCsr, pRight, pRc);
  147964. }
  147965. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  147966. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  147967. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  147968. pExpr->iDocid = pLeft->iDocid;
  147969. }else{
  147970. pExpr->iDocid = pRight->iDocid;
  147971. }
  147972. break;
  147973. }
  147974. case FTSQUERY_NOT: {
  147975. Fts3Expr *pLeft = pExpr->pLeft;
  147976. Fts3Expr *pRight = pExpr->pRight;
  147977. if( pRight->bStart==0 ){
  147978. fts3EvalNextRow(pCsr, pRight, pRc);
  147979. assert( *pRc!=SQLITE_OK || pRight->bStart );
  147980. }
  147981. fts3EvalNextRow(pCsr, pLeft, pRc);
  147982. if( pLeft->bEof==0 ){
  147983. while( !*pRc
  147984. && !pRight->bEof
  147985. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  147986. ){
  147987. fts3EvalNextRow(pCsr, pRight, pRc);
  147988. }
  147989. }
  147990. pExpr->iDocid = pLeft->iDocid;
  147991. pExpr->bEof = pLeft->bEof;
  147992. break;
  147993. }
  147994. default: {
  147995. Fts3Phrase *pPhrase = pExpr->pPhrase;
  147996. fts3EvalInvalidatePoslist(pPhrase);
  147997. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  147998. pExpr->iDocid = pPhrase->doclist.iDocid;
  147999. break;
  148000. }
  148001. }
  148002. }
  148003. }
  148004. /*
  148005. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  148006. ** cluster, then this function returns 1 immediately.
  148007. **
  148008. ** Otherwise, it checks if the current row really does match the NEAR
  148009. ** expression, using the data currently stored in the position lists
  148010. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  148011. **
  148012. ** If the current row is a match, the position list associated with each
  148013. ** phrase in the NEAR expression is edited in place to contain only those
  148014. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  148015. ** constraints. In this case it returns 1. If the NEAR expression does not
  148016. ** match the current row, 0 is returned. The position lists may or may not
  148017. ** be edited if 0 is returned.
  148018. */
  148019. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  148020. int res = 1;
  148021. /* The following block runs if pExpr is the root of a NEAR query.
  148022. ** For example, the query:
  148023. **
  148024. ** "w" NEAR "x" NEAR "y" NEAR "z"
  148025. **
  148026. ** which is represented in tree form as:
  148027. **
  148028. ** |
  148029. ** +--NEAR--+ <-- root of NEAR query
  148030. ** | |
  148031. ** +--NEAR--+ "z"
  148032. ** | |
  148033. ** +--NEAR--+ "y"
  148034. ** | |
  148035. ** "w" "x"
  148036. **
  148037. ** The right-hand child of a NEAR node is always a phrase. The
  148038. ** left-hand child may be either a phrase or a NEAR node. There are
  148039. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  148040. */
  148041. if( *pRc==SQLITE_OK
  148042. && pExpr->eType==FTSQUERY_NEAR
  148043. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  148044. ){
  148045. Fts3Expr *p;
  148046. int nTmp = 0; /* Bytes of temp space */
  148047. char *aTmp; /* Temp space for PoslistNearMerge() */
  148048. /* Allocate temporary working space. */
  148049. for(p=pExpr; p->pLeft; p=p->pLeft){
  148050. assert( p->pRight->pPhrase->doclist.nList>0 );
  148051. nTmp += p->pRight->pPhrase->doclist.nList;
  148052. }
  148053. nTmp += p->pPhrase->doclist.nList;
  148054. aTmp = sqlite3_malloc(nTmp*2);
  148055. if( !aTmp ){
  148056. *pRc = SQLITE_NOMEM;
  148057. res = 0;
  148058. }else{
  148059. char *aPoslist = p->pPhrase->doclist.pList;
  148060. int nToken = p->pPhrase->nToken;
  148061. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  148062. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  148063. int nNear = p->nNear;
  148064. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  148065. }
  148066. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  148067. nToken = pExpr->pRight->pPhrase->nToken;
  148068. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  148069. int nNear;
  148070. Fts3Phrase *pPhrase;
  148071. assert( p->pParent && p->pParent->pLeft==p );
  148072. nNear = p->pParent->nNear;
  148073. pPhrase = (
  148074. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  148075. );
  148076. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  148077. }
  148078. }
  148079. sqlite3_free(aTmp);
  148080. }
  148081. return res;
  148082. }
  148083. /*
  148084. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  148085. ** Assuming no error occurs or has occurred, It returns non-zero if the
  148086. ** expression passed as the second argument matches the row that pCsr
  148087. ** currently points to, or zero if it does not.
  148088. **
  148089. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  148090. ** If an error occurs during execution of this function, *pRc is set to
  148091. ** the appropriate SQLite error code. In this case the returned value is
  148092. ** undefined.
  148093. */
  148094. static int fts3EvalTestExpr(
  148095. Fts3Cursor *pCsr, /* FTS cursor handle */
  148096. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  148097. int *pRc /* IN/OUT: Error code */
  148098. ){
  148099. int bHit = 1; /* Return value */
  148100. if( *pRc==SQLITE_OK ){
  148101. switch( pExpr->eType ){
  148102. case FTSQUERY_NEAR:
  148103. case FTSQUERY_AND:
  148104. bHit = (
  148105. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  148106. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  148107. && fts3EvalNearTest(pExpr, pRc)
  148108. );
  148109. /* If the NEAR expression does not match any rows, zero the doclist for
  148110. ** all phrases involved in the NEAR. This is because the snippet(),
  148111. ** offsets() and matchinfo() functions are not supposed to recognize
  148112. ** any instances of phrases that are part of unmatched NEAR queries.
  148113. ** For example if this expression:
  148114. **
  148115. ** ... MATCH 'a OR (b NEAR c)'
  148116. **
  148117. ** is matched against a row containing:
  148118. **
  148119. ** 'a b d e'
  148120. **
  148121. ** then any snippet() should ony highlight the "a" term, not the "b"
  148122. ** (as "b" is part of a non-matching NEAR clause).
  148123. */
  148124. if( bHit==0
  148125. && pExpr->eType==FTSQUERY_NEAR
  148126. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  148127. ){
  148128. Fts3Expr *p;
  148129. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  148130. if( p->pRight->iDocid==pCsr->iPrevId ){
  148131. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  148132. }
  148133. }
  148134. if( p->iDocid==pCsr->iPrevId ){
  148135. fts3EvalInvalidatePoslist(p->pPhrase);
  148136. }
  148137. }
  148138. break;
  148139. case FTSQUERY_OR: {
  148140. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  148141. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  148142. bHit = bHit1 || bHit2;
  148143. break;
  148144. }
  148145. case FTSQUERY_NOT:
  148146. bHit = (
  148147. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  148148. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  148149. );
  148150. break;
  148151. default: {
  148152. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  148153. if( pCsr->pDeferred
  148154. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  148155. ){
  148156. Fts3Phrase *pPhrase = pExpr->pPhrase;
  148157. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  148158. if( pExpr->bDeferred ){
  148159. fts3EvalInvalidatePoslist(pPhrase);
  148160. }
  148161. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  148162. bHit = (pPhrase->doclist.pList!=0);
  148163. pExpr->iDocid = pCsr->iPrevId;
  148164. }else
  148165. #endif
  148166. {
  148167. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  148168. }
  148169. break;
  148170. }
  148171. }
  148172. }
  148173. return bHit;
  148174. }
  148175. /*
  148176. ** This function is called as the second part of each xNext operation when
  148177. ** iterating through the results of a full-text query. At this point the
  148178. ** cursor points to a row that matches the query expression, with the
  148179. ** following caveats:
  148180. **
  148181. ** * Up until this point, "NEAR" operators in the expression have been
  148182. ** treated as "AND".
  148183. **
  148184. ** * Deferred tokens have not yet been considered.
  148185. **
  148186. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  148187. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  148188. ** operators and deferred tokens the current row is still a match for the
  148189. ** expression. It returns 1 if both of the following are true:
  148190. **
  148191. ** 1. *pRc is SQLITE_OK when this function returns, and
  148192. **
  148193. ** 2. After scanning the current FTS table row for the deferred tokens,
  148194. ** it is determined that the row does *not* match the query.
  148195. **
  148196. ** Or, if no error occurs and it seems the current row does match the FTS
  148197. ** query, return 0.
  148198. */
  148199. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  148200. int rc = *pRc;
  148201. int bMiss = 0;
  148202. if( rc==SQLITE_OK ){
  148203. /* If there are one or more deferred tokens, load the current row into
  148204. ** memory and scan it to determine the position list for each deferred
  148205. ** token. Then, see if this row is really a match, considering deferred
  148206. ** tokens and NEAR operators (neither of which were taken into account
  148207. ** earlier, by fts3EvalNextRow()).
  148208. */
  148209. if( pCsr->pDeferred ){
  148210. rc = fts3CursorSeek(0, pCsr);
  148211. if( rc==SQLITE_OK ){
  148212. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  148213. }
  148214. }
  148215. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  148216. /* Free the position-lists accumulated for each deferred token above. */
  148217. sqlite3Fts3FreeDeferredDoclists(pCsr);
  148218. *pRc = rc;
  148219. }
  148220. return (rc==SQLITE_OK && bMiss);
  148221. }
  148222. /*
  148223. ** Advance to the next document that matches the FTS expression in
  148224. ** Fts3Cursor.pExpr.
  148225. */
  148226. static int fts3EvalNext(Fts3Cursor *pCsr){
  148227. int rc = SQLITE_OK; /* Return Code */
  148228. Fts3Expr *pExpr = pCsr->pExpr;
  148229. assert( pCsr->isEof==0 );
  148230. if( pExpr==0 ){
  148231. pCsr->isEof = 1;
  148232. }else{
  148233. do {
  148234. if( pCsr->isRequireSeek==0 ){
  148235. sqlite3_reset(pCsr->pStmt);
  148236. }
  148237. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  148238. fts3EvalNextRow(pCsr, pExpr, &rc);
  148239. pCsr->isEof = pExpr->bEof;
  148240. pCsr->isRequireSeek = 1;
  148241. pCsr->isMatchinfoNeeded = 1;
  148242. pCsr->iPrevId = pExpr->iDocid;
  148243. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  148244. }
  148245. /* Check if the cursor is past the end of the docid range specified
  148246. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  148247. if( rc==SQLITE_OK && (
  148248. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  148249. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  148250. )){
  148251. pCsr->isEof = 1;
  148252. }
  148253. return rc;
  148254. }
  148255. /*
  148256. ** Restart interation for expression pExpr so that the next call to
  148257. ** fts3EvalNext() visits the first row. Do not allow incremental
  148258. ** loading or merging of phrase doclists for this iteration.
  148259. **
  148260. ** If *pRc is other than SQLITE_OK when this function is called, it is
  148261. ** a no-op. If an error occurs within this function, *pRc is set to an
  148262. ** SQLite error code before returning.
  148263. */
  148264. static void fts3EvalRestart(
  148265. Fts3Cursor *pCsr,
  148266. Fts3Expr *pExpr,
  148267. int *pRc
  148268. ){
  148269. if( pExpr && *pRc==SQLITE_OK ){
  148270. Fts3Phrase *pPhrase = pExpr->pPhrase;
  148271. if( pPhrase ){
  148272. fts3EvalInvalidatePoslist(pPhrase);
  148273. if( pPhrase->bIncr ){
  148274. int i;
  148275. for(i=0; i<pPhrase->nToken; i++){
  148276. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  148277. assert( pToken->pDeferred==0 );
  148278. if( pToken->pSegcsr ){
  148279. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  148280. }
  148281. }
  148282. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  148283. }
  148284. pPhrase->doclist.pNextDocid = 0;
  148285. pPhrase->doclist.iDocid = 0;
  148286. pPhrase->pOrPoslist = 0;
  148287. }
  148288. pExpr->iDocid = 0;
  148289. pExpr->bEof = 0;
  148290. pExpr->bStart = 0;
  148291. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  148292. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  148293. }
  148294. }
  148295. /*
  148296. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  148297. ** expression rooted at pExpr, the cursor iterates through all rows matched
  148298. ** by pExpr, calling this function for each row. This function increments
  148299. ** the values in Fts3Expr.aMI[] according to the position-list currently
  148300. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  148301. ** expression nodes.
  148302. */
  148303. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  148304. if( pExpr ){
  148305. Fts3Phrase *pPhrase = pExpr->pPhrase;
  148306. if( pPhrase && pPhrase->doclist.pList ){
  148307. int iCol = 0;
  148308. char *p = pPhrase->doclist.pList;
  148309. assert( *p );
  148310. while( 1 ){
  148311. u8 c = 0;
  148312. int iCnt = 0;
  148313. while( 0xFE & (*p | c) ){
  148314. if( (c&0x80)==0 ) iCnt++;
  148315. c = *p++ & 0x80;
  148316. }
  148317. /* aMI[iCol*3 + 1] = Number of occurrences
  148318. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  148319. */
  148320. pExpr->aMI[iCol*3 + 1] += iCnt;
  148321. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  148322. if( *p==0x00 ) break;
  148323. p++;
  148324. p += fts3GetVarint32(p, &iCol);
  148325. }
  148326. }
  148327. fts3EvalUpdateCounts(pExpr->pLeft);
  148328. fts3EvalUpdateCounts(pExpr->pRight);
  148329. }
  148330. }
  148331. /*
  148332. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  148333. **
  148334. ** If it is not already allocated and populated, this function allocates and
  148335. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  148336. ** of a NEAR expression, then it also allocates and populates the same array
  148337. ** for all other phrases that are part of the NEAR expression.
  148338. **
  148339. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  148340. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  148341. */
  148342. static int fts3EvalGatherStats(
  148343. Fts3Cursor *pCsr, /* Cursor object */
  148344. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  148345. ){
  148346. int rc = SQLITE_OK; /* Return code */
  148347. assert( pExpr->eType==FTSQUERY_PHRASE );
  148348. if( pExpr->aMI==0 ){
  148349. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  148350. Fts3Expr *pRoot; /* Root of NEAR expression */
  148351. Fts3Expr *p; /* Iterator used for several purposes */
  148352. sqlite3_int64 iPrevId = pCsr->iPrevId;
  148353. sqlite3_int64 iDocid;
  148354. u8 bEof;
  148355. /* Find the root of the NEAR expression */
  148356. pRoot = pExpr;
  148357. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  148358. pRoot = pRoot->pParent;
  148359. }
  148360. iDocid = pRoot->iDocid;
  148361. bEof = pRoot->bEof;
  148362. assert( pRoot->bStart );
  148363. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  148364. for(p=pRoot; p; p=p->pLeft){
  148365. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  148366. assert( pE->aMI==0 );
  148367. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  148368. if( !pE->aMI ) return SQLITE_NOMEM;
  148369. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  148370. }
  148371. fts3EvalRestart(pCsr, pRoot, &rc);
  148372. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  148373. do {
  148374. /* Ensure the %_content statement is reset. */
  148375. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  148376. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  148377. /* Advance to the next document */
  148378. fts3EvalNextRow(pCsr, pRoot, &rc);
  148379. pCsr->isEof = pRoot->bEof;
  148380. pCsr->isRequireSeek = 1;
  148381. pCsr->isMatchinfoNeeded = 1;
  148382. pCsr->iPrevId = pRoot->iDocid;
  148383. }while( pCsr->isEof==0
  148384. && pRoot->eType==FTSQUERY_NEAR
  148385. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  148386. );
  148387. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  148388. fts3EvalUpdateCounts(pRoot);
  148389. }
  148390. }
  148391. pCsr->isEof = 0;
  148392. pCsr->iPrevId = iPrevId;
  148393. if( bEof ){
  148394. pRoot->bEof = bEof;
  148395. }else{
  148396. /* Caution: pRoot may iterate through docids in ascending or descending
  148397. ** order. For this reason, even though it seems more defensive, the
  148398. ** do loop can not be written:
  148399. **
  148400. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  148401. */
  148402. fts3EvalRestart(pCsr, pRoot, &rc);
  148403. do {
  148404. fts3EvalNextRow(pCsr, pRoot, &rc);
  148405. assert( pRoot->bEof==0 );
  148406. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  148407. }
  148408. }
  148409. return rc;
  148410. }
  148411. /*
  148412. ** This function is used by the matchinfo() module to query a phrase
  148413. ** expression node for the following information:
  148414. **
  148415. ** 1. The total number of occurrences of the phrase in each column of
  148416. ** the FTS table (considering all rows), and
  148417. **
  148418. ** 2. For each column, the number of rows in the table for which the
  148419. ** column contains at least one instance of the phrase.
  148420. **
  148421. ** If no error occurs, SQLITE_OK is returned and the values for each column
  148422. ** written into the array aiOut as follows:
  148423. **
  148424. ** aiOut[iCol*3 + 1] = Number of occurrences
  148425. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  148426. **
  148427. ** Caveats:
  148428. **
  148429. ** * If a phrase consists entirely of deferred tokens, then all output
  148430. ** values are set to the number of documents in the table. In other
  148431. ** words we assume that very common tokens occur exactly once in each
  148432. ** column of each row of the table.
  148433. **
  148434. ** * If a phrase contains some deferred tokens (and some non-deferred
  148435. ** tokens), count the potential occurrence identified by considering
  148436. ** the non-deferred tokens instead of actual phrase occurrences.
  148437. **
  148438. ** * If the phrase is part of a NEAR expression, then only phrase instances
  148439. ** that meet the NEAR constraint are included in the counts.
  148440. */
  148441. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  148442. Fts3Cursor *pCsr, /* FTS cursor handle */
  148443. Fts3Expr *pExpr, /* Phrase expression */
  148444. u32 *aiOut /* Array to write results into (see above) */
  148445. ){
  148446. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  148447. int rc = SQLITE_OK;
  148448. int iCol;
  148449. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  148450. assert( pCsr->nDoc>0 );
  148451. for(iCol=0; iCol<pTab->nColumn; iCol++){
  148452. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  148453. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  148454. }
  148455. }else{
  148456. rc = fts3EvalGatherStats(pCsr, pExpr);
  148457. if( rc==SQLITE_OK ){
  148458. assert( pExpr->aMI );
  148459. for(iCol=0; iCol<pTab->nColumn; iCol++){
  148460. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  148461. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  148462. }
  148463. }
  148464. }
  148465. return rc;
  148466. }
  148467. /*
  148468. ** The expression pExpr passed as the second argument to this function
  148469. ** must be of type FTSQUERY_PHRASE.
  148470. **
  148471. ** The returned value is either NULL or a pointer to a buffer containing
  148472. ** a position-list indicating the occurrences of the phrase in column iCol
  148473. ** of the current row.
  148474. **
  148475. ** More specifically, the returned buffer contains 1 varint for each
  148476. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  148477. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  148478. ** if the requested column contains "a b X c d X X" and the position-list
  148479. ** for 'X' is requested, the buffer returned may contain:
  148480. **
  148481. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  148482. **
  148483. ** This function works regardless of whether or not the phrase is deferred,
  148484. ** incremental, or neither.
  148485. */
  148486. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  148487. Fts3Cursor *pCsr, /* FTS3 cursor object */
  148488. Fts3Expr *pExpr, /* Phrase to return doclist for */
  148489. int iCol, /* Column to return position list for */
  148490. char **ppOut /* OUT: Pointer to position list */
  148491. ){
  148492. Fts3Phrase *pPhrase = pExpr->pPhrase;
  148493. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  148494. char *pIter;
  148495. int iThis;
  148496. sqlite3_int64 iDocid;
  148497. /* If this phrase is applies specifically to some column other than
  148498. ** column iCol, return a NULL pointer. */
  148499. *ppOut = 0;
  148500. assert( iCol>=0 && iCol<pTab->nColumn );
  148501. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  148502. return SQLITE_OK;
  148503. }
  148504. iDocid = pExpr->iDocid;
  148505. pIter = pPhrase->doclist.pList;
  148506. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  148507. int rc = SQLITE_OK;
  148508. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  148509. int bOr = 0;
  148510. u8 bTreeEof = 0;
  148511. Fts3Expr *p; /* Used to iterate from pExpr to root */
  148512. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  148513. int bMatch;
  148514. /* Check if this phrase descends from an OR expression node. If not,
  148515. ** return NULL. Otherwise, the entry that corresponds to docid
  148516. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  148517. ** tree that the node is part of has been marked as EOF, but the node
  148518. ** itself is not EOF, then it may point to an earlier entry. */
  148519. pNear = pExpr;
  148520. for(p=pExpr->pParent; p; p=p->pParent){
  148521. if( p->eType==FTSQUERY_OR ) bOr = 1;
  148522. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  148523. if( p->bEof ) bTreeEof = 1;
  148524. }
  148525. if( bOr==0 ) return SQLITE_OK;
  148526. /* This is the descendent of an OR node. In this case we cannot use
  148527. ** an incremental phrase. Load the entire doclist for the phrase
  148528. ** into memory in this case. */
  148529. if( pPhrase->bIncr ){
  148530. int bEofSave = pNear->bEof;
  148531. fts3EvalRestart(pCsr, pNear, &rc);
  148532. while( rc==SQLITE_OK && !pNear->bEof ){
  148533. fts3EvalNextRow(pCsr, pNear, &rc);
  148534. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  148535. }
  148536. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  148537. }
  148538. if( bTreeEof ){
  148539. while( rc==SQLITE_OK && !pNear->bEof ){
  148540. fts3EvalNextRow(pCsr, pNear, &rc);
  148541. }
  148542. }
  148543. if( rc!=SQLITE_OK ) return rc;
  148544. bMatch = 1;
  148545. for(p=pNear; p; p=p->pLeft){
  148546. u8 bEof = 0;
  148547. Fts3Expr *pTest = p;
  148548. Fts3Phrase *pPh;
  148549. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  148550. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  148551. assert( pTest->eType==FTSQUERY_PHRASE );
  148552. pPh = pTest->pPhrase;
  148553. pIter = pPh->pOrPoslist;
  148554. iDocid = pPh->iOrDocid;
  148555. if( pCsr->bDesc==bDescDoclist ){
  148556. bEof = !pPh->doclist.nAll ||
  148557. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  148558. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  148559. sqlite3Fts3DoclistNext(
  148560. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  148561. &pIter, &iDocid, &bEof
  148562. );
  148563. }
  148564. }else{
  148565. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  148566. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  148567. int dummy;
  148568. sqlite3Fts3DoclistPrev(
  148569. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  148570. &pIter, &iDocid, &dummy, &bEof
  148571. );
  148572. }
  148573. }
  148574. pPh->pOrPoslist = pIter;
  148575. pPh->iOrDocid = iDocid;
  148576. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  148577. }
  148578. if( bMatch ){
  148579. pIter = pPhrase->pOrPoslist;
  148580. }else{
  148581. pIter = 0;
  148582. }
  148583. }
  148584. if( pIter==0 ) return SQLITE_OK;
  148585. if( *pIter==0x01 ){
  148586. pIter++;
  148587. pIter += fts3GetVarint32(pIter, &iThis);
  148588. }else{
  148589. iThis = 0;
  148590. }
  148591. while( iThis<iCol ){
  148592. fts3ColumnlistCopy(0, &pIter);
  148593. if( *pIter==0x00 ) return SQLITE_OK;
  148594. pIter++;
  148595. pIter += fts3GetVarint32(pIter, &iThis);
  148596. }
  148597. if( *pIter==0x00 ){
  148598. pIter = 0;
  148599. }
  148600. *ppOut = ((iCol==iThis)?pIter:0);
  148601. return SQLITE_OK;
  148602. }
  148603. /*
  148604. ** Free all components of the Fts3Phrase structure that were allocated by
  148605. ** the eval module. Specifically, this means to free:
  148606. **
  148607. ** * the contents of pPhrase->doclist, and
  148608. ** * any Fts3MultiSegReader objects held by phrase tokens.
  148609. */
  148610. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  148611. if( pPhrase ){
  148612. int i;
  148613. sqlite3_free(pPhrase->doclist.aAll);
  148614. fts3EvalInvalidatePoslist(pPhrase);
  148615. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  148616. for(i=0; i<pPhrase->nToken; i++){
  148617. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  148618. pPhrase->aToken[i].pSegcsr = 0;
  148619. }
  148620. }
  148621. }
  148622. /*
  148623. ** Return SQLITE_CORRUPT_VTAB.
  148624. */
  148625. #ifdef SQLITE_DEBUG
  148626. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  148627. return SQLITE_CORRUPT_VTAB;
  148628. }
  148629. #endif
  148630. #if !SQLITE_CORE
  148631. /*
  148632. ** Initialize API pointer table, if required.
  148633. */
  148634. #ifdef _WIN32
  148635. __declspec(dllexport)
  148636. #endif
  148637. SQLITE_API int sqlite3_fts3_init(
  148638. sqlite3 *db,
  148639. char **pzErrMsg,
  148640. const sqlite3_api_routines *pApi
  148641. ){
  148642. SQLITE_EXTENSION_INIT2(pApi)
  148643. return sqlite3Fts3Init(db);
  148644. }
  148645. #endif
  148646. #endif
  148647. /************** End of fts3.c ************************************************/
  148648. /************** Begin file fts3_aux.c ****************************************/
  148649. /*
  148650. ** 2011 Jan 27
  148651. **
  148652. ** The author disclaims copyright to this source code. In place of
  148653. ** a legal notice, here is a blessing:
  148654. **
  148655. ** May you do good and not evil.
  148656. ** May you find forgiveness for yourself and forgive others.
  148657. ** May you share freely, never taking more than you give.
  148658. **
  148659. ******************************************************************************
  148660. **
  148661. */
  148662. /* #include "fts3Int.h" */
  148663. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  148664. /* #include <string.h> */
  148665. /* #include <assert.h> */
  148666. typedef struct Fts3auxTable Fts3auxTable;
  148667. typedef struct Fts3auxCursor Fts3auxCursor;
  148668. struct Fts3auxTable {
  148669. sqlite3_vtab base; /* Base class used by SQLite core */
  148670. Fts3Table *pFts3Tab;
  148671. };
  148672. struct Fts3auxCursor {
  148673. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  148674. Fts3MultiSegReader csr; /* Must be right after "base" */
  148675. Fts3SegFilter filter;
  148676. char *zStop;
  148677. int nStop; /* Byte-length of string zStop */
  148678. int iLangid; /* Language id to query */
  148679. int isEof; /* True if cursor is at EOF */
  148680. sqlite3_int64 iRowid; /* Current rowid */
  148681. int iCol; /* Current value of 'col' column */
  148682. int nStat; /* Size of aStat[] array */
  148683. struct Fts3auxColstats {
  148684. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  148685. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  148686. } *aStat;
  148687. };
  148688. /*
  148689. ** Schema of the terms table.
  148690. */
  148691. #define FTS3_AUX_SCHEMA \
  148692. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  148693. /*
  148694. ** This function does all the work for both the xConnect and xCreate methods.
  148695. ** These tables have no persistent representation of their own, so xConnect
  148696. ** and xCreate are identical operations.
  148697. */
  148698. static int fts3auxConnectMethod(
  148699. sqlite3 *db, /* Database connection */
  148700. void *pUnused, /* Unused */
  148701. int argc, /* Number of elements in argv array */
  148702. const char * const *argv, /* xCreate/xConnect argument array */
  148703. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  148704. char **pzErr /* OUT: sqlite3_malloc'd error message */
  148705. ){
  148706. char const *zDb; /* Name of database (e.g. "main") */
  148707. char const *zFts3; /* Name of fts3 table */
  148708. int nDb; /* Result of strlen(zDb) */
  148709. int nFts3; /* Result of strlen(zFts3) */
  148710. int nByte; /* Bytes of space to allocate here */
  148711. int rc; /* value returned by declare_vtab() */
  148712. Fts3auxTable *p; /* Virtual table object to return */
  148713. UNUSED_PARAMETER(pUnused);
  148714. /* The user should invoke this in one of two forms:
  148715. **
  148716. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  148717. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  148718. */
  148719. if( argc!=4 && argc!=5 ) goto bad_args;
  148720. zDb = argv[1];
  148721. nDb = (int)strlen(zDb);
  148722. if( argc==5 ){
  148723. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  148724. zDb = argv[3];
  148725. nDb = (int)strlen(zDb);
  148726. zFts3 = argv[4];
  148727. }else{
  148728. goto bad_args;
  148729. }
  148730. }else{
  148731. zFts3 = argv[3];
  148732. }
  148733. nFts3 = (int)strlen(zFts3);
  148734. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  148735. if( rc!=SQLITE_OK ) return rc;
  148736. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  148737. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  148738. if( !p ) return SQLITE_NOMEM;
  148739. memset(p, 0, nByte);
  148740. p->pFts3Tab = (Fts3Table *)&p[1];
  148741. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  148742. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  148743. p->pFts3Tab->db = db;
  148744. p->pFts3Tab->nIndex = 1;
  148745. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  148746. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  148747. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  148748. *ppVtab = (sqlite3_vtab *)p;
  148749. return SQLITE_OK;
  148750. bad_args:
  148751. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  148752. return SQLITE_ERROR;
  148753. }
  148754. /*
  148755. ** This function does the work for both the xDisconnect and xDestroy methods.
  148756. ** These tables have no persistent representation of their own, so xDisconnect
  148757. ** and xDestroy are identical operations.
  148758. */
  148759. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  148760. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  148761. Fts3Table *pFts3 = p->pFts3Tab;
  148762. int i;
  148763. /* Free any prepared statements held */
  148764. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  148765. sqlite3_finalize(pFts3->aStmt[i]);
  148766. }
  148767. sqlite3_free(pFts3->zSegmentsTbl);
  148768. sqlite3_free(p);
  148769. return SQLITE_OK;
  148770. }
  148771. #define FTS4AUX_EQ_CONSTRAINT 1
  148772. #define FTS4AUX_GE_CONSTRAINT 2
  148773. #define FTS4AUX_LE_CONSTRAINT 4
  148774. /*
  148775. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  148776. */
  148777. static int fts3auxBestIndexMethod(
  148778. sqlite3_vtab *pVTab,
  148779. sqlite3_index_info *pInfo
  148780. ){
  148781. int i;
  148782. int iEq = -1;
  148783. int iGe = -1;
  148784. int iLe = -1;
  148785. int iLangid = -1;
  148786. int iNext = 1; /* Next free argvIndex value */
  148787. UNUSED_PARAMETER(pVTab);
  148788. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  148789. if( pInfo->nOrderBy==1
  148790. && pInfo->aOrderBy[0].iColumn==0
  148791. && pInfo->aOrderBy[0].desc==0
  148792. ){
  148793. pInfo->orderByConsumed = 1;
  148794. }
  148795. /* Search for equality and range constraints on the "term" column.
  148796. ** And equality constraints on the hidden "languageid" column. */
  148797. for(i=0; i<pInfo->nConstraint; i++){
  148798. if( pInfo->aConstraint[i].usable ){
  148799. int op = pInfo->aConstraint[i].op;
  148800. int iCol = pInfo->aConstraint[i].iColumn;
  148801. if( iCol==0 ){
  148802. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  148803. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  148804. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  148805. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  148806. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  148807. }
  148808. if( iCol==4 ){
  148809. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  148810. }
  148811. }
  148812. }
  148813. if( iEq>=0 ){
  148814. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  148815. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  148816. pInfo->estimatedCost = 5;
  148817. }else{
  148818. pInfo->idxNum = 0;
  148819. pInfo->estimatedCost = 20000;
  148820. if( iGe>=0 ){
  148821. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  148822. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  148823. pInfo->estimatedCost /= 2;
  148824. }
  148825. if( iLe>=0 ){
  148826. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  148827. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  148828. pInfo->estimatedCost /= 2;
  148829. }
  148830. }
  148831. if( iLangid>=0 ){
  148832. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  148833. pInfo->estimatedCost--;
  148834. }
  148835. return SQLITE_OK;
  148836. }
  148837. /*
  148838. ** xOpen - Open a cursor.
  148839. */
  148840. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  148841. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  148842. UNUSED_PARAMETER(pVTab);
  148843. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  148844. if( !pCsr ) return SQLITE_NOMEM;
  148845. memset(pCsr, 0, sizeof(Fts3auxCursor));
  148846. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  148847. return SQLITE_OK;
  148848. }
  148849. /*
  148850. ** xClose - Close a cursor.
  148851. */
  148852. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  148853. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  148854. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  148855. sqlite3Fts3SegmentsClose(pFts3);
  148856. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  148857. sqlite3_free((void *)pCsr->filter.zTerm);
  148858. sqlite3_free(pCsr->zStop);
  148859. sqlite3_free(pCsr->aStat);
  148860. sqlite3_free(pCsr);
  148861. return SQLITE_OK;
  148862. }
  148863. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  148864. if( nSize>pCsr->nStat ){
  148865. struct Fts3auxColstats *aNew;
  148866. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  148867. sizeof(struct Fts3auxColstats) * nSize
  148868. );
  148869. if( aNew==0 ) return SQLITE_NOMEM;
  148870. memset(&aNew[pCsr->nStat], 0,
  148871. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  148872. );
  148873. pCsr->aStat = aNew;
  148874. pCsr->nStat = nSize;
  148875. }
  148876. return SQLITE_OK;
  148877. }
  148878. /*
  148879. ** xNext - Advance the cursor to the next row, if any.
  148880. */
  148881. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  148882. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  148883. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  148884. int rc;
  148885. /* Increment our pretend rowid value. */
  148886. pCsr->iRowid++;
  148887. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  148888. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  148889. }
  148890. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  148891. if( rc==SQLITE_ROW ){
  148892. int i = 0;
  148893. int nDoclist = pCsr->csr.nDoclist;
  148894. char *aDoclist = pCsr->csr.aDoclist;
  148895. int iCol;
  148896. int eState = 0;
  148897. if( pCsr->zStop ){
  148898. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  148899. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  148900. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  148901. pCsr->isEof = 1;
  148902. return SQLITE_OK;
  148903. }
  148904. }
  148905. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  148906. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  148907. iCol = 0;
  148908. while( i<nDoclist ){
  148909. sqlite3_int64 v = 0;
  148910. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  148911. switch( eState ){
  148912. /* State 0. In this state the integer just read was a docid. */
  148913. case 0:
  148914. pCsr->aStat[0].nDoc++;
  148915. eState = 1;
  148916. iCol = 0;
  148917. break;
  148918. /* State 1. In this state we are expecting either a 1, indicating
  148919. ** that the following integer will be a column number, or the
  148920. ** start of a position list for column 0.
  148921. **
  148922. ** The only difference between state 1 and state 2 is that if the
  148923. ** integer encountered in state 1 is not 0 or 1, then we need to
  148924. ** increment the column 0 "nDoc" count for this term.
  148925. */
  148926. case 1:
  148927. assert( iCol==0 );
  148928. if( v>1 ){
  148929. pCsr->aStat[1].nDoc++;
  148930. }
  148931. eState = 2;
  148932. /* fall through */
  148933. case 2:
  148934. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  148935. eState = 0;
  148936. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  148937. eState = 3;
  148938. }else{ /* 2 or greater. A position. */
  148939. pCsr->aStat[iCol+1].nOcc++;
  148940. pCsr->aStat[0].nOcc++;
  148941. }
  148942. break;
  148943. /* State 3. The integer just read is a column number. */
  148944. default: assert( eState==3 );
  148945. iCol = (int)v;
  148946. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  148947. pCsr->aStat[iCol+1].nDoc++;
  148948. eState = 2;
  148949. break;
  148950. }
  148951. }
  148952. pCsr->iCol = 0;
  148953. rc = SQLITE_OK;
  148954. }else{
  148955. pCsr->isEof = 1;
  148956. }
  148957. return rc;
  148958. }
  148959. /*
  148960. ** xFilter - Initialize a cursor to point at the start of its data.
  148961. */
  148962. static int fts3auxFilterMethod(
  148963. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  148964. int idxNum, /* Strategy index */
  148965. const char *idxStr, /* Unused */
  148966. int nVal, /* Number of elements in apVal */
  148967. sqlite3_value **apVal /* Arguments for the indexing scheme */
  148968. ){
  148969. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  148970. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  148971. int rc;
  148972. int isScan = 0;
  148973. int iLangVal = 0; /* Language id to query */
  148974. int iEq = -1; /* Index of term=? value in apVal */
  148975. int iGe = -1; /* Index of term>=? value in apVal */
  148976. int iLe = -1; /* Index of term<=? value in apVal */
  148977. int iLangid = -1; /* Index of languageid=? value in apVal */
  148978. int iNext = 0;
  148979. UNUSED_PARAMETER(nVal);
  148980. UNUSED_PARAMETER(idxStr);
  148981. assert( idxStr==0 );
  148982. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  148983. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  148984. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  148985. );
  148986. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  148987. iEq = iNext++;
  148988. }else{
  148989. isScan = 1;
  148990. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  148991. iGe = iNext++;
  148992. }
  148993. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  148994. iLe = iNext++;
  148995. }
  148996. }
  148997. if( iNext<nVal ){
  148998. iLangid = iNext++;
  148999. }
  149000. /* In case this cursor is being reused, close and zero it. */
  149001. testcase(pCsr->filter.zTerm);
  149002. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  149003. sqlite3_free((void *)pCsr->filter.zTerm);
  149004. sqlite3_free(pCsr->aStat);
  149005. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  149006. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  149007. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  149008. if( iEq>=0 || iGe>=0 ){
  149009. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  149010. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  149011. if( zStr ){
  149012. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  149013. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  149014. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  149015. }
  149016. }
  149017. if( iLe>=0 ){
  149018. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  149019. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  149020. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  149021. }
  149022. if( iLangid>=0 ){
  149023. iLangVal = sqlite3_value_int(apVal[iLangid]);
  149024. /* If the user specified a negative value for the languageid, use zero
  149025. ** instead. This works, as the "languageid=?" constraint will also
  149026. ** be tested by the VDBE layer. The test will always be false (since
  149027. ** this module will not return a row with a negative languageid), and
  149028. ** so the overall query will return zero rows. */
  149029. if( iLangVal<0 ) iLangVal = 0;
  149030. }
  149031. pCsr->iLangid = iLangVal;
  149032. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  149033. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  149034. );
  149035. if( rc==SQLITE_OK ){
  149036. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  149037. }
  149038. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  149039. return rc;
  149040. }
  149041. /*
  149042. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  149043. */
  149044. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  149045. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  149046. return pCsr->isEof;
  149047. }
  149048. /*
  149049. ** xColumn - Return a column value.
  149050. */
  149051. static int fts3auxColumnMethod(
  149052. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  149053. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  149054. int iCol /* Index of column to read value from */
  149055. ){
  149056. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  149057. assert( p->isEof==0 );
  149058. switch( iCol ){
  149059. case 0: /* term */
  149060. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  149061. break;
  149062. case 1: /* col */
  149063. if( p->iCol ){
  149064. sqlite3_result_int(pCtx, p->iCol-1);
  149065. }else{
  149066. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  149067. }
  149068. break;
  149069. case 2: /* documents */
  149070. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  149071. break;
  149072. case 3: /* occurrences */
  149073. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  149074. break;
  149075. default: /* languageid */
  149076. assert( iCol==4 );
  149077. sqlite3_result_int(pCtx, p->iLangid);
  149078. break;
  149079. }
  149080. return SQLITE_OK;
  149081. }
  149082. /*
  149083. ** xRowid - Return the current rowid for the cursor.
  149084. */
  149085. static int fts3auxRowidMethod(
  149086. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  149087. sqlite_int64 *pRowid /* OUT: Rowid value */
  149088. ){
  149089. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  149090. *pRowid = pCsr->iRowid;
  149091. return SQLITE_OK;
  149092. }
  149093. /*
  149094. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  149095. ** if successful or an error code if sqlite3_create_module() fails.
  149096. */
  149097. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  149098. static const sqlite3_module fts3aux_module = {
  149099. 0, /* iVersion */
  149100. fts3auxConnectMethod, /* xCreate */
  149101. fts3auxConnectMethod, /* xConnect */
  149102. fts3auxBestIndexMethod, /* xBestIndex */
  149103. fts3auxDisconnectMethod, /* xDisconnect */
  149104. fts3auxDisconnectMethod, /* xDestroy */
  149105. fts3auxOpenMethod, /* xOpen */
  149106. fts3auxCloseMethod, /* xClose */
  149107. fts3auxFilterMethod, /* xFilter */
  149108. fts3auxNextMethod, /* xNext */
  149109. fts3auxEofMethod, /* xEof */
  149110. fts3auxColumnMethod, /* xColumn */
  149111. fts3auxRowidMethod, /* xRowid */
  149112. 0, /* xUpdate */
  149113. 0, /* xBegin */
  149114. 0, /* xSync */
  149115. 0, /* xCommit */
  149116. 0, /* xRollback */
  149117. 0, /* xFindFunction */
  149118. 0, /* xRename */
  149119. 0, /* xSavepoint */
  149120. 0, /* xRelease */
  149121. 0 /* xRollbackTo */
  149122. };
  149123. int rc; /* Return code */
  149124. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  149125. return rc;
  149126. }
  149127. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  149128. /************** End of fts3_aux.c ********************************************/
  149129. /************** Begin file fts3_expr.c ***************************************/
  149130. /*
  149131. ** 2008 Nov 28
  149132. **
  149133. ** The author disclaims copyright to this source code. In place of
  149134. ** a legal notice, here is a blessing:
  149135. **
  149136. ** May you do good and not evil.
  149137. ** May you find forgiveness for yourself and forgive others.
  149138. ** May you share freely, never taking more than you give.
  149139. **
  149140. ******************************************************************************
  149141. **
  149142. ** This module contains code that implements a parser for fts3 query strings
  149143. ** (the right-hand argument to the MATCH operator). Because the supported
  149144. ** syntax is relatively simple, the whole tokenizer/parser system is
  149145. ** hand-coded.
  149146. */
  149147. /* #include "fts3Int.h" */
  149148. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  149149. /*
  149150. ** By default, this module parses the legacy syntax that has been
  149151. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  149152. ** is defined, then it uses the new syntax. The differences between
  149153. ** the new and the old syntaxes are:
  149154. **
  149155. ** a) The new syntax supports parenthesis. The old does not.
  149156. **
  149157. ** b) The new syntax supports the AND and NOT operators. The old does not.
  149158. **
  149159. ** c) The old syntax supports the "-" token qualifier. This is not
  149160. ** supported by the new syntax (it is replaced by the NOT operator).
  149161. **
  149162. ** d) When using the old syntax, the OR operator has a greater precedence
  149163. ** than an implicit AND. When using the new, both implicity and explicit
  149164. ** AND operators have a higher precedence than OR.
  149165. **
  149166. ** If compiled with SQLITE_TEST defined, then this module exports the
  149167. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  149168. ** to zero causes the module to use the old syntax. If it is set to
  149169. ** non-zero the new syntax is activated. This is so both syntaxes can
  149170. ** be tested using a single build of testfixture.
  149171. **
  149172. ** The following describes the syntax supported by the fts3 MATCH
  149173. ** operator in a similar format to that used by the lemon parser
  149174. ** generator. This module does not use actually lemon, it uses a
  149175. ** custom parser.
  149176. **
  149177. ** query ::= andexpr (OR andexpr)*.
  149178. **
  149179. ** andexpr ::= notexpr (AND? notexpr)*.
  149180. **
  149181. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  149182. ** notexpr ::= LP query RP.
  149183. **
  149184. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  149185. **
  149186. ** distance_opt ::= .
  149187. ** distance_opt ::= / INTEGER.
  149188. **
  149189. ** phrase ::= TOKEN.
  149190. ** phrase ::= COLUMN:TOKEN.
  149191. ** phrase ::= "TOKEN TOKEN TOKEN...".
  149192. */
  149193. #ifdef SQLITE_TEST
  149194. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  149195. #else
  149196. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  149197. # define sqlite3_fts3_enable_parentheses 1
  149198. # else
  149199. # define sqlite3_fts3_enable_parentheses 0
  149200. # endif
  149201. #endif
  149202. /*
  149203. ** Default span for NEAR operators.
  149204. */
  149205. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  149206. /* #include <string.h> */
  149207. /* #include <assert.h> */
  149208. /*
  149209. ** isNot:
  149210. ** This variable is used by function getNextNode(). When getNextNode() is
  149211. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  149212. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  149213. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  149214. ** zero.
  149215. */
  149216. typedef struct ParseContext ParseContext;
  149217. struct ParseContext {
  149218. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  149219. int iLangid; /* Language id used with tokenizer */
  149220. const char **azCol; /* Array of column names for fts3 table */
  149221. int bFts4; /* True to allow FTS4-only syntax */
  149222. int nCol; /* Number of entries in azCol[] */
  149223. int iDefaultCol; /* Default column to query */
  149224. int isNot; /* True if getNextNode() sees a unary - */
  149225. sqlite3_context *pCtx; /* Write error message here */
  149226. int nNest; /* Number of nested brackets */
  149227. };
  149228. /*
  149229. ** This function is equivalent to the standard isspace() function.
  149230. **
  149231. ** The standard isspace() can be awkward to use safely, because although it
  149232. ** is defined to accept an argument of type int, its behavior when passed
  149233. ** an integer that falls outside of the range of the unsigned char type
  149234. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  149235. ** is defined to accept an argument of type char, and always returns 0 for
  149236. ** any values that fall outside of the range of the unsigned char type (i.e.
  149237. ** negative values).
  149238. */
  149239. static int fts3isspace(char c){
  149240. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  149241. }
  149242. /*
  149243. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  149244. ** zero the memory before returning a pointer to it. If unsuccessful,
  149245. ** return NULL.
  149246. */
  149247. static void *fts3MallocZero(int nByte){
  149248. void *pRet = sqlite3_malloc(nByte);
  149249. if( pRet ) memset(pRet, 0, nByte);
  149250. return pRet;
  149251. }
  149252. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  149253. sqlite3_tokenizer *pTokenizer,
  149254. int iLangid,
  149255. const char *z,
  149256. int n,
  149257. sqlite3_tokenizer_cursor **ppCsr
  149258. ){
  149259. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  149260. sqlite3_tokenizer_cursor *pCsr = 0;
  149261. int rc;
  149262. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  149263. assert( rc==SQLITE_OK || pCsr==0 );
  149264. if( rc==SQLITE_OK ){
  149265. pCsr->pTokenizer = pTokenizer;
  149266. if( pModule->iVersion>=1 ){
  149267. rc = pModule->xLanguageid(pCsr, iLangid);
  149268. if( rc!=SQLITE_OK ){
  149269. pModule->xClose(pCsr);
  149270. pCsr = 0;
  149271. }
  149272. }
  149273. }
  149274. *ppCsr = pCsr;
  149275. return rc;
  149276. }
  149277. /*
  149278. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  149279. ** call fts3ExprParse(). So this forward declaration is required.
  149280. */
  149281. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  149282. /*
  149283. ** Extract the next token from buffer z (length n) using the tokenizer
  149284. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  149285. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  149286. ** single token and set *ppExpr to point to it. If the end of the buffer is
  149287. ** reached before a token is found, set *ppExpr to zero. It is the
  149288. ** responsibility of the caller to eventually deallocate the allocated
  149289. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  149290. **
  149291. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  149292. ** fails.
  149293. */
  149294. static int getNextToken(
  149295. ParseContext *pParse, /* fts3 query parse context */
  149296. int iCol, /* Value for Fts3Phrase.iColumn */
  149297. const char *z, int n, /* Input string */
  149298. Fts3Expr **ppExpr, /* OUT: expression */
  149299. int *pnConsumed /* OUT: Number of bytes consumed */
  149300. ){
  149301. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  149302. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  149303. int rc;
  149304. sqlite3_tokenizer_cursor *pCursor;
  149305. Fts3Expr *pRet = 0;
  149306. int i = 0;
  149307. /* Set variable i to the maximum number of bytes of input to tokenize. */
  149308. for(i=0; i<n; i++){
  149309. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  149310. if( z[i]=='"' ) break;
  149311. }
  149312. *pnConsumed = i;
  149313. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  149314. if( rc==SQLITE_OK ){
  149315. const char *zToken;
  149316. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  149317. int nByte; /* total space to allocate */
  149318. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  149319. if( rc==SQLITE_OK ){
  149320. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  149321. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  149322. if( !pRet ){
  149323. rc = SQLITE_NOMEM;
  149324. }else{
  149325. pRet->eType = FTSQUERY_PHRASE;
  149326. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  149327. pRet->pPhrase->nToken = 1;
  149328. pRet->pPhrase->iColumn = iCol;
  149329. pRet->pPhrase->aToken[0].n = nToken;
  149330. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  149331. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  149332. if( iEnd<n && z[iEnd]=='*' ){
  149333. pRet->pPhrase->aToken[0].isPrefix = 1;
  149334. iEnd++;
  149335. }
  149336. while( 1 ){
  149337. if( !sqlite3_fts3_enable_parentheses
  149338. && iStart>0 && z[iStart-1]=='-'
  149339. ){
  149340. pParse->isNot = 1;
  149341. iStart--;
  149342. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  149343. pRet->pPhrase->aToken[0].bFirst = 1;
  149344. iStart--;
  149345. }else{
  149346. break;
  149347. }
  149348. }
  149349. }
  149350. *pnConsumed = iEnd;
  149351. }else if( i && rc==SQLITE_DONE ){
  149352. rc = SQLITE_OK;
  149353. }
  149354. pModule->xClose(pCursor);
  149355. }
  149356. *ppExpr = pRet;
  149357. return rc;
  149358. }
  149359. /*
  149360. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  149361. ** then free the old allocation.
  149362. */
  149363. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  149364. void *pRet = sqlite3_realloc(pOrig, nNew);
  149365. if( !pRet ){
  149366. sqlite3_free(pOrig);
  149367. }
  149368. return pRet;
  149369. }
  149370. /*
  149371. ** Buffer zInput, length nInput, contains the contents of a quoted string
  149372. ** that appeared as part of an fts3 query expression. Neither quote character
  149373. ** is included in the buffer. This function attempts to tokenize the entire
  149374. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  149375. ** containing the results.
  149376. **
  149377. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  149378. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  149379. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  149380. ** to 0.
  149381. */
  149382. static int getNextString(
  149383. ParseContext *pParse, /* fts3 query parse context */
  149384. const char *zInput, int nInput, /* Input string */
  149385. Fts3Expr **ppExpr /* OUT: expression */
  149386. ){
  149387. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  149388. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  149389. int rc;
  149390. Fts3Expr *p = 0;
  149391. sqlite3_tokenizer_cursor *pCursor = 0;
  149392. char *zTemp = 0;
  149393. int nTemp = 0;
  149394. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  149395. int nToken = 0;
  149396. /* The final Fts3Expr data structure, including the Fts3Phrase,
  149397. ** Fts3PhraseToken structures token buffers are all stored as a single
  149398. ** allocation so that the expression can be freed with a single call to
  149399. ** sqlite3_free(). Setting this up requires a two pass approach.
  149400. **
  149401. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  149402. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  149403. ** to assemble data in two dynamic buffers:
  149404. **
  149405. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  149406. ** structure, followed by the array of Fts3PhraseToken
  149407. ** structures. This pass only populates the Fts3PhraseToken array.
  149408. **
  149409. ** Buffer zTemp: Contains copies of all tokens.
  149410. **
  149411. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  149412. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  149413. ** structures.
  149414. */
  149415. rc = sqlite3Fts3OpenTokenizer(
  149416. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  149417. if( rc==SQLITE_OK ){
  149418. int ii;
  149419. for(ii=0; rc==SQLITE_OK; ii++){
  149420. const char *zByte;
  149421. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  149422. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  149423. if( rc==SQLITE_OK ){
  149424. Fts3PhraseToken *pToken;
  149425. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  149426. if( !p ) goto no_mem;
  149427. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  149428. if( !zTemp ) goto no_mem;
  149429. assert( nToken==ii );
  149430. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  149431. memset(pToken, 0, sizeof(Fts3PhraseToken));
  149432. memcpy(&zTemp[nTemp], zByte, nByte);
  149433. nTemp += nByte;
  149434. pToken->n = nByte;
  149435. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  149436. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  149437. nToken = ii+1;
  149438. }
  149439. }
  149440. pModule->xClose(pCursor);
  149441. pCursor = 0;
  149442. }
  149443. if( rc==SQLITE_DONE ){
  149444. int jj;
  149445. char *zBuf = 0;
  149446. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  149447. if( !p ) goto no_mem;
  149448. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  149449. p->eType = FTSQUERY_PHRASE;
  149450. p->pPhrase = (Fts3Phrase *)&p[1];
  149451. p->pPhrase->iColumn = pParse->iDefaultCol;
  149452. p->pPhrase->nToken = nToken;
  149453. zBuf = (char *)&p->pPhrase->aToken[nToken];
  149454. if( zTemp ){
  149455. memcpy(zBuf, zTemp, nTemp);
  149456. sqlite3_free(zTemp);
  149457. }else{
  149458. assert( nTemp==0 );
  149459. }
  149460. for(jj=0; jj<p->pPhrase->nToken; jj++){
  149461. p->pPhrase->aToken[jj].z = zBuf;
  149462. zBuf += p->pPhrase->aToken[jj].n;
  149463. }
  149464. rc = SQLITE_OK;
  149465. }
  149466. *ppExpr = p;
  149467. return rc;
  149468. no_mem:
  149469. if( pCursor ){
  149470. pModule->xClose(pCursor);
  149471. }
  149472. sqlite3_free(zTemp);
  149473. sqlite3_free(p);
  149474. *ppExpr = 0;
  149475. return SQLITE_NOMEM;
  149476. }
  149477. /*
  149478. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  149479. ** structure, or set to 0 if the end of the input buffer is reached.
  149480. **
  149481. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  149482. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  149483. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  149484. */
  149485. static int getNextNode(
  149486. ParseContext *pParse, /* fts3 query parse context */
  149487. const char *z, int n, /* Input string */
  149488. Fts3Expr **ppExpr, /* OUT: expression */
  149489. int *pnConsumed /* OUT: Number of bytes consumed */
  149490. ){
  149491. static const struct Fts3Keyword {
  149492. char *z; /* Keyword text */
  149493. unsigned char n; /* Length of the keyword */
  149494. unsigned char parenOnly; /* Only valid in paren mode */
  149495. unsigned char eType; /* Keyword code */
  149496. } aKeyword[] = {
  149497. { "OR" , 2, 0, FTSQUERY_OR },
  149498. { "AND", 3, 1, FTSQUERY_AND },
  149499. { "NOT", 3, 1, FTSQUERY_NOT },
  149500. { "NEAR", 4, 0, FTSQUERY_NEAR }
  149501. };
  149502. int ii;
  149503. int iCol;
  149504. int iColLen;
  149505. int rc;
  149506. Fts3Expr *pRet = 0;
  149507. const char *zInput = z;
  149508. int nInput = n;
  149509. pParse->isNot = 0;
  149510. /* Skip over any whitespace before checking for a keyword, an open or
  149511. ** close bracket, or a quoted string.
  149512. */
  149513. while( nInput>0 && fts3isspace(*zInput) ){
  149514. nInput--;
  149515. zInput++;
  149516. }
  149517. if( nInput==0 ){
  149518. return SQLITE_DONE;
  149519. }
  149520. /* See if we are dealing with a keyword. */
  149521. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  149522. const struct Fts3Keyword *pKey = &aKeyword[ii];
  149523. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  149524. continue;
  149525. }
  149526. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  149527. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  149528. int nKey = pKey->n;
  149529. char cNext;
  149530. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  149531. if( pKey->eType==FTSQUERY_NEAR ){
  149532. assert( nKey==4 );
  149533. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  149534. nNear = 0;
  149535. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  149536. nNear = nNear * 10 + (zInput[nKey] - '0');
  149537. }
  149538. }
  149539. }
  149540. /* At this point this is probably a keyword. But for that to be true,
  149541. ** the next byte must contain either whitespace, an open or close
  149542. ** parenthesis, a quote character, or EOF.
  149543. */
  149544. cNext = zInput[nKey];
  149545. if( fts3isspace(cNext)
  149546. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  149547. ){
  149548. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  149549. if( !pRet ){
  149550. return SQLITE_NOMEM;
  149551. }
  149552. pRet->eType = pKey->eType;
  149553. pRet->nNear = nNear;
  149554. *ppExpr = pRet;
  149555. *pnConsumed = (int)((zInput - z) + nKey);
  149556. return SQLITE_OK;
  149557. }
  149558. /* Turns out that wasn't a keyword after all. This happens if the
  149559. ** user has supplied a token such as "ORacle". Continue.
  149560. */
  149561. }
  149562. }
  149563. /* See if we are dealing with a quoted phrase. If this is the case, then
  149564. ** search for the closing quote and pass the whole string to getNextString()
  149565. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  149566. ** a quote character embedded in a string.
  149567. */
  149568. if( *zInput=='"' ){
  149569. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  149570. *pnConsumed = (int)((zInput - z) + ii + 1);
  149571. if( ii==nInput ){
  149572. return SQLITE_ERROR;
  149573. }
  149574. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  149575. }
  149576. if( sqlite3_fts3_enable_parentheses ){
  149577. if( *zInput=='(' ){
  149578. int nConsumed = 0;
  149579. pParse->nNest++;
  149580. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  149581. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  149582. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  149583. return rc;
  149584. }else if( *zInput==')' ){
  149585. pParse->nNest--;
  149586. *pnConsumed = (int)((zInput - z) + 1);
  149587. *ppExpr = 0;
  149588. return SQLITE_DONE;
  149589. }
  149590. }
  149591. /* If control flows to this point, this must be a regular token, or
  149592. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  149593. ** interface. Before doing so, figure out if there is an explicit
  149594. ** column specifier for the token.
  149595. **
  149596. ** TODO: Strangely, it is not possible to associate a column specifier
  149597. ** with a quoted phrase, only with a single token. Not sure if this was
  149598. ** an implementation artifact or an intentional decision when fts3 was
  149599. ** first implemented. Whichever it was, this module duplicates the
  149600. ** limitation.
  149601. */
  149602. iCol = pParse->iDefaultCol;
  149603. iColLen = 0;
  149604. for(ii=0; ii<pParse->nCol; ii++){
  149605. const char *zStr = pParse->azCol[ii];
  149606. int nStr = (int)strlen(zStr);
  149607. if( nInput>nStr && zInput[nStr]==':'
  149608. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  149609. ){
  149610. iCol = ii;
  149611. iColLen = (int)((zInput - z) + nStr + 1);
  149612. break;
  149613. }
  149614. }
  149615. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  149616. *pnConsumed += iColLen;
  149617. return rc;
  149618. }
  149619. /*
  149620. ** The argument is an Fts3Expr structure for a binary operator (any type
  149621. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  149622. ** precedence of the operator. Lower values have a higher precedence (i.e.
  149623. ** group more tightly). For example, in the C language, the == operator
  149624. ** groups more tightly than ||, and would therefore have a higher precedence.
  149625. **
  149626. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  149627. ** is defined), the order of the operators in precedence from highest to
  149628. ** lowest is:
  149629. **
  149630. ** NEAR
  149631. ** NOT
  149632. ** AND (including implicit ANDs)
  149633. ** OR
  149634. **
  149635. ** Note that when using the old query syntax, the OR operator has a higher
  149636. ** precedence than the AND operator.
  149637. */
  149638. static int opPrecedence(Fts3Expr *p){
  149639. assert( p->eType!=FTSQUERY_PHRASE );
  149640. if( sqlite3_fts3_enable_parentheses ){
  149641. return p->eType;
  149642. }else if( p->eType==FTSQUERY_NEAR ){
  149643. return 1;
  149644. }else if( p->eType==FTSQUERY_OR ){
  149645. return 2;
  149646. }
  149647. assert( p->eType==FTSQUERY_AND );
  149648. return 3;
  149649. }
  149650. /*
  149651. ** Argument ppHead contains a pointer to the current head of a query
  149652. ** expression tree being parsed. pPrev is the expression node most recently
  149653. ** inserted into the tree. This function adds pNew, which is always a binary
  149654. ** operator node, into the expression tree based on the relative precedence
  149655. ** of pNew and the existing nodes of the tree. This may result in the head
  149656. ** of the tree changing, in which case *ppHead is set to the new root node.
  149657. */
  149658. static void insertBinaryOperator(
  149659. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  149660. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  149661. Fts3Expr *pNew /* New binary node to insert into expression tree */
  149662. ){
  149663. Fts3Expr *pSplit = pPrev;
  149664. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  149665. pSplit = pSplit->pParent;
  149666. }
  149667. if( pSplit->pParent ){
  149668. assert( pSplit->pParent->pRight==pSplit );
  149669. pSplit->pParent->pRight = pNew;
  149670. pNew->pParent = pSplit->pParent;
  149671. }else{
  149672. *ppHead = pNew;
  149673. }
  149674. pNew->pLeft = pSplit;
  149675. pSplit->pParent = pNew;
  149676. }
  149677. /*
  149678. ** Parse the fts3 query expression found in buffer z, length n. This function
  149679. ** returns either when the end of the buffer is reached or an unmatched
  149680. ** closing bracket - ')' - is encountered.
  149681. **
  149682. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  149683. ** parsed form of the expression and *pnConsumed is set to the number of
  149684. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  149685. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  149686. */
  149687. static int fts3ExprParse(
  149688. ParseContext *pParse, /* fts3 query parse context */
  149689. const char *z, int n, /* Text of MATCH query */
  149690. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  149691. int *pnConsumed /* OUT: Number of bytes consumed */
  149692. ){
  149693. Fts3Expr *pRet = 0;
  149694. Fts3Expr *pPrev = 0;
  149695. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  149696. int nIn = n;
  149697. const char *zIn = z;
  149698. int rc = SQLITE_OK;
  149699. int isRequirePhrase = 1;
  149700. while( rc==SQLITE_OK ){
  149701. Fts3Expr *p = 0;
  149702. int nByte = 0;
  149703. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  149704. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  149705. if( rc==SQLITE_OK ){
  149706. if( p ){
  149707. int isPhrase;
  149708. if( !sqlite3_fts3_enable_parentheses
  149709. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  149710. ){
  149711. /* Create an implicit NOT operator. */
  149712. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  149713. if( !pNot ){
  149714. sqlite3Fts3ExprFree(p);
  149715. rc = SQLITE_NOMEM;
  149716. goto exprparse_out;
  149717. }
  149718. pNot->eType = FTSQUERY_NOT;
  149719. pNot->pRight = p;
  149720. p->pParent = pNot;
  149721. if( pNotBranch ){
  149722. pNot->pLeft = pNotBranch;
  149723. pNotBranch->pParent = pNot;
  149724. }
  149725. pNotBranch = pNot;
  149726. p = pPrev;
  149727. }else{
  149728. int eType = p->eType;
  149729. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  149730. /* The isRequirePhrase variable is set to true if a phrase or
  149731. ** an expression contained in parenthesis is required. If a
  149732. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  149733. ** isRequirePhrase is set, this is a syntax error.
  149734. */
  149735. if( !isPhrase && isRequirePhrase ){
  149736. sqlite3Fts3ExprFree(p);
  149737. rc = SQLITE_ERROR;
  149738. goto exprparse_out;
  149739. }
  149740. if( isPhrase && !isRequirePhrase ){
  149741. /* Insert an implicit AND operator. */
  149742. Fts3Expr *pAnd;
  149743. assert( pRet && pPrev );
  149744. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  149745. if( !pAnd ){
  149746. sqlite3Fts3ExprFree(p);
  149747. rc = SQLITE_NOMEM;
  149748. goto exprparse_out;
  149749. }
  149750. pAnd->eType = FTSQUERY_AND;
  149751. insertBinaryOperator(&pRet, pPrev, pAnd);
  149752. pPrev = pAnd;
  149753. }
  149754. /* This test catches attempts to make either operand of a NEAR
  149755. ** operator something other than a phrase. For example, either of
  149756. ** the following:
  149757. **
  149758. ** (bracketed expression) NEAR phrase
  149759. ** phrase NEAR (bracketed expression)
  149760. **
  149761. ** Return an error in either case.
  149762. */
  149763. if( pPrev && (
  149764. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  149765. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  149766. )){
  149767. sqlite3Fts3ExprFree(p);
  149768. rc = SQLITE_ERROR;
  149769. goto exprparse_out;
  149770. }
  149771. if( isPhrase ){
  149772. if( pRet ){
  149773. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  149774. pPrev->pRight = p;
  149775. p->pParent = pPrev;
  149776. }else{
  149777. pRet = p;
  149778. }
  149779. }else{
  149780. insertBinaryOperator(&pRet, pPrev, p);
  149781. }
  149782. isRequirePhrase = !isPhrase;
  149783. }
  149784. pPrev = p;
  149785. }
  149786. assert( nByte>0 );
  149787. }
  149788. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  149789. nIn -= nByte;
  149790. zIn += nByte;
  149791. }
  149792. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  149793. rc = SQLITE_ERROR;
  149794. }
  149795. if( rc==SQLITE_DONE ){
  149796. rc = SQLITE_OK;
  149797. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  149798. if( !pRet ){
  149799. rc = SQLITE_ERROR;
  149800. }else{
  149801. Fts3Expr *pIter = pNotBranch;
  149802. while( pIter->pLeft ){
  149803. pIter = pIter->pLeft;
  149804. }
  149805. pIter->pLeft = pRet;
  149806. pRet->pParent = pIter;
  149807. pRet = pNotBranch;
  149808. }
  149809. }
  149810. }
  149811. *pnConsumed = n - nIn;
  149812. exprparse_out:
  149813. if( rc!=SQLITE_OK ){
  149814. sqlite3Fts3ExprFree(pRet);
  149815. sqlite3Fts3ExprFree(pNotBranch);
  149816. pRet = 0;
  149817. }
  149818. *ppExpr = pRet;
  149819. return rc;
  149820. }
  149821. /*
  149822. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  149823. ** as the only argument is more than nMaxDepth.
  149824. */
  149825. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  149826. int rc = SQLITE_OK;
  149827. if( p ){
  149828. if( nMaxDepth<0 ){
  149829. rc = SQLITE_TOOBIG;
  149830. }else{
  149831. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  149832. if( rc==SQLITE_OK ){
  149833. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  149834. }
  149835. }
  149836. }
  149837. return rc;
  149838. }
  149839. /*
  149840. ** This function attempts to transform the expression tree at (*pp) to
  149841. ** an equivalent but more balanced form. The tree is modified in place.
  149842. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  149843. ** new root expression node.
  149844. **
  149845. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  149846. **
  149847. ** Otherwise, if an error occurs, an SQLite error code is returned and
  149848. ** expression (*pp) freed.
  149849. */
  149850. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  149851. int rc = SQLITE_OK; /* Return code */
  149852. Fts3Expr *pRoot = *pp; /* Initial root node */
  149853. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  149854. int eType = pRoot->eType; /* Type of node in this tree */
  149855. if( nMaxDepth==0 ){
  149856. rc = SQLITE_ERROR;
  149857. }
  149858. if( rc==SQLITE_OK ){
  149859. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  149860. Fts3Expr **apLeaf;
  149861. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  149862. if( 0==apLeaf ){
  149863. rc = SQLITE_NOMEM;
  149864. }else{
  149865. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  149866. }
  149867. if( rc==SQLITE_OK ){
  149868. int i;
  149869. Fts3Expr *p;
  149870. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  149871. for(p=pRoot; p->eType==eType; p=p->pLeft){
  149872. assert( p->pParent==0 || p->pParent->pLeft==p );
  149873. assert( p->pLeft && p->pRight );
  149874. }
  149875. /* This loop runs once for each leaf in the tree of eType nodes. */
  149876. while( 1 ){
  149877. int iLvl;
  149878. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  149879. assert( pParent==0 || pParent->pLeft==p );
  149880. p->pParent = 0;
  149881. if( pParent ){
  149882. pParent->pLeft = 0;
  149883. }else{
  149884. pRoot = 0;
  149885. }
  149886. rc = fts3ExprBalance(&p, nMaxDepth-1);
  149887. if( rc!=SQLITE_OK ) break;
  149888. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  149889. if( apLeaf[iLvl]==0 ){
  149890. apLeaf[iLvl] = p;
  149891. p = 0;
  149892. }else{
  149893. assert( pFree );
  149894. pFree->pLeft = apLeaf[iLvl];
  149895. pFree->pRight = p;
  149896. pFree->pLeft->pParent = pFree;
  149897. pFree->pRight->pParent = pFree;
  149898. p = pFree;
  149899. pFree = pFree->pParent;
  149900. p->pParent = 0;
  149901. apLeaf[iLvl] = 0;
  149902. }
  149903. }
  149904. if( p ){
  149905. sqlite3Fts3ExprFree(p);
  149906. rc = SQLITE_TOOBIG;
  149907. break;
  149908. }
  149909. /* If that was the last leaf node, break out of the loop */
  149910. if( pParent==0 ) break;
  149911. /* Set $p to point to the next leaf in the tree of eType nodes */
  149912. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  149913. /* Remove pParent from the original tree. */
  149914. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  149915. pParent->pRight->pParent = pParent->pParent;
  149916. if( pParent->pParent ){
  149917. pParent->pParent->pLeft = pParent->pRight;
  149918. }else{
  149919. assert( pParent==pRoot );
  149920. pRoot = pParent->pRight;
  149921. }
  149922. /* Link pParent into the free node list. It will be used as an
  149923. ** internal node of the new tree. */
  149924. pParent->pParent = pFree;
  149925. pFree = pParent;
  149926. }
  149927. if( rc==SQLITE_OK ){
  149928. p = 0;
  149929. for(i=0; i<nMaxDepth; i++){
  149930. if( apLeaf[i] ){
  149931. if( p==0 ){
  149932. p = apLeaf[i];
  149933. p->pParent = 0;
  149934. }else{
  149935. assert( pFree!=0 );
  149936. pFree->pRight = p;
  149937. pFree->pLeft = apLeaf[i];
  149938. pFree->pLeft->pParent = pFree;
  149939. pFree->pRight->pParent = pFree;
  149940. p = pFree;
  149941. pFree = pFree->pParent;
  149942. p->pParent = 0;
  149943. }
  149944. }
  149945. }
  149946. pRoot = p;
  149947. }else{
  149948. /* An error occurred. Delete the contents of the apLeaf[] array
  149949. ** and pFree list. Everything else is cleaned up by the call to
  149950. ** sqlite3Fts3ExprFree(pRoot) below. */
  149951. Fts3Expr *pDel;
  149952. for(i=0; i<nMaxDepth; i++){
  149953. sqlite3Fts3ExprFree(apLeaf[i]);
  149954. }
  149955. while( (pDel=pFree)!=0 ){
  149956. pFree = pDel->pParent;
  149957. sqlite3_free(pDel);
  149958. }
  149959. }
  149960. assert( pFree==0 );
  149961. sqlite3_free( apLeaf );
  149962. }
  149963. }else if( eType==FTSQUERY_NOT ){
  149964. Fts3Expr *pLeft = pRoot->pLeft;
  149965. Fts3Expr *pRight = pRoot->pRight;
  149966. pRoot->pLeft = 0;
  149967. pRoot->pRight = 0;
  149968. pLeft->pParent = 0;
  149969. pRight->pParent = 0;
  149970. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  149971. if( rc==SQLITE_OK ){
  149972. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  149973. }
  149974. if( rc!=SQLITE_OK ){
  149975. sqlite3Fts3ExprFree(pRight);
  149976. sqlite3Fts3ExprFree(pLeft);
  149977. }else{
  149978. assert( pLeft && pRight );
  149979. pRoot->pLeft = pLeft;
  149980. pLeft->pParent = pRoot;
  149981. pRoot->pRight = pRight;
  149982. pRight->pParent = pRoot;
  149983. }
  149984. }
  149985. }
  149986. if( rc!=SQLITE_OK ){
  149987. sqlite3Fts3ExprFree(pRoot);
  149988. pRoot = 0;
  149989. }
  149990. *pp = pRoot;
  149991. return rc;
  149992. }
  149993. /*
  149994. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  149995. ** differences:
  149996. **
  149997. ** 1. It does not do expression rebalancing.
  149998. ** 2. It does not check that the expression does not exceed the
  149999. ** maximum allowable depth.
  150000. ** 3. Even if it fails, *ppExpr may still be set to point to an
  150001. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  150002. ** in this case.
  150003. */
  150004. static int fts3ExprParseUnbalanced(
  150005. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  150006. int iLangid, /* Language id for tokenizer */
  150007. char **azCol, /* Array of column names for fts3 table */
  150008. int bFts4, /* True to allow FTS4-only syntax */
  150009. int nCol, /* Number of entries in azCol[] */
  150010. int iDefaultCol, /* Default column to query */
  150011. const char *z, int n, /* Text of MATCH query */
  150012. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  150013. ){
  150014. int nParsed;
  150015. int rc;
  150016. ParseContext sParse;
  150017. memset(&sParse, 0, sizeof(ParseContext));
  150018. sParse.pTokenizer = pTokenizer;
  150019. sParse.iLangid = iLangid;
  150020. sParse.azCol = (const char **)azCol;
  150021. sParse.nCol = nCol;
  150022. sParse.iDefaultCol = iDefaultCol;
  150023. sParse.bFts4 = bFts4;
  150024. if( z==0 ){
  150025. *ppExpr = 0;
  150026. return SQLITE_OK;
  150027. }
  150028. if( n<0 ){
  150029. n = (int)strlen(z);
  150030. }
  150031. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  150032. assert( rc==SQLITE_OK || *ppExpr==0 );
  150033. /* Check for mismatched parenthesis */
  150034. if( rc==SQLITE_OK && sParse.nNest ){
  150035. rc = SQLITE_ERROR;
  150036. }
  150037. return rc;
  150038. }
  150039. /*
  150040. ** Parameters z and n contain a pointer to and length of a buffer containing
  150041. ** an fts3 query expression, respectively. This function attempts to parse the
  150042. ** query expression and create a tree of Fts3Expr structures representing the
  150043. ** parsed expression. If successful, *ppExpr is set to point to the head
  150044. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  150045. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  150046. ** error) is returned and *ppExpr is set to 0.
  150047. **
  150048. ** If parameter n is a negative number, then z is assumed to point to a
  150049. ** nul-terminated string and the length is determined using strlen().
  150050. **
  150051. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  150052. ** use to normalize query tokens while parsing the expression. The azCol[]
  150053. ** array, which is assumed to contain nCol entries, should contain the names
  150054. ** of each column in the target fts3 table, in order from left to right.
  150055. ** Column names must be nul-terminated strings.
  150056. **
  150057. ** The iDefaultCol parameter should be passed the index of the table column
  150058. ** that appears on the left-hand-side of the MATCH operator (the default
  150059. ** column to match against for tokens for which a column name is not explicitly
  150060. ** specified as part of the query string), or -1 if tokens may by default
  150061. ** match any table column.
  150062. */
  150063. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  150064. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  150065. int iLangid, /* Language id for tokenizer */
  150066. char **azCol, /* Array of column names for fts3 table */
  150067. int bFts4, /* True to allow FTS4-only syntax */
  150068. int nCol, /* Number of entries in azCol[] */
  150069. int iDefaultCol, /* Default column to query */
  150070. const char *z, int n, /* Text of MATCH query */
  150071. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  150072. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  150073. ){
  150074. int rc = fts3ExprParseUnbalanced(
  150075. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  150076. );
  150077. /* Rebalance the expression. And check that its depth does not exceed
  150078. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  150079. if( rc==SQLITE_OK && *ppExpr ){
  150080. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  150081. if( rc==SQLITE_OK ){
  150082. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  150083. }
  150084. }
  150085. if( rc!=SQLITE_OK ){
  150086. sqlite3Fts3ExprFree(*ppExpr);
  150087. *ppExpr = 0;
  150088. if( rc==SQLITE_TOOBIG ){
  150089. sqlite3Fts3ErrMsg(pzErr,
  150090. "FTS expression tree is too large (maximum depth %d)",
  150091. SQLITE_FTS3_MAX_EXPR_DEPTH
  150092. );
  150093. rc = SQLITE_ERROR;
  150094. }else if( rc==SQLITE_ERROR ){
  150095. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  150096. }
  150097. }
  150098. return rc;
  150099. }
  150100. /*
  150101. ** Free a single node of an expression tree.
  150102. */
  150103. static void fts3FreeExprNode(Fts3Expr *p){
  150104. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  150105. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  150106. sqlite3_free(p->aMI);
  150107. sqlite3_free(p);
  150108. }
  150109. /*
  150110. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  150111. **
  150112. ** This function would be simpler if it recursively called itself. But
  150113. ** that would mean passing a sufficiently large expression to ExprParse()
  150114. ** could cause a stack overflow.
  150115. */
  150116. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  150117. Fts3Expr *p;
  150118. assert( pDel==0 || pDel->pParent==0 );
  150119. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  150120. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  150121. }
  150122. while( p ){
  150123. Fts3Expr *pParent = p->pParent;
  150124. fts3FreeExprNode(p);
  150125. if( pParent && p==pParent->pLeft && pParent->pRight ){
  150126. p = pParent->pRight;
  150127. while( p && (p->pLeft || p->pRight) ){
  150128. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  150129. p = (p->pLeft ? p->pLeft : p->pRight);
  150130. }
  150131. }else{
  150132. p = pParent;
  150133. }
  150134. }
  150135. }
  150136. /****************************************************************************
  150137. *****************************************************************************
  150138. ** Everything after this point is just test code.
  150139. */
  150140. #ifdef SQLITE_TEST
  150141. /* #include <stdio.h> */
  150142. /*
  150143. ** Return a pointer to a buffer containing a text representation of the
  150144. ** expression passed as the first argument. The buffer is obtained from
  150145. ** sqlite3_malloc(). It is the responsibility of the caller to use
  150146. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  150147. ** NULL is returned.
  150148. **
  150149. ** If the second argument is not NULL, then its contents are prepended to
  150150. ** the returned expression text and then freed using sqlite3_free().
  150151. */
  150152. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  150153. if( pExpr==0 ){
  150154. return sqlite3_mprintf("");
  150155. }
  150156. switch( pExpr->eType ){
  150157. case FTSQUERY_PHRASE: {
  150158. Fts3Phrase *pPhrase = pExpr->pPhrase;
  150159. int i;
  150160. zBuf = sqlite3_mprintf(
  150161. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  150162. for(i=0; zBuf && i<pPhrase->nToken; i++){
  150163. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  150164. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  150165. (pPhrase->aToken[i].isPrefix?"+":"")
  150166. );
  150167. }
  150168. return zBuf;
  150169. }
  150170. case FTSQUERY_NEAR:
  150171. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  150172. break;
  150173. case FTSQUERY_NOT:
  150174. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  150175. break;
  150176. case FTSQUERY_AND:
  150177. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  150178. break;
  150179. case FTSQUERY_OR:
  150180. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  150181. break;
  150182. }
  150183. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  150184. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  150185. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  150186. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  150187. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  150188. return zBuf;
  150189. }
  150190. /*
  150191. ** This is the implementation of a scalar SQL function used to test the
  150192. ** expression parser. It should be called as follows:
  150193. **
  150194. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  150195. **
  150196. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  150197. ** to parse the query expression (see README.tokenizers). The second argument
  150198. ** is the query expression to parse. Each subsequent argument is the name
  150199. ** of a column of the fts3 table that the query expression may refer to.
  150200. ** For example:
  150201. **
  150202. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  150203. */
  150204. static void fts3ExprTestCommon(
  150205. int bRebalance,
  150206. sqlite3_context *context,
  150207. int argc,
  150208. sqlite3_value **argv
  150209. ){
  150210. sqlite3_tokenizer *pTokenizer = 0;
  150211. int rc;
  150212. char **azCol = 0;
  150213. const char *zExpr;
  150214. int nExpr;
  150215. int nCol;
  150216. int ii;
  150217. Fts3Expr *pExpr;
  150218. char *zBuf = 0;
  150219. Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
  150220. const char *zTokenizer = 0;
  150221. char *zErr = 0;
  150222. if( argc<3 ){
  150223. sqlite3_result_error(context,
  150224. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  150225. );
  150226. return;
  150227. }
  150228. zTokenizer = (const char*)sqlite3_value_text(argv[0]);
  150229. rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
  150230. if( rc!=SQLITE_OK ){
  150231. if( rc==SQLITE_NOMEM ){
  150232. sqlite3_result_error_nomem(context);
  150233. }else{
  150234. sqlite3_result_error(context, zErr, -1);
  150235. }
  150236. sqlite3_free(zErr);
  150237. return;
  150238. }
  150239. zExpr = (const char *)sqlite3_value_text(argv[1]);
  150240. nExpr = sqlite3_value_bytes(argv[1]);
  150241. nCol = argc-2;
  150242. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  150243. if( !azCol ){
  150244. sqlite3_result_error_nomem(context);
  150245. goto exprtest_out;
  150246. }
  150247. for(ii=0; ii<nCol; ii++){
  150248. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  150249. }
  150250. if( bRebalance ){
  150251. char *zDummy = 0;
  150252. rc = sqlite3Fts3ExprParse(
  150253. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  150254. );
  150255. assert( rc==SQLITE_OK || pExpr==0 );
  150256. sqlite3_free(zDummy);
  150257. }else{
  150258. rc = fts3ExprParseUnbalanced(
  150259. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  150260. );
  150261. }
  150262. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  150263. sqlite3Fts3ExprFree(pExpr);
  150264. sqlite3_result_error(context, "Error parsing expression", -1);
  150265. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  150266. sqlite3_result_error_nomem(context);
  150267. }else{
  150268. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  150269. sqlite3_free(zBuf);
  150270. }
  150271. sqlite3Fts3ExprFree(pExpr);
  150272. exprtest_out:
  150273. if( pTokenizer ){
  150274. rc = pTokenizer->pModule->xDestroy(pTokenizer);
  150275. }
  150276. sqlite3_free(azCol);
  150277. }
  150278. static void fts3ExprTest(
  150279. sqlite3_context *context,
  150280. int argc,
  150281. sqlite3_value **argv
  150282. ){
  150283. fts3ExprTestCommon(0, context, argc, argv);
  150284. }
  150285. static void fts3ExprTestRebalance(
  150286. sqlite3_context *context,
  150287. int argc,
  150288. sqlite3_value **argv
  150289. ){
  150290. fts3ExprTestCommon(1, context, argc, argv);
  150291. }
  150292. /*
  150293. ** Register the query expression parser test function fts3_exprtest()
  150294. ** with database connection db.
  150295. */
  150296. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
  150297. int rc = sqlite3_create_function(
  150298. db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
  150299. );
  150300. if( rc==SQLITE_OK ){
  150301. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  150302. -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
  150303. );
  150304. }
  150305. return rc;
  150306. }
  150307. #endif
  150308. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  150309. /************** End of fts3_expr.c *******************************************/
  150310. /************** Begin file fts3_hash.c ***************************************/
  150311. /*
  150312. ** 2001 September 22
  150313. **
  150314. ** The author disclaims copyright to this source code. In place of
  150315. ** a legal notice, here is a blessing:
  150316. **
  150317. ** May you do good and not evil.
  150318. ** May you find forgiveness for yourself and forgive others.
  150319. ** May you share freely, never taking more than you give.
  150320. **
  150321. *************************************************************************
  150322. ** This is the implementation of generic hash-tables used in SQLite.
  150323. ** We've modified it slightly to serve as a standalone hash table
  150324. ** implementation for the full-text indexing module.
  150325. */
  150326. /*
  150327. ** The code in this file is only compiled if:
  150328. **
  150329. ** * The FTS3 module is being built as an extension
  150330. ** (in which case SQLITE_CORE is not defined), or
  150331. **
  150332. ** * The FTS3 module is being built into the core of
  150333. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  150334. */
  150335. /* #include "fts3Int.h" */
  150336. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150337. /* #include <assert.h> */
  150338. /* #include <stdlib.h> */
  150339. /* #include <string.h> */
  150340. /* #include "fts3_hash.h" */
  150341. /*
  150342. ** Malloc and Free functions
  150343. */
  150344. static void *fts3HashMalloc(int n){
  150345. void *p = sqlite3_malloc(n);
  150346. if( p ){
  150347. memset(p, 0, n);
  150348. }
  150349. return p;
  150350. }
  150351. static void fts3HashFree(void *p){
  150352. sqlite3_free(p);
  150353. }
  150354. /* Turn bulk memory into a hash table object by initializing the
  150355. ** fields of the Hash structure.
  150356. **
  150357. ** "pNew" is a pointer to the hash table that is to be initialized.
  150358. ** keyClass is one of the constants
  150359. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  150360. ** determines what kind of key the hash table will use. "copyKey" is
  150361. ** true if the hash table should make its own private copy of keys and
  150362. ** false if it should just use the supplied pointer.
  150363. */
  150364. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  150365. assert( pNew!=0 );
  150366. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  150367. pNew->keyClass = keyClass;
  150368. pNew->copyKey = copyKey;
  150369. pNew->first = 0;
  150370. pNew->count = 0;
  150371. pNew->htsize = 0;
  150372. pNew->ht = 0;
  150373. }
  150374. /* Remove all entries from a hash table. Reclaim all memory.
  150375. ** Call this routine to delete a hash table or to reset a hash table
  150376. ** to the empty state.
  150377. */
  150378. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  150379. Fts3HashElem *elem; /* For looping over all elements of the table */
  150380. assert( pH!=0 );
  150381. elem = pH->first;
  150382. pH->first = 0;
  150383. fts3HashFree(pH->ht);
  150384. pH->ht = 0;
  150385. pH->htsize = 0;
  150386. while( elem ){
  150387. Fts3HashElem *next_elem = elem->next;
  150388. if( pH->copyKey && elem->pKey ){
  150389. fts3HashFree(elem->pKey);
  150390. }
  150391. fts3HashFree(elem);
  150392. elem = next_elem;
  150393. }
  150394. pH->count = 0;
  150395. }
  150396. /*
  150397. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  150398. */
  150399. static int fts3StrHash(const void *pKey, int nKey){
  150400. const char *z = (const char *)pKey;
  150401. unsigned h = 0;
  150402. if( nKey<=0 ) nKey = (int) strlen(z);
  150403. while( nKey > 0 ){
  150404. h = (h<<3) ^ h ^ *z++;
  150405. nKey--;
  150406. }
  150407. return (int)(h & 0x7fffffff);
  150408. }
  150409. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  150410. if( n1!=n2 ) return 1;
  150411. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  150412. }
  150413. /*
  150414. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  150415. */
  150416. static int fts3BinHash(const void *pKey, int nKey){
  150417. int h = 0;
  150418. const char *z = (const char *)pKey;
  150419. while( nKey-- > 0 ){
  150420. h = (h<<3) ^ h ^ *(z++);
  150421. }
  150422. return h & 0x7fffffff;
  150423. }
  150424. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  150425. if( n1!=n2 ) return 1;
  150426. return memcmp(pKey1,pKey2,n1);
  150427. }
  150428. /*
  150429. ** Return a pointer to the appropriate hash function given the key class.
  150430. **
  150431. ** The C syntax in this function definition may be unfamilar to some
  150432. ** programmers, so we provide the following additional explanation:
  150433. **
  150434. ** The name of the function is "ftsHashFunction". The function takes a
  150435. ** single parameter "keyClass". The return value of ftsHashFunction()
  150436. ** is a pointer to another function. Specifically, the return value
  150437. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  150438. ** with types "const void*" and "int" and returns an "int".
  150439. */
  150440. static int (*ftsHashFunction(int keyClass))(const void*,int){
  150441. if( keyClass==FTS3_HASH_STRING ){
  150442. return &fts3StrHash;
  150443. }else{
  150444. assert( keyClass==FTS3_HASH_BINARY );
  150445. return &fts3BinHash;
  150446. }
  150447. }
  150448. /*
  150449. ** Return a pointer to the appropriate hash function given the key class.
  150450. **
  150451. ** For help in interpreted the obscure C code in the function definition,
  150452. ** see the header comment on the previous function.
  150453. */
  150454. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  150455. if( keyClass==FTS3_HASH_STRING ){
  150456. return &fts3StrCompare;
  150457. }else{
  150458. assert( keyClass==FTS3_HASH_BINARY );
  150459. return &fts3BinCompare;
  150460. }
  150461. }
  150462. /* Link an element into the hash table
  150463. */
  150464. static void fts3HashInsertElement(
  150465. Fts3Hash *pH, /* The complete hash table */
  150466. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  150467. Fts3HashElem *pNew /* The element to be inserted */
  150468. ){
  150469. Fts3HashElem *pHead; /* First element already in pEntry */
  150470. pHead = pEntry->chain;
  150471. if( pHead ){
  150472. pNew->next = pHead;
  150473. pNew->prev = pHead->prev;
  150474. if( pHead->prev ){ pHead->prev->next = pNew; }
  150475. else { pH->first = pNew; }
  150476. pHead->prev = pNew;
  150477. }else{
  150478. pNew->next = pH->first;
  150479. if( pH->first ){ pH->first->prev = pNew; }
  150480. pNew->prev = 0;
  150481. pH->first = pNew;
  150482. }
  150483. pEntry->count++;
  150484. pEntry->chain = pNew;
  150485. }
  150486. /* Resize the hash table so that it cantains "new_size" buckets.
  150487. ** "new_size" must be a power of 2. The hash table might fail
  150488. ** to resize if sqliteMalloc() fails.
  150489. **
  150490. ** Return non-zero if a memory allocation error occurs.
  150491. */
  150492. static int fts3Rehash(Fts3Hash *pH, int new_size){
  150493. struct _fts3ht *new_ht; /* The new hash table */
  150494. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  150495. int (*xHash)(const void*,int); /* The hash function */
  150496. assert( (new_size & (new_size-1))==0 );
  150497. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  150498. if( new_ht==0 ) return 1;
  150499. fts3HashFree(pH->ht);
  150500. pH->ht = new_ht;
  150501. pH->htsize = new_size;
  150502. xHash = ftsHashFunction(pH->keyClass);
  150503. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  150504. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  150505. next_elem = elem->next;
  150506. fts3HashInsertElement(pH, &new_ht[h], elem);
  150507. }
  150508. return 0;
  150509. }
  150510. /* This function (for internal use only) locates an element in an
  150511. ** hash table that matches the given key. The hash for this key has
  150512. ** already been computed and is passed as the 4th parameter.
  150513. */
  150514. static Fts3HashElem *fts3FindElementByHash(
  150515. const Fts3Hash *pH, /* The pH to be searched */
  150516. const void *pKey, /* The key we are searching for */
  150517. int nKey,
  150518. int h /* The hash for this key. */
  150519. ){
  150520. Fts3HashElem *elem; /* Used to loop thru the element list */
  150521. int count; /* Number of elements left to test */
  150522. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  150523. if( pH->ht ){
  150524. struct _fts3ht *pEntry = &pH->ht[h];
  150525. elem = pEntry->chain;
  150526. count = pEntry->count;
  150527. xCompare = ftsCompareFunction(pH->keyClass);
  150528. while( count-- && elem ){
  150529. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  150530. return elem;
  150531. }
  150532. elem = elem->next;
  150533. }
  150534. }
  150535. return 0;
  150536. }
  150537. /* Remove a single entry from the hash table given a pointer to that
  150538. ** element and a hash on the element's key.
  150539. */
  150540. static void fts3RemoveElementByHash(
  150541. Fts3Hash *pH, /* The pH containing "elem" */
  150542. Fts3HashElem* elem, /* The element to be removed from the pH */
  150543. int h /* Hash value for the element */
  150544. ){
  150545. struct _fts3ht *pEntry;
  150546. if( elem->prev ){
  150547. elem->prev->next = elem->next;
  150548. }else{
  150549. pH->first = elem->next;
  150550. }
  150551. if( elem->next ){
  150552. elem->next->prev = elem->prev;
  150553. }
  150554. pEntry = &pH->ht[h];
  150555. if( pEntry->chain==elem ){
  150556. pEntry->chain = elem->next;
  150557. }
  150558. pEntry->count--;
  150559. if( pEntry->count<=0 ){
  150560. pEntry->chain = 0;
  150561. }
  150562. if( pH->copyKey && elem->pKey ){
  150563. fts3HashFree(elem->pKey);
  150564. }
  150565. fts3HashFree( elem );
  150566. pH->count--;
  150567. if( pH->count<=0 ){
  150568. assert( pH->first==0 );
  150569. assert( pH->count==0 );
  150570. fts3HashClear(pH);
  150571. }
  150572. }
  150573. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  150574. const Fts3Hash *pH,
  150575. const void *pKey,
  150576. int nKey
  150577. ){
  150578. int h; /* A hash on key */
  150579. int (*xHash)(const void*,int); /* The hash function */
  150580. if( pH==0 || pH->ht==0 ) return 0;
  150581. xHash = ftsHashFunction(pH->keyClass);
  150582. assert( xHash!=0 );
  150583. h = (*xHash)(pKey,nKey);
  150584. assert( (pH->htsize & (pH->htsize-1))==0 );
  150585. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  150586. }
  150587. /*
  150588. ** Attempt to locate an element of the hash table pH with a key
  150589. ** that matches pKey,nKey. Return the data for this element if it is
  150590. ** found, or NULL if there is no match.
  150591. */
  150592. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  150593. Fts3HashElem *pElem; /* The element that matches key (if any) */
  150594. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  150595. return pElem ? pElem->data : 0;
  150596. }
  150597. /* Insert an element into the hash table pH. The key is pKey,nKey
  150598. ** and the data is "data".
  150599. **
  150600. ** If no element exists with a matching key, then a new
  150601. ** element is created. A copy of the key is made if the copyKey
  150602. ** flag is set. NULL is returned.
  150603. **
  150604. ** If another element already exists with the same key, then the
  150605. ** new data replaces the old data and the old data is returned.
  150606. ** The key is not copied in this instance. If a malloc fails, then
  150607. ** the new data is returned and the hash table is unchanged.
  150608. **
  150609. ** If the "data" parameter to this function is NULL, then the
  150610. ** element corresponding to "key" is removed from the hash table.
  150611. */
  150612. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  150613. Fts3Hash *pH, /* The hash table to insert into */
  150614. const void *pKey, /* The key */
  150615. int nKey, /* Number of bytes in the key */
  150616. void *data /* The data */
  150617. ){
  150618. int hraw; /* Raw hash value of the key */
  150619. int h; /* the hash of the key modulo hash table size */
  150620. Fts3HashElem *elem; /* Used to loop thru the element list */
  150621. Fts3HashElem *new_elem; /* New element added to the pH */
  150622. int (*xHash)(const void*,int); /* The hash function */
  150623. assert( pH!=0 );
  150624. xHash = ftsHashFunction(pH->keyClass);
  150625. assert( xHash!=0 );
  150626. hraw = (*xHash)(pKey, nKey);
  150627. assert( (pH->htsize & (pH->htsize-1))==0 );
  150628. h = hraw & (pH->htsize-1);
  150629. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  150630. if( elem ){
  150631. void *old_data = elem->data;
  150632. if( data==0 ){
  150633. fts3RemoveElementByHash(pH,elem,h);
  150634. }else{
  150635. elem->data = data;
  150636. }
  150637. return old_data;
  150638. }
  150639. if( data==0 ) return 0;
  150640. if( (pH->htsize==0 && fts3Rehash(pH,8))
  150641. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  150642. ){
  150643. pH->count = 0;
  150644. return data;
  150645. }
  150646. assert( pH->htsize>0 );
  150647. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  150648. if( new_elem==0 ) return data;
  150649. if( pH->copyKey && pKey!=0 ){
  150650. new_elem->pKey = fts3HashMalloc( nKey );
  150651. if( new_elem->pKey==0 ){
  150652. fts3HashFree(new_elem);
  150653. return data;
  150654. }
  150655. memcpy((void*)new_elem->pKey, pKey, nKey);
  150656. }else{
  150657. new_elem->pKey = (void*)pKey;
  150658. }
  150659. new_elem->nKey = nKey;
  150660. pH->count++;
  150661. assert( pH->htsize>0 );
  150662. assert( (pH->htsize & (pH->htsize-1))==0 );
  150663. h = hraw & (pH->htsize-1);
  150664. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  150665. new_elem->data = data;
  150666. return 0;
  150667. }
  150668. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  150669. /************** End of fts3_hash.c *******************************************/
  150670. /************** Begin file fts3_porter.c *************************************/
  150671. /*
  150672. ** 2006 September 30
  150673. **
  150674. ** The author disclaims copyright to this source code. In place of
  150675. ** a legal notice, here is a blessing:
  150676. **
  150677. ** May you do good and not evil.
  150678. ** May you find forgiveness for yourself and forgive others.
  150679. ** May you share freely, never taking more than you give.
  150680. **
  150681. *************************************************************************
  150682. ** Implementation of the full-text-search tokenizer that implements
  150683. ** a Porter stemmer.
  150684. */
  150685. /*
  150686. ** The code in this file is only compiled if:
  150687. **
  150688. ** * The FTS3 module is being built as an extension
  150689. ** (in which case SQLITE_CORE is not defined), or
  150690. **
  150691. ** * The FTS3 module is being built into the core of
  150692. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  150693. */
  150694. /* #include "fts3Int.h" */
  150695. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150696. /* #include <assert.h> */
  150697. /* #include <stdlib.h> */
  150698. /* #include <stdio.h> */
  150699. /* #include <string.h> */
  150700. /* #include "fts3_tokenizer.h" */
  150701. /*
  150702. ** Class derived from sqlite3_tokenizer
  150703. */
  150704. typedef struct porter_tokenizer {
  150705. sqlite3_tokenizer base; /* Base class */
  150706. } porter_tokenizer;
  150707. /*
  150708. ** Class derived from sqlite3_tokenizer_cursor
  150709. */
  150710. typedef struct porter_tokenizer_cursor {
  150711. sqlite3_tokenizer_cursor base;
  150712. const char *zInput; /* input we are tokenizing */
  150713. int nInput; /* size of the input */
  150714. int iOffset; /* current position in zInput */
  150715. int iToken; /* index of next token to be returned */
  150716. char *zToken; /* storage for current token */
  150717. int nAllocated; /* space allocated to zToken buffer */
  150718. } porter_tokenizer_cursor;
  150719. /*
  150720. ** Create a new tokenizer instance.
  150721. */
  150722. static int porterCreate(
  150723. int argc, const char * const *argv,
  150724. sqlite3_tokenizer **ppTokenizer
  150725. ){
  150726. porter_tokenizer *t;
  150727. UNUSED_PARAMETER(argc);
  150728. UNUSED_PARAMETER(argv);
  150729. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  150730. if( t==NULL ) return SQLITE_NOMEM;
  150731. memset(t, 0, sizeof(*t));
  150732. *ppTokenizer = &t->base;
  150733. return SQLITE_OK;
  150734. }
  150735. /*
  150736. ** Destroy a tokenizer
  150737. */
  150738. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  150739. sqlite3_free(pTokenizer);
  150740. return SQLITE_OK;
  150741. }
  150742. /*
  150743. ** Prepare to begin tokenizing a particular string. The input
  150744. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  150745. ** used to incrementally tokenize this string is returned in
  150746. ** *ppCursor.
  150747. */
  150748. static int porterOpen(
  150749. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  150750. const char *zInput, int nInput, /* String to be tokenized */
  150751. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  150752. ){
  150753. porter_tokenizer_cursor *c;
  150754. UNUSED_PARAMETER(pTokenizer);
  150755. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  150756. if( c==NULL ) return SQLITE_NOMEM;
  150757. c->zInput = zInput;
  150758. if( zInput==0 ){
  150759. c->nInput = 0;
  150760. }else if( nInput<0 ){
  150761. c->nInput = (int)strlen(zInput);
  150762. }else{
  150763. c->nInput = nInput;
  150764. }
  150765. c->iOffset = 0; /* start tokenizing at the beginning */
  150766. c->iToken = 0;
  150767. c->zToken = NULL; /* no space allocated, yet. */
  150768. c->nAllocated = 0;
  150769. *ppCursor = &c->base;
  150770. return SQLITE_OK;
  150771. }
  150772. /*
  150773. ** Close a tokenization cursor previously opened by a call to
  150774. ** porterOpen() above.
  150775. */
  150776. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  150777. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  150778. sqlite3_free(c->zToken);
  150779. sqlite3_free(c);
  150780. return SQLITE_OK;
  150781. }
  150782. /*
  150783. ** Vowel or consonant
  150784. */
  150785. static const char cType[] = {
  150786. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  150787. 1, 1, 1, 2, 1
  150788. };
  150789. /*
  150790. ** isConsonant() and isVowel() determine if their first character in
  150791. ** the string they point to is a consonant or a vowel, according
  150792. ** to Porter ruls.
  150793. **
  150794. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  150795. ** 'Y' is a consonant unless it follows another consonant,
  150796. ** in which case it is a vowel.
  150797. **
  150798. ** In these routine, the letters are in reverse order. So the 'y' rule
  150799. ** is that 'y' is a consonant unless it is followed by another
  150800. ** consonent.
  150801. */
  150802. static int isVowel(const char*);
  150803. static int isConsonant(const char *z){
  150804. int j;
  150805. char x = *z;
  150806. if( x==0 ) return 0;
  150807. assert( x>='a' && x<='z' );
  150808. j = cType[x-'a'];
  150809. if( j<2 ) return j;
  150810. return z[1]==0 || isVowel(z + 1);
  150811. }
  150812. static int isVowel(const char *z){
  150813. int j;
  150814. char x = *z;
  150815. if( x==0 ) return 0;
  150816. assert( x>='a' && x<='z' );
  150817. j = cType[x-'a'];
  150818. if( j<2 ) return 1-j;
  150819. return isConsonant(z + 1);
  150820. }
  150821. /*
  150822. ** Let any sequence of one or more vowels be represented by V and let
  150823. ** C be sequence of one or more consonants. Then every word can be
  150824. ** represented as:
  150825. **
  150826. ** [C] (VC){m} [V]
  150827. **
  150828. ** In prose: A word is an optional consonant followed by zero or
  150829. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  150830. ** number of vowel consonant pairs. This routine computes the value
  150831. ** of m for the first i bytes of a word.
  150832. **
  150833. ** Return true if the m-value for z is 1 or more. In other words,
  150834. ** return true if z contains at least one vowel that is followed
  150835. ** by a consonant.
  150836. **
  150837. ** In this routine z[] is in reverse order. So we are really looking
  150838. ** for an instance of a consonant followed by a vowel.
  150839. */
  150840. static int m_gt_0(const char *z){
  150841. while( isVowel(z) ){ z++; }
  150842. if( *z==0 ) return 0;
  150843. while( isConsonant(z) ){ z++; }
  150844. return *z!=0;
  150845. }
  150846. /* Like mgt0 above except we are looking for a value of m which is
  150847. ** exactly 1
  150848. */
  150849. static int m_eq_1(const char *z){
  150850. while( isVowel(z) ){ z++; }
  150851. if( *z==0 ) return 0;
  150852. while( isConsonant(z) ){ z++; }
  150853. if( *z==0 ) return 0;
  150854. while( isVowel(z) ){ z++; }
  150855. if( *z==0 ) return 1;
  150856. while( isConsonant(z) ){ z++; }
  150857. return *z==0;
  150858. }
  150859. /* Like mgt0 above except we are looking for a value of m>1 instead
  150860. ** or m>0
  150861. */
  150862. static int m_gt_1(const char *z){
  150863. while( isVowel(z) ){ z++; }
  150864. if( *z==0 ) return 0;
  150865. while( isConsonant(z) ){ z++; }
  150866. if( *z==0 ) return 0;
  150867. while( isVowel(z) ){ z++; }
  150868. if( *z==0 ) return 0;
  150869. while( isConsonant(z) ){ z++; }
  150870. return *z!=0;
  150871. }
  150872. /*
  150873. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  150874. */
  150875. static int hasVowel(const char *z){
  150876. while( isConsonant(z) ){ z++; }
  150877. return *z!=0;
  150878. }
  150879. /*
  150880. ** Return TRUE if the word ends in a double consonant.
  150881. **
  150882. ** The text is reversed here. So we are really looking at
  150883. ** the first two characters of z[].
  150884. */
  150885. static int doubleConsonant(const char *z){
  150886. return isConsonant(z) && z[0]==z[1];
  150887. }
  150888. /*
  150889. ** Return TRUE if the word ends with three letters which
  150890. ** are consonant-vowel-consonent and where the final consonant
  150891. ** is not 'w', 'x', or 'y'.
  150892. **
  150893. ** The word is reversed here. So we are really checking the
  150894. ** first three letters and the first one cannot be in [wxy].
  150895. */
  150896. static int star_oh(const char *z){
  150897. return
  150898. isConsonant(z) &&
  150899. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  150900. isVowel(z+1) &&
  150901. isConsonant(z+2);
  150902. }
  150903. /*
  150904. ** If the word ends with zFrom and xCond() is true for the stem
  150905. ** of the word that preceeds the zFrom ending, then change the
  150906. ** ending to zTo.
  150907. **
  150908. ** The input word *pz and zFrom are both in reverse order. zTo
  150909. ** is in normal order.
  150910. **
  150911. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  150912. ** match. Not that TRUE is returned even if xCond() fails and
  150913. ** no substitution occurs.
  150914. */
  150915. static int stem(
  150916. char **pz, /* The word being stemmed (Reversed) */
  150917. const char *zFrom, /* If the ending matches this... (Reversed) */
  150918. const char *zTo, /* ... change the ending to this (not reversed) */
  150919. int (*xCond)(const char*) /* Condition that must be true */
  150920. ){
  150921. char *z = *pz;
  150922. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  150923. if( *zFrom!=0 ) return 0;
  150924. if( xCond && !xCond(z) ) return 1;
  150925. while( *zTo ){
  150926. *(--z) = *(zTo++);
  150927. }
  150928. *pz = z;
  150929. return 1;
  150930. }
  150931. /*
  150932. ** This is the fallback stemmer used when the porter stemmer is
  150933. ** inappropriate. The input word is copied into the output with
  150934. ** US-ASCII case folding. If the input word is too long (more
  150935. ** than 20 bytes if it contains no digits or more than 6 bytes if
  150936. ** it contains digits) then word is truncated to 20 or 6 bytes
  150937. ** by taking 10 or 3 bytes from the beginning and end.
  150938. */
  150939. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  150940. int i, mx, j;
  150941. int hasDigit = 0;
  150942. for(i=0; i<nIn; i++){
  150943. char c = zIn[i];
  150944. if( c>='A' && c<='Z' ){
  150945. zOut[i] = c - 'A' + 'a';
  150946. }else{
  150947. if( c>='0' && c<='9' ) hasDigit = 1;
  150948. zOut[i] = c;
  150949. }
  150950. }
  150951. mx = hasDigit ? 3 : 10;
  150952. if( nIn>mx*2 ){
  150953. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  150954. zOut[j] = zOut[i];
  150955. }
  150956. i = j;
  150957. }
  150958. zOut[i] = 0;
  150959. *pnOut = i;
  150960. }
  150961. /*
  150962. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  150963. ** zOut is at least big enough to hold nIn bytes. Write the actual
  150964. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  150965. **
  150966. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  150967. ** are converted to lower case. Upper-case UTF characters are
  150968. ** unchanged.
  150969. **
  150970. ** Words that are longer than about 20 bytes are stemmed by retaining
  150971. ** a few bytes from the beginning and the end of the word. If the
  150972. ** word contains digits, 3 bytes are taken from the beginning and
  150973. ** 3 bytes from the end. For long words without digits, 10 bytes
  150974. ** are taken from each end. US-ASCII case folding still applies.
  150975. **
  150976. ** If the input word contains not digits but does characters not
  150977. ** in [a-zA-Z] then no stemming is attempted and this routine just
  150978. ** copies the input into the input into the output with US-ASCII
  150979. ** case folding.
  150980. **
  150981. ** Stemming never increases the length of the word. So there is
  150982. ** no chance of overflowing the zOut buffer.
  150983. */
  150984. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  150985. int i, j;
  150986. char zReverse[28];
  150987. char *z, *z2;
  150988. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  150989. /* The word is too big or too small for the porter stemmer.
  150990. ** Fallback to the copy stemmer */
  150991. copy_stemmer(zIn, nIn, zOut, pnOut);
  150992. return;
  150993. }
  150994. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  150995. char c = zIn[i];
  150996. if( c>='A' && c<='Z' ){
  150997. zReverse[j] = c + 'a' - 'A';
  150998. }else if( c>='a' && c<='z' ){
  150999. zReverse[j] = c;
  151000. }else{
  151001. /* The use of a character not in [a-zA-Z] means that we fallback
  151002. ** to the copy stemmer */
  151003. copy_stemmer(zIn, nIn, zOut, pnOut);
  151004. return;
  151005. }
  151006. }
  151007. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  151008. z = &zReverse[j+1];
  151009. /* Step 1a */
  151010. if( z[0]=='s' ){
  151011. if(
  151012. !stem(&z, "sess", "ss", 0) &&
  151013. !stem(&z, "sei", "i", 0) &&
  151014. !stem(&z, "ss", "ss", 0)
  151015. ){
  151016. z++;
  151017. }
  151018. }
  151019. /* Step 1b */
  151020. z2 = z;
  151021. if( stem(&z, "dee", "ee", m_gt_0) ){
  151022. /* Do nothing. The work was all in the test */
  151023. }else if(
  151024. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  151025. && z!=z2
  151026. ){
  151027. if( stem(&z, "ta", "ate", 0) ||
  151028. stem(&z, "lb", "ble", 0) ||
  151029. stem(&z, "zi", "ize", 0) ){
  151030. /* Do nothing. The work was all in the test */
  151031. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  151032. z++;
  151033. }else if( m_eq_1(z) && star_oh(z) ){
  151034. *(--z) = 'e';
  151035. }
  151036. }
  151037. /* Step 1c */
  151038. if( z[0]=='y' && hasVowel(z+1) ){
  151039. z[0] = 'i';
  151040. }
  151041. /* Step 2 */
  151042. switch( z[1] ){
  151043. case 'a':
  151044. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  151045. stem(&z, "lanoit", "tion", m_gt_0);
  151046. }
  151047. break;
  151048. case 'c':
  151049. if( !stem(&z, "icne", "ence", m_gt_0) ){
  151050. stem(&z, "icna", "ance", m_gt_0);
  151051. }
  151052. break;
  151053. case 'e':
  151054. stem(&z, "rezi", "ize", m_gt_0);
  151055. break;
  151056. case 'g':
  151057. stem(&z, "igol", "log", m_gt_0);
  151058. break;
  151059. case 'l':
  151060. if( !stem(&z, "ilb", "ble", m_gt_0)
  151061. && !stem(&z, "illa", "al", m_gt_0)
  151062. && !stem(&z, "iltne", "ent", m_gt_0)
  151063. && !stem(&z, "ile", "e", m_gt_0)
  151064. ){
  151065. stem(&z, "ilsuo", "ous", m_gt_0);
  151066. }
  151067. break;
  151068. case 'o':
  151069. if( !stem(&z, "noitazi", "ize", m_gt_0)
  151070. && !stem(&z, "noita", "ate", m_gt_0)
  151071. ){
  151072. stem(&z, "rota", "ate", m_gt_0);
  151073. }
  151074. break;
  151075. case 's':
  151076. if( !stem(&z, "msila", "al", m_gt_0)
  151077. && !stem(&z, "ssenevi", "ive", m_gt_0)
  151078. && !stem(&z, "ssenluf", "ful", m_gt_0)
  151079. ){
  151080. stem(&z, "ssensuo", "ous", m_gt_0);
  151081. }
  151082. break;
  151083. case 't':
  151084. if( !stem(&z, "itila", "al", m_gt_0)
  151085. && !stem(&z, "itivi", "ive", m_gt_0)
  151086. ){
  151087. stem(&z, "itilib", "ble", m_gt_0);
  151088. }
  151089. break;
  151090. }
  151091. /* Step 3 */
  151092. switch( z[0] ){
  151093. case 'e':
  151094. if( !stem(&z, "etaci", "ic", m_gt_0)
  151095. && !stem(&z, "evita", "", m_gt_0)
  151096. ){
  151097. stem(&z, "ezila", "al", m_gt_0);
  151098. }
  151099. break;
  151100. case 'i':
  151101. stem(&z, "itici", "ic", m_gt_0);
  151102. break;
  151103. case 'l':
  151104. if( !stem(&z, "laci", "ic", m_gt_0) ){
  151105. stem(&z, "luf", "", m_gt_0);
  151106. }
  151107. break;
  151108. case 's':
  151109. stem(&z, "ssen", "", m_gt_0);
  151110. break;
  151111. }
  151112. /* Step 4 */
  151113. switch( z[1] ){
  151114. case 'a':
  151115. if( z[0]=='l' && m_gt_1(z+2) ){
  151116. z += 2;
  151117. }
  151118. break;
  151119. case 'c':
  151120. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  151121. z += 4;
  151122. }
  151123. break;
  151124. case 'e':
  151125. if( z[0]=='r' && m_gt_1(z+2) ){
  151126. z += 2;
  151127. }
  151128. break;
  151129. case 'i':
  151130. if( z[0]=='c' && m_gt_1(z+2) ){
  151131. z += 2;
  151132. }
  151133. break;
  151134. case 'l':
  151135. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  151136. z += 4;
  151137. }
  151138. break;
  151139. case 'n':
  151140. if( z[0]=='t' ){
  151141. if( z[2]=='a' ){
  151142. if( m_gt_1(z+3) ){
  151143. z += 3;
  151144. }
  151145. }else if( z[2]=='e' ){
  151146. if( !stem(&z, "tneme", "", m_gt_1)
  151147. && !stem(&z, "tnem", "", m_gt_1)
  151148. ){
  151149. stem(&z, "tne", "", m_gt_1);
  151150. }
  151151. }
  151152. }
  151153. break;
  151154. case 'o':
  151155. if( z[0]=='u' ){
  151156. if( m_gt_1(z+2) ){
  151157. z += 2;
  151158. }
  151159. }else if( z[3]=='s' || z[3]=='t' ){
  151160. stem(&z, "noi", "", m_gt_1);
  151161. }
  151162. break;
  151163. case 's':
  151164. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  151165. z += 3;
  151166. }
  151167. break;
  151168. case 't':
  151169. if( !stem(&z, "eta", "", m_gt_1) ){
  151170. stem(&z, "iti", "", m_gt_1);
  151171. }
  151172. break;
  151173. case 'u':
  151174. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  151175. z += 3;
  151176. }
  151177. break;
  151178. case 'v':
  151179. case 'z':
  151180. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  151181. z += 3;
  151182. }
  151183. break;
  151184. }
  151185. /* Step 5a */
  151186. if( z[0]=='e' ){
  151187. if( m_gt_1(z+1) ){
  151188. z++;
  151189. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  151190. z++;
  151191. }
  151192. }
  151193. /* Step 5b */
  151194. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  151195. z++;
  151196. }
  151197. /* z[] is now the stemmed word in reverse order. Flip it back
  151198. ** around into forward order and return.
  151199. */
  151200. *pnOut = i = (int)strlen(z);
  151201. zOut[i] = 0;
  151202. while( *z ){
  151203. zOut[--i] = *(z++);
  151204. }
  151205. }
  151206. /*
  151207. ** Characters that can be part of a token. We assume any character
  151208. ** whose value is greater than 0x80 (any UTF character) can be
  151209. ** part of a token. In other words, delimiters all must have
  151210. ** values of 0x7f or lower.
  151211. */
  151212. static const char porterIdChar[] = {
  151213. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  151214. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  151215. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  151216. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  151217. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  151218. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  151219. };
  151220. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  151221. /*
  151222. ** Extract the next token from a tokenization cursor. The cursor must
  151223. ** have been opened by a prior call to porterOpen().
  151224. */
  151225. static int porterNext(
  151226. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  151227. const char **pzToken, /* OUT: *pzToken is the token text */
  151228. int *pnBytes, /* OUT: Number of bytes in token */
  151229. int *piStartOffset, /* OUT: Starting offset of token */
  151230. int *piEndOffset, /* OUT: Ending offset of token */
  151231. int *piPosition /* OUT: Position integer of token */
  151232. ){
  151233. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  151234. const char *z = c->zInput;
  151235. while( c->iOffset<c->nInput ){
  151236. int iStartOffset, ch;
  151237. /* Scan past delimiter characters */
  151238. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  151239. c->iOffset++;
  151240. }
  151241. /* Count non-delimiter characters. */
  151242. iStartOffset = c->iOffset;
  151243. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  151244. c->iOffset++;
  151245. }
  151246. if( c->iOffset>iStartOffset ){
  151247. int n = c->iOffset-iStartOffset;
  151248. if( n>c->nAllocated ){
  151249. char *pNew;
  151250. c->nAllocated = n+20;
  151251. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  151252. if( !pNew ) return SQLITE_NOMEM;
  151253. c->zToken = pNew;
  151254. }
  151255. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  151256. *pzToken = c->zToken;
  151257. *piStartOffset = iStartOffset;
  151258. *piEndOffset = c->iOffset;
  151259. *piPosition = c->iToken++;
  151260. return SQLITE_OK;
  151261. }
  151262. }
  151263. return SQLITE_DONE;
  151264. }
  151265. /*
  151266. ** The set of routines that implement the porter-stemmer tokenizer
  151267. */
  151268. static const sqlite3_tokenizer_module porterTokenizerModule = {
  151269. 0,
  151270. porterCreate,
  151271. porterDestroy,
  151272. porterOpen,
  151273. porterClose,
  151274. porterNext,
  151275. 0
  151276. };
  151277. /*
  151278. ** Allocate a new porter tokenizer. Return a pointer to the new
  151279. ** tokenizer in *ppModule
  151280. */
  151281. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  151282. sqlite3_tokenizer_module const**ppModule
  151283. ){
  151284. *ppModule = &porterTokenizerModule;
  151285. }
  151286. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  151287. /************** End of fts3_porter.c *****************************************/
  151288. /************** Begin file fts3_tokenizer.c **********************************/
  151289. /*
  151290. ** 2007 June 22
  151291. **
  151292. ** The author disclaims copyright to this source code. In place of
  151293. ** a legal notice, here is a blessing:
  151294. **
  151295. ** May you do good and not evil.
  151296. ** May you find forgiveness for yourself and forgive others.
  151297. ** May you share freely, never taking more than you give.
  151298. **
  151299. ******************************************************************************
  151300. **
  151301. ** This is part of an SQLite module implementing full-text search.
  151302. ** This particular file implements the generic tokenizer interface.
  151303. */
  151304. /*
  151305. ** The code in this file is only compiled if:
  151306. **
  151307. ** * The FTS3 module is being built as an extension
  151308. ** (in which case SQLITE_CORE is not defined), or
  151309. **
  151310. ** * The FTS3 module is being built into the core of
  151311. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  151312. */
  151313. /* #include "fts3Int.h" */
  151314. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  151315. /* #include <assert.h> */
  151316. /* #include <string.h> */
  151317. /*
  151318. ** Return true if the two-argument version of fts3_tokenizer()
  151319. ** has been activated via a prior call to sqlite3_db_config(db,
  151320. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  151321. */
  151322. static int fts3TokenizerEnabled(sqlite3_context *context){
  151323. sqlite3 *db = sqlite3_context_db_handle(context);
  151324. int isEnabled = 0;
  151325. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  151326. return isEnabled;
  151327. }
  151328. /*
  151329. ** Implementation of the SQL scalar function for accessing the underlying
  151330. ** hash table. This function may be called as follows:
  151331. **
  151332. ** SELECT <function-name>(<key-name>);
  151333. ** SELECT <function-name>(<key-name>, <pointer>);
  151334. **
  151335. ** where <function-name> is the name passed as the second argument
  151336. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  151337. **
  151338. ** If the <pointer> argument is specified, it must be a blob value
  151339. ** containing a pointer to be stored as the hash data corresponding
  151340. ** to the string <key-name>. If <pointer> is not specified, then
  151341. ** the string <key-name> must already exist in the has table. Otherwise,
  151342. ** an error is returned.
  151343. **
  151344. ** Whether or not the <pointer> argument is specified, the value returned
  151345. ** is a blob containing the pointer stored as the hash data corresponding
  151346. ** to string <key-name> (after the hash-table is updated, if applicable).
  151347. */
  151348. static void fts3TokenizerFunc(
  151349. sqlite3_context *context,
  151350. int argc,
  151351. sqlite3_value **argv
  151352. ){
  151353. Fts3Hash *pHash;
  151354. void *pPtr = 0;
  151355. const unsigned char *zName;
  151356. int nName;
  151357. assert( argc==1 || argc==2 );
  151358. pHash = (Fts3Hash *)sqlite3_user_data(context);
  151359. zName = sqlite3_value_text(argv[0]);
  151360. nName = sqlite3_value_bytes(argv[0])+1;
  151361. if( argc==2 ){
  151362. if( fts3TokenizerEnabled(context) ){
  151363. void *pOld;
  151364. int n = sqlite3_value_bytes(argv[1]);
  151365. if( zName==0 || n!=sizeof(pPtr) ){
  151366. sqlite3_result_error(context, "argument type mismatch", -1);
  151367. return;
  151368. }
  151369. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  151370. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  151371. if( pOld==pPtr ){
  151372. sqlite3_result_error(context, "out of memory", -1);
  151373. }
  151374. }else{
  151375. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  151376. return;
  151377. }
  151378. }else{
  151379. if( zName ){
  151380. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  151381. }
  151382. if( !pPtr ){
  151383. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  151384. sqlite3_result_error(context, zErr, -1);
  151385. sqlite3_free(zErr);
  151386. return;
  151387. }
  151388. }
  151389. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  151390. }
  151391. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  151392. static const char isFtsIdChar[] = {
  151393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  151394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  151395. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  151396. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  151397. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  151398. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  151399. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  151400. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  151401. };
  151402. return (c&0x80 || isFtsIdChar[(int)(c)]);
  151403. }
  151404. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  151405. const char *z1;
  151406. const char *z2 = 0;
  151407. /* Find the start of the next token. */
  151408. z1 = zStr;
  151409. while( z2==0 ){
  151410. char c = *z1;
  151411. switch( c ){
  151412. case '\0': return 0; /* No more tokens here */
  151413. case '\'':
  151414. case '"':
  151415. case '`': {
  151416. z2 = z1;
  151417. while( *++z2 && (*z2!=c || *++z2==c) );
  151418. break;
  151419. }
  151420. case '[':
  151421. z2 = &z1[1];
  151422. while( *z2 && z2[0]!=']' ) z2++;
  151423. if( *z2 ) z2++;
  151424. break;
  151425. default:
  151426. if( sqlite3Fts3IsIdChar(*z1) ){
  151427. z2 = &z1[1];
  151428. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  151429. }else{
  151430. z1++;
  151431. }
  151432. }
  151433. }
  151434. *pn = (int)(z2-z1);
  151435. return z1;
  151436. }
  151437. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  151438. Fts3Hash *pHash, /* Tokenizer hash table */
  151439. const char *zArg, /* Tokenizer name */
  151440. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  151441. char **pzErr /* OUT: Set to malloced error message */
  151442. ){
  151443. int rc;
  151444. char *z = (char *)zArg;
  151445. int n = 0;
  151446. char *zCopy;
  151447. char *zEnd; /* Pointer to nul-term of zCopy */
  151448. sqlite3_tokenizer_module *m;
  151449. zCopy = sqlite3_mprintf("%s", zArg);
  151450. if( !zCopy ) return SQLITE_NOMEM;
  151451. zEnd = &zCopy[strlen(zCopy)];
  151452. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  151453. if( z==0 ){
  151454. assert( n==0 );
  151455. z = zCopy;
  151456. }
  151457. z[n] = '\0';
  151458. sqlite3Fts3Dequote(z);
  151459. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  151460. if( !m ){
  151461. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  151462. rc = SQLITE_ERROR;
  151463. }else{
  151464. char const **aArg = 0;
  151465. int iArg = 0;
  151466. z = &z[n+1];
  151467. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  151468. int nNew = sizeof(char *)*(iArg+1);
  151469. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  151470. if( !aNew ){
  151471. sqlite3_free(zCopy);
  151472. sqlite3_free((void *)aArg);
  151473. return SQLITE_NOMEM;
  151474. }
  151475. aArg = aNew;
  151476. aArg[iArg++] = z;
  151477. z[n] = '\0';
  151478. sqlite3Fts3Dequote(z);
  151479. z = &z[n+1];
  151480. }
  151481. rc = m->xCreate(iArg, aArg, ppTok);
  151482. assert( rc!=SQLITE_OK || *ppTok );
  151483. if( rc!=SQLITE_OK ){
  151484. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  151485. }else{
  151486. (*ppTok)->pModule = m;
  151487. }
  151488. sqlite3_free((void *)aArg);
  151489. }
  151490. sqlite3_free(zCopy);
  151491. return rc;
  151492. }
  151493. #ifdef SQLITE_TEST
  151494. #if defined(INCLUDE_SQLITE_TCL_H)
  151495. # include "sqlite_tcl.h"
  151496. #else
  151497. # include "tcl.h"
  151498. #endif
  151499. /* #include <string.h> */
  151500. /*
  151501. ** Implementation of a special SQL scalar function for testing tokenizers
  151502. ** designed to be used in concert with the Tcl testing framework. This
  151503. ** function must be called with two or more arguments:
  151504. **
  151505. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  151506. **
  151507. ** where <function-name> is the name passed as the second argument
  151508. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  151509. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  151510. **
  151511. ** The return value is a string that may be interpreted as a Tcl
  151512. ** list. For each token in the <input-string>, three elements are
  151513. ** added to the returned list. The first is the token position, the
  151514. ** second is the token text (folded, stemmed, etc.) and the third is the
  151515. ** substring of <input-string> associated with the token. For example,
  151516. ** using the built-in "simple" tokenizer:
  151517. **
  151518. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  151519. **
  151520. ** will return the string:
  151521. **
  151522. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  151523. **
  151524. */
  151525. static void testFunc(
  151526. sqlite3_context *context,
  151527. int argc,
  151528. sqlite3_value **argv
  151529. ){
  151530. Fts3Hash *pHash;
  151531. sqlite3_tokenizer_module *p;
  151532. sqlite3_tokenizer *pTokenizer = 0;
  151533. sqlite3_tokenizer_cursor *pCsr = 0;
  151534. const char *zErr = 0;
  151535. const char *zName;
  151536. int nName;
  151537. const char *zInput;
  151538. int nInput;
  151539. const char *azArg[64];
  151540. const char *zToken;
  151541. int nToken = 0;
  151542. int iStart = 0;
  151543. int iEnd = 0;
  151544. int iPos = 0;
  151545. int i;
  151546. Tcl_Obj *pRet;
  151547. if( argc<2 ){
  151548. sqlite3_result_error(context, "insufficient arguments", -1);
  151549. return;
  151550. }
  151551. nName = sqlite3_value_bytes(argv[0]);
  151552. zName = (const char *)sqlite3_value_text(argv[0]);
  151553. nInput = sqlite3_value_bytes(argv[argc-1]);
  151554. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  151555. pHash = (Fts3Hash *)sqlite3_user_data(context);
  151556. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  151557. if( !p ){
  151558. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  151559. sqlite3_result_error(context, zErr2, -1);
  151560. sqlite3_free(zErr2);
  151561. return;
  151562. }
  151563. pRet = Tcl_NewObj();
  151564. Tcl_IncrRefCount(pRet);
  151565. for(i=1; i<argc-1; i++){
  151566. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  151567. }
  151568. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  151569. zErr = "error in xCreate()";
  151570. goto finish;
  151571. }
  151572. pTokenizer->pModule = p;
  151573. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  151574. zErr = "error in xOpen()";
  151575. goto finish;
  151576. }
  151577. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  151578. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  151579. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  151580. zToken = &zInput[iStart];
  151581. nToken = iEnd-iStart;
  151582. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  151583. }
  151584. if( SQLITE_OK!=p->xClose(pCsr) ){
  151585. zErr = "error in xClose()";
  151586. goto finish;
  151587. }
  151588. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  151589. zErr = "error in xDestroy()";
  151590. goto finish;
  151591. }
  151592. finish:
  151593. if( zErr ){
  151594. sqlite3_result_error(context, zErr, -1);
  151595. }else{
  151596. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  151597. }
  151598. Tcl_DecrRefCount(pRet);
  151599. }
  151600. static
  151601. int registerTokenizer(
  151602. sqlite3 *db,
  151603. char *zName,
  151604. const sqlite3_tokenizer_module *p
  151605. ){
  151606. int rc;
  151607. sqlite3_stmt *pStmt;
  151608. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  151609. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  151610. if( rc!=SQLITE_OK ){
  151611. return rc;
  151612. }
  151613. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  151614. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  151615. sqlite3_step(pStmt);
  151616. return sqlite3_finalize(pStmt);
  151617. }
  151618. static
  151619. int queryTokenizer(
  151620. sqlite3 *db,
  151621. char *zName,
  151622. const sqlite3_tokenizer_module **pp
  151623. ){
  151624. int rc;
  151625. sqlite3_stmt *pStmt;
  151626. const char zSql[] = "SELECT fts3_tokenizer(?)";
  151627. *pp = 0;
  151628. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  151629. if( rc!=SQLITE_OK ){
  151630. return rc;
  151631. }
  151632. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  151633. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  151634. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  151635. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  151636. }
  151637. }
  151638. return sqlite3_finalize(pStmt);
  151639. }
  151640. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  151641. /*
  151642. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  151643. ** This function is used for testing only, it is not included in the
  151644. ** build unless SQLITE_TEST is defined.
  151645. **
  151646. ** The purpose of this is to test that the fts3_tokenizer() function
  151647. ** can be used as designed by the C-code in the queryTokenizer and
  151648. ** registerTokenizer() functions above. These two functions are repeated
  151649. ** in the README.tokenizer file as an example, so it is important to
  151650. ** test them.
  151651. **
  151652. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  151653. ** function with no arguments. An assert() will fail if a problem is
  151654. ** detected. i.e.:
  151655. **
  151656. ** SELECT fts3_tokenizer_internal_test();
  151657. **
  151658. */
  151659. static void intTestFunc(
  151660. sqlite3_context *context,
  151661. int argc,
  151662. sqlite3_value **argv
  151663. ){
  151664. int rc;
  151665. const sqlite3_tokenizer_module *p1;
  151666. const sqlite3_tokenizer_module *p2;
  151667. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  151668. UNUSED_PARAMETER(argc);
  151669. UNUSED_PARAMETER(argv);
  151670. /* Test the query function */
  151671. sqlite3Fts3SimpleTokenizerModule(&p1);
  151672. rc = queryTokenizer(db, "simple", &p2);
  151673. assert( rc==SQLITE_OK );
  151674. assert( p1==p2 );
  151675. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  151676. assert( rc==SQLITE_ERROR );
  151677. assert( p2==0 );
  151678. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  151679. /* Test the storage function */
  151680. if( fts3TokenizerEnabled(context) ){
  151681. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  151682. assert( rc==SQLITE_OK );
  151683. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  151684. assert( rc==SQLITE_OK );
  151685. assert( p2==p1 );
  151686. }
  151687. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  151688. }
  151689. #endif
  151690. /*
  151691. ** Set up SQL objects in database db used to access the contents of
  151692. ** the hash table pointed to by argument pHash. The hash table must
  151693. ** been initialized to use string keys, and to take a private copy
  151694. ** of the key when a value is inserted. i.e. by a call similar to:
  151695. **
  151696. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  151697. **
  151698. ** This function adds a scalar function (see header comment above
  151699. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  151700. ** defined at compilation time, a temporary virtual table (see header
  151701. ** comment above struct HashTableVtab) to the database schema. Both
  151702. ** provide read/write access to the contents of *pHash.
  151703. **
  151704. ** The third argument to this function, zName, is used as the name
  151705. ** of both the scalar and, if created, the virtual table.
  151706. */
  151707. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  151708. sqlite3 *db,
  151709. Fts3Hash *pHash,
  151710. const char *zName
  151711. ){
  151712. int rc = SQLITE_OK;
  151713. void *p = (void *)pHash;
  151714. const int any = SQLITE_ANY;
  151715. #ifdef SQLITE_TEST
  151716. char *zTest = 0;
  151717. char *zTest2 = 0;
  151718. void *pdb = (void *)db;
  151719. zTest = sqlite3_mprintf("%s_test", zName);
  151720. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  151721. if( !zTest || !zTest2 ){
  151722. rc = SQLITE_NOMEM;
  151723. }
  151724. #endif
  151725. if( SQLITE_OK==rc ){
  151726. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  151727. }
  151728. if( SQLITE_OK==rc ){
  151729. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  151730. }
  151731. #ifdef SQLITE_TEST
  151732. if( SQLITE_OK==rc ){
  151733. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  151734. }
  151735. if( SQLITE_OK==rc ){
  151736. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  151737. }
  151738. #endif
  151739. #ifdef SQLITE_TEST
  151740. sqlite3_free(zTest);
  151741. sqlite3_free(zTest2);
  151742. #endif
  151743. return rc;
  151744. }
  151745. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  151746. /************** End of fts3_tokenizer.c **************************************/
  151747. /************** Begin file fts3_tokenizer1.c *********************************/
  151748. /*
  151749. ** 2006 Oct 10
  151750. **
  151751. ** The author disclaims copyright to this source code. In place of
  151752. ** a legal notice, here is a blessing:
  151753. **
  151754. ** May you do good and not evil.
  151755. ** May you find forgiveness for yourself and forgive others.
  151756. ** May you share freely, never taking more than you give.
  151757. **
  151758. ******************************************************************************
  151759. **
  151760. ** Implementation of the "simple" full-text-search tokenizer.
  151761. */
  151762. /*
  151763. ** The code in this file is only compiled if:
  151764. **
  151765. ** * The FTS3 module is being built as an extension
  151766. ** (in which case SQLITE_CORE is not defined), or
  151767. **
  151768. ** * The FTS3 module is being built into the core of
  151769. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  151770. */
  151771. /* #include "fts3Int.h" */
  151772. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  151773. /* #include <assert.h> */
  151774. /* #include <stdlib.h> */
  151775. /* #include <stdio.h> */
  151776. /* #include <string.h> */
  151777. /* #include "fts3_tokenizer.h" */
  151778. typedef struct simple_tokenizer {
  151779. sqlite3_tokenizer base;
  151780. char delim[128]; /* flag ASCII delimiters */
  151781. } simple_tokenizer;
  151782. typedef struct simple_tokenizer_cursor {
  151783. sqlite3_tokenizer_cursor base;
  151784. const char *pInput; /* input we are tokenizing */
  151785. int nBytes; /* size of the input */
  151786. int iOffset; /* current position in pInput */
  151787. int iToken; /* index of next token to be returned */
  151788. char *pToken; /* storage for current token */
  151789. int nTokenAllocated; /* space allocated to zToken buffer */
  151790. } simple_tokenizer_cursor;
  151791. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  151792. return c<0x80 && t->delim[c];
  151793. }
  151794. static int fts3_isalnum(int x){
  151795. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  151796. }
  151797. /*
  151798. ** Create a new tokenizer instance.
  151799. */
  151800. static int simpleCreate(
  151801. int argc, const char * const *argv,
  151802. sqlite3_tokenizer **ppTokenizer
  151803. ){
  151804. simple_tokenizer *t;
  151805. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  151806. if( t==NULL ) return SQLITE_NOMEM;
  151807. memset(t, 0, sizeof(*t));
  151808. /* TODO(shess) Delimiters need to remain the same from run to run,
  151809. ** else we need to reindex. One solution would be a meta-table to
  151810. ** track such information in the database, then we'd only want this
  151811. ** information on the initial create.
  151812. */
  151813. if( argc>1 ){
  151814. int i, n = (int)strlen(argv[1]);
  151815. for(i=0; i<n; i++){
  151816. unsigned char ch = argv[1][i];
  151817. /* We explicitly don't support UTF-8 delimiters for now. */
  151818. if( ch>=0x80 ){
  151819. sqlite3_free(t);
  151820. return SQLITE_ERROR;
  151821. }
  151822. t->delim[ch] = 1;
  151823. }
  151824. } else {
  151825. /* Mark non-alphanumeric ASCII characters as delimiters */
  151826. int i;
  151827. for(i=1; i<0x80; i++){
  151828. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  151829. }
  151830. }
  151831. *ppTokenizer = &t->base;
  151832. return SQLITE_OK;
  151833. }
  151834. /*
  151835. ** Destroy a tokenizer
  151836. */
  151837. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  151838. sqlite3_free(pTokenizer);
  151839. return SQLITE_OK;
  151840. }
  151841. /*
  151842. ** Prepare to begin tokenizing a particular string. The input
  151843. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  151844. ** used to incrementally tokenize this string is returned in
  151845. ** *ppCursor.
  151846. */
  151847. static int simpleOpen(
  151848. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  151849. const char *pInput, int nBytes, /* String to be tokenized */
  151850. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  151851. ){
  151852. simple_tokenizer_cursor *c;
  151853. UNUSED_PARAMETER(pTokenizer);
  151854. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  151855. if( c==NULL ) return SQLITE_NOMEM;
  151856. c->pInput = pInput;
  151857. if( pInput==0 ){
  151858. c->nBytes = 0;
  151859. }else if( nBytes<0 ){
  151860. c->nBytes = (int)strlen(pInput);
  151861. }else{
  151862. c->nBytes = nBytes;
  151863. }
  151864. c->iOffset = 0; /* start tokenizing at the beginning */
  151865. c->iToken = 0;
  151866. c->pToken = NULL; /* no space allocated, yet. */
  151867. c->nTokenAllocated = 0;
  151868. *ppCursor = &c->base;
  151869. return SQLITE_OK;
  151870. }
  151871. /*
  151872. ** Close a tokenization cursor previously opened by a call to
  151873. ** simpleOpen() above.
  151874. */
  151875. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  151876. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  151877. sqlite3_free(c->pToken);
  151878. sqlite3_free(c);
  151879. return SQLITE_OK;
  151880. }
  151881. /*
  151882. ** Extract the next token from a tokenization cursor. The cursor must
  151883. ** have been opened by a prior call to simpleOpen().
  151884. */
  151885. static int simpleNext(
  151886. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  151887. const char **ppToken, /* OUT: *ppToken is the token text */
  151888. int *pnBytes, /* OUT: Number of bytes in token */
  151889. int *piStartOffset, /* OUT: Starting offset of token */
  151890. int *piEndOffset, /* OUT: Ending offset of token */
  151891. int *piPosition /* OUT: Position integer of token */
  151892. ){
  151893. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  151894. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  151895. unsigned char *p = (unsigned char *)c->pInput;
  151896. while( c->iOffset<c->nBytes ){
  151897. int iStartOffset;
  151898. /* Scan past delimiter characters */
  151899. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  151900. c->iOffset++;
  151901. }
  151902. /* Count non-delimiter characters. */
  151903. iStartOffset = c->iOffset;
  151904. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  151905. c->iOffset++;
  151906. }
  151907. if( c->iOffset>iStartOffset ){
  151908. int i, n = c->iOffset-iStartOffset;
  151909. if( n>c->nTokenAllocated ){
  151910. char *pNew;
  151911. c->nTokenAllocated = n+20;
  151912. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  151913. if( !pNew ) return SQLITE_NOMEM;
  151914. c->pToken = pNew;
  151915. }
  151916. for(i=0; i<n; i++){
  151917. /* TODO(shess) This needs expansion to handle UTF-8
  151918. ** case-insensitivity.
  151919. */
  151920. unsigned char ch = p[iStartOffset+i];
  151921. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  151922. }
  151923. *ppToken = c->pToken;
  151924. *pnBytes = n;
  151925. *piStartOffset = iStartOffset;
  151926. *piEndOffset = c->iOffset;
  151927. *piPosition = c->iToken++;
  151928. return SQLITE_OK;
  151929. }
  151930. }
  151931. return SQLITE_DONE;
  151932. }
  151933. /*
  151934. ** The set of routines that implement the simple tokenizer
  151935. */
  151936. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  151937. 0,
  151938. simpleCreate,
  151939. simpleDestroy,
  151940. simpleOpen,
  151941. simpleClose,
  151942. simpleNext,
  151943. 0,
  151944. };
  151945. /*
  151946. ** Allocate a new simple tokenizer. Return a pointer to the new
  151947. ** tokenizer in *ppModule
  151948. */
  151949. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  151950. sqlite3_tokenizer_module const**ppModule
  151951. ){
  151952. *ppModule = &simpleTokenizerModule;
  151953. }
  151954. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  151955. /************** End of fts3_tokenizer1.c *************************************/
  151956. /************** Begin file fts3_tokenize_vtab.c ******************************/
  151957. /*
  151958. ** 2013 Apr 22
  151959. **
  151960. ** The author disclaims copyright to this source code. In place of
  151961. ** a legal notice, here is a blessing:
  151962. **
  151963. ** May you do good and not evil.
  151964. ** May you find forgiveness for yourself and forgive others.
  151965. ** May you share freely, never taking more than you give.
  151966. **
  151967. ******************************************************************************
  151968. **
  151969. ** This file contains code for the "fts3tokenize" virtual table module.
  151970. ** An fts3tokenize virtual table is created as follows:
  151971. **
  151972. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  151973. ** <tokenizer-name>, <arg-1>, ...
  151974. ** );
  151975. **
  151976. ** The table created has the following schema:
  151977. **
  151978. ** CREATE TABLE <tbl>(input, token, start, end, position)
  151979. **
  151980. ** When queried, the query must include a WHERE clause of type:
  151981. **
  151982. ** input = <string>
  151983. **
  151984. ** The virtual table module tokenizes this <string>, using the FTS3
  151985. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  151986. ** statement and returns one row for each token in the result. With
  151987. ** fields set as follows:
  151988. **
  151989. ** input: Always set to a copy of <string>
  151990. ** token: A token from the input.
  151991. ** start: Byte offset of the token within the input <string>.
  151992. ** end: Byte offset of the byte immediately following the end of the
  151993. ** token within the input string.
  151994. ** pos: Token offset of token within input.
  151995. **
  151996. */
  151997. /* #include "fts3Int.h" */
  151998. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  151999. /* #include <string.h> */
  152000. /* #include <assert.h> */
  152001. typedef struct Fts3tokTable Fts3tokTable;
  152002. typedef struct Fts3tokCursor Fts3tokCursor;
  152003. /*
  152004. ** Virtual table structure.
  152005. */
  152006. struct Fts3tokTable {
  152007. sqlite3_vtab base; /* Base class used by SQLite core */
  152008. const sqlite3_tokenizer_module *pMod;
  152009. sqlite3_tokenizer *pTok;
  152010. };
  152011. /*
  152012. ** Virtual table cursor structure.
  152013. */
  152014. struct Fts3tokCursor {
  152015. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  152016. char *zInput; /* Input string */
  152017. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  152018. int iRowid; /* Current 'rowid' value */
  152019. const char *zToken; /* Current 'token' value */
  152020. int nToken; /* Size of zToken in bytes */
  152021. int iStart; /* Current 'start' value */
  152022. int iEnd; /* Current 'end' value */
  152023. int iPos; /* Current 'pos' value */
  152024. };
  152025. /*
  152026. ** Query FTS for the tokenizer implementation named zName.
  152027. */
  152028. static int fts3tokQueryTokenizer(
  152029. Fts3Hash *pHash,
  152030. const char *zName,
  152031. const sqlite3_tokenizer_module **pp,
  152032. char **pzErr
  152033. ){
  152034. sqlite3_tokenizer_module *p;
  152035. int nName = (int)strlen(zName);
  152036. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  152037. if( !p ){
  152038. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  152039. return SQLITE_ERROR;
  152040. }
  152041. *pp = p;
  152042. return SQLITE_OK;
  152043. }
  152044. /*
  152045. ** The second argument, argv[], is an array of pointers to nul-terminated
  152046. ** strings. This function makes a copy of the array and strings into a
  152047. ** single block of memory. It then dequotes any of the strings that appear
  152048. ** to be quoted.
  152049. **
  152050. ** If successful, output parameter *pazDequote is set to point at the
  152051. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  152052. ** responsible for eventually calling sqlite3_free() to free the array
  152053. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  152054. ** The final value of *pazDequote is undefined in this case.
  152055. */
  152056. static int fts3tokDequoteArray(
  152057. int argc, /* Number of elements in argv[] */
  152058. const char * const *argv, /* Input array */
  152059. char ***pazDequote /* Output array */
  152060. ){
  152061. int rc = SQLITE_OK; /* Return code */
  152062. if( argc==0 ){
  152063. *pazDequote = 0;
  152064. }else{
  152065. int i;
  152066. int nByte = 0;
  152067. char **azDequote;
  152068. for(i=0; i<argc; i++){
  152069. nByte += (int)(strlen(argv[i]) + 1);
  152070. }
  152071. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  152072. if( azDequote==0 ){
  152073. rc = SQLITE_NOMEM;
  152074. }else{
  152075. char *pSpace = (char *)&azDequote[argc];
  152076. for(i=0; i<argc; i++){
  152077. int n = (int)strlen(argv[i]);
  152078. azDequote[i] = pSpace;
  152079. memcpy(pSpace, argv[i], n+1);
  152080. sqlite3Fts3Dequote(pSpace);
  152081. pSpace += (n+1);
  152082. }
  152083. }
  152084. }
  152085. return rc;
  152086. }
  152087. /*
  152088. ** Schema of the tokenizer table.
  152089. */
  152090. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  152091. /*
  152092. ** This function does all the work for both the xConnect and xCreate methods.
  152093. ** These tables have no persistent representation of their own, so xConnect
  152094. ** and xCreate are identical operations.
  152095. **
  152096. ** argv[0]: module name
  152097. ** argv[1]: database name
  152098. ** argv[2]: table name
  152099. ** argv[3]: first argument (tokenizer name)
  152100. */
  152101. static int fts3tokConnectMethod(
  152102. sqlite3 *db, /* Database connection */
  152103. void *pHash, /* Hash table of tokenizers */
  152104. int argc, /* Number of elements in argv array */
  152105. const char * const *argv, /* xCreate/xConnect argument array */
  152106. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  152107. char **pzErr /* OUT: sqlite3_malloc'd error message */
  152108. ){
  152109. Fts3tokTable *pTab = 0;
  152110. const sqlite3_tokenizer_module *pMod = 0;
  152111. sqlite3_tokenizer *pTok = 0;
  152112. int rc;
  152113. char **azDequote = 0;
  152114. int nDequote;
  152115. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  152116. if( rc!=SQLITE_OK ) return rc;
  152117. nDequote = argc-3;
  152118. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  152119. if( rc==SQLITE_OK ){
  152120. const char *zModule;
  152121. if( nDequote<1 ){
  152122. zModule = "simple";
  152123. }else{
  152124. zModule = azDequote[0];
  152125. }
  152126. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  152127. }
  152128. assert( (rc==SQLITE_OK)==(pMod!=0) );
  152129. if( rc==SQLITE_OK ){
  152130. const char * const *azArg = (const char * const *)&azDequote[1];
  152131. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  152132. }
  152133. if( rc==SQLITE_OK ){
  152134. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  152135. if( pTab==0 ){
  152136. rc = SQLITE_NOMEM;
  152137. }
  152138. }
  152139. if( rc==SQLITE_OK ){
  152140. memset(pTab, 0, sizeof(Fts3tokTable));
  152141. pTab->pMod = pMod;
  152142. pTab->pTok = pTok;
  152143. *ppVtab = &pTab->base;
  152144. }else{
  152145. if( pTok ){
  152146. pMod->xDestroy(pTok);
  152147. }
  152148. }
  152149. sqlite3_free(azDequote);
  152150. return rc;
  152151. }
  152152. /*
  152153. ** This function does the work for both the xDisconnect and xDestroy methods.
  152154. ** These tables have no persistent representation of their own, so xDisconnect
  152155. ** and xDestroy are identical operations.
  152156. */
  152157. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  152158. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  152159. pTab->pMod->xDestroy(pTab->pTok);
  152160. sqlite3_free(pTab);
  152161. return SQLITE_OK;
  152162. }
  152163. /*
  152164. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  152165. */
  152166. static int fts3tokBestIndexMethod(
  152167. sqlite3_vtab *pVTab,
  152168. sqlite3_index_info *pInfo
  152169. ){
  152170. int i;
  152171. UNUSED_PARAMETER(pVTab);
  152172. for(i=0; i<pInfo->nConstraint; i++){
  152173. if( pInfo->aConstraint[i].usable
  152174. && pInfo->aConstraint[i].iColumn==0
  152175. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  152176. ){
  152177. pInfo->idxNum = 1;
  152178. pInfo->aConstraintUsage[i].argvIndex = 1;
  152179. pInfo->aConstraintUsage[i].omit = 1;
  152180. pInfo->estimatedCost = 1;
  152181. return SQLITE_OK;
  152182. }
  152183. }
  152184. pInfo->idxNum = 0;
  152185. assert( pInfo->estimatedCost>1000000.0 );
  152186. return SQLITE_OK;
  152187. }
  152188. /*
  152189. ** xOpen - Open a cursor.
  152190. */
  152191. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  152192. Fts3tokCursor *pCsr;
  152193. UNUSED_PARAMETER(pVTab);
  152194. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  152195. if( pCsr==0 ){
  152196. return SQLITE_NOMEM;
  152197. }
  152198. memset(pCsr, 0, sizeof(Fts3tokCursor));
  152199. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  152200. return SQLITE_OK;
  152201. }
  152202. /*
  152203. ** Reset the tokenizer cursor passed as the only argument. As if it had
  152204. ** just been returned by fts3tokOpenMethod().
  152205. */
  152206. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  152207. if( pCsr->pCsr ){
  152208. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  152209. pTab->pMod->xClose(pCsr->pCsr);
  152210. pCsr->pCsr = 0;
  152211. }
  152212. sqlite3_free(pCsr->zInput);
  152213. pCsr->zInput = 0;
  152214. pCsr->zToken = 0;
  152215. pCsr->nToken = 0;
  152216. pCsr->iStart = 0;
  152217. pCsr->iEnd = 0;
  152218. pCsr->iPos = 0;
  152219. pCsr->iRowid = 0;
  152220. }
  152221. /*
  152222. ** xClose - Close a cursor.
  152223. */
  152224. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  152225. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  152226. fts3tokResetCursor(pCsr);
  152227. sqlite3_free(pCsr);
  152228. return SQLITE_OK;
  152229. }
  152230. /*
  152231. ** xNext - Advance the cursor to the next row, if any.
  152232. */
  152233. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  152234. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  152235. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  152236. int rc; /* Return code */
  152237. pCsr->iRowid++;
  152238. rc = pTab->pMod->xNext(pCsr->pCsr,
  152239. &pCsr->zToken, &pCsr->nToken,
  152240. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  152241. );
  152242. if( rc!=SQLITE_OK ){
  152243. fts3tokResetCursor(pCsr);
  152244. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  152245. }
  152246. return rc;
  152247. }
  152248. /*
  152249. ** xFilter - Initialize a cursor to point at the start of its data.
  152250. */
  152251. static int fts3tokFilterMethod(
  152252. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  152253. int idxNum, /* Strategy index */
  152254. const char *idxStr, /* Unused */
  152255. int nVal, /* Number of elements in apVal */
  152256. sqlite3_value **apVal /* Arguments for the indexing scheme */
  152257. ){
  152258. int rc = SQLITE_ERROR;
  152259. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  152260. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  152261. UNUSED_PARAMETER(idxStr);
  152262. UNUSED_PARAMETER(nVal);
  152263. fts3tokResetCursor(pCsr);
  152264. if( idxNum==1 ){
  152265. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  152266. int nByte = sqlite3_value_bytes(apVal[0]);
  152267. pCsr->zInput = sqlite3_malloc(nByte+1);
  152268. if( pCsr->zInput==0 ){
  152269. rc = SQLITE_NOMEM;
  152270. }else{
  152271. memcpy(pCsr->zInput, zByte, nByte);
  152272. pCsr->zInput[nByte] = 0;
  152273. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  152274. if( rc==SQLITE_OK ){
  152275. pCsr->pCsr->pTokenizer = pTab->pTok;
  152276. }
  152277. }
  152278. }
  152279. if( rc!=SQLITE_OK ) return rc;
  152280. return fts3tokNextMethod(pCursor);
  152281. }
  152282. /*
  152283. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  152284. */
  152285. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  152286. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  152287. return (pCsr->zToken==0);
  152288. }
  152289. /*
  152290. ** xColumn - Return a column value.
  152291. */
  152292. static int fts3tokColumnMethod(
  152293. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  152294. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  152295. int iCol /* Index of column to read value from */
  152296. ){
  152297. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  152298. /* CREATE TABLE x(input, token, start, end, position) */
  152299. switch( iCol ){
  152300. case 0:
  152301. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  152302. break;
  152303. case 1:
  152304. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  152305. break;
  152306. case 2:
  152307. sqlite3_result_int(pCtx, pCsr->iStart);
  152308. break;
  152309. case 3:
  152310. sqlite3_result_int(pCtx, pCsr->iEnd);
  152311. break;
  152312. default:
  152313. assert( iCol==4 );
  152314. sqlite3_result_int(pCtx, pCsr->iPos);
  152315. break;
  152316. }
  152317. return SQLITE_OK;
  152318. }
  152319. /*
  152320. ** xRowid - Return the current rowid for the cursor.
  152321. */
  152322. static int fts3tokRowidMethod(
  152323. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  152324. sqlite_int64 *pRowid /* OUT: Rowid value */
  152325. ){
  152326. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  152327. *pRowid = (sqlite3_int64)pCsr->iRowid;
  152328. return SQLITE_OK;
  152329. }
  152330. /*
  152331. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  152332. ** if successful or an error code if sqlite3_create_module() fails.
  152333. */
  152334. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  152335. static const sqlite3_module fts3tok_module = {
  152336. 0, /* iVersion */
  152337. fts3tokConnectMethod, /* xCreate */
  152338. fts3tokConnectMethod, /* xConnect */
  152339. fts3tokBestIndexMethod, /* xBestIndex */
  152340. fts3tokDisconnectMethod, /* xDisconnect */
  152341. fts3tokDisconnectMethod, /* xDestroy */
  152342. fts3tokOpenMethod, /* xOpen */
  152343. fts3tokCloseMethod, /* xClose */
  152344. fts3tokFilterMethod, /* xFilter */
  152345. fts3tokNextMethod, /* xNext */
  152346. fts3tokEofMethod, /* xEof */
  152347. fts3tokColumnMethod, /* xColumn */
  152348. fts3tokRowidMethod, /* xRowid */
  152349. 0, /* xUpdate */
  152350. 0, /* xBegin */
  152351. 0, /* xSync */
  152352. 0, /* xCommit */
  152353. 0, /* xRollback */
  152354. 0, /* xFindFunction */
  152355. 0, /* xRename */
  152356. 0, /* xSavepoint */
  152357. 0, /* xRelease */
  152358. 0 /* xRollbackTo */
  152359. };
  152360. int rc; /* Return code */
  152361. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  152362. return rc;
  152363. }
  152364. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  152365. /************** End of fts3_tokenize_vtab.c **********************************/
  152366. /************** Begin file fts3_write.c **************************************/
  152367. /*
  152368. ** 2009 Oct 23
  152369. **
  152370. ** The author disclaims copyright to this source code. In place of
  152371. ** a legal notice, here is a blessing:
  152372. **
  152373. ** May you do good and not evil.
  152374. ** May you find forgiveness for yourself and forgive others.
  152375. ** May you share freely, never taking more than you give.
  152376. **
  152377. ******************************************************************************
  152378. **
  152379. ** This file is part of the SQLite FTS3 extension module. Specifically,
  152380. ** this file contains code to insert, update and delete rows from FTS3
  152381. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  152382. ** of the sub-routines used to merge segments are also used by the query
  152383. ** code in fts3.c.
  152384. */
  152385. /* #include "fts3Int.h" */
  152386. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  152387. /* #include <string.h> */
  152388. /* #include <assert.h> */
  152389. /* #include <stdlib.h> */
  152390. #define FTS_MAX_APPENDABLE_HEIGHT 16
  152391. /*
  152392. ** When full-text index nodes are loaded from disk, the buffer that they
  152393. ** are loaded into has the following number of bytes of padding at the end
  152394. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  152395. ** of 920 bytes is allocated for it.
  152396. **
  152397. ** This means that if we have a pointer into a buffer containing node data,
  152398. ** it is always safe to read up to two varints from it without risking an
  152399. ** overread, even if the node data is corrupted.
  152400. */
  152401. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  152402. /*
  152403. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  152404. ** memory incrementally instead of all at once. This can be a big performance
  152405. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  152406. ** method before retrieving all query results (as may happen, for example,
  152407. ** if a query has a LIMIT clause).
  152408. **
  152409. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  152410. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  152411. ** The code is written so that the hard lower-limit for each of these values
  152412. ** is 1. Clearly such small values would be inefficient, but can be useful
  152413. ** for testing purposes.
  152414. **
  152415. ** If this module is built with SQLITE_TEST defined, these constants may
  152416. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  152417. ** a Tcl interface to read and write the values.
  152418. */
  152419. #ifdef SQLITE_TEST
  152420. int test_fts3_node_chunksize = (4*1024);
  152421. int test_fts3_node_chunk_threshold = (4*1024)*4;
  152422. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  152423. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  152424. #else
  152425. # define FTS3_NODE_CHUNKSIZE (4*1024)
  152426. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  152427. #endif
  152428. /*
  152429. ** The two values that may be meaningfully bound to the :1 parameter in
  152430. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  152431. */
  152432. #define FTS_STAT_DOCTOTAL 0
  152433. #define FTS_STAT_INCRMERGEHINT 1
  152434. #define FTS_STAT_AUTOINCRMERGE 2
  152435. /*
  152436. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  152437. ** and incremental merge operation that takes place. This is used for
  152438. ** debugging FTS only, it should not usually be turned on in production
  152439. ** systems.
  152440. */
  152441. #ifdef FTS3_LOG_MERGES
  152442. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  152443. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  152444. }
  152445. #else
  152446. #define fts3LogMerge(x, y)
  152447. #endif
  152448. typedef struct PendingList PendingList;
  152449. typedef struct SegmentNode SegmentNode;
  152450. typedef struct SegmentWriter SegmentWriter;
  152451. /*
  152452. ** An instance of the following data structure is used to build doclists
  152453. ** incrementally. See function fts3PendingListAppend() for details.
  152454. */
  152455. struct PendingList {
  152456. int nData;
  152457. char *aData;
  152458. int nSpace;
  152459. sqlite3_int64 iLastDocid;
  152460. sqlite3_int64 iLastCol;
  152461. sqlite3_int64 iLastPos;
  152462. };
  152463. /*
  152464. ** Each cursor has a (possibly empty) linked list of the following objects.
  152465. */
  152466. struct Fts3DeferredToken {
  152467. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  152468. int iCol; /* Column token must occur in */
  152469. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  152470. PendingList *pList; /* Doclist is assembled here */
  152471. };
  152472. /*
  152473. ** An instance of this structure is used to iterate through the terms on
  152474. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  152475. ** this structure are only manipulated by code in this file, opaque handles
  152476. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  152477. ** terms when querying the full-text index. See functions:
  152478. **
  152479. ** sqlite3Fts3SegReaderNew()
  152480. ** sqlite3Fts3SegReaderFree()
  152481. ** sqlite3Fts3SegReaderIterate()
  152482. **
  152483. ** Methods used to manipulate Fts3SegReader structures:
  152484. **
  152485. ** fts3SegReaderNext()
  152486. ** fts3SegReaderFirstDocid()
  152487. ** fts3SegReaderNextDocid()
  152488. */
  152489. struct Fts3SegReader {
  152490. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  152491. u8 bLookup; /* True for a lookup only */
  152492. u8 rootOnly; /* True for a root-only reader */
  152493. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  152494. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  152495. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  152496. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  152497. char *aNode; /* Pointer to node data (or NULL) */
  152498. int nNode; /* Size of buffer at aNode (or 0) */
  152499. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  152500. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  152501. Fts3HashElem **ppNextElem;
  152502. /* Variables set by fts3SegReaderNext(). These may be read directly
  152503. ** by the caller. They are valid from the time SegmentReaderNew() returns
  152504. ** until SegmentReaderNext() returns something other than SQLITE_OK
  152505. ** (i.e. SQLITE_DONE).
  152506. */
  152507. int nTerm; /* Number of bytes in current term */
  152508. char *zTerm; /* Pointer to current term */
  152509. int nTermAlloc; /* Allocated size of zTerm buffer */
  152510. char *aDoclist; /* Pointer to doclist of current entry */
  152511. int nDoclist; /* Size of doclist in current entry */
  152512. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  152513. ** through the current doclist (aDoclist/nDoclist).
  152514. */
  152515. char *pOffsetList;
  152516. int nOffsetList; /* For descending pending seg-readers only */
  152517. sqlite3_int64 iDocid;
  152518. };
  152519. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  152520. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  152521. /*
  152522. ** An instance of this structure is used to create a segment b-tree in the
  152523. ** database. The internal details of this type are only accessed by the
  152524. ** following functions:
  152525. **
  152526. ** fts3SegWriterAdd()
  152527. ** fts3SegWriterFlush()
  152528. ** fts3SegWriterFree()
  152529. */
  152530. struct SegmentWriter {
  152531. SegmentNode *pTree; /* Pointer to interior tree structure */
  152532. sqlite3_int64 iFirst; /* First slot in %_segments written */
  152533. sqlite3_int64 iFree; /* Next free slot in %_segments */
  152534. char *zTerm; /* Pointer to previous term buffer */
  152535. int nTerm; /* Number of bytes in zTerm */
  152536. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  152537. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  152538. int nSize; /* Size of allocation at aData */
  152539. int nData; /* Bytes of data in aData */
  152540. char *aData; /* Pointer to block from malloc() */
  152541. i64 nLeafData; /* Number of bytes of leaf data written */
  152542. };
  152543. /*
  152544. ** Type SegmentNode is used by the following three functions to create
  152545. ** the interior part of the segment b+-tree structures (everything except
  152546. ** the leaf nodes). These functions and type are only ever used by code
  152547. ** within the fts3SegWriterXXX() family of functions described above.
  152548. **
  152549. ** fts3NodeAddTerm()
  152550. ** fts3NodeWrite()
  152551. ** fts3NodeFree()
  152552. **
  152553. ** When a b+tree is written to the database (either as a result of a merge
  152554. ** or the pending-terms table being flushed), leaves are written into the
  152555. ** database file as soon as they are completely populated. The interior of
  152556. ** the tree is assembled in memory and written out only once all leaves have
  152557. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  152558. ** very large, meaning that the interior of the tree consumes relatively
  152559. ** little memory.
  152560. */
  152561. struct SegmentNode {
  152562. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  152563. SegmentNode *pRight; /* Pointer to right-sibling */
  152564. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  152565. int nEntry; /* Number of terms written to node so far */
  152566. char *zTerm; /* Pointer to previous term buffer */
  152567. int nTerm; /* Number of bytes in zTerm */
  152568. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  152569. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  152570. int nData; /* Bytes of valid data so far */
  152571. char *aData; /* Node data */
  152572. };
  152573. /*
  152574. ** Valid values for the second argument to fts3SqlStmt().
  152575. */
  152576. #define SQL_DELETE_CONTENT 0
  152577. #define SQL_IS_EMPTY 1
  152578. #define SQL_DELETE_ALL_CONTENT 2
  152579. #define SQL_DELETE_ALL_SEGMENTS 3
  152580. #define SQL_DELETE_ALL_SEGDIR 4
  152581. #define SQL_DELETE_ALL_DOCSIZE 5
  152582. #define SQL_DELETE_ALL_STAT 6
  152583. #define SQL_SELECT_CONTENT_BY_ROWID 7
  152584. #define SQL_NEXT_SEGMENT_INDEX 8
  152585. #define SQL_INSERT_SEGMENTS 9
  152586. #define SQL_NEXT_SEGMENTS_ID 10
  152587. #define SQL_INSERT_SEGDIR 11
  152588. #define SQL_SELECT_LEVEL 12
  152589. #define SQL_SELECT_LEVEL_RANGE 13
  152590. #define SQL_SELECT_LEVEL_COUNT 14
  152591. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  152592. #define SQL_DELETE_SEGDIR_LEVEL 16
  152593. #define SQL_DELETE_SEGMENTS_RANGE 17
  152594. #define SQL_CONTENT_INSERT 18
  152595. #define SQL_DELETE_DOCSIZE 19
  152596. #define SQL_REPLACE_DOCSIZE 20
  152597. #define SQL_SELECT_DOCSIZE 21
  152598. #define SQL_SELECT_STAT 22
  152599. #define SQL_REPLACE_STAT 23
  152600. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  152601. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  152602. #define SQL_DELETE_SEGDIR_RANGE 26
  152603. #define SQL_SELECT_ALL_LANGID 27
  152604. #define SQL_FIND_MERGE_LEVEL 28
  152605. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  152606. #define SQL_DELETE_SEGDIR_ENTRY 30
  152607. #define SQL_SHIFT_SEGDIR_ENTRY 31
  152608. #define SQL_SELECT_SEGDIR 32
  152609. #define SQL_CHOMP_SEGDIR 33
  152610. #define SQL_SEGMENT_IS_APPENDABLE 34
  152611. #define SQL_SELECT_INDEXES 35
  152612. #define SQL_SELECT_MXLEVEL 36
  152613. #define SQL_SELECT_LEVEL_RANGE2 37
  152614. #define SQL_UPDATE_LEVEL_IDX 38
  152615. #define SQL_UPDATE_LEVEL 39
  152616. /*
  152617. ** This function is used to obtain an SQLite prepared statement handle
  152618. ** for the statement identified by the second argument. If successful,
  152619. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  152620. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  152621. **
  152622. ** If argument apVal is not NULL, then it must point to an array with
  152623. ** at least as many entries as the requested statement has bound
  152624. ** parameters. The values are bound to the statements parameters before
  152625. ** returning.
  152626. */
  152627. static int fts3SqlStmt(
  152628. Fts3Table *p, /* Virtual table handle */
  152629. int eStmt, /* One of the SQL_XXX constants above */
  152630. sqlite3_stmt **pp, /* OUT: Statement handle */
  152631. sqlite3_value **apVal /* Values to bind to statement */
  152632. ){
  152633. const char *azSql[] = {
  152634. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  152635. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  152636. /* 2 */ "DELETE FROM %Q.'%q_content'",
  152637. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  152638. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  152639. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  152640. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  152641. /* 7 */ "SELECT %s WHERE rowid=?",
  152642. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  152643. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  152644. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  152645. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  152646. /* Return segments in order from oldest to newest.*/
  152647. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  152648. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  152649. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  152650. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  152651. "ORDER BY level DESC, idx ASC",
  152652. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  152653. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  152654. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  152655. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  152656. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  152657. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  152658. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  152659. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  152660. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  152661. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  152662. /* 24 */ "",
  152663. /* 25 */ "",
  152664. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  152665. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  152666. /* This statement is used to determine which level to read the input from
  152667. ** when performing an incremental merge. It returns the absolute level number
  152668. ** of the oldest level in the db that contains at least ? segments. Or,
  152669. ** if no level in the FTS index contains more than ? segments, the statement
  152670. ** returns zero rows. */
  152671. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  152672. " GROUP BY level HAVING cnt>=?"
  152673. " ORDER BY (level %% 1024) ASC LIMIT 1",
  152674. /* Estimate the upper limit on the number of leaf nodes in a new segment
  152675. ** created by merging the oldest :2 segments from absolute level :1. See
  152676. ** function sqlite3Fts3Incrmerge() for details. */
  152677. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  152678. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  152679. /* SQL_DELETE_SEGDIR_ENTRY
  152680. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  152681. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  152682. /* SQL_SHIFT_SEGDIR_ENTRY
  152683. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  152684. ** to :1. */
  152685. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  152686. /* SQL_SELECT_SEGDIR
  152687. ** Read a single entry from the %_segdir table. The entry from absolute
  152688. ** level :1 with index value :2. */
  152689. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  152690. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  152691. /* SQL_CHOMP_SEGDIR
  152692. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  152693. ** entry located on absolute level :3 with index :4. */
  152694. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  152695. "WHERE level = ? AND idx = ?",
  152696. /* SQL_SEGMENT_IS_APPENDABLE
  152697. ** Return a single row if the segment with end_block=? is appendable. Or
  152698. ** no rows otherwise. */
  152699. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  152700. /* SQL_SELECT_INDEXES
  152701. ** Return the list of valid segment indexes for absolute level ? */
  152702. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  152703. /* SQL_SELECT_MXLEVEL
  152704. ** Return the largest relative level in the FTS index or indexes. */
  152705. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  152706. /* Return segments in order from oldest to newest.*/
  152707. /* 37 */ "SELECT level, idx, end_block "
  152708. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  152709. "ORDER BY level DESC, idx ASC",
  152710. /* Update statements used while promoting segments */
  152711. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  152712. "WHERE level=? AND idx=?",
  152713. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  152714. };
  152715. int rc = SQLITE_OK;
  152716. sqlite3_stmt *pStmt;
  152717. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  152718. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  152719. pStmt = p->aStmt[eStmt];
  152720. if( !pStmt ){
  152721. char *zSql;
  152722. if( eStmt==SQL_CONTENT_INSERT ){
  152723. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  152724. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  152725. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  152726. }else{
  152727. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  152728. }
  152729. if( !zSql ){
  152730. rc = SQLITE_NOMEM;
  152731. }else{
  152732. rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  152733. &pStmt, NULL);
  152734. sqlite3_free(zSql);
  152735. assert( rc==SQLITE_OK || pStmt==0 );
  152736. p->aStmt[eStmt] = pStmt;
  152737. }
  152738. }
  152739. if( apVal ){
  152740. int i;
  152741. int nParam = sqlite3_bind_parameter_count(pStmt);
  152742. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  152743. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  152744. }
  152745. }
  152746. *pp = pStmt;
  152747. return rc;
  152748. }
  152749. static int fts3SelectDocsize(
  152750. Fts3Table *pTab, /* FTS3 table handle */
  152751. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  152752. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  152753. ){
  152754. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  152755. int rc; /* Return code */
  152756. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  152757. if( rc==SQLITE_OK ){
  152758. sqlite3_bind_int64(pStmt, 1, iDocid);
  152759. rc = sqlite3_step(pStmt);
  152760. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  152761. rc = sqlite3_reset(pStmt);
  152762. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  152763. pStmt = 0;
  152764. }else{
  152765. rc = SQLITE_OK;
  152766. }
  152767. }
  152768. *ppStmt = pStmt;
  152769. return rc;
  152770. }
  152771. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  152772. Fts3Table *pTab, /* Fts3 table handle */
  152773. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  152774. ){
  152775. sqlite3_stmt *pStmt = 0;
  152776. int rc;
  152777. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  152778. if( rc==SQLITE_OK ){
  152779. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  152780. if( sqlite3_step(pStmt)!=SQLITE_ROW
  152781. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  152782. ){
  152783. rc = sqlite3_reset(pStmt);
  152784. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  152785. pStmt = 0;
  152786. }
  152787. }
  152788. *ppStmt = pStmt;
  152789. return rc;
  152790. }
  152791. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  152792. Fts3Table *pTab, /* Fts3 table handle */
  152793. sqlite3_int64 iDocid, /* Docid to read size data for */
  152794. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  152795. ){
  152796. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  152797. }
  152798. /*
  152799. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  152800. ** array apVal[] to the SQL statement identified by eStmt, the statement
  152801. ** is executed.
  152802. **
  152803. ** Returns SQLITE_OK if the statement is successfully executed, or an
  152804. ** SQLite error code otherwise.
  152805. */
  152806. static void fts3SqlExec(
  152807. int *pRC, /* Result code */
  152808. Fts3Table *p, /* The FTS3 table */
  152809. int eStmt, /* Index of statement to evaluate */
  152810. sqlite3_value **apVal /* Parameters to bind */
  152811. ){
  152812. sqlite3_stmt *pStmt;
  152813. int rc;
  152814. if( *pRC ) return;
  152815. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  152816. if( rc==SQLITE_OK ){
  152817. sqlite3_step(pStmt);
  152818. rc = sqlite3_reset(pStmt);
  152819. }
  152820. *pRC = rc;
  152821. }
  152822. /*
  152823. ** This function ensures that the caller has obtained an exclusive
  152824. ** shared-cache table-lock on the %_segdir table. This is required before
  152825. ** writing data to the fts3 table. If this lock is not acquired first, then
  152826. ** the caller may end up attempting to take this lock as part of committing
  152827. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  152828. ** LOCKED_SHAREDCACHEto a COMMIT command.
  152829. **
  152830. ** It is best to avoid this because if FTS3 returns any error when
  152831. ** committing a transaction, the whole transaction will be rolled back.
  152832. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  152833. ** It can still happen if the user locks the underlying tables directly
  152834. ** instead of accessing them via FTS.
  152835. */
  152836. static int fts3Writelock(Fts3Table *p){
  152837. int rc = SQLITE_OK;
  152838. if( p->nPendingData==0 ){
  152839. sqlite3_stmt *pStmt;
  152840. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  152841. if( rc==SQLITE_OK ){
  152842. sqlite3_bind_null(pStmt, 1);
  152843. sqlite3_step(pStmt);
  152844. rc = sqlite3_reset(pStmt);
  152845. }
  152846. }
  152847. return rc;
  152848. }
  152849. /*
  152850. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  152851. ** Within each language id, a separate index is maintained to store the
  152852. ** document terms, and each configured prefix size (configured the FTS
  152853. ** "prefix=" option). And each index consists of multiple levels ("relative
  152854. ** levels").
  152855. **
  152856. ** All three of these values (the language id, the specific index and the
  152857. ** level within the index) are encoded in 64-bit integer values stored
  152858. ** in the %_segdir table on disk. This function is used to convert three
  152859. ** separate component values into the single 64-bit integer value that
  152860. ** can be used to query the %_segdir table.
  152861. **
  152862. ** Specifically, each language-id/index combination is allocated 1024
  152863. ** 64-bit integer level values ("absolute levels"). The main terms index
  152864. ** for language-id 0 is allocate values 0-1023. The first prefix index
  152865. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  152866. ** Language 1 indexes are allocated immediately following language 0.
  152867. **
  152868. ** So, for a system with nPrefix prefix indexes configured, the block of
  152869. ** absolute levels that corresponds to language-id iLangid and index
  152870. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  152871. */
  152872. static sqlite3_int64 getAbsoluteLevel(
  152873. Fts3Table *p, /* FTS3 table handle */
  152874. int iLangid, /* Language id */
  152875. int iIndex, /* Index in p->aIndex[] */
  152876. int iLevel /* Level of segments */
  152877. ){
  152878. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  152879. assert( iLangid>=0 );
  152880. assert( p->nIndex>0 );
  152881. assert( iIndex>=0 && iIndex<p->nIndex );
  152882. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  152883. return iBase + iLevel;
  152884. }
  152885. /*
  152886. ** Set *ppStmt to a statement handle that may be used to iterate through
  152887. ** all rows in the %_segdir table, from oldest to newest. If successful,
  152888. ** return SQLITE_OK. If an error occurs while preparing the statement,
  152889. ** return an SQLite error code.
  152890. **
  152891. ** There is only ever one instance of this SQL statement compiled for
  152892. ** each FTS3 table.
  152893. **
  152894. ** The statement returns the following columns from the %_segdir table:
  152895. **
  152896. ** 0: idx
  152897. ** 1: start_block
  152898. ** 2: leaves_end_block
  152899. ** 3: end_block
  152900. ** 4: root
  152901. */
  152902. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  152903. Fts3Table *p, /* FTS3 table */
  152904. int iLangid, /* Language being queried */
  152905. int iIndex, /* Index for p->aIndex[] */
  152906. int iLevel, /* Level to select (relative level) */
  152907. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  152908. ){
  152909. int rc;
  152910. sqlite3_stmt *pStmt = 0;
  152911. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  152912. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  152913. assert( iIndex>=0 && iIndex<p->nIndex );
  152914. if( iLevel<0 ){
  152915. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  152916. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  152917. if( rc==SQLITE_OK ){
  152918. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  152919. sqlite3_bind_int64(pStmt, 2,
  152920. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  152921. );
  152922. }
  152923. }else{
  152924. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  152925. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  152926. if( rc==SQLITE_OK ){
  152927. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  152928. }
  152929. }
  152930. *ppStmt = pStmt;
  152931. return rc;
  152932. }
  152933. /*
  152934. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  152935. ** if successful, or an SQLite error code otherwise.
  152936. **
  152937. ** This function also serves to allocate the PendingList structure itself.
  152938. ** For example, to create a new PendingList structure containing two
  152939. ** varints:
  152940. **
  152941. ** PendingList *p = 0;
  152942. ** fts3PendingListAppendVarint(&p, 1);
  152943. ** fts3PendingListAppendVarint(&p, 2);
  152944. */
  152945. static int fts3PendingListAppendVarint(
  152946. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  152947. sqlite3_int64 i /* Value to append to data */
  152948. ){
  152949. PendingList *p = *pp;
  152950. /* Allocate or grow the PendingList as required. */
  152951. if( !p ){
  152952. p = sqlite3_malloc(sizeof(*p) + 100);
  152953. if( !p ){
  152954. return SQLITE_NOMEM;
  152955. }
  152956. p->nSpace = 100;
  152957. p->aData = (char *)&p[1];
  152958. p->nData = 0;
  152959. }
  152960. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  152961. int nNew = p->nSpace * 2;
  152962. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  152963. if( !p ){
  152964. sqlite3_free(*pp);
  152965. *pp = 0;
  152966. return SQLITE_NOMEM;
  152967. }
  152968. p->nSpace = nNew;
  152969. p->aData = (char *)&p[1];
  152970. }
  152971. /* Append the new serialized varint to the end of the list. */
  152972. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  152973. p->aData[p->nData] = '\0';
  152974. *pp = p;
  152975. return SQLITE_OK;
  152976. }
  152977. /*
  152978. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  152979. ** is returned if the structure is sqlite3_realloced as part of adding
  152980. ** the entry. Otherwise, zero.
  152981. **
  152982. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  152983. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  152984. ** it is set to SQLITE_OK.
  152985. */
  152986. static int fts3PendingListAppend(
  152987. PendingList **pp, /* IN/OUT: PendingList structure */
  152988. sqlite3_int64 iDocid, /* Docid for entry to add */
  152989. sqlite3_int64 iCol, /* Column for entry to add */
  152990. sqlite3_int64 iPos, /* Position of term for entry to add */
  152991. int *pRc /* OUT: Return code */
  152992. ){
  152993. PendingList *p = *pp;
  152994. int rc = SQLITE_OK;
  152995. assert( !p || p->iLastDocid<=iDocid );
  152996. if( !p || p->iLastDocid!=iDocid ){
  152997. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  152998. if( p ){
  152999. assert( p->nData<p->nSpace );
  153000. assert( p->aData[p->nData]==0 );
  153001. p->nData++;
  153002. }
  153003. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  153004. goto pendinglistappend_out;
  153005. }
  153006. p->iLastCol = -1;
  153007. p->iLastPos = 0;
  153008. p->iLastDocid = iDocid;
  153009. }
  153010. if( iCol>0 && p->iLastCol!=iCol ){
  153011. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  153012. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  153013. ){
  153014. goto pendinglistappend_out;
  153015. }
  153016. p->iLastCol = iCol;
  153017. p->iLastPos = 0;
  153018. }
  153019. if( iCol>=0 ){
  153020. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  153021. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  153022. if( rc==SQLITE_OK ){
  153023. p->iLastPos = iPos;
  153024. }
  153025. }
  153026. pendinglistappend_out:
  153027. *pRc = rc;
  153028. if( p!=*pp ){
  153029. *pp = p;
  153030. return 1;
  153031. }
  153032. return 0;
  153033. }
  153034. /*
  153035. ** Free a PendingList object allocated by fts3PendingListAppend().
  153036. */
  153037. static void fts3PendingListDelete(PendingList *pList){
  153038. sqlite3_free(pList);
  153039. }
  153040. /*
  153041. ** Add an entry to one of the pending-terms hash tables.
  153042. */
  153043. static int fts3PendingTermsAddOne(
  153044. Fts3Table *p,
  153045. int iCol,
  153046. int iPos,
  153047. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  153048. const char *zToken,
  153049. int nToken
  153050. ){
  153051. PendingList *pList;
  153052. int rc = SQLITE_OK;
  153053. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  153054. if( pList ){
  153055. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  153056. }
  153057. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  153058. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  153059. /* Malloc failed while inserting the new entry. This can only
  153060. ** happen if there was no previous entry for this token.
  153061. */
  153062. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  153063. sqlite3_free(pList);
  153064. rc = SQLITE_NOMEM;
  153065. }
  153066. }
  153067. if( rc==SQLITE_OK ){
  153068. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  153069. }
  153070. return rc;
  153071. }
  153072. /*
  153073. ** Tokenize the nul-terminated string zText and add all tokens to the
  153074. ** pending-terms hash-table. The docid used is that currently stored in
  153075. ** p->iPrevDocid, and the column is specified by argument iCol.
  153076. **
  153077. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  153078. */
  153079. static int fts3PendingTermsAdd(
  153080. Fts3Table *p, /* Table into which text will be inserted */
  153081. int iLangid, /* Language id to use */
  153082. const char *zText, /* Text of document to be inserted */
  153083. int iCol, /* Column into which text is being inserted */
  153084. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  153085. ){
  153086. int rc;
  153087. int iStart = 0;
  153088. int iEnd = 0;
  153089. int iPos = 0;
  153090. int nWord = 0;
  153091. char const *zToken;
  153092. int nToken = 0;
  153093. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  153094. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  153095. sqlite3_tokenizer_cursor *pCsr;
  153096. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  153097. const char**,int*,int*,int*,int*);
  153098. assert( pTokenizer && pModule );
  153099. /* If the user has inserted a NULL value, this function may be called with
  153100. ** zText==0. In this case, add zero token entries to the hash table and
  153101. ** return early. */
  153102. if( zText==0 ){
  153103. *pnWord = 0;
  153104. return SQLITE_OK;
  153105. }
  153106. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  153107. if( rc!=SQLITE_OK ){
  153108. return rc;
  153109. }
  153110. xNext = pModule->xNext;
  153111. while( SQLITE_OK==rc
  153112. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  153113. ){
  153114. int i;
  153115. if( iPos>=nWord ) nWord = iPos+1;
  153116. /* Positions cannot be negative; we use -1 as a terminator internally.
  153117. ** Tokens must have a non-zero length.
  153118. */
  153119. if( iPos<0 || !zToken || nToken<=0 ){
  153120. rc = SQLITE_ERROR;
  153121. break;
  153122. }
  153123. /* Add the term to the terms index */
  153124. rc = fts3PendingTermsAddOne(
  153125. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  153126. );
  153127. /* Add the term to each of the prefix indexes that it is not too
  153128. ** short for. */
  153129. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  153130. struct Fts3Index *pIndex = &p->aIndex[i];
  153131. if( nToken<pIndex->nPrefix ) continue;
  153132. rc = fts3PendingTermsAddOne(
  153133. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  153134. );
  153135. }
  153136. }
  153137. pModule->xClose(pCsr);
  153138. *pnWord += nWord;
  153139. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  153140. }
  153141. /*
  153142. ** Calling this function indicates that subsequent calls to
  153143. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  153144. ** contents of the document with docid iDocid.
  153145. */
  153146. static int fts3PendingTermsDocid(
  153147. Fts3Table *p, /* Full-text table handle */
  153148. int bDelete, /* True if this op is a delete */
  153149. int iLangid, /* Language id of row being written */
  153150. sqlite_int64 iDocid /* Docid of row being written */
  153151. ){
  153152. assert( iLangid>=0 );
  153153. assert( bDelete==1 || bDelete==0 );
  153154. /* TODO(shess) Explore whether partially flushing the buffer on
  153155. ** forced-flush would provide better performance. I suspect that if
  153156. ** we ordered the doclists by size and flushed the largest until the
  153157. ** buffer was half empty, that would let the less frequent terms
  153158. ** generate longer doclists.
  153159. */
  153160. if( iDocid<p->iPrevDocid
  153161. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  153162. || p->iPrevLangid!=iLangid
  153163. || p->nPendingData>p->nMaxPendingData
  153164. ){
  153165. int rc = sqlite3Fts3PendingTermsFlush(p);
  153166. if( rc!=SQLITE_OK ) return rc;
  153167. }
  153168. p->iPrevDocid = iDocid;
  153169. p->iPrevLangid = iLangid;
  153170. p->bPrevDelete = bDelete;
  153171. return SQLITE_OK;
  153172. }
  153173. /*
  153174. ** Discard the contents of the pending-terms hash tables.
  153175. */
  153176. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  153177. int i;
  153178. for(i=0; i<p->nIndex; i++){
  153179. Fts3HashElem *pElem;
  153180. Fts3Hash *pHash = &p->aIndex[i].hPending;
  153181. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  153182. PendingList *pList = (PendingList *)fts3HashData(pElem);
  153183. fts3PendingListDelete(pList);
  153184. }
  153185. fts3HashClear(pHash);
  153186. }
  153187. p->nPendingData = 0;
  153188. }
  153189. /*
  153190. ** This function is called by the xUpdate() method as part of an INSERT
  153191. ** operation. It adds entries for each term in the new record to the
  153192. ** pendingTerms hash table.
  153193. **
  153194. ** Argument apVal is the same as the similarly named argument passed to
  153195. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  153196. */
  153197. static int fts3InsertTerms(
  153198. Fts3Table *p,
  153199. int iLangid,
  153200. sqlite3_value **apVal,
  153201. u32 *aSz
  153202. ){
  153203. int i; /* Iterator variable */
  153204. for(i=2; i<p->nColumn+2; i++){
  153205. int iCol = i-2;
  153206. if( p->abNotindexed[iCol]==0 ){
  153207. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  153208. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  153209. if( rc!=SQLITE_OK ){
  153210. return rc;
  153211. }
  153212. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  153213. }
  153214. }
  153215. return SQLITE_OK;
  153216. }
  153217. /*
  153218. ** This function is called by the xUpdate() method for an INSERT operation.
  153219. ** The apVal parameter is passed a copy of the apVal argument passed by
  153220. ** SQLite to the xUpdate() method. i.e:
  153221. **
  153222. ** apVal[0] Not used for INSERT.
  153223. ** apVal[1] rowid
  153224. ** apVal[2] Left-most user-defined column
  153225. ** ...
  153226. ** apVal[p->nColumn+1] Right-most user-defined column
  153227. ** apVal[p->nColumn+2] Hidden column with same name as table
  153228. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  153229. ** apVal[p->nColumn+4] Hidden languageid column
  153230. */
  153231. static int fts3InsertData(
  153232. Fts3Table *p, /* Full-text table */
  153233. sqlite3_value **apVal, /* Array of values to insert */
  153234. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  153235. ){
  153236. int rc; /* Return code */
  153237. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  153238. if( p->zContentTbl ){
  153239. sqlite3_value *pRowid = apVal[p->nColumn+3];
  153240. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  153241. pRowid = apVal[1];
  153242. }
  153243. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  153244. return SQLITE_CONSTRAINT;
  153245. }
  153246. *piDocid = sqlite3_value_int64(pRowid);
  153247. return SQLITE_OK;
  153248. }
  153249. /* Locate the statement handle used to insert data into the %_content
  153250. ** table. The SQL for this statement is:
  153251. **
  153252. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  153253. **
  153254. ** The statement features N '?' variables, where N is the number of user
  153255. ** defined columns in the FTS3 table, plus one for the docid field.
  153256. */
  153257. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  153258. if( rc==SQLITE_OK && p->zLanguageid ){
  153259. rc = sqlite3_bind_int(
  153260. pContentInsert, p->nColumn+2,
  153261. sqlite3_value_int(apVal[p->nColumn+4])
  153262. );
  153263. }
  153264. if( rc!=SQLITE_OK ) return rc;
  153265. /* There is a quirk here. The users INSERT statement may have specified
  153266. ** a value for the "rowid" field, for the "docid" field, or for both.
  153267. ** Which is a problem, since "rowid" and "docid" are aliases for the
  153268. ** same value. For example:
  153269. **
  153270. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  153271. **
  153272. ** In FTS3, this is an error. It is an error to specify non-NULL values
  153273. ** for both docid and some other rowid alias.
  153274. */
  153275. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  153276. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  153277. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  153278. ){
  153279. /* A rowid/docid conflict. */
  153280. return SQLITE_ERROR;
  153281. }
  153282. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  153283. if( rc!=SQLITE_OK ) return rc;
  153284. }
  153285. /* Execute the statement to insert the record. Set *piDocid to the
  153286. ** new docid value.
  153287. */
  153288. sqlite3_step(pContentInsert);
  153289. rc = sqlite3_reset(pContentInsert);
  153290. *piDocid = sqlite3_last_insert_rowid(p->db);
  153291. return rc;
  153292. }
  153293. /*
  153294. ** Remove all data from the FTS3 table. Clear the hash table containing
  153295. ** pending terms.
  153296. */
  153297. static int fts3DeleteAll(Fts3Table *p, int bContent){
  153298. int rc = SQLITE_OK; /* Return code */
  153299. /* Discard the contents of the pending-terms hash table. */
  153300. sqlite3Fts3PendingTermsClear(p);
  153301. /* Delete everything from the shadow tables. Except, leave %_content as
  153302. ** is if bContent is false. */
  153303. assert( p->zContentTbl==0 || bContent==0 );
  153304. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  153305. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  153306. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  153307. if( p->bHasDocsize ){
  153308. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  153309. }
  153310. if( p->bHasStat ){
  153311. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  153312. }
  153313. return rc;
  153314. }
  153315. /*
  153316. **
  153317. */
  153318. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  153319. int iLangid = 0;
  153320. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  153321. return iLangid;
  153322. }
  153323. /*
  153324. ** The first element in the apVal[] array is assumed to contain the docid
  153325. ** (an integer) of a row about to be deleted. Remove all terms from the
  153326. ** full-text index.
  153327. */
  153328. static void fts3DeleteTerms(
  153329. int *pRC, /* Result code */
  153330. Fts3Table *p, /* The FTS table to delete from */
  153331. sqlite3_value *pRowid, /* The docid to be deleted */
  153332. u32 *aSz, /* Sizes of deleted document written here */
  153333. int *pbFound /* OUT: Set to true if row really does exist */
  153334. ){
  153335. int rc;
  153336. sqlite3_stmt *pSelect;
  153337. assert( *pbFound==0 );
  153338. if( *pRC ) return;
  153339. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  153340. if( rc==SQLITE_OK ){
  153341. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  153342. int i;
  153343. int iLangid = langidFromSelect(p, pSelect);
  153344. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  153345. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  153346. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  153347. int iCol = i-1;
  153348. if( p->abNotindexed[iCol]==0 ){
  153349. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  153350. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  153351. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  153352. }
  153353. }
  153354. if( rc!=SQLITE_OK ){
  153355. sqlite3_reset(pSelect);
  153356. *pRC = rc;
  153357. return;
  153358. }
  153359. *pbFound = 1;
  153360. }
  153361. rc = sqlite3_reset(pSelect);
  153362. }else{
  153363. sqlite3_reset(pSelect);
  153364. }
  153365. *pRC = rc;
  153366. }
  153367. /*
  153368. ** Forward declaration to account for the circular dependency between
  153369. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  153370. */
  153371. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  153372. /*
  153373. ** This function allocates a new level iLevel index in the segdir table.
  153374. ** Usually, indexes are allocated within a level sequentially starting
  153375. ** with 0, so the allocated index is one greater than the value returned
  153376. ** by:
  153377. **
  153378. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  153379. **
  153380. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  153381. ** level, they are merged into a single level (iLevel+1) segment and the
  153382. ** allocated index is 0.
  153383. **
  153384. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  153385. ** returned. Otherwise, an SQLite error code is returned.
  153386. */
  153387. static int fts3AllocateSegdirIdx(
  153388. Fts3Table *p,
  153389. int iLangid, /* Language id */
  153390. int iIndex, /* Index for p->aIndex */
  153391. int iLevel,
  153392. int *piIdx
  153393. ){
  153394. int rc; /* Return Code */
  153395. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  153396. int iNext = 0; /* Result of query pNextIdx */
  153397. assert( iLangid>=0 );
  153398. assert( p->nIndex>=1 );
  153399. /* Set variable iNext to the next available segdir index at level iLevel. */
  153400. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  153401. if( rc==SQLITE_OK ){
  153402. sqlite3_bind_int64(
  153403. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  153404. );
  153405. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  153406. iNext = sqlite3_column_int(pNextIdx, 0);
  153407. }
  153408. rc = sqlite3_reset(pNextIdx);
  153409. }
  153410. if( rc==SQLITE_OK ){
  153411. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  153412. ** full, merge all segments in level iLevel into a single iLevel+1
  153413. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  153414. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  153415. */
  153416. if( iNext>=FTS3_MERGE_COUNT ){
  153417. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  153418. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  153419. *piIdx = 0;
  153420. }else{
  153421. *piIdx = iNext;
  153422. }
  153423. }
  153424. return rc;
  153425. }
  153426. /*
  153427. ** The %_segments table is declared as follows:
  153428. **
  153429. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  153430. **
  153431. ** This function reads data from a single row of the %_segments table. The
  153432. ** specific row is identified by the iBlockid parameter. If paBlob is not
  153433. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  153434. ** with the contents of the blob stored in the "block" column of the
  153435. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  153436. ** to the size of the blob in bytes before returning.
  153437. **
  153438. ** If an error occurs, or the table does not contain the specified row,
  153439. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  153440. ** paBlob is non-NULL, then it is the responsibility of the caller to
  153441. ** eventually free the returned buffer.
  153442. **
  153443. ** This function may leave an open sqlite3_blob* handle in the
  153444. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  153445. ** to this function. The handle may be closed by calling the
  153446. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  153447. ** performance improvement, but the blob handle should always be closed
  153448. ** before control is returned to the user (to prevent a lock being held
  153449. ** on the database file for longer than necessary). Thus, any virtual table
  153450. ** method (xFilter etc.) that may directly or indirectly call this function
  153451. ** must call sqlite3Fts3SegmentsClose() before returning.
  153452. */
  153453. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  153454. Fts3Table *p, /* FTS3 table handle */
  153455. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  153456. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  153457. int *pnBlob, /* OUT: Size of blob data */
  153458. int *pnLoad /* OUT: Bytes actually loaded */
  153459. ){
  153460. int rc; /* Return code */
  153461. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  153462. assert( pnBlob );
  153463. if( p->pSegments ){
  153464. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  153465. }else{
  153466. if( 0==p->zSegmentsTbl ){
  153467. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  153468. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  153469. }
  153470. rc = sqlite3_blob_open(
  153471. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  153472. );
  153473. }
  153474. if( rc==SQLITE_OK ){
  153475. int nByte = sqlite3_blob_bytes(p->pSegments);
  153476. *pnBlob = nByte;
  153477. if( paBlob ){
  153478. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  153479. if( !aByte ){
  153480. rc = SQLITE_NOMEM;
  153481. }else{
  153482. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  153483. nByte = FTS3_NODE_CHUNKSIZE;
  153484. *pnLoad = nByte;
  153485. }
  153486. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  153487. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  153488. if( rc!=SQLITE_OK ){
  153489. sqlite3_free(aByte);
  153490. aByte = 0;
  153491. }
  153492. }
  153493. *paBlob = aByte;
  153494. }
  153495. }
  153496. return rc;
  153497. }
  153498. /*
  153499. ** Close the blob handle at p->pSegments, if it is open. See comments above
  153500. ** the sqlite3Fts3ReadBlock() function for details.
  153501. */
  153502. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  153503. sqlite3_blob_close(p->pSegments);
  153504. p->pSegments = 0;
  153505. }
  153506. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  153507. int nRead; /* Number of bytes to read */
  153508. int rc; /* Return code */
  153509. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  153510. rc = sqlite3_blob_read(
  153511. pReader->pBlob,
  153512. &pReader->aNode[pReader->nPopulate],
  153513. nRead,
  153514. pReader->nPopulate
  153515. );
  153516. if( rc==SQLITE_OK ){
  153517. pReader->nPopulate += nRead;
  153518. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  153519. if( pReader->nPopulate==pReader->nNode ){
  153520. sqlite3_blob_close(pReader->pBlob);
  153521. pReader->pBlob = 0;
  153522. pReader->nPopulate = 0;
  153523. }
  153524. }
  153525. return rc;
  153526. }
  153527. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  153528. int rc = SQLITE_OK;
  153529. assert( !pReader->pBlob
  153530. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  153531. );
  153532. while( pReader->pBlob && rc==SQLITE_OK
  153533. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  153534. ){
  153535. rc = fts3SegReaderIncrRead(pReader);
  153536. }
  153537. return rc;
  153538. }
  153539. /*
  153540. ** Set an Fts3SegReader cursor to point at EOF.
  153541. */
  153542. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  153543. if( !fts3SegReaderIsRootOnly(pSeg) ){
  153544. sqlite3_free(pSeg->aNode);
  153545. sqlite3_blob_close(pSeg->pBlob);
  153546. pSeg->pBlob = 0;
  153547. }
  153548. pSeg->aNode = 0;
  153549. }
  153550. /*
  153551. ** Move the iterator passed as the first argument to the next term in the
  153552. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  153553. ** SQLITE_DONE. Otherwise, an SQLite error code.
  153554. */
  153555. static int fts3SegReaderNext(
  153556. Fts3Table *p,
  153557. Fts3SegReader *pReader,
  153558. int bIncr
  153559. ){
  153560. int rc; /* Return code of various sub-routines */
  153561. char *pNext; /* Cursor variable */
  153562. int nPrefix; /* Number of bytes in term prefix */
  153563. int nSuffix; /* Number of bytes in term suffix */
  153564. if( !pReader->aDoclist ){
  153565. pNext = pReader->aNode;
  153566. }else{
  153567. pNext = &pReader->aDoclist[pReader->nDoclist];
  153568. }
  153569. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  153570. if( fts3SegReaderIsPending(pReader) ){
  153571. Fts3HashElem *pElem = *(pReader->ppNextElem);
  153572. sqlite3_free(pReader->aNode);
  153573. pReader->aNode = 0;
  153574. if( pElem ){
  153575. char *aCopy;
  153576. PendingList *pList = (PendingList *)fts3HashData(pElem);
  153577. int nCopy = pList->nData+1;
  153578. pReader->zTerm = (char *)fts3HashKey(pElem);
  153579. pReader->nTerm = fts3HashKeysize(pElem);
  153580. aCopy = (char*)sqlite3_malloc(nCopy);
  153581. if( !aCopy ) return SQLITE_NOMEM;
  153582. memcpy(aCopy, pList->aData, nCopy);
  153583. pReader->nNode = pReader->nDoclist = nCopy;
  153584. pReader->aNode = pReader->aDoclist = aCopy;
  153585. pReader->ppNextElem++;
  153586. assert( pReader->aNode );
  153587. }
  153588. return SQLITE_OK;
  153589. }
  153590. fts3SegReaderSetEof(pReader);
  153591. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  153592. ** blocks have already been traversed. */
  153593. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  153594. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  153595. return SQLITE_OK;
  153596. }
  153597. rc = sqlite3Fts3ReadBlock(
  153598. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  153599. (bIncr ? &pReader->nPopulate : 0)
  153600. );
  153601. if( rc!=SQLITE_OK ) return rc;
  153602. assert( pReader->pBlob==0 );
  153603. if( bIncr && pReader->nPopulate<pReader->nNode ){
  153604. pReader->pBlob = p->pSegments;
  153605. p->pSegments = 0;
  153606. }
  153607. pNext = pReader->aNode;
  153608. }
  153609. assert( !fts3SegReaderIsPending(pReader) );
  153610. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  153611. if( rc!=SQLITE_OK ) return rc;
  153612. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  153613. ** safe (no risk of overread) even if the node data is corrupted. */
  153614. pNext += fts3GetVarint32(pNext, &nPrefix);
  153615. pNext += fts3GetVarint32(pNext, &nSuffix);
  153616. if( nPrefix<0 || nSuffix<=0
  153617. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  153618. ){
  153619. return FTS_CORRUPT_VTAB;
  153620. }
  153621. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  153622. int nNew = (nPrefix+nSuffix)*2;
  153623. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  153624. if( !zNew ){
  153625. return SQLITE_NOMEM;
  153626. }
  153627. pReader->zTerm = zNew;
  153628. pReader->nTermAlloc = nNew;
  153629. }
  153630. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  153631. if( rc!=SQLITE_OK ) return rc;
  153632. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  153633. pReader->nTerm = nPrefix+nSuffix;
  153634. pNext += nSuffix;
  153635. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  153636. pReader->aDoclist = pNext;
  153637. pReader->pOffsetList = 0;
  153638. /* Check that the doclist does not appear to extend past the end of the
  153639. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  153640. ** of these statements is untrue, then the data structure is corrupt.
  153641. */
  153642. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  153643. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  153644. ){
  153645. return FTS_CORRUPT_VTAB;
  153646. }
  153647. return SQLITE_OK;
  153648. }
  153649. /*
  153650. ** Set the SegReader to point to the first docid in the doclist associated
  153651. ** with the current term.
  153652. */
  153653. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  153654. int rc = SQLITE_OK;
  153655. assert( pReader->aDoclist );
  153656. assert( !pReader->pOffsetList );
  153657. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  153658. u8 bEof = 0;
  153659. pReader->iDocid = 0;
  153660. pReader->nOffsetList = 0;
  153661. sqlite3Fts3DoclistPrev(0,
  153662. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  153663. &pReader->iDocid, &pReader->nOffsetList, &bEof
  153664. );
  153665. }else{
  153666. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  153667. if( rc==SQLITE_OK ){
  153668. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  153669. pReader->pOffsetList = &pReader->aDoclist[n];
  153670. }
  153671. }
  153672. return rc;
  153673. }
  153674. /*
  153675. ** Advance the SegReader to point to the next docid in the doclist
  153676. ** associated with the current term.
  153677. **
  153678. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  153679. ** *ppOffsetList is set to point to the first column-offset list
  153680. ** in the doclist entry (i.e. immediately past the docid varint).
  153681. ** *pnOffsetList is set to the length of the set of column-offset
  153682. ** lists, not including the nul-terminator byte. For example:
  153683. */
  153684. static int fts3SegReaderNextDocid(
  153685. Fts3Table *pTab,
  153686. Fts3SegReader *pReader, /* Reader to advance to next docid */
  153687. char **ppOffsetList, /* OUT: Pointer to current position-list */
  153688. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  153689. ){
  153690. int rc = SQLITE_OK;
  153691. char *p = pReader->pOffsetList;
  153692. char c = 0;
  153693. assert( p );
  153694. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  153695. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  153696. ** Pending-terms doclists are always built up in ascending order, so
  153697. ** we have to iterate through them backwards here. */
  153698. u8 bEof = 0;
  153699. if( ppOffsetList ){
  153700. *ppOffsetList = pReader->pOffsetList;
  153701. *pnOffsetList = pReader->nOffsetList - 1;
  153702. }
  153703. sqlite3Fts3DoclistPrev(0,
  153704. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  153705. &pReader->nOffsetList, &bEof
  153706. );
  153707. if( bEof ){
  153708. pReader->pOffsetList = 0;
  153709. }else{
  153710. pReader->pOffsetList = p;
  153711. }
  153712. }else{
  153713. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  153714. /* Pointer p currently points at the first byte of an offset list. The
  153715. ** following block advances it to point one byte past the end of
  153716. ** the same offset list. */
  153717. while( 1 ){
  153718. /* The following line of code (and the "p++" below the while() loop) is
  153719. ** normally all that is required to move pointer p to the desired
  153720. ** position. The exception is if this node is being loaded from disk
  153721. ** incrementally and pointer "p" now points to the first byte past
  153722. ** the populated part of pReader->aNode[].
  153723. */
  153724. while( *p | c ) c = *p++ & 0x80;
  153725. assert( *p==0 );
  153726. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  153727. rc = fts3SegReaderIncrRead(pReader);
  153728. if( rc!=SQLITE_OK ) return rc;
  153729. }
  153730. p++;
  153731. /* If required, populate the output variables with a pointer to and the
  153732. ** size of the previous offset-list.
  153733. */
  153734. if( ppOffsetList ){
  153735. *ppOffsetList = pReader->pOffsetList;
  153736. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  153737. }
  153738. /* List may have been edited in place by fts3EvalNearTrim() */
  153739. while( p<pEnd && *p==0 ) p++;
  153740. /* If there are no more entries in the doclist, set pOffsetList to
  153741. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  153742. ** Fts3SegReader.pOffsetList to point to the next offset list before
  153743. ** returning.
  153744. */
  153745. if( p>=pEnd ){
  153746. pReader->pOffsetList = 0;
  153747. }else{
  153748. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  153749. if( rc==SQLITE_OK ){
  153750. sqlite3_int64 iDelta;
  153751. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  153752. if( pTab->bDescIdx ){
  153753. pReader->iDocid -= iDelta;
  153754. }else{
  153755. pReader->iDocid += iDelta;
  153756. }
  153757. }
  153758. }
  153759. }
  153760. return SQLITE_OK;
  153761. }
  153762. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  153763. Fts3Cursor *pCsr,
  153764. Fts3MultiSegReader *pMsr,
  153765. int *pnOvfl
  153766. ){
  153767. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  153768. int nOvfl = 0;
  153769. int ii;
  153770. int rc = SQLITE_OK;
  153771. int pgsz = p->nPgsz;
  153772. assert( p->bFts4 );
  153773. assert( pgsz>0 );
  153774. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  153775. Fts3SegReader *pReader = pMsr->apSegment[ii];
  153776. if( !fts3SegReaderIsPending(pReader)
  153777. && !fts3SegReaderIsRootOnly(pReader)
  153778. ){
  153779. sqlite3_int64 jj;
  153780. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  153781. int nBlob;
  153782. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  153783. if( rc!=SQLITE_OK ) break;
  153784. if( (nBlob+35)>pgsz ){
  153785. nOvfl += (nBlob + 34)/pgsz;
  153786. }
  153787. }
  153788. }
  153789. }
  153790. *pnOvfl = nOvfl;
  153791. return rc;
  153792. }
  153793. /*
  153794. ** Free all allocations associated with the iterator passed as the
  153795. ** second argument.
  153796. */
  153797. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  153798. if( pReader ){
  153799. if( !fts3SegReaderIsPending(pReader) ){
  153800. sqlite3_free(pReader->zTerm);
  153801. }
  153802. if( !fts3SegReaderIsRootOnly(pReader) ){
  153803. sqlite3_free(pReader->aNode);
  153804. }
  153805. sqlite3_blob_close(pReader->pBlob);
  153806. }
  153807. sqlite3_free(pReader);
  153808. }
  153809. /*
  153810. ** Allocate a new SegReader object.
  153811. */
  153812. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  153813. int iAge, /* Segment "age". */
  153814. int bLookup, /* True for a lookup only */
  153815. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  153816. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  153817. sqlite3_int64 iEndBlock, /* Final block of segment */
  153818. const char *zRoot, /* Buffer containing root node */
  153819. int nRoot, /* Size of buffer containing root node */
  153820. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  153821. ){
  153822. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  153823. int nExtra = 0; /* Bytes to allocate segment root node */
  153824. assert( iStartLeaf<=iEndLeaf );
  153825. if( iStartLeaf==0 ){
  153826. nExtra = nRoot + FTS3_NODE_PADDING;
  153827. }
  153828. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  153829. if( !pReader ){
  153830. return SQLITE_NOMEM;
  153831. }
  153832. memset(pReader, 0, sizeof(Fts3SegReader));
  153833. pReader->iIdx = iAge;
  153834. pReader->bLookup = bLookup!=0;
  153835. pReader->iStartBlock = iStartLeaf;
  153836. pReader->iLeafEndBlock = iEndLeaf;
  153837. pReader->iEndBlock = iEndBlock;
  153838. if( nExtra ){
  153839. /* The entire segment is stored in the root node. */
  153840. pReader->aNode = (char *)&pReader[1];
  153841. pReader->rootOnly = 1;
  153842. pReader->nNode = nRoot;
  153843. memcpy(pReader->aNode, zRoot, nRoot);
  153844. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  153845. }else{
  153846. pReader->iCurrentBlock = iStartLeaf-1;
  153847. }
  153848. *ppReader = pReader;
  153849. return SQLITE_OK;
  153850. }
  153851. /*
  153852. ** This is a comparison function used as a qsort() callback when sorting
  153853. ** an array of pending terms by term. This occurs as part of flushing
  153854. ** the contents of the pending-terms hash table to the database.
  153855. */
  153856. static int SQLITE_CDECL fts3CompareElemByTerm(
  153857. const void *lhs,
  153858. const void *rhs
  153859. ){
  153860. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  153861. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  153862. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  153863. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  153864. int n = (n1<n2 ? n1 : n2);
  153865. int c = memcmp(z1, z2, n);
  153866. if( c==0 ){
  153867. c = n1 - n2;
  153868. }
  153869. return c;
  153870. }
  153871. /*
  153872. ** This function is used to allocate an Fts3SegReader that iterates through
  153873. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  153874. **
  153875. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  153876. ** through each term in the pending-terms table. Or, if isPrefixIter is
  153877. ** non-zero, it iterates through each term and its prefixes. For example, if
  153878. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  153879. ** "firebird", then the iterator visits the following 'terms' (in the order
  153880. ** shown):
  153881. **
  153882. ** f fi fir fire fireb firebi firebir firebird
  153883. ** m my mys mysq mysql
  153884. ** s sq sql sqli sqlit sqlite
  153885. **
  153886. ** Whereas if isPrefixIter is zero, the terms visited are:
  153887. **
  153888. ** firebird mysql sqlite
  153889. */
  153890. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  153891. Fts3Table *p, /* Virtual table handle */
  153892. int iIndex, /* Index for p->aIndex */
  153893. const char *zTerm, /* Term to search for */
  153894. int nTerm, /* Size of buffer zTerm */
  153895. int bPrefix, /* True for a prefix iterator */
  153896. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  153897. ){
  153898. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  153899. Fts3HashElem *pE; /* Iterator variable */
  153900. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  153901. int nElem = 0; /* Size of array at aElem */
  153902. int rc = SQLITE_OK; /* Return Code */
  153903. Fts3Hash *pHash;
  153904. pHash = &p->aIndex[iIndex].hPending;
  153905. if( bPrefix ){
  153906. int nAlloc = 0; /* Size of allocated array at aElem */
  153907. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  153908. char *zKey = (char *)fts3HashKey(pE);
  153909. int nKey = fts3HashKeysize(pE);
  153910. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  153911. if( nElem==nAlloc ){
  153912. Fts3HashElem **aElem2;
  153913. nAlloc += 16;
  153914. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  153915. aElem, nAlloc*sizeof(Fts3HashElem *)
  153916. );
  153917. if( !aElem2 ){
  153918. rc = SQLITE_NOMEM;
  153919. nElem = 0;
  153920. break;
  153921. }
  153922. aElem = aElem2;
  153923. }
  153924. aElem[nElem++] = pE;
  153925. }
  153926. }
  153927. /* If more than one term matches the prefix, sort the Fts3HashElem
  153928. ** objects in term order using qsort(). This uses the same comparison
  153929. ** callback as is used when flushing terms to disk.
  153930. */
  153931. if( nElem>1 ){
  153932. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  153933. }
  153934. }else{
  153935. /* The query is a simple term lookup that matches at most one term in
  153936. ** the index. All that is required is a straight hash-lookup.
  153937. **
  153938. ** Because the stack address of pE may be accessed via the aElem pointer
  153939. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  153940. ** within this entire function, not just this "else{...}" block.
  153941. */
  153942. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  153943. if( pE ){
  153944. aElem = &pE;
  153945. nElem = 1;
  153946. }
  153947. }
  153948. if( nElem>0 ){
  153949. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  153950. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  153951. if( !pReader ){
  153952. rc = SQLITE_NOMEM;
  153953. }else{
  153954. memset(pReader, 0, nByte);
  153955. pReader->iIdx = 0x7FFFFFFF;
  153956. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  153957. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  153958. }
  153959. }
  153960. if( bPrefix ){
  153961. sqlite3_free(aElem);
  153962. }
  153963. *ppReader = pReader;
  153964. return rc;
  153965. }
  153966. /*
  153967. ** Compare the entries pointed to by two Fts3SegReader structures.
  153968. ** Comparison is as follows:
  153969. **
  153970. ** 1) EOF is greater than not EOF.
  153971. **
  153972. ** 2) The current terms (if any) are compared using memcmp(). If one
  153973. ** term is a prefix of another, the longer term is considered the
  153974. ** larger.
  153975. **
  153976. ** 3) By segment age. An older segment is considered larger.
  153977. */
  153978. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  153979. int rc;
  153980. if( pLhs->aNode && pRhs->aNode ){
  153981. int rc2 = pLhs->nTerm - pRhs->nTerm;
  153982. if( rc2<0 ){
  153983. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  153984. }else{
  153985. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  153986. }
  153987. if( rc==0 ){
  153988. rc = rc2;
  153989. }
  153990. }else{
  153991. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  153992. }
  153993. if( rc==0 ){
  153994. rc = pRhs->iIdx - pLhs->iIdx;
  153995. }
  153996. assert( rc!=0 );
  153997. return rc;
  153998. }
  153999. /*
  154000. ** A different comparison function for SegReader structures. In this
  154001. ** version, it is assumed that each SegReader points to an entry in
  154002. ** a doclist for identical terms. Comparison is made as follows:
  154003. **
  154004. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  154005. **
  154006. ** 2) By current docid.
  154007. **
  154008. ** 3) By segment age. An older segment is considered larger.
  154009. */
  154010. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  154011. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  154012. if( rc==0 ){
  154013. if( pLhs->iDocid==pRhs->iDocid ){
  154014. rc = pRhs->iIdx - pLhs->iIdx;
  154015. }else{
  154016. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  154017. }
  154018. }
  154019. assert( pLhs->aNode && pRhs->aNode );
  154020. return rc;
  154021. }
  154022. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  154023. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  154024. if( rc==0 ){
  154025. if( pLhs->iDocid==pRhs->iDocid ){
  154026. rc = pRhs->iIdx - pLhs->iIdx;
  154027. }else{
  154028. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  154029. }
  154030. }
  154031. assert( pLhs->aNode && pRhs->aNode );
  154032. return rc;
  154033. }
  154034. /*
  154035. ** Compare the term that the Fts3SegReader object passed as the first argument
  154036. ** points to with the term specified by arguments zTerm and nTerm.
  154037. **
  154038. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  154039. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  154040. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  154041. */
  154042. static int fts3SegReaderTermCmp(
  154043. Fts3SegReader *pSeg, /* Segment reader object */
  154044. const char *zTerm, /* Term to compare to */
  154045. int nTerm /* Size of term zTerm in bytes */
  154046. ){
  154047. int res = 0;
  154048. if( pSeg->aNode ){
  154049. if( pSeg->nTerm>nTerm ){
  154050. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  154051. }else{
  154052. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  154053. }
  154054. if( res==0 ){
  154055. res = pSeg->nTerm-nTerm;
  154056. }
  154057. }
  154058. return res;
  154059. }
  154060. /*
  154061. ** Argument apSegment is an array of nSegment elements. It is known that
  154062. ** the final (nSegment-nSuspect) members are already in sorted order
  154063. ** (according to the comparison function provided). This function shuffles
  154064. ** the array around until all entries are in sorted order.
  154065. */
  154066. static void fts3SegReaderSort(
  154067. Fts3SegReader **apSegment, /* Array to sort entries of */
  154068. int nSegment, /* Size of apSegment array */
  154069. int nSuspect, /* Unsorted entry count */
  154070. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  154071. ){
  154072. int i; /* Iterator variable */
  154073. assert( nSuspect<=nSegment );
  154074. if( nSuspect==nSegment ) nSuspect--;
  154075. for(i=nSuspect-1; i>=0; i--){
  154076. int j;
  154077. for(j=i; j<(nSegment-1); j++){
  154078. Fts3SegReader *pTmp;
  154079. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  154080. pTmp = apSegment[j+1];
  154081. apSegment[j+1] = apSegment[j];
  154082. apSegment[j] = pTmp;
  154083. }
  154084. }
  154085. #ifndef NDEBUG
  154086. /* Check that the list really is sorted now. */
  154087. for(i=0; i<(nSuspect-1); i++){
  154088. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  154089. }
  154090. #endif
  154091. }
  154092. /*
  154093. ** Insert a record into the %_segments table.
  154094. */
  154095. static int fts3WriteSegment(
  154096. Fts3Table *p, /* Virtual table handle */
  154097. sqlite3_int64 iBlock, /* Block id for new block */
  154098. char *z, /* Pointer to buffer containing block data */
  154099. int n /* Size of buffer z in bytes */
  154100. ){
  154101. sqlite3_stmt *pStmt;
  154102. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  154103. if( rc==SQLITE_OK ){
  154104. sqlite3_bind_int64(pStmt, 1, iBlock);
  154105. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  154106. sqlite3_step(pStmt);
  154107. rc = sqlite3_reset(pStmt);
  154108. sqlite3_bind_null(pStmt, 2);
  154109. }
  154110. return rc;
  154111. }
  154112. /*
  154113. ** Find the largest relative level number in the table. If successful, set
  154114. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  154115. ** set *pnMax to zero and return an SQLite error code.
  154116. */
  154117. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  154118. int rc;
  154119. int mxLevel = 0;
  154120. sqlite3_stmt *pStmt = 0;
  154121. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  154122. if( rc==SQLITE_OK ){
  154123. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  154124. mxLevel = sqlite3_column_int(pStmt, 0);
  154125. }
  154126. rc = sqlite3_reset(pStmt);
  154127. }
  154128. *pnMax = mxLevel;
  154129. return rc;
  154130. }
  154131. /*
  154132. ** Insert a record into the %_segdir table.
  154133. */
  154134. static int fts3WriteSegdir(
  154135. Fts3Table *p, /* Virtual table handle */
  154136. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  154137. int iIdx, /* Value for "idx" field */
  154138. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  154139. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  154140. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  154141. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  154142. char *zRoot, /* Blob value for "root" field */
  154143. int nRoot /* Number of bytes in buffer zRoot */
  154144. ){
  154145. sqlite3_stmt *pStmt;
  154146. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  154147. if( rc==SQLITE_OK ){
  154148. sqlite3_bind_int64(pStmt, 1, iLevel);
  154149. sqlite3_bind_int(pStmt, 2, iIdx);
  154150. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  154151. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  154152. if( nLeafData==0 ){
  154153. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  154154. }else{
  154155. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  154156. if( !zEnd ) return SQLITE_NOMEM;
  154157. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  154158. }
  154159. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  154160. sqlite3_step(pStmt);
  154161. rc = sqlite3_reset(pStmt);
  154162. sqlite3_bind_null(pStmt, 6);
  154163. }
  154164. return rc;
  154165. }
  154166. /*
  154167. ** Return the size of the common prefix (if any) shared by zPrev and
  154168. ** zNext, in bytes. For example,
  154169. **
  154170. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  154171. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  154172. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  154173. */
  154174. static int fts3PrefixCompress(
  154175. const char *zPrev, /* Buffer containing previous term */
  154176. int nPrev, /* Size of buffer zPrev in bytes */
  154177. const char *zNext, /* Buffer containing next term */
  154178. int nNext /* Size of buffer zNext in bytes */
  154179. ){
  154180. int n;
  154181. UNUSED_PARAMETER(nNext);
  154182. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  154183. return n;
  154184. }
  154185. /*
  154186. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  154187. ** (according to memcmp) than the previous term.
  154188. */
  154189. static int fts3NodeAddTerm(
  154190. Fts3Table *p, /* Virtual table handle */
  154191. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  154192. int isCopyTerm, /* True if zTerm/nTerm is transient */
  154193. const char *zTerm, /* Pointer to buffer containing term */
  154194. int nTerm /* Size of term in bytes */
  154195. ){
  154196. SegmentNode *pTree = *ppTree;
  154197. int rc;
  154198. SegmentNode *pNew;
  154199. /* First try to append the term to the current node. Return early if
  154200. ** this is possible.
  154201. */
  154202. if( pTree ){
  154203. int nData = pTree->nData; /* Current size of node in bytes */
  154204. int nReq = nData; /* Required space after adding zTerm */
  154205. int nPrefix; /* Number of bytes of prefix compression */
  154206. int nSuffix; /* Suffix length */
  154207. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  154208. nSuffix = nTerm-nPrefix;
  154209. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  154210. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  154211. if( nReq>p->nNodeSize ){
  154212. /* An unusual case: this is the first term to be added to the node
  154213. ** and the static node buffer (p->nNodeSize bytes) is not large
  154214. ** enough. Use a separately malloced buffer instead This wastes
  154215. ** p->nNodeSize bytes, but since this scenario only comes about when
  154216. ** the database contain two terms that share a prefix of almost 2KB,
  154217. ** this is not expected to be a serious problem.
  154218. */
  154219. assert( pTree->aData==(char *)&pTree[1] );
  154220. pTree->aData = (char *)sqlite3_malloc(nReq);
  154221. if( !pTree->aData ){
  154222. return SQLITE_NOMEM;
  154223. }
  154224. }
  154225. if( pTree->zTerm ){
  154226. /* There is no prefix-length field for first term in a node */
  154227. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  154228. }
  154229. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  154230. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  154231. pTree->nData = nData + nSuffix;
  154232. pTree->nEntry++;
  154233. if( isCopyTerm ){
  154234. if( pTree->nMalloc<nTerm ){
  154235. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  154236. if( !zNew ){
  154237. return SQLITE_NOMEM;
  154238. }
  154239. pTree->nMalloc = nTerm*2;
  154240. pTree->zMalloc = zNew;
  154241. }
  154242. pTree->zTerm = pTree->zMalloc;
  154243. memcpy(pTree->zTerm, zTerm, nTerm);
  154244. pTree->nTerm = nTerm;
  154245. }else{
  154246. pTree->zTerm = (char *)zTerm;
  154247. pTree->nTerm = nTerm;
  154248. }
  154249. return SQLITE_OK;
  154250. }
  154251. }
  154252. /* If control flows to here, it was not possible to append zTerm to the
  154253. ** current node. Create a new node (a right-sibling of the current node).
  154254. ** If this is the first node in the tree, the term is added to it.
  154255. **
  154256. ** Otherwise, the term is not added to the new node, it is left empty for
  154257. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  154258. ** has no parent, one is created here.
  154259. */
  154260. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  154261. if( !pNew ){
  154262. return SQLITE_NOMEM;
  154263. }
  154264. memset(pNew, 0, sizeof(SegmentNode));
  154265. pNew->nData = 1 + FTS3_VARINT_MAX;
  154266. pNew->aData = (char *)&pNew[1];
  154267. if( pTree ){
  154268. SegmentNode *pParent = pTree->pParent;
  154269. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  154270. if( pTree->pParent==0 ){
  154271. pTree->pParent = pParent;
  154272. }
  154273. pTree->pRight = pNew;
  154274. pNew->pLeftmost = pTree->pLeftmost;
  154275. pNew->pParent = pParent;
  154276. pNew->zMalloc = pTree->zMalloc;
  154277. pNew->nMalloc = pTree->nMalloc;
  154278. pTree->zMalloc = 0;
  154279. }else{
  154280. pNew->pLeftmost = pNew;
  154281. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  154282. }
  154283. *ppTree = pNew;
  154284. return rc;
  154285. }
  154286. /*
  154287. ** Helper function for fts3NodeWrite().
  154288. */
  154289. static int fts3TreeFinishNode(
  154290. SegmentNode *pTree,
  154291. int iHeight,
  154292. sqlite3_int64 iLeftChild
  154293. ){
  154294. int nStart;
  154295. assert( iHeight>=1 && iHeight<128 );
  154296. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  154297. pTree->aData[nStart] = (char)iHeight;
  154298. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  154299. return nStart;
  154300. }
  154301. /*
  154302. ** Write the buffer for the segment node pTree and all of its peers to the
  154303. ** database. Then call this function recursively to write the parent of
  154304. ** pTree and its peers to the database.
  154305. **
  154306. ** Except, if pTree is a root node, do not write it to the database. Instead,
  154307. ** set output variables *paRoot and *pnRoot to contain the root node.
  154308. **
  154309. ** If successful, SQLITE_OK is returned and output variable *piLast is
  154310. ** set to the largest blockid written to the database (or zero if no
  154311. ** blocks were written to the db). Otherwise, an SQLite error code is
  154312. ** returned.
  154313. */
  154314. static int fts3NodeWrite(
  154315. Fts3Table *p, /* Virtual table handle */
  154316. SegmentNode *pTree, /* SegmentNode handle */
  154317. int iHeight, /* Height of this node in tree */
  154318. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  154319. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  154320. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  154321. char **paRoot, /* OUT: Data for root node */
  154322. int *pnRoot /* OUT: Size of root node in bytes */
  154323. ){
  154324. int rc = SQLITE_OK;
  154325. if( !pTree->pParent ){
  154326. /* Root node of the tree. */
  154327. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  154328. *piLast = iFree-1;
  154329. *pnRoot = pTree->nData - nStart;
  154330. *paRoot = &pTree->aData[nStart];
  154331. }else{
  154332. SegmentNode *pIter;
  154333. sqlite3_int64 iNextFree = iFree;
  154334. sqlite3_int64 iNextLeaf = iLeaf;
  154335. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  154336. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  154337. int nWrite = pIter->nData - nStart;
  154338. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  154339. iNextFree++;
  154340. iNextLeaf += (pIter->nEntry+1);
  154341. }
  154342. if( rc==SQLITE_OK ){
  154343. assert( iNextLeaf==iFree );
  154344. rc = fts3NodeWrite(
  154345. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  154346. );
  154347. }
  154348. }
  154349. return rc;
  154350. }
  154351. /*
  154352. ** Free all memory allocations associated with the tree pTree.
  154353. */
  154354. static void fts3NodeFree(SegmentNode *pTree){
  154355. if( pTree ){
  154356. SegmentNode *p = pTree->pLeftmost;
  154357. fts3NodeFree(p->pParent);
  154358. while( p ){
  154359. SegmentNode *pRight = p->pRight;
  154360. if( p->aData!=(char *)&p[1] ){
  154361. sqlite3_free(p->aData);
  154362. }
  154363. assert( pRight==0 || p->zMalloc==0 );
  154364. sqlite3_free(p->zMalloc);
  154365. sqlite3_free(p);
  154366. p = pRight;
  154367. }
  154368. }
  154369. }
  154370. /*
  154371. ** Add a term to the segment being constructed by the SegmentWriter object
  154372. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  154373. ** be passed NULL. This function will allocate a new SegmentWriter object
  154374. ** and return it via the input/output variable *ppWriter in this case.
  154375. **
  154376. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  154377. */
  154378. static int fts3SegWriterAdd(
  154379. Fts3Table *p, /* Virtual table handle */
  154380. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  154381. int isCopyTerm, /* True if buffer zTerm must be copied */
  154382. const char *zTerm, /* Pointer to buffer containing term */
  154383. int nTerm, /* Size of term in bytes */
  154384. const char *aDoclist, /* Pointer to buffer containing doclist */
  154385. int nDoclist /* Size of doclist in bytes */
  154386. ){
  154387. int nPrefix; /* Size of term prefix in bytes */
  154388. int nSuffix; /* Size of term suffix in bytes */
  154389. int nReq; /* Number of bytes required on leaf page */
  154390. int nData;
  154391. SegmentWriter *pWriter = *ppWriter;
  154392. if( !pWriter ){
  154393. int rc;
  154394. sqlite3_stmt *pStmt;
  154395. /* Allocate the SegmentWriter structure */
  154396. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  154397. if( !pWriter ) return SQLITE_NOMEM;
  154398. memset(pWriter, 0, sizeof(SegmentWriter));
  154399. *ppWriter = pWriter;
  154400. /* Allocate a buffer in which to accumulate data */
  154401. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  154402. if( !pWriter->aData ) return SQLITE_NOMEM;
  154403. pWriter->nSize = p->nNodeSize;
  154404. /* Find the next free blockid in the %_segments table */
  154405. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  154406. if( rc!=SQLITE_OK ) return rc;
  154407. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  154408. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  154409. pWriter->iFirst = pWriter->iFree;
  154410. }
  154411. rc = sqlite3_reset(pStmt);
  154412. if( rc!=SQLITE_OK ) return rc;
  154413. }
  154414. nData = pWriter->nData;
  154415. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  154416. nSuffix = nTerm-nPrefix;
  154417. /* Figure out how many bytes are required by this new entry */
  154418. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  154419. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  154420. nSuffix + /* Term suffix */
  154421. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  154422. nDoclist; /* Doclist data */
  154423. if( nData>0 && nData+nReq>p->nNodeSize ){
  154424. int rc;
  154425. /* The current leaf node is full. Write it out to the database. */
  154426. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  154427. if( rc!=SQLITE_OK ) return rc;
  154428. p->nLeafAdd++;
  154429. /* Add the current term to the interior node tree. The term added to
  154430. ** the interior tree must:
  154431. **
  154432. ** a) be greater than the largest term on the leaf node just written
  154433. ** to the database (still available in pWriter->zTerm), and
  154434. **
  154435. ** b) be less than or equal to the term about to be added to the new
  154436. ** leaf node (zTerm/nTerm).
  154437. **
  154438. ** In other words, it must be the prefix of zTerm 1 byte longer than
  154439. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  154440. */
  154441. assert( nPrefix<nTerm );
  154442. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  154443. if( rc!=SQLITE_OK ) return rc;
  154444. nData = 0;
  154445. pWriter->nTerm = 0;
  154446. nPrefix = 0;
  154447. nSuffix = nTerm;
  154448. nReq = 1 + /* varint containing prefix size */
  154449. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  154450. nTerm + /* Term suffix */
  154451. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  154452. nDoclist; /* Doclist data */
  154453. }
  154454. /* Increase the total number of bytes written to account for the new entry. */
  154455. pWriter->nLeafData += nReq;
  154456. /* If the buffer currently allocated is too small for this entry, realloc
  154457. ** the buffer to make it large enough.
  154458. */
  154459. if( nReq>pWriter->nSize ){
  154460. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  154461. if( !aNew ) return SQLITE_NOMEM;
  154462. pWriter->aData = aNew;
  154463. pWriter->nSize = nReq;
  154464. }
  154465. assert( nData+nReq<=pWriter->nSize );
  154466. /* Append the prefix-compressed term and doclist to the buffer. */
  154467. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  154468. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  154469. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  154470. nData += nSuffix;
  154471. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  154472. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  154473. pWriter->nData = nData + nDoclist;
  154474. /* Save the current term so that it can be used to prefix-compress the next.
  154475. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  154476. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  154477. ** store a copy of the pointer.
  154478. */
  154479. if( isCopyTerm ){
  154480. if( nTerm>pWriter->nMalloc ){
  154481. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  154482. if( !zNew ){
  154483. return SQLITE_NOMEM;
  154484. }
  154485. pWriter->nMalloc = nTerm*2;
  154486. pWriter->zMalloc = zNew;
  154487. pWriter->zTerm = zNew;
  154488. }
  154489. assert( pWriter->zTerm==pWriter->zMalloc );
  154490. memcpy(pWriter->zTerm, zTerm, nTerm);
  154491. }else{
  154492. pWriter->zTerm = (char *)zTerm;
  154493. }
  154494. pWriter->nTerm = nTerm;
  154495. return SQLITE_OK;
  154496. }
  154497. /*
  154498. ** Flush all data associated with the SegmentWriter object pWriter to the
  154499. ** database. This function must be called after all terms have been added
  154500. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  154501. ** returned. Otherwise, an SQLite error code.
  154502. */
  154503. static int fts3SegWriterFlush(
  154504. Fts3Table *p, /* Virtual table handle */
  154505. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  154506. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  154507. int iIdx /* Value for 'idx' column of %_segdir */
  154508. ){
  154509. int rc; /* Return code */
  154510. if( pWriter->pTree ){
  154511. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  154512. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  154513. char *zRoot = NULL; /* Pointer to buffer containing root node */
  154514. int nRoot = 0; /* Size of buffer zRoot */
  154515. iLastLeaf = pWriter->iFree;
  154516. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  154517. if( rc==SQLITE_OK ){
  154518. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  154519. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  154520. }
  154521. if( rc==SQLITE_OK ){
  154522. rc = fts3WriteSegdir(p, iLevel, iIdx,
  154523. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  154524. }
  154525. }else{
  154526. /* The entire tree fits on the root node. Write it to the segdir table. */
  154527. rc = fts3WriteSegdir(p, iLevel, iIdx,
  154528. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  154529. }
  154530. p->nLeafAdd++;
  154531. return rc;
  154532. }
  154533. /*
  154534. ** Release all memory held by the SegmentWriter object passed as the
  154535. ** first argument.
  154536. */
  154537. static void fts3SegWriterFree(SegmentWriter *pWriter){
  154538. if( pWriter ){
  154539. sqlite3_free(pWriter->aData);
  154540. sqlite3_free(pWriter->zMalloc);
  154541. fts3NodeFree(pWriter->pTree);
  154542. sqlite3_free(pWriter);
  154543. }
  154544. }
  154545. /*
  154546. ** The first value in the apVal[] array is assumed to contain an integer.
  154547. ** This function tests if there exist any documents with docid values that
  154548. ** are different from that integer. i.e. if deleting the document with docid
  154549. ** pRowid would mean the FTS3 table were empty.
  154550. **
  154551. ** If successful, *pisEmpty is set to true if the table is empty except for
  154552. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  154553. ** error occurs, an SQLite error code is returned.
  154554. */
  154555. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  154556. sqlite3_stmt *pStmt;
  154557. int rc;
  154558. if( p->zContentTbl ){
  154559. /* If using the content=xxx option, assume the table is never empty */
  154560. *pisEmpty = 0;
  154561. rc = SQLITE_OK;
  154562. }else{
  154563. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  154564. if( rc==SQLITE_OK ){
  154565. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  154566. *pisEmpty = sqlite3_column_int(pStmt, 0);
  154567. }
  154568. rc = sqlite3_reset(pStmt);
  154569. }
  154570. }
  154571. return rc;
  154572. }
  154573. /*
  154574. ** Set *pnMax to the largest segment level in the database for the index
  154575. ** iIndex.
  154576. **
  154577. ** Segment levels are stored in the 'level' column of the %_segdir table.
  154578. **
  154579. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  154580. */
  154581. static int fts3SegmentMaxLevel(
  154582. Fts3Table *p,
  154583. int iLangid,
  154584. int iIndex,
  154585. sqlite3_int64 *pnMax
  154586. ){
  154587. sqlite3_stmt *pStmt;
  154588. int rc;
  154589. assert( iIndex>=0 && iIndex<p->nIndex );
  154590. /* Set pStmt to the compiled version of:
  154591. **
  154592. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  154593. **
  154594. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  154595. */
  154596. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  154597. if( rc!=SQLITE_OK ) return rc;
  154598. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  154599. sqlite3_bind_int64(pStmt, 2,
  154600. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  154601. );
  154602. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  154603. *pnMax = sqlite3_column_int64(pStmt, 0);
  154604. }
  154605. return sqlite3_reset(pStmt);
  154606. }
  154607. /*
  154608. ** iAbsLevel is an absolute level that may be assumed to exist within
  154609. ** the database. This function checks if it is the largest level number
  154610. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  154611. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  154612. ** is returned. If an error occurs, an error code is returned and the
  154613. ** final value of *pbMax is undefined.
  154614. */
  154615. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  154616. /* Set pStmt to the compiled version of:
  154617. **
  154618. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  154619. **
  154620. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  154621. */
  154622. sqlite3_stmt *pStmt;
  154623. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  154624. if( rc!=SQLITE_OK ) return rc;
  154625. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  154626. sqlite3_bind_int64(pStmt, 2,
  154627. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  154628. );
  154629. *pbMax = 0;
  154630. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  154631. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  154632. }
  154633. return sqlite3_reset(pStmt);
  154634. }
  154635. /*
  154636. ** Delete all entries in the %_segments table associated with the segment
  154637. ** opened with seg-reader pSeg. This function does not affect the contents
  154638. ** of the %_segdir table.
  154639. */
  154640. static int fts3DeleteSegment(
  154641. Fts3Table *p, /* FTS table handle */
  154642. Fts3SegReader *pSeg /* Segment to delete */
  154643. ){
  154644. int rc = SQLITE_OK; /* Return code */
  154645. if( pSeg->iStartBlock ){
  154646. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  154647. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  154648. if( rc==SQLITE_OK ){
  154649. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  154650. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  154651. sqlite3_step(pDelete);
  154652. rc = sqlite3_reset(pDelete);
  154653. }
  154654. }
  154655. return rc;
  154656. }
  154657. /*
  154658. ** This function is used after merging multiple segments into a single large
  154659. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  154660. ** it:
  154661. **
  154662. ** 1) Deletes all %_segments entries for the segments associated with
  154663. ** each of the SegReader objects in the array passed as the third
  154664. ** argument, and
  154665. **
  154666. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  154667. ** entries regardless of level if (iLevel<0).
  154668. **
  154669. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  154670. */
  154671. static int fts3DeleteSegdir(
  154672. Fts3Table *p, /* Virtual table handle */
  154673. int iLangid, /* Language id */
  154674. int iIndex, /* Index for p->aIndex */
  154675. int iLevel, /* Level of %_segdir entries to delete */
  154676. Fts3SegReader **apSegment, /* Array of SegReader objects */
  154677. int nReader /* Size of array apSegment */
  154678. ){
  154679. int rc = SQLITE_OK; /* Return Code */
  154680. int i; /* Iterator variable */
  154681. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  154682. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  154683. rc = fts3DeleteSegment(p, apSegment[i]);
  154684. }
  154685. if( rc!=SQLITE_OK ){
  154686. return rc;
  154687. }
  154688. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  154689. if( iLevel==FTS3_SEGCURSOR_ALL ){
  154690. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  154691. if( rc==SQLITE_OK ){
  154692. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  154693. sqlite3_bind_int64(pDelete, 2,
  154694. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  154695. );
  154696. }
  154697. }else{
  154698. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  154699. if( rc==SQLITE_OK ){
  154700. sqlite3_bind_int64(
  154701. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  154702. );
  154703. }
  154704. }
  154705. if( rc==SQLITE_OK ){
  154706. sqlite3_step(pDelete);
  154707. rc = sqlite3_reset(pDelete);
  154708. }
  154709. return rc;
  154710. }
  154711. /*
  154712. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  154713. ** a position list that may (or may not) feature multiple columns. This
  154714. ** function adjusts the pointer *ppList and the length *pnList so that they
  154715. ** identify the subset of the position list that corresponds to column iCol.
  154716. **
  154717. ** If there are no entries in the input position list for column iCol, then
  154718. ** *pnList is set to zero before returning.
  154719. **
  154720. ** If parameter bZero is non-zero, then any part of the input list following
  154721. ** the end of the output list is zeroed before returning.
  154722. */
  154723. static void fts3ColumnFilter(
  154724. int iCol, /* Column to filter on */
  154725. int bZero, /* Zero out anything following *ppList */
  154726. char **ppList, /* IN/OUT: Pointer to position list */
  154727. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  154728. ){
  154729. char *pList = *ppList;
  154730. int nList = *pnList;
  154731. char *pEnd = &pList[nList];
  154732. int iCurrent = 0;
  154733. char *p = pList;
  154734. assert( iCol>=0 );
  154735. while( 1 ){
  154736. char c = 0;
  154737. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  154738. if( iCol==iCurrent ){
  154739. nList = (int)(p - pList);
  154740. break;
  154741. }
  154742. nList -= (int)(p - pList);
  154743. pList = p;
  154744. if( nList==0 ){
  154745. break;
  154746. }
  154747. p = &pList[1];
  154748. p += fts3GetVarint32(p, &iCurrent);
  154749. }
  154750. if( bZero && &pList[nList]!=pEnd ){
  154751. memset(&pList[nList], 0, pEnd - &pList[nList]);
  154752. }
  154753. *ppList = pList;
  154754. *pnList = nList;
  154755. }
  154756. /*
  154757. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  154758. ** existing data). Grow the buffer if required.
  154759. **
  154760. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  154761. ** trying to resize the buffer, return SQLITE_NOMEM.
  154762. */
  154763. static int fts3MsrBufferData(
  154764. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  154765. char *pList,
  154766. int nList
  154767. ){
  154768. if( nList>pMsr->nBuffer ){
  154769. char *pNew;
  154770. pMsr->nBuffer = nList*2;
  154771. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  154772. if( !pNew ) return SQLITE_NOMEM;
  154773. pMsr->aBuffer = pNew;
  154774. }
  154775. memcpy(pMsr->aBuffer, pList, nList);
  154776. return SQLITE_OK;
  154777. }
  154778. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  154779. Fts3Table *p, /* Virtual table handle */
  154780. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  154781. sqlite3_int64 *piDocid, /* OUT: Docid value */
  154782. char **paPoslist, /* OUT: Pointer to position list */
  154783. int *pnPoslist /* OUT: Size of position list in bytes */
  154784. ){
  154785. int nMerge = pMsr->nAdvance;
  154786. Fts3SegReader **apSegment = pMsr->apSegment;
  154787. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  154788. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  154789. );
  154790. if( nMerge==0 ){
  154791. *paPoslist = 0;
  154792. return SQLITE_OK;
  154793. }
  154794. while( 1 ){
  154795. Fts3SegReader *pSeg;
  154796. pSeg = pMsr->apSegment[0];
  154797. if( pSeg->pOffsetList==0 ){
  154798. *paPoslist = 0;
  154799. break;
  154800. }else{
  154801. int rc;
  154802. char *pList;
  154803. int nList;
  154804. int j;
  154805. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  154806. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  154807. j = 1;
  154808. while( rc==SQLITE_OK
  154809. && j<nMerge
  154810. && apSegment[j]->pOffsetList
  154811. && apSegment[j]->iDocid==iDocid
  154812. ){
  154813. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  154814. j++;
  154815. }
  154816. if( rc!=SQLITE_OK ) return rc;
  154817. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  154818. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  154819. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  154820. if( rc!=SQLITE_OK ) return rc;
  154821. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  154822. pList = pMsr->aBuffer;
  154823. }
  154824. if( pMsr->iColFilter>=0 ){
  154825. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  154826. }
  154827. if( nList>0 ){
  154828. *paPoslist = pList;
  154829. *piDocid = iDocid;
  154830. *pnPoslist = nList;
  154831. break;
  154832. }
  154833. }
  154834. }
  154835. return SQLITE_OK;
  154836. }
  154837. static int fts3SegReaderStart(
  154838. Fts3Table *p, /* Virtual table handle */
  154839. Fts3MultiSegReader *pCsr, /* Cursor object */
  154840. const char *zTerm, /* Term searched for (or NULL) */
  154841. int nTerm /* Length of zTerm in bytes */
  154842. ){
  154843. int i;
  154844. int nSeg = pCsr->nSegment;
  154845. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  154846. ** for, then advance each segment iterator until it points to a term of
  154847. ** equal or greater value than the specified term. This prevents many
  154848. ** unnecessary merge/sort operations for the case where single segment
  154849. ** b-tree leaf nodes contain more than one term.
  154850. */
  154851. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  154852. int res = 0;
  154853. Fts3SegReader *pSeg = pCsr->apSegment[i];
  154854. do {
  154855. int rc = fts3SegReaderNext(p, pSeg, 0);
  154856. if( rc!=SQLITE_OK ) return rc;
  154857. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  154858. if( pSeg->bLookup && res!=0 ){
  154859. fts3SegReaderSetEof(pSeg);
  154860. }
  154861. }
  154862. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  154863. return SQLITE_OK;
  154864. }
  154865. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  154866. Fts3Table *p, /* Virtual table handle */
  154867. Fts3MultiSegReader *pCsr, /* Cursor object */
  154868. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  154869. ){
  154870. pCsr->pFilter = pFilter;
  154871. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  154872. }
  154873. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  154874. Fts3Table *p, /* Virtual table handle */
  154875. Fts3MultiSegReader *pCsr, /* Cursor object */
  154876. int iCol, /* Column to match on. */
  154877. const char *zTerm, /* Term to iterate through a doclist for */
  154878. int nTerm /* Number of bytes in zTerm */
  154879. ){
  154880. int i;
  154881. int rc;
  154882. int nSegment = pCsr->nSegment;
  154883. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  154884. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  154885. );
  154886. assert( pCsr->pFilter==0 );
  154887. assert( zTerm && nTerm>0 );
  154888. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  154889. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  154890. if( rc!=SQLITE_OK ) return rc;
  154891. /* Determine how many of the segments actually point to zTerm/nTerm. */
  154892. for(i=0; i<nSegment; i++){
  154893. Fts3SegReader *pSeg = pCsr->apSegment[i];
  154894. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  154895. break;
  154896. }
  154897. }
  154898. pCsr->nAdvance = i;
  154899. /* Advance each of the segments to point to the first docid. */
  154900. for(i=0; i<pCsr->nAdvance; i++){
  154901. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  154902. if( rc!=SQLITE_OK ) return rc;
  154903. }
  154904. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  154905. assert( iCol<0 || iCol<p->nColumn );
  154906. pCsr->iColFilter = iCol;
  154907. return SQLITE_OK;
  154908. }
  154909. /*
  154910. ** This function is called on a MultiSegReader that has been started using
  154911. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  154912. ** have been made. Calling this function puts the MultiSegReader in such
  154913. ** a state that if the next two calls are:
  154914. **
  154915. ** sqlite3Fts3SegReaderStart()
  154916. ** sqlite3Fts3SegReaderStep()
  154917. **
  154918. ** then the entire doclist for the term is available in
  154919. ** MultiSegReader.aDoclist/nDoclist.
  154920. */
  154921. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  154922. int i; /* Used to iterate through segment-readers */
  154923. assert( pCsr->zTerm==0 );
  154924. assert( pCsr->nTerm==0 );
  154925. assert( pCsr->aDoclist==0 );
  154926. assert( pCsr->nDoclist==0 );
  154927. pCsr->nAdvance = 0;
  154928. pCsr->bRestart = 1;
  154929. for(i=0; i<pCsr->nSegment; i++){
  154930. pCsr->apSegment[i]->pOffsetList = 0;
  154931. pCsr->apSegment[i]->nOffsetList = 0;
  154932. pCsr->apSegment[i]->iDocid = 0;
  154933. }
  154934. return SQLITE_OK;
  154935. }
  154936. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  154937. Fts3Table *p, /* Virtual table handle */
  154938. Fts3MultiSegReader *pCsr /* Cursor object */
  154939. ){
  154940. int rc = SQLITE_OK;
  154941. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  154942. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  154943. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  154944. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  154945. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  154946. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  154947. Fts3SegReader **apSegment = pCsr->apSegment;
  154948. int nSegment = pCsr->nSegment;
  154949. Fts3SegFilter *pFilter = pCsr->pFilter;
  154950. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  154951. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  154952. );
  154953. if( pCsr->nSegment==0 ) return SQLITE_OK;
  154954. do {
  154955. int nMerge;
  154956. int i;
  154957. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  154958. ** forward. Then sort the list in order of current term again.
  154959. */
  154960. for(i=0; i<pCsr->nAdvance; i++){
  154961. Fts3SegReader *pSeg = apSegment[i];
  154962. if( pSeg->bLookup ){
  154963. fts3SegReaderSetEof(pSeg);
  154964. }else{
  154965. rc = fts3SegReaderNext(p, pSeg, 0);
  154966. }
  154967. if( rc!=SQLITE_OK ) return rc;
  154968. }
  154969. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  154970. pCsr->nAdvance = 0;
  154971. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  154972. assert( rc==SQLITE_OK );
  154973. if( apSegment[0]->aNode==0 ) break;
  154974. pCsr->nTerm = apSegment[0]->nTerm;
  154975. pCsr->zTerm = apSegment[0]->zTerm;
  154976. /* If this is a prefix-search, and if the term that apSegment[0] points
  154977. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  154978. ** required callbacks have been made. In this case exit early.
  154979. **
  154980. ** Similarly, if this is a search for an exact match, and the first term
  154981. ** of segment apSegment[0] is not a match, exit early.
  154982. */
  154983. if( pFilter->zTerm && !isScan ){
  154984. if( pCsr->nTerm<pFilter->nTerm
  154985. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  154986. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  154987. ){
  154988. break;
  154989. }
  154990. }
  154991. nMerge = 1;
  154992. while( nMerge<nSegment
  154993. && apSegment[nMerge]->aNode
  154994. && apSegment[nMerge]->nTerm==pCsr->nTerm
  154995. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  154996. ){
  154997. nMerge++;
  154998. }
  154999. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  155000. if( nMerge==1
  155001. && !isIgnoreEmpty
  155002. && !isFirst
  155003. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  155004. ){
  155005. pCsr->nDoclist = apSegment[0]->nDoclist;
  155006. if( fts3SegReaderIsPending(apSegment[0]) ){
  155007. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  155008. pCsr->aDoclist = pCsr->aBuffer;
  155009. }else{
  155010. pCsr->aDoclist = apSegment[0]->aDoclist;
  155011. }
  155012. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  155013. }else{
  155014. int nDoclist = 0; /* Size of doclist */
  155015. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  155016. /* The current term of the first nMerge entries in the array
  155017. ** of Fts3SegReader objects is the same. The doclists must be merged
  155018. ** and a single term returned with the merged doclist.
  155019. */
  155020. for(i=0; i<nMerge; i++){
  155021. fts3SegReaderFirstDocid(p, apSegment[i]);
  155022. }
  155023. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  155024. while( apSegment[0]->pOffsetList ){
  155025. int j; /* Number of segments that share a docid */
  155026. char *pList = 0;
  155027. int nList = 0;
  155028. int nByte;
  155029. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  155030. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  155031. j = 1;
  155032. while( j<nMerge
  155033. && apSegment[j]->pOffsetList
  155034. && apSegment[j]->iDocid==iDocid
  155035. ){
  155036. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  155037. j++;
  155038. }
  155039. if( isColFilter ){
  155040. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  155041. }
  155042. if( !isIgnoreEmpty || nList>0 ){
  155043. /* Calculate the 'docid' delta value to write into the merged
  155044. ** doclist. */
  155045. sqlite3_int64 iDelta;
  155046. if( p->bDescIdx && nDoclist>0 ){
  155047. iDelta = iPrev - iDocid;
  155048. }else{
  155049. iDelta = iDocid - iPrev;
  155050. }
  155051. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  155052. assert( nDoclist>0 || iDelta==iDocid );
  155053. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  155054. if( nDoclist+nByte>pCsr->nBuffer ){
  155055. char *aNew;
  155056. pCsr->nBuffer = (nDoclist+nByte)*2;
  155057. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  155058. if( !aNew ){
  155059. return SQLITE_NOMEM;
  155060. }
  155061. pCsr->aBuffer = aNew;
  155062. }
  155063. if( isFirst ){
  155064. char *a = &pCsr->aBuffer[nDoclist];
  155065. int nWrite;
  155066. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  155067. if( nWrite ){
  155068. iPrev = iDocid;
  155069. nDoclist += nWrite;
  155070. }
  155071. }else{
  155072. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  155073. iPrev = iDocid;
  155074. if( isRequirePos ){
  155075. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  155076. nDoclist += nList;
  155077. pCsr->aBuffer[nDoclist++] = '\0';
  155078. }
  155079. }
  155080. }
  155081. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  155082. }
  155083. if( nDoclist>0 ){
  155084. pCsr->aDoclist = pCsr->aBuffer;
  155085. pCsr->nDoclist = nDoclist;
  155086. rc = SQLITE_ROW;
  155087. }
  155088. }
  155089. pCsr->nAdvance = nMerge;
  155090. }while( rc==SQLITE_OK );
  155091. return rc;
  155092. }
  155093. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  155094. Fts3MultiSegReader *pCsr /* Cursor object */
  155095. ){
  155096. if( pCsr ){
  155097. int i;
  155098. for(i=0; i<pCsr->nSegment; i++){
  155099. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  155100. }
  155101. sqlite3_free(pCsr->apSegment);
  155102. sqlite3_free(pCsr->aBuffer);
  155103. pCsr->nSegment = 0;
  155104. pCsr->apSegment = 0;
  155105. pCsr->aBuffer = 0;
  155106. }
  155107. }
  155108. /*
  155109. ** Decode the "end_block" field, selected by column iCol of the SELECT
  155110. ** statement passed as the first argument.
  155111. **
  155112. ** The "end_block" field may contain either an integer, or a text field
  155113. ** containing the text representation of two non-negative integers separated
  155114. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  155115. ** to the integer value and *pnByte to zero before returning. In the second,
  155116. ** set *piEndBlock to the first value and *pnByte to the second.
  155117. */
  155118. static void fts3ReadEndBlockField(
  155119. sqlite3_stmt *pStmt,
  155120. int iCol,
  155121. i64 *piEndBlock,
  155122. i64 *pnByte
  155123. ){
  155124. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  155125. if( zText ){
  155126. int i;
  155127. int iMul = 1;
  155128. i64 iVal = 0;
  155129. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  155130. iVal = iVal*10 + (zText[i] - '0');
  155131. }
  155132. *piEndBlock = iVal;
  155133. while( zText[i]==' ' ) i++;
  155134. iVal = 0;
  155135. if( zText[i]=='-' ){
  155136. i++;
  155137. iMul = -1;
  155138. }
  155139. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  155140. iVal = iVal*10 + (zText[i] - '0');
  155141. }
  155142. *pnByte = (iVal * (i64)iMul);
  155143. }
  155144. }
  155145. /*
  155146. ** A segment of size nByte bytes has just been written to absolute level
  155147. ** iAbsLevel. Promote any segments that should be promoted as a result.
  155148. */
  155149. static int fts3PromoteSegments(
  155150. Fts3Table *p, /* FTS table handle */
  155151. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  155152. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  155153. ){
  155154. int rc = SQLITE_OK;
  155155. sqlite3_stmt *pRange;
  155156. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  155157. if( rc==SQLITE_OK ){
  155158. int bOk = 0;
  155159. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  155160. i64 nLimit = (nByte*3)/2;
  155161. /* Loop through all entries in the %_segdir table corresponding to
  155162. ** segments in this index on levels greater than iAbsLevel. If there is
  155163. ** at least one such segment, and it is possible to determine that all
  155164. ** such segments are smaller than nLimit bytes in size, they will be
  155165. ** promoted to level iAbsLevel. */
  155166. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  155167. sqlite3_bind_int64(pRange, 2, iLast);
  155168. while( SQLITE_ROW==sqlite3_step(pRange) ){
  155169. i64 nSize = 0, dummy;
  155170. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  155171. if( nSize<=0 || nSize>nLimit ){
  155172. /* If nSize==0, then the %_segdir.end_block field does not not
  155173. ** contain a size value. This happens if it was written by an
  155174. ** old version of FTS. In this case it is not possible to determine
  155175. ** the size of the segment, and so segment promotion does not
  155176. ** take place. */
  155177. bOk = 0;
  155178. break;
  155179. }
  155180. bOk = 1;
  155181. }
  155182. rc = sqlite3_reset(pRange);
  155183. if( bOk ){
  155184. int iIdx = 0;
  155185. sqlite3_stmt *pUpdate1 = 0;
  155186. sqlite3_stmt *pUpdate2 = 0;
  155187. if( rc==SQLITE_OK ){
  155188. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  155189. }
  155190. if( rc==SQLITE_OK ){
  155191. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  155192. }
  155193. if( rc==SQLITE_OK ){
  155194. /* Loop through all %_segdir entries for segments in this index with
  155195. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  155196. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  155197. ** oldest segment in the range, 1 for the next oldest, and so on.
  155198. **
  155199. ** In other words, move all segments being promoted to level -1,
  155200. ** setting the "idx" fields as appropriate to keep them in the same
  155201. ** order. The contents of level -1 (which is never used, except
  155202. ** transiently here), will be moved back to level iAbsLevel below. */
  155203. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  155204. while( SQLITE_ROW==sqlite3_step(pRange) ){
  155205. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  155206. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  155207. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  155208. sqlite3_step(pUpdate1);
  155209. rc = sqlite3_reset(pUpdate1);
  155210. if( rc!=SQLITE_OK ){
  155211. sqlite3_reset(pRange);
  155212. break;
  155213. }
  155214. }
  155215. }
  155216. if( rc==SQLITE_OK ){
  155217. rc = sqlite3_reset(pRange);
  155218. }
  155219. /* Move level -1 to level iAbsLevel */
  155220. if( rc==SQLITE_OK ){
  155221. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  155222. sqlite3_step(pUpdate2);
  155223. rc = sqlite3_reset(pUpdate2);
  155224. }
  155225. }
  155226. }
  155227. return rc;
  155228. }
  155229. /*
  155230. ** Merge all level iLevel segments in the database into a single
  155231. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  155232. ** single segment with a level equal to the numerically largest level
  155233. ** currently present in the database.
  155234. **
  155235. ** If this function is called with iLevel<0, but there is only one
  155236. ** segment in the database, SQLITE_DONE is returned immediately.
  155237. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  155238. ** an SQLite error code is returned.
  155239. */
  155240. static int fts3SegmentMerge(
  155241. Fts3Table *p,
  155242. int iLangid, /* Language id to merge */
  155243. int iIndex, /* Index in p->aIndex[] to merge */
  155244. int iLevel /* Level to merge */
  155245. ){
  155246. int rc; /* Return code */
  155247. int iIdx = 0; /* Index of new segment */
  155248. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  155249. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  155250. Fts3SegFilter filter; /* Segment term filter condition */
  155251. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  155252. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  155253. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  155254. assert( iLevel==FTS3_SEGCURSOR_ALL
  155255. || iLevel==FTS3_SEGCURSOR_PENDING
  155256. || iLevel>=0
  155257. );
  155258. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  155259. assert( iIndex>=0 && iIndex<p->nIndex );
  155260. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  155261. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  155262. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  155263. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  155264. if( rc!=SQLITE_OK ) goto finished;
  155265. }
  155266. if( iLevel==FTS3_SEGCURSOR_ALL ){
  155267. /* This call is to merge all segments in the database to a single
  155268. ** segment. The level of the new segment is equal to the numerically
  155269. ** greatest segment level currently present in the database for this
  155270. ** index. The idx of the new segment is always 0. */
  155271. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  155272. rc = SQLITE_DONE;
  155273. goto finished;
  155274. }
  155275. iNewLevel = iMaxLevel;
  155276. bIgnoreEmpty = 1;
  155277. }else{
  155278. /* This call is to merge all segments at level iLevel. find the next
  155279. ** available segment index at level iLevel+1. The call to
  155280. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  155281. ** a single iLevel+2 segment if necessary. */
  155282. assert( FTS3_SEGCURSOR_PENDING==-1 );
  155283. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  155284. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  155285. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  155286. }
  155287. if( rc!=SQLITE_OK ) goto finished;
  155288. assert( csr.nSegment>0 );
  155289. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  155290. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  155291. memset(&filter, 0, sizeof(Fts3SegFilter));
  155292. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  155293. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  155294. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  155295. while( SQLITE_OK==rc ){
  155296. rc = sqlite3Fts3SegReaderStep(p, &csr);
  155297. if( rc!=SQLITE_ROW ) break;
  155298. rc = fts3SegWriterAdd(p, &pWriter, 1,
  155299. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  155300. }
  155301. if( rc!=SQLITE_OK ) goto finished;
  155302. assert( pWriter || bIgnoreEmpty );
  155303. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  155304. rc = fts3DeleteSegdir(
  155305. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  155306. );
  155307. if( rc!=SQLITE_OK ) goto finished;
  155308. }
  155309. if( pWriter ){
  155310. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  155311. if( rc==SQLITE_OK ){
  155312. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  155313. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  155314. }
  155315. }
  155316. }
  155317. finished:
  155318. fts3SegWriterFree(pWriter);
  155319. sqlite3Fts3SegReaderFinish(&csr);
  155320. return rc;
  155321. }
  155322. /*
  155323. ** Flush the contents of pendingTerms to level 0 segments.
  155324. */
  155325. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  155326. int rc = SQLITE_OK;
  155327. int i;
  155328. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  155329. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  155330. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  155331. }
  155332. sqlite3Fts3PendingTermsClear(p);
  155333. /* Determine the auto-incr-merge setting if unknown. If enabled,
  155334. ** estimate the number of leaf blocks of content to be written
  155335. */
  155336. if( rc==SQLITE_OK && p->bHasStat
  155337. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  155338. ){
  155339. sqlite3_stmt *pStmt = 0;
  155340. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  155341. if( rc==SQLITE_OK ){
  155342. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  155343. rc = sqlite3_step(pStmt);
  155344. if( rc==SQLITE_ROW ){
  155345. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  155346. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  155347. }else if( rc==SQLITE_DONE ){
  155348. p->nAutoincrmerge = 0;
  155349. }
  155350. rc = sqlite3_reset(pStmt);
  155351. }
  155352. }
  155353. return rc;
  155354. }
  155355. /*
  155356. ** Encode N integers as varints into a blob.
  155357. */
  155358. static void fts3EncodeIntArray(
  155359. int N, /* The number of integers to encode */
  155360. u32 *a, /* The integer values */
  155361. char *zBuf, /* Write the BLOB here */
  155362. int *pNBuf /* Write number of bytes if zBuf[] used here */
  155363. ){
  155364. int i, j;
  155365. for(i=j=0; i<N; i++){
  155366. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  155367. }
  155368. *pNBuf = j;
  155369. }
  155370. /*
  155371. ** Decode a blob of varints into N integers
  155372. */
  155373. static void fts3DecodeIntArray(
  155374. int N, /* The number of integers to decode */
  155375. u32 *a, /* Write the integer values */
  155376. const char *zBuf, /* The BLOB containing the varints */
  155377. int nBuf /* size of the BLOB */
  155378. ){
  155379. int i, j;
  155380. UNUSED_PARAMETER(nBuf);
  155381. for(i=j=0; i<N; i++){
  155382. sqlite3_int64 x;
  155383. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  155384. assert(j<=nBuf);
  155385. a[i] = (u32)(x & 0xffffffff);
  155386. }
  155387. }
  155388. /*
  155389. ** Insert the sizes (in tokens) for each column of the document
  155390. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  155391. ** a blob of varints.
  155392. */
  155393. static void fts3InsertDocsize(
  155394. int *pRC, /* Result code */
  155395. Fts3Table *p, /* Table into which to insert */
  155396. u32 *aSz /* Sizes of each column, in tokens */
  155397. ){
  155398. char *pBlob; /* The BLOB encoding of the document size */
  155399. int nBlob; /* Number of bytes in the BLOB */
  155400. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  155401. int rc; /* Result code from subfunctions */
  155402. if( *pRC ) return;
  155403. pBlob = sqlite3_malloc( 10*p->nColumn );
  155404. if( pBlob==0 ){
  155405. *pRC = SQLITE_NOMEM;
  155406. return;
  155407. }
  155408. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  155409. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  155410. if( rc ){
  155411. sqlite3_free(pBlob);
  155412. *pRC = rc;
  155413. return;
  155414. }
  155415. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  155416. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  155417. sqlite3_step(pStmt);
  155418. *pRC = sqlite3_reset(pStmt);
  155419. }
  155420. /*
  155421. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  155422. ** where N is the number of user defined columns in the fts3 table plus
  155423. ** two. If nCol is the number of user defined columns, then values of the
  155424. ** varints are set as follows:
  155425. **
  155426. ** Varint 0: Total number of rows in the table.
  155427. **
  155428. ** Varint 1..nCol: For each column, the total number of tokens stored in
  155429. ** the column for all rows of the table.
  155430. **
  155431. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  155432. ** columns of all rows of the table.
  155433. **
  155434. */
  155435. static void fts3UpdateDocTotals(
  155436. int *pRC, /* The result code */
  155437. Fts3Table *p, /* Table being updated */
  155438. u32 *aSzIns, /* Size increases */
  155439. u32 *aSzDel, /* Size decreases */
  155440. int nChng /* Change in the number of documents */
  155441. ){
  155442. char *pBlob; /* Storage for BLOB written into %_stat */
  155443. int nBlob; /* Size of BLOB written into %_stat */
  155444. u32 *a; /* Array of integers that becomes the BLOB */
  155445. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  155446. int i; /* Loop counter */
  155447. int rc; /* Result code from subfunctions */
  155448. const int nStat = p->nColumn+2;
  155449. if( *pRC ) return;
  155450. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  155451. if( a==0 ){
  155452. *pRC = SQLITE_NOMEM;
  155453. return;
  155454. }
  155455. pBlob = (char*)&a[nStat];
  155456. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  155457. if( rc ){
  155458. sqlite3_free(a);
  155459. *pRC = rc;
  155460. return;
  155461. }
  155462. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  155463. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  155464. fts3DecodeIntArray(nStat, a,
  155465. sqlite3_column_blob(pStmt, 0),
  155466. sqlite3_column_bytes(pStmt, 0));
  155467. }else{
  155468. memset(a, 0, sizeof(u32)*(nStat) );
  155469. }
  155470. rc = sqlite3_reset(pStmt);
  155471. if( rc!=SQLITE_OK ){
  155472. sqlite3_free(a);
  155473. *pRC = rc;
  155474. return;
  155475. }
  155476. if( nChng<0 && a[0]<(u32)(-nChng) ){
  155477. a[0] = 0;
  155478. }else{
  155479. a[0] += nChng;
  155480. }
  155481. for(i=0; i<p->nColumn+1; i++){
  155482. u32 x = a[i+1];
  155483. if( x+aSzIns[i] < aSzDel[i] ){
  155484. x = 0;
  155485. }else{
  155486. x = x + aSzIns[i] - aSzDel[i];
  155487. }
  155488. a[i+1] = x;
  155489. }
  155490. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  155491. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  155492. if( rc ){
  155493. sqlite3_free(a);
  155494. *pRC = rc;
  155495. return;
  155496. }
  155497. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  155498. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  155499. sqlite3_step(pStmt);
  155500. *pRC = sqlite3_reset(pStmt);
  155501. sqlite3_bind_null(pStmt, 2);
  155502. sqlite3_free(a);
  155503. }
  155504. /*
  155505. ** Merge the entire database so that there is one segment for each
  155506. ** iIndex/iLangid combination.
  155507. */
  155508. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  155509. int bSeenDone = 0;
  155510. int rc;
  155511. sqlite3_stmt *pAllLangid = 0;
  155512. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  155513. if( rc==SQLITE_OK ){
  155514. int rc2;
  155515. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  155516. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  155517. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  155518. int i;
  155519. int iLangid = sqlite3_column_int(pAllLangid, 0);
  155520. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  155521. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  155522. if( rc==SQLITE_DONE ){
  155523. bSeenDone = 1;
  155524. rc = SQLITE_OK;
  155525. }
  155526. }
  155527. }
  155528. rc2 = sqlite3_reset(pAllLangid);
  155529. if( rc==SQLITE_OK ) rc = rc2;
  155530. }
  155531. sqlite3Fts3SegmentsClose(p);
  155532. sqlite3Fts3PendingTermsClear(p);
  155533. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  155534. }
  155535. /*
  155536. ** This function is called when the user executes the following statement:
  155537. **
  155538. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  155539. **
  155540. ** The entire FTS index is discarded and rebuilt. If the table is one
  155541. ** created using the content=xxx option, then the new index is based on
  155542. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  155543. ** on the contents of the %_content table.
  155544. */
  155545. static int fts3DoRebuild(Fts3Table *p){
  155546. int rc; /* Return Code */
  155547. rc = fts3DeleteAll(p, 0);
  155548. if( rc==SQLITE_OK ){
  155549. u32 *aSz = 0;
  155550. u32 *aSzIns = 0;
  155551. u32 *aSzDel = 0;
  155552. sqlite3_stmt *pStmt = 0;
  155553. int nEntry = 0;
  155554. /* Compose and prepare an SQL statement to loop through the content table */
  155555. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  155556. if( !zSql ){
  155557. rc = SQLITE_NOMEM;
  155558. }else{
  155559. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  155560. sqlite3_free(zSql);
  155561. }
  155562. if( rc==SQLITE_OK ){
  155563. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  155564. aSz = (u32 *)sqlite3_malloc(nByte);
  155565. if( aSz==0 ){
  155566. rc = SQLITE_NOMEM;
  155567. }else{
  155568. memset(aSz, 0, nByte);
  155569. aSzIns = &aSz[p->nColumn+1];
  155570. aSzDel = &aSzIns[p->nColumn+1];
  155571. }
  155572. }
  155573. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  155574. int iCol;
  155575. int iLangid = langidFromSelect(p, pStmt);
  155576. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  155577. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  155578. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  155579. if( p->abNotindexed[iCol]==0 ){
  155580. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  155581. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  155582. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  155583. }
  155584. }
  155585. if( p->bHasDocsize ){
  155586. fts3InsertDocsize(&rc, p, aSz);
  155587. }
  155588. if( rc!=SQLITE_OK ){
  155589. sqlite3_finalize(pStmt);
  155590. pStmt = 0;
  155591. }else{
  155592. nEntry++;
  155593. for(iCol=0; iCol<=p->nColumn; iCol++){
  155594. aSzIns[iCol] += aSz[iCol];
  155595. }
  155596. }
  155597. }
  155598. if( p->bFts4 ){
  155599. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  155600. }
  155601. sqlite3_free(aSz);
  155602. if( pStmt ){
  155603. int rc2 = sqlite3_finalize(pStmt);
  155604. if( rc==SQLITE_OK ){
  155605. rc = rc2;
  155606. }
  155607. }
  155608. }
  155609. return rc;
  155610. }
  155611. /*
  155612. ** This function opens a cursor used to read the input data for an
  155613. ** incremental merge operation. Specifically, it opens a cursor to scan
  155614. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  155615. ** level iAbsLevel.
  155616. */
  155617. static int fts3IncrmergeCsr(
  155618. Fts3Table *p, /* FTS3 table handle */
  155619. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  155620. int nSeg, /* Number of segments to merge */
  155621. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  155622. ){
  155623. int rc; /* Return Code */
  155624. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  155625. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  155626. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  155627. memset(pCsr, 0, sizeof(*pCsr));
  155628. nByte = sizeof(Fts3SegReader *) * nSeg;
  155629. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  155630. if( pCsr->apSegment==0 ){
  155631. rc = SQLITE_NOMEM;
  155632. }else{
  155633. memset(pCsr->apSegment, 0, nByte);
  155634. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  155635. }
  155636. if( rc==SQLITE_OK ){
  155637. int i;
  155638. int rc2;
  155639. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  155640. assert( pCsr->nSegment==0 );
  155641. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  155642. rc = sqlite3Fts3SegReaderNew(i, 0,
  155643. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  155644. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  155645. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  155646. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  155647. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  155648. &pCsr->apSegment[i]
  155649. );
  155650. pCsr->nSegment++;
  155651. }
  155652. rc2 = sqlite3_reset(pStmt);
  155653. if( rc==SQLITE_OK ) rc = rc2;
  155654. }
  155655. return rc;
  155656. }
  155657. typedef struct IncrmergeWriter IncrmergeWriter;
  155658. typedef struct NodeWriter NodeWriter;
  155659. typedef struct Blob Blob;
  155660. typedef struct NodeReader NodeReader;
  155661. /*
  155662. ** An instance of the following structure is used as a dynamic buffer
  155663. ** to build up nodes or other blobs of data in.
  155664. **
  155665. ** The function blobGrowBuffer() is used to extend the allocation.
  155666. */
  155667. struct Blob {
  155668. char *a; /* Pointer to allocation */
  155669. int n; /* Number of valid bytes of data in a[] */
  155670. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  155671. };
  155672. /*
  155673. ** This structure is used to build up buffers containing segment b-tree
  155674. ** nodes (blocks).
  155675. */
  155676. struct NodeWriter {
  155677. sqlite3_int64 iBlock; /* Current block id */
  155678. Blob key; /* Last key written to the current block */
  155679. Blob block; /* Current block image */
  155680. };
  155681. /*
  155682. ** An object of this type contains the state required to create or append
  155683. ** to an appendable b-tree segment.
  155684. */
  155685. struct IncrmergeWriter {
  155686. int nLeafEst; /* Space allocated for leaf blocks */
  155687. int nWork; /* Number of leaf pages flushed */
  155688. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  155689. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  155690. sqlite3_int64 iStart; /* Block number of first allocated block */
  155691. sqlite3_int64 iEnd; /* Block number of last allocated block */
  155692. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  155693. u8 bNoLeafData; /* If true, store 0 for segment size */
  155694. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  155695. };
  155696. /*
  155697. ** An object of the following type is used to read data from a single
  155698. ** FTS segment node. See the following functions:
  155699. **
  155700. ** nodeReaderInit()
  155701. ** nodeReaderNext()
  155702. ** nodeReaderRelease()
  155703. */
  155704. struct NodeReader {
  155705. const char *aNode;
  155706. int nNode;
  155707. int iOff; /* Current offset within aNode[] */
  155708. /* Output variables. Containing the current node entry. */
  155709. sqlite3_int64 iChild; /* Pointer to child node */
  155710. Blob term; /* Current term */
  155711. const char *aDoclist; /* Pointer to doclist */
  155712. int nDoclist; /* Size of doclist in bytes */
  155713. };
  155714. /*
  155715. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  155716. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  155717. ** bytes in size, extend (realloc) it to be so.
  155718. **
  155719. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  155720. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  155721. ** to reflect the new size of the pBlob->a[] buffer.
  155722. */
  155723. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  155724. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  155725. int nAlloc = nMin;
  155726. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  155727. if( a ){
  155728. pBlob->nAlloc = nAlloc;
  155729. pBlob->a = a;
  155730. }else{
  155731. *pRc = SQLITE_NOMEM;
  155732. }
  155733. }
  155734. }
  155735. /*
  155736. ** Attempt to advance the node-reader object passed as the first argument to
  155737. ** the next entry on the node.
  155738. **
  155739. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  155740. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  155741. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  155742. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  155743. ** variables for the new entry.
  155744. */
  155745. static int nodeReaderNext(NodeReader *p){
  155746. int bFirst = (p->term.n==0); /* True for first term on the node */
  155747. int nPrefix = 0; /* Bytes to copy from previous term */
  155748. int nSuffix = 0; /* Bytes to append to the prefix */
  155749. int rc = SQLITE_OK; /* Return code */
  155750. assert( p->aNode );
  155751. if( p->iChild && bFirst==0 ) p->iChild++;
  155752. if( p->iOff>=p->nNode ){
  155753. /* EOF */
  155754. p->aNode = 0;
  155755. }else{
  155756. if( bFirst==0 ){
  155757. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  155758. }
  155759. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  155760. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  155761. if( rc==SQLITE_OK ){
  155762. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  155763. p->term.n = nPrefix+nSuffix;
  155764. p->iOff += nSuffix;
  155765. if( p->iChild==0 ){
  155766. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  155767. p->aDoclist = &p->aNode[p->iOff];
  155768. p->iOff += p->nDoclist;
  155769. }
  155770. }
  155771. }
  155772. assert( p->iOff<=p->nNode );
  155773. return rc;
  155774. }
  155775. /*
  155776. ** Release all dynamic resources held by node-reader object *p.
  155777. */
  155778. static void nodeReaderRelease(NodeReader *p){
  155779. sqlite3_free(p->term.a);
  155780. }
  155781. /*
  155782. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  155783. **
  155784. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  155785. ** point to the first entry on the node (if any). Otherwise, an SQLite
  155786. ** error code is returned.
  155787. */
  155788. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  155789. memset(p, 0, sizeof(NodeReader));
  155790. p->aNode = aNode;
  155791. p->nNode = nNode;
  155792. /* Figure out if this is a leaf or an internal node. */
  155793. if( p->aNode[0] ){
  155794. /* An internal node. */
  155795. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  155796. }else{
  155797. p->iOff = 1;
  155798. }
  155799. return nodeReaderNext(p);
  155800. }
  155801. /*
  155802. ** This function is called while writing an FTS segment each time a leaf o
  155803. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  155804. ** to be greater than the largest key on the node just written, but smaller
  155805. ** than or equal to the first key that will be written to the next leaf
  155806. ** node.
  155807. **
  155808. ** The block id of the leaf node just written to disk may be found in
  155809. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  155810. */
  155811. static int fts3IncrmergePush(
  155812. Fts3Table *p, /* Fts3 table handle */
  155813. IncrmergeWriter *pWriter, /* Writer object */
  155814. const char *zTerm, /* Term to write to internal node */
  155815. int nTerm /* Bytes at zTerm */
  155816. ){
  155817. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  155818. int iLayer;
  155819. assert( nTerm>0 );
  155820. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  155821. sqlite3_int64 iNextPtr = 0;
  155822. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  155823. int rc = SQLITE_OK;
  155824. int nPrefix;
  155825. int nSuffix;
  155826. int nSpace;
  155827. /* Figure out how much space the key will consume if it is written to
  155828. ** the current node of layer iLayer. Due to the prefix compression,
  155829. ** the space required changes depending on which node the key is to
  155830. ** be added to. */
  155831. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  155832. nSuffix = nTerm - nPrefix;
  155833. nSpace = sqlite3Fts3VarintLen(nPrefix);
  155834. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  155835. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  155836. /* If the current node of layer iLayer contains zero keys, or if adding
  155837. ** the key to it will not cause it to grow to larger than nNodeSize
  155838. ** bytes in size, write the key here. */
  155839. Blob *pBlk = &pNode->block;
  155840. if( pBlk->n==0 ){
  155841. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  155842. if( rc==SQLITE_OK ){
  155843. pBlk->a[0] = (char)iLayer;
  155844. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  155845. }
  155846. }
  155847. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  155848. blobGrowBuffer(&pNode->key, nTerm, &rc);
  155849. if( rc==SQLITE_OK ){
  155850. if( pNode->key.n ){
  155851. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  155852. }
  155853. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  155854. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  155855. pBlk->n += nSuffix;
  155856. memcpy(pNode->key.a, zTerm, nTerm);
  155857. pNode->key.n = nTerm;
  155858. }
  155859. }else{
  155860. /* Otherwise, flush the current node of layer iLayer to disk.
  155861. ** Then allocate a new, empty sibling node. The key will be written
  155862. ** into the parent of this node. */
  155863. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  155864. assert( pNode->block.nAlloc>=p->nNodeSize );
  155865. pNode->block.a[0] = (char)iLayer;
  155866. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  155867. iNextPtr = pNode->iBlock;
  155868. pNode->iBlock++;
  155869. pNode->key.n = 0;
  155870. }
  155871. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  155872. iPtr = iNextPtr;
  155873. }
  155874. assert( 0 );
  155875. return 0;
  155876. }
  155877. /*
  155878. ** Append a term and (optionally) doclist to the FTS segment node currently
  155879. ** stored in blob *pNode. The node need not contain any terms, but the
  155880. ** header must be written before this function is called.
  155881. **
  155882. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  155883. ** followed by the left-hand-child varint for an internal node.
  155884. **
  155885. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  155886. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  155887. ** node, both aDoclist and nDoclist must be passed 0.
  155888. **
  155889. ** If the size of the value in blob pPrev is zero, then this is the first
  155890. ** term written to the node. Otherwise, pPrev contains a copy of the
  155891. ** previous term. Before this function returns, it is updated to contain a
  155892. ** copy of zTerm/nTerm.
  155893. **
  155894. ** It is assumed that the buffer associated with pNode is already large
  155895. ** enough to accommodate the new entry. The buffer associated with pPrev
  155896. ** is extended by this function if requrired.
  155897. **
  155898. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  155899. ** returned. Otherwise, SQLITE_OK.
  155900. */
  155901. static int fts3AppendToNode(
  155902. Blob *pNode, /* Current node image to append to */
  155903. Blob *pPrev, /* Buffer containing previous term written */
  155904. const char *zTerm, /* New term to write */
  155905. int nTerm, /* Size of zTerm in bytes */
  155906. const char *aDoclist, /* Doclist (or NULL) to write */
  155907. int nDoclist /* Size of aDoclist in bytes */
  155908. ){
  155909. int rc = SQLITE_OK; /* Return code */
  155910. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  155911. int nPrefix; /* Size of term prefix in bytes */
  155912. int nSuffix; /* Size of term suffix in bytes */
  155913. /* Node must have already been started. There must be a doclist for a
  155914. ** leaf node, and there must not be a doclist for an internal node. */
  155915. assert( pNode->n>0 );
  155916. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  155917. blobGrowBuffer(pPrev, nTerm, &rc);
  155918. if( rc!=SQLITE_OK ) return rc;
  155919. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  155920. nSuffix = nTerm - nPrefix;
  155921. memcpy(pPrev->a, zTerm, nTerm);
  155922. pPrev->n = nTerm;
  155923. if( bFirst==0 ){
  155924. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  155925. }
  155926. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  155927. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  155928. pNode->n += nSuffix;
  155929. if( aDoclist ){
  155930. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  155931. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  155932. pNode->n += nDoclist;
  155933. }
  155934. assert( pNode->n<=pNode->nAlloc );
  155935. return SQLITE_OK;
  155936. }
  155937. /*
  155938. ** Append the current term and doclist pointed to by cursor pCsr to the
  155939. ** appendable b-tree segment opened for writing by pWriter.
  155940. **
  155941. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  155942. */
  155943. static int fts3IncrmergeAppend(
  155944. Fts3Table *p, /* Fts3 table handle */
  155945. IncrmergeWriter *pWriter, /* Writer object */
  155946. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  155947. ){
  155948. const char *zTerm = pCsr->zTerm;
  155949. int nTerm = pCsr->nTerm;
  155950. const char *aDoclist = pCsr->aDoclist;
  155951. int nDoclist = pCsr->nDoclist;
  155952. int rc = SQLITE_OK; /* Return code */
  155953. int nSpace; /* Total space in bytes required on leaf */
  155954. int nPrefix; /* Size of prefix shared with previous term */
  155955. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  155956. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  155957. pLeaf = &pWriter->aNodeWriter[0];
  155958. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  155959. nSuffix = nTerm - nPrefix;
  155960. nSpace = sqlite3Fts3VarintLen(nPrefix);
  155961. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  155962. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  155963. /* If the current block is not empty, and if adding this term/doclist
  155964. ** to the current block would make it larger than Fts3Table.nNodeSize
  155965. ** bytes, write this block out to the database. */
  155966. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  155967. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  155968. pWriter->nWork++;
  155969. /* Add the current term to the parent node. The term added to the
  155970. ** parent must:
  155971. **
  155972. ** a) be greater than the largest term on the leaf node just written
  155973. ** to the database (still available in pLeaf->key), and
  155974. **
  155975. ** b) be less than or equal to the term about to be added to the new
  155976. ** leaf node (zTerm/nTerm).
  155977. **
  155978. ** In other words, it must be the prefix of zTerm 1 byte longer than
  155979. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  155980. */
  155981. if( rc==SQLITE_OK ){
  155982. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  155983. }
  155984. /* Advance to the next output block */
  155985. pLeaf->iBlock++;
  155986. pLeaf->key.n = 0;
  155987. pLeaf->block.n = 0;
  155988. nSuffix = nTerm;
  155989. nSpace = 1;
  155990. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  155991. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  155992. }
  155993. pWriter->nLeafData += nSpace;
  155994. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  155995. if( rc==SQLITE_OK ){
  155996. if( pLeaf->block.n==0 ){
  155997. pLeaf->block.n = 1;
  155998. pLeaf->block.a[0] = '\0';
  155999. }
  156000. rc = fts3AppendToNode(
  156001. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  156002. );
  156003. }
  156004. return rc;
  156005. }
  156006. /*
  156007. ** This function is called to release all dynamic resources held by the
  156008. ** merge-writer object pWriter, and if no error has occurred, to flush
  156009. ** all outstanding node buffers held by pWriter to disk.
  156010. **
  156011. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  156012. ** is made to write any data to disk. Instead, this function serves only
  156013. ** to release outstanding resources.
  156014. **
  156015. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  156016. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  156017. ** returning.
  156018. */
  156019. static void fts3IncrmergeRelease(
  156020. Fts3Table *p, /* FTS3 table handle */
  156021. IncrmergeWriter *pWriter, /* Merge-writer object */
  156022. int *pRc /* IN/OUT: Error code */
  156023. ){
  156024. int i; /* Used to iterate through non-root layers */
  156025. int iRoot; /* Index of root in pWriter->aNodeWriter */
  156026. NodeWriter *pRoot; /* NodeWriter for root node */
  156027. int rc = *pRc; /* Error code */
  156028. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  156029. ** root node. If the segment fits entirely on a single leaf node, iRoot
  156030. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  156031. ** will be 1. And so on. */
  156032. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  156033. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  156034. if( pNode->block.n>0 ) break;
  156035. assert( *pRc || pNode->block.nAlloc==0 );
  156036. assert( *pRc || pNode->key.nAlloc==0 );
  156037. sqlite3_free(pNode->block.a);
  156038. sqlite3_free(pNode->key.a);
  156039. }
  156040. /* Empty output segment. This is a no-op. */
  156041. if( iRoot<0 ) return;
  156042. /* The entire output segment fits on a single node. Normally, this means
  156043. ** the node would be stored as a blob in the "root" column of the %_segdir
  156044. ** table. However, this is not permitted in this case. The problem is that
  156045. ** space has already been reserved in the %_segments table, and so the
  156046. ** start_block and end_block fields of the %_segdir table must be populated.
  156047. ** And, by design or by accident, released versions of FTS cannot handle
  156048. ** segments that fit entirely on the root node with start_block!=0.
  156049. **
  156050. ** Instead, create a synthetic root node that contains nothing but a
  156051. ** pointer to the single content node. So that the segment consists of a
  156052. ** single leaf and a single interior (root) node.
  156053. **
  156054. ** Todo: Better might be to defer allocating space in the %_segments
  156055. ** table until we are sure it is needed.
  156056. */
  156057. if( iRoot==0 ){
  156058. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  156059. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  156060. if( rc==SQLITE_OK ){
  156061. pBlock->a[0] = 0x01;
  156062. pBlock->n = 1 + sqlite3Fts3PutVarint(
  156063. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  156064. );
  156065. }
  156066. iRoot = 1;
  156067. }
  156068. pRoot = &pWriter->aNodeWriter[iRoot];
  156069. /* Flush all currently outstanding nodes to disk. */
  156070. for(i=0; i<iRoot; i++){
  156071. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  156072. if( pNode->block.n>0 && rc==SQLITE_OK ){
  156073. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  156074. }
  156075. sqlite3_free(pNode->block.a);
  156076. sqlite3_free(pNode->key.a);
  156077. }
  156078. /* Write the %_segdir record. */
  156079. if( rc==SQLITE_OK ){
  156080. rc = fts3WriteSegdir(p,
  156081. pWriter->iAbsLevel+1, /* level */
  156082. pWriter->iIdx, /* idx */
  156083. pWriter->iStart, /* start_block */
  156084. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  156085. pWriter->iEnd, /* end_block */
  156086. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  156087. pRoot->block.a, pRoot->block.n /* root */
  156088. );
  156089. }
  156090. sqlite3_free(pRoot->block.a);
  156091. sqlite3_free(pRoot->key.a);
  156092. *pRc = rc;
  156093. }
  156094. /*
  156095. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  156096. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  156097. ** the other, it is considered to be smaller than the other.
  156098. **
  156099. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  156100. ** if it is greater.
  156101. */
  156102. static int fts3TermCmp(
  156103. const char *zLhs, int nLhs, /* LHS of comparison */
  156104. const char *zRhs, int nRhs /* RHS of comparison */
  156105. ){
  156106. int nCmp = MIN(nLhs, nRhs);
  156107. int res;
  156108. res = memcmp(zLhs, zRhs, nCmp);
  156109. if( res==0 ) res = nLhs - nRhs;
  156110. return res;
  156111. }
  156112. /*
  156113. ** Query to see if the entry in the %_segments table with blockid iEnd is
  156114. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  156115. ** returning. Otherwise, set *pbRes to 0.
  156116. **
  156117. ** Or, if an error occurs while querying the database, return an SQLite
  156118. ** error code. The final value of *pbRes is undefined in this case.
  156119. **
  156120. ** This is used to test if a segment is an "appendable" segment. If it
  156121. ** is, then a NULL entry has been inserted into the %_segments table
  156122. ** with blockid %_segdir.end_block.
  156123. */
  156124. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  156125. int bRes = 0; /* Result to set *pbRes to */
  156126. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  156127. int rc; /* Return code */
  156128. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  156129. if( rc==SQLITE_OK ){
  156130. sqlite3_bind_int64(pCheck, 1, iEnd);
  156131. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  156132. rc = sqlite3_reset(pCheck);
  156133. }
  156134. *pbRes = bRes;
  156135. return rc;
  156136. }
  156137. /*
  156138. ** This function is called when initializing an incremental-merge operation.
  156139. ** It checks if the existing segment with index value iIdx at absolute level
  156140. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  156141. ** merge-writer object *pWriter is initialized to write to it.
  156142. **
  156143. ** An existing segment can be appended to by an incremental merge if:
  156144. **
  156145. ** * It was initially created as an appendable segment (with all required
  156146. ** space pre-allocated), and
  156147. **
  156148. ** * The first key read from the input (arguments zKey and nKey) is
  156149. ** greater than the largest key currently stored in the potential
  156150. ** output segment.
  156151. */
  156152. static int fts3IncrmergeLoad(
  156153. Fts3Table *p, /* Fts3 table handle */
  156154. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  156155. int iIdx, /* Index of candidate output segment */
  156156. const char *zKey, /* First key to write */
  156157. int nKey, /* Number of bytes in nKey */
  156158. IncrmergeWriter *pWriter /* Populate this object */
  156159. ){
  156160. int rc; /* Return code */
  156161. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  156162. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  156163. if( rc==SQLITE_OK ){
  156164. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  156165. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  156166. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  156167. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  156168. int nRoot = 0; /* Size of aRoot[] in bytes */
  156169. int rc2; /* Return code from sqlite3_reset() */
  156170. int bAppendable = 0; /* Set to true if segment is appendable */
  156171. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  156172. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  156173. sqlite3_bind_int(pSelect, 2, iIdx);
  156174. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  156175. iStart = sqlite3_column_int64(pSelect, 1);
  156176. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  156177. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  156178. if( pWriter->nLeafData<0 ){
  156179. pWriter->nLeafData = pWriter->nLeafData * -1;
  156180. }
  156181. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  156182. nRoot = sqlite3_column_bytes(pSelect, 4);
  156183. aRoot = sqlite3_column_blob(pSelect, 4);
  156184. }else{
  156185. return sqlite3_reset(pSelect);
  156186. }
  156187. /* Check for the zero-length marker in the %_segments table */
  156188. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  156189. /* Check that zKey/nKey is larger than the largest key the candidate */
  156190. if( rc==SQLITE_OK && bAppendable ){
  156191. char *aLeaf = 0;
  156192. int nLeaf = 0;
  156193. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  156194. if( rc==SQLITE_OK ){
  156195. NodeReader reader;
  156196. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  156197. rc==SQLITE_OK && reader.aNode;
  156198. rc = nodeReaderNext(&reader)
  156199. ){
  156200. assert( reader.aNode );
  156201. }
  156202. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  156203. bAppendable = 0;
  156204. }
  156205. nodeReaderRelease(&reader);
  156206. }
  156207. sqlite3_free(aLeaf);
  156208. }
  156209. if( rc==SQLITE_OK && bAppendable ){
  156210. /* It is possible to append to this segment. Set up the IncrmergeWriter
  156211. ** object to do so. */
  156212. int i;
  156213. int nHeight = (int)aRoot[0];
  156214. NodeWriter *pNode;
  156215. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  156216. pWriter->iStart = iStart;
  156217. pWriter->iEnd = iEnd;
  156218. pWriter->iAbsLevel = iAbsLevel;
  156219. pWriter->iIdx = iIdx;
  156220. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  156221. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  156222. }
  156223. pNode = &pWriter->aNodeWriter[nHeight];
  156224. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  156225. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  156226. if( rc==SQLITE_OK ){
  156227. memcpy(pNode->block.a, aRoot, nRoot);
  156228. pNode->block.n = nRoot;
  156229. }
  156230. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  156231. NodeReader reader;
  156232. pNode = &pWriter->aNodeWriter[i];
  156233. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  156234. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  156235. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  156236. if( rc==SQLITE_OK ){
  156237. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  156238. pNode->key.n = reader.term.n;
  156239. if( i>0 ){
  156240. char *aBlock = 0;
  156241. int nBlock = 0;
  156242. pNode = &pWriter->aNodeWriter[i-1];
  156243. pNode->iBlock = reader.iChild;
  156244. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  156245. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  156246. if( rc==SQLITE_OK ){
  156247. memcpy(pNode->block.a, aBlock, nBlock);
  156248. pNode->block.n = nBlock;
  156249. }
  156250. sqlite3_free(aBlock);
  156251. }
  156252. }
  156253. nodeReaderRelease(&reader);
  156254. }
  156255. }
  156256. rc2 = sqlite3_reset(pSelect);
  156257. if( rc==SQLITE_OK ) rc = rc2;
  156258. }
  156259. return rc;
  156260. }
  156261. /*
  156262. ** Determine the largest segment index value that exists within absolute
  156263. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  156264. ** one before returning SQLITE_OK. Or, if there are no segments at all
  156265. ** within level iAbsLevel, set *piIdx to zero.
  156266. **
  156267. ** If an error occurs, return an SQLite error code. The final value of
  156268. ** *piIdx is undefined in this case.
  156269. */
  156270. static int fts3IncrmergeOutputIdx(
  156271. Fts3Table *p, /* FTS Table handle */
  156272. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  156273. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  156274. ){
  156275. int rc;
  156276. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  156277. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  156278. if( rc==SQLITE_OK ){
  156279. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  156280. sqlite3_step(pOutputIdx);
  156281. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  156282. rc = sqlite3_reset(pOutputIdx);
  156283. }
  156284. return rc;
  156285. }
  156286. /*
  156287. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  156288. ** with idx value iIdx.
  156289. **
  156290. ** In the %_segdir table, a segment is defined by the values in three
  156291. ** columns:
  156292. **
  156293. ** start_block
  156294. ** leaves_end_block
  156295. ** end_block
  156296. **
  156297. ** When an appendable segment is allocated, it is estimated that the
  156298. ** maximum number of leaf blocks that may be required is the sum of the
  156299. ** number of leaf blocks consumed by the input segments, plus the number
  156300. ** of input segments, multiplied by two. This value is stored in stack
  156301. ** variable nLeafEst.
  156302. **
  156303. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  156304. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  156305. ** array of leaf nodes starts at the first block allocated. The array
  156306. ** of interior nodes that are parents of the leaf nodes start at block
  156307. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  156308. **
  156309. ** In the actual code below, the value "16" is replaced with the
  156310. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  156311. */
  156312. static int fts3IncrmergeWriter(
  156313. Fts3Table *p, /* Fts3 table handle */
  156314. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  156315. int iIdx, /* Index of new output segment */
  156316. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  156317. IncrmergeWriter *pWriter /* Populate this object */
  156318. ){
  156319. int rc; /* Return Code */
  156320. int i; /* Iterator variable */
  156321. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  156322. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  156323. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  156324. /* Calculate nLeafEst. */
  156325. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  156326. if( rc==SQLITE_OK ){
  156327. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  156328. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  156329. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  156330. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  156331. }
  156332. rc = sqlite3_reset(pLeafEst);
  156333. }
  156334. if( rc!=SQLITE_OK ) return rc;
  156335. /* Calculate the first block to use in the output segment */
  156336. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  156337. if( rc==SQLITE_OK ){
  156338. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  156339. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  156340. pWriter->iEnd = pWriter->iStart - 1;
  156341. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  156342. }
  156343. rc = sqlite3_reset(pFirstBlock);
  156344. }
  156345. if( rc!=SQLITE_OK ) return rc;
  156346. /* Insert the marker in the %_segments table to make sure nobody tries
  156347. ** to steal the space just allocated. This is also used to identify
  156348. ** appendable segments. */
  156349. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  156350. if( rc!=SQLITE_OK ) return rc;
  156351. pWriter->iAbsLevel = iAbsLevel;
  156352. pWriter->nLeafEst = nLeafEst;
  156353. pWriter->iIdx = iIdx;
  156354. /* Set up the array of NodeWriter objects */
  156355. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  156356. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  156357. }
  156358. return SQLITE_OK;
  156359. }
  156360. /*
  156361. ** Remove an entry from the %_segdir table. This involves running the
  156362. ** following two statements:
  156363. **
  156364. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  156365. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  156366. **
  156367. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  156368. ** statement ensures that the remaining segments have contiguously allocated
  156369. ** idx values.
  156370. */
  156371. static int fts3RemoveSegdirEntry(
  156372. Fts3Table *p, /* FTS3 table handle */
  156373. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  156374. int iIdx /* Index of %_segdir entry to delete */
  156375. ){
  156376. int rc; /* Return code */
  156377. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  156378. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  156379. if( rc==SQLITE_OK ){
  156380. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  156381. sqlite3_bind_int(pDelete, 2, iIdx);
  156382. sqlite3_step(pDelete);
  156383. rc = sqlite3_reset(pDelete);
  156384. }
  156385. return rc;
  156386. }
  156387. /*
  156388. ** One or more segments have just been removed from absolute level iAbsLevel.
  156389. ** Update the 'idx' values of the remaining segments in the level so that
  156390. ** the idx values are a contiguous sequence starting from 0.
  156391. */
  156392. static int fts3RepackSegdirLevel(
  156393. Fts3Table *p, /* FTS3 table handle */
  156394. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  156395. ){
  156396. int rc; /* Return code */
  156397. int *aIdx = 0; /* Array of remaining idx values */
  156398. int nIdx = 0; /* Valid entries in aIdx[] */
  156399. int nAlloc = 0; /* Allocated size of aIdx[] */
  156400. int i; /* Iterator variable */
  156401. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  156402. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  156403. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  156404. if( rc==SQLITE_OK ){
  156405. int rc2;
  156406. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  156407. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  156408. if( nIdx>=nAlloc ){
  156409. int *aNew;
  156410. nAlloc += 16;
  156411. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  156412. if( !aNew ){
  156413. rc = SQLITE_NOMEM;
  156414. break;
  156415. }
  156416. aIdx = aNew;
  156417. }
  156418. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  156419. }
  156420. rc2 = sqlite3_reset(pSelect);
  156421. if( rc==SQLITE_OK ) rc = rc2;
  156422. }
  156423. if( rc==SQLITE_OK ){
  156424. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  156425. }
  156426. if( rc==SQLITE_OK ){
  156427. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  156428. }
  156429. assert( p->bIgnoreSavepoint==0 );
  156430. p->bIgnoreSavepoint = 1;
  156431. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  156432. if( aIdx[i]!=i ){
  156433. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  156434. sqlite3_bind_int(pUpdate, 1, i);
  156435. sqlite3_step(pUpdate);
  156436. rc = sqlite3_reset(pUpdate);
  156437. }
  156438. }
  156439. p->bIgnoreSavepoint = 0;
  156440. sqlite3_free(aIdx);
  156441. return rc;
  156442. }
  156443. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  156444. pNode->a[0] = (char)iHeight;
  156445. if( iChild ){
  156446. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  156447. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  156448. }else{
  156449. assert( pNode->nAlloc>=1 );
  156450. pNode->n = 1;
  156451. }
  156452. }
  156453. /*
  156454. ** The first two arguments are a pointer to and the size of a segment b-tree
  156455. ** node. The node may be a leaf or an internal node.
  156456. **
  156457. ** This function creates a new node image in blob object *pNew by copying
  156458. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  156459. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  156460. */
  156461. static int fts3TruncateNode(
  156462. const char *aNode, /* Current node image */
  156463. int nNode, /* Size of aNode in bytes */
  156464. Blob *pNew, /* OUT: Write new node image here */
  156465. const char *zTerm, /* Omit all terms smaller than this */
  156466. int nTerm, /* Size of zTerm in bytes */
  156467. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  156468. ){
  156469. NodeReader reader; /* Reader object */
  156470. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  156471. int rc = SQLITE_OK; /* Return code */
  156472. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  156473. /* Allocate required output space */
  156474. blobGrowBuffer(pNew, nNode, &rc);
  156475. if( rc!=SQLITE_OK ) return rc;
  156476. pNew->n = 0;
  156477. /* Populate new node buffer */
  156478. for(rc = nodeReaderInit(&reader, aNode, nNode);
  156479. rc==SQLITE_OK && reader.aNode;
  156480. rc = nodeReaderNext(&reader)
  156481. ){
  156482. if( pNew->n==0 ){
  156483. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  156484. if( res<0 || (bLeaf==0 && res==0) ) continue;
  156485. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  156486. *piBlock = reader.iChild;
  156487. }
  156488. rc = fts3AppendToNode(
  156489. pNew, &prev, reader.term.a, reader.term.n,
  156490. reader.aDoclist, reader.nDoclist
  156491. );
  156492. if( rc!=SQLITE_OK ) break;
  156493. }
  156494. if( pNew->n==0 ){
  156495. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  156496. *piBlock = reader.iChild;
  156497. }
  156498. assert( pNew->n<=pNew->nAlloc );
  156499. nodeReaderRelease(&reader);
  156500. sqlite3_free(prev.a);
  156501. return rc;
  156502. }
  156503. /*
  156504. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  156505. ** level iAbsLevel. This may involve deleting entries from the %_segments
  156506. ** table, and modifying existing entries in both the %_segments and %_segdir
  156507. ** tables.
  156508. **
  156509. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  156510. ** SQLite error code otherwise.
  156511. */
  156512. static int fts3TruncateSegment(
  156513. Fts3Table *p, /* FTS3 table handle */
  156514. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  156515. int iIdx, /* Index within level of segment to modify */
  156516. const char *zTerm, /* Remove terms smaller than this */
  156517. int nTerm /* Number of bytes in buffer zTerm */
  156518. ){
  156519. int rc = SQLITE_OK; /* Return code */
  156520. Blob root = {0,0,0}; /* New root page image */
  156521. Blob block = {0,0,0}; /* Buffer used for any other block */
  156522. sqlite3_int64 iBlock = 0; /* Block id */
  156523. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  156524. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  156525. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  156526. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  156527. if( rc==SQLITE_OK ){
  156528. int rc2; /* sqlite3_reset() return code */
  156529. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  156530. sqlite3_bind_int(pFetch, 2, iIdx);
  156531. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  156532. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  156533. int nRoot = sqlite3_column_bytes(pFetch, 4);
  156534. iOldStart = sqlite3_column_int64(pFetch, 1);
  156535. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  156536. }
  156537. rc2 = sqlite3_reset(pFetch);
  156538. if( rc==SQLITE_OK ) rc = rc2;
  156539. }
  156540. while( rc==SQLITE_OK && iBlock ){
  156541. char *aBlock = 0;
  156542. int nBlock = 0;
  156543. iNewStart = iBlock;
  156544. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  156545. if( rc==SQLITE_OK ){
  156546. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  156547. }
  156548. if( rc==SQLITE_OK ){
  156549. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  156550. }
  156551. sqlite3_free(aBlock);
  156552. }
  156553. /* Variable iNewStart now contains the first valid leaf node. */
  156554. if( rc==SQLITE_OK && iNewStart ){
  156555. sqlite3_stmt *pDel = 0;
  156556. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  156557. if( rc==SQLITE_OK ){
  156558. sqlite3_bind_int64(pDel, 1, iOldStart);
  156559. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  156560. sqlite3_step(pDel);
  156561. rc = sqlite3_reset(pDel);
  156562. }
  156563. }
  156564. if( rc==SQLITE_OK ){
  156565. sqlite3_stmt *pChomp = 0;
  156566. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  156567. if( rc==SQLITE_OK ){
  156568. sqlite3_bind_int64(pChomp, 1, iNewStart);
  156569. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  156570. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  156571. sqlite3_bind_int(pChomp, 4, iIdx);
  156572. sqlite3_step(pChomp);
  156573. rc = sqlite3_reset(pChomp);
  156574. sqlite3_bind_null(pChomp, 2);
  156575. }
  156576. }
  156577. sqlite3_free(root.a);
  156578. sqlite3_free(block.a);
  156579. return rc;
  156580. }
  156581. /*
  156582. ** This function is called after an incrmental-merge operation has run to
  156583. ** merge (or partially merge) two or more segments from absolute level
  156584. ** iAbsLevel.
  156585. **
  156586. ** Each input segment is either removed from the db completely (if all of
  156587. ** its data was copied to the output segment by the incrmerge operation)
  156588. ** or modified in place so that it no longer contains those entries that
  156589. ** have been duplicated in the output segment.
  156590. */
  156591. static int fts3IncrmergeChomp(
  156592. Fts3Table *p, /* FTS table handle */
  156593. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  156594. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  156595. int *pnRem /* Number of segments not deleted */
  156596. ){
  156597. int i;
  156598. int nRem = 0;
  156599. int rc = SQLITE_OK;
  156600. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  156601. Fts3SegReader *pSeg = 0;
  156602. int j;
  156603. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  156604. ** somewhere in the pCsr->apSegment[] array. */
  156605. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  156606. pSeg = pCsr->apSegment[j];
  156607. if( pSeg->iIdx==i ) break;
  156608. }
  156609. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  156610. if( pSeg->aNode==0 ){
  156611. /* Seg-reader is at EOF. Remove the entire input segment. */
  156612. rc = fts3DeleteSegment(p, pSeg);
  156613. if( rc==SQLITE_OK ){
  156614. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  156615. }
  156616. *pnRem = 0;
  156617. }else{
  156618. /* The incremental merge did not copy all the data from this
  156619. ** segment to the upper level. The segment is modified in place
  156620. ** so that it contains no keys smaller than zTerm/nTerm. */
  156621. const char *zTerm = pSeg->zTerm;
  156622. int nTerm = pSeg->nTerm;
  156623. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  156624. nRem++;
  156625. }
  156626. }
  156627. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  156628. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  156629. }
  156630. *pnRem = nRem;
  156631. return rc;
  156632. }
  156633. /*
  156634. ** Store an incr-merge hint in the database.
  156635. */
  156636. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  156637. sqlite3_stmt *pReplace = 0;
  156638. int rc; /* Return code */
  156639. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  156640. if( rc==SQLITE_OK ){
  156641. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  156642. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  156643. sqlite3_step(pReplace);
  156644. rc = sqlite3_reset(pReplace);
  156645. sqlite3_bind_null(pReplace, 2);
  156646. }
  156647. return rc;
  156648. }
  156649. /*
  156650. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  156651. ** exists, is stored in the rowid==1 row of the %_stat table.
  156652. **
  156653. ** If successful, populate blob *pHint with the value read from the %_stat
  156654. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  156655. ** SQLite error code.
  156656. */
  156657. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  156658. sqlite3_stmt *pSelect = 0;
  156659. int rc;
  156660. pHint->n = 0;
  156661. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  156662. if( rc==SQLITE_OK ){
  156663. int rc2;
  156664. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  156665. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  156666. const char *aHint = sqlite3_column_blob(pSelect, 0);
  156667. int nHint = sqlite3_column_bytes(pSelect, 0);
  156668. if( aHint ){
  156669. blobGrowBuffer(pHint, nHint, &rc);
  156670. if( rc==SQLITE_OK ){
  156671. memcpy(pHint->a, aHint, nHint);
  156672. pHint->n = nHint;
  156673. }
  156674. }
  156675. }
  156676. rc2 = sqlite3_reset(pSelect);
  156677. if( rc==SQLITE_OK ) rc = rc2;
  156678. }
  156679. return rc;
  156680. }
  156681. /*
  156682. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  156683. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  156684. ** consists of two varints, the absolute level number of the input segments
  156685. ** and the number of input segments.
  156686. **
  156687. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  156688. ** set *pRc to an SQLite error code before returning.
  156689. */
  156690. static void fts3IncrmergeHintPush(
  156691. Blob *pHint, /* Hint blob to append to */
  156692. i64 iAbsLevel, /* First varint to store in hint */
  156693. int nInput, /* Second varint to store in hint */
  156694. int *pRc /* IN/OUT: Error code */
  156695. ){
  156696. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  156697. if( *pRc==SQLITE_OK ){
  156698. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  156699. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  156700. }
  156701. }
  156702. /*
  156703. ** Read the last entry (most recently pushed) from the hint blob *pHint
  156704. ** and then remove the entry. Write the two values read to *piAbsLevel and
  156705. ** *pnInput before returning.
  156706. **
  156707. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  156708. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  156709. */
  156710. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  156711. const int nHint = pHint->n;
  156712. int i;
  156713. i = pHint->n-2;
  156714. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  156715. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  156716. pHint->n = i;
  156717. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  156718. i += fts3GetVarint32(&pHint->a[i], pnInput);
  156719. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  156720. return SQLITE_OK;
  156721. }
  156722. /*
  156723. ** Attempt an incremental merge that writes nMerge leaf blocks.
  156724. **
  156725. ** Incremental merges happen nMin segments at a time. The segments
  156726. ** to be merged are the nMin oldest segments (the ones with the smallest
  156727. ** values for the _segdir.idx field) in the highest level that contains
  156728. ** at least nMin segments. Multiple merges might occur in an attempt to
  156729. ** write the quota of nMerge leaf blocks.
  156730. */
  156731. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  156732. int rc; /* Return code */
  156733. int nRem = nMerge; /* Number of leaf pages yet to be written */
  156734. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  156735. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  156736. IncrmergeWriter *pWriter; /* Writer object */
  156737. int nSeg = 0; /* Number of input segments */
  156738. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  156739. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  156740. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  156741. /* Allocate space for the cursor, filter and writer objects */
  156742. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  156743. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  156744. if( !pWriter ) return SQLITE_NOMEM;
  156745. pFilter = (Fts3SegFilter *)&pWriter[1];
  156746. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  156747. rc = fts3IncrmergeHintLoad(p, &hint);
  156748. while( rc==SQLITE_OK && nRem>0 ){
  156749. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  156750. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  156751. int bUseHint = 0; /* True if attempting to append */
  156752. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  156753. /* Search the %_segdir table for the absolute level with the smallest
  156754. ** relative level number that contains at least nMin segments, if any.
  156755. ** If one is found, set iAbsLevel to the absolute level number and
  156756. ** nSeg to nMin. If no level with at least nMin segments can be found,
  156757. ** set nSeg to -1.
  156758. */
  156759. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  156760. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  156761. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  156762. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  156763. nSeg = sqlite3_column_int(pFindLevel, 1);
  156764. assert( nSeg>=2 );
  156765. }else{
  156766. nSeg = -1;
  156767. }
  156768. rc = sqlite3_reset(pFindLevel);
  156769. /* If the hint read from the %_stat table is not empty, check if the
  156770. ** last entry in it specifies a relative level smaller than or equal
  156771. ** to the level identified by the block above (if any). If so, this
  156772. ** iteration of the loop will work on merging at the hinted level.
  156773. */
  156774. if( rc==SQLITE_OK && hint.n ){
  156775. int nHint = hint.n;
  156776. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  156777. int nHintSeg = 0; /* Hint number of segments */
  156778. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  156779. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  156780. iAbsLevel = iHintAbsLevel;
  156781. nSeg = nHintSeg;
  156782. bUseHint = 1;
  156783. bDirtyHint = 1;
  156784. }else{
  156785. /* This undoes the effect of the HintPop() above - so that no entry
  156786. ** is removed from the hint blob. */
  156787. hint.n = nHint;
  156788. }
  156789. }
  156790. /* If nSeg is less that zero, then there is no level with at least
  156791. ** nMin segments and no hint in the %_stat table. No work to do.
  156792. ** Exit early in this case. */
  156793. if( nSeg<0 ) break;
  156794. /* Open a cursor to iterate through the contents of the oldest nSeg
  156795. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  156796. ** the 'hint' parameters, it is possible that there are less than nSeg
  156797. ** segments available in level iAbsLevel. In this case, no work is
  156798. ** done on iAbsLevel - fall through to the next iteration of the loop
  156799. ** to start work on some other level. */
  156800. memset(pWriter, 0, nAlloc);
  156801. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  156802. if( rc==SQLITE_OK ){
  156803. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  156804. assert( bUseHint==1 || bUseHint==0 );
  156805. if( iIdx==0 || (bUseHint && iIdx==1) ){
  156806. int bIgnore = 0;
  156807. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  156808. if( bIgnore ){
  156809. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  156810. }
  156811. }
  156812. }
  156813. if( rc==SQLITE_OK ){
  156814. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  156815. }
  156816. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  156817. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  156818. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  156819. ){
  156820. if( bUseHint && iIdx>0 ){
  156821. const char *zKey = pCsr->zTerm;
  156822. int nKey = pCsr->nTerm;
  156823. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  156824. }else{
  156825. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  156826. }
  156827. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  156828. fts3LogMerge(nSeg, iAbsLevel);
  156829. do {
  156830. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  156831. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  156832. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  156833. }while( rc==SQLITE_ROW );
  156834. /* Update or delete the input segments */
  156835. if( rc==SQLITE_OK ){
  156836. nRem -= (1 + pWriter->nWork);
  156837. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  156838. if( nSeg!=0 ){
  156839. bDirtyHint = 1;
  156840. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  156841. }
  156842. }
  156843. }
  156844. if( nSeg!=0 ){
  156845. pWriter->nLeafData = pWriter->nLeafData * -1;
  156846. }
  156847. fts3IncrmergeRelease(p, pWriter, &rc);
  156848. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  156849. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  156850. }
  156851. }
  156852. sqlite3Fts3SegReaderFinish(pCsr);
  156853. }
  156854. /* Write the hint values into the %_stat table for the next incr-merger */
  156855. if( bDirtyHint && rc==SQLITE_OK ){
  156856. rc = fts3IncrmergeHintStore(p, &hint);
  156857. }
  156858. sqlite3_free(pWriter);
  156859. sqlite3_free(hint.a);
  156860. return rc;
  156861. }
  156862. /*
  156863. ** Convert the text beginning at *pz into an integer and return
  156864. ** its value. Advance *pz to point to the first character past
  156865. ** the integer.
  156866. **
  156867. ** This function used for parameters to merge= and incrmerge=
  156868. ** commands.
  156869. */
  156870. static int fts3Getint(const char **pz){
  156871. const char *z = *pz;
  156872. int i = 0;
  156873. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  156874. *pz = z;
  156875. return i;
  156876. }
  156877. /*
  156878. ** Process statements of the form:
  156879. **
  156880. ** INSERT INTO table(table) VALUES('merge=A,B');
  156881. **
  156882. ** A and B are integers that decode to be the number of leaf pages
  156883. ** written for the merge, and the minimum number of segments on a level
  156884. ** before it will be selected for a merge, respectively.
  156885. */
  156886. static int fts3DoIncrmerge(
  156887. Fts3Table *p, /* FTS3 table handle */
  156888. const char *zParam /* Nul-terminated string containing "A,B" */
  156889. ){
  156890. int rc;
  156891. int nMin = (FTS3_MERGE_COUNT / 2);
  156892. int nMerge = 0;
  156893. const char *z = zParam;
  156894. /* Read the first integer value */
  156895. nMerge = fts3Getint(&z);
  156896. /* If the first integer value is followed by a ',', read the second
  156897. ** integer value. */
  156898. if( z[0]==',' && z[1]!='\0' ){
  156899. z++;
  156900. nMin = fts3Getint(&z);
  156901. }
  156902. if( z[0]!='\0' || nMin<2 ){
  156903. rc = SQLITE_ERROR;
  156904. }else{
  156905. rc = SQLITE_OK;
  156906. if( !p->bHasStat ){
  156907. assert( p->bFts4==0 );
  156908. sqlite3Fts3CreateStatTable(&rc, p);
  156909. }
  156910. if( rc==SQLITE_OK ){
  156911. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  156912. }
  156913. sqlite3Fts3SegmentsClose(p);
  156914. }
  156915. return rc;
  156916. }
  156917. /*
  156918. ** Process statements of the form:
  156919. **
  156920. ** INSERT INTO table(table) VALUES('automerge=X');
  156921. **
  156922. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  156923. ** turn it on. The setting is persistent.
  156924. */
  156925. static int fts3DoAutoincrmerge(
  156926. Fts3Table *p, /* FTS3 table handle */
  156927. const char *zParam /* Nul-terminated string containing boolean */
  156928. ){
  156929. int rc = SQLITE_OK;
  156930. sqlite3_stmt *pStmt = 0;
  156931. p->nAutoincrmerge = fts3Getint(&zParam);
  156932. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  156933. p->nAutoincrmerge = 8;
  156934. }
  156935. if( !p->bHasStat ){
  156936. assert( p->bFts4==0 );
  156937. sqlite3Fts3CreateStatTable(&rc, p);
  156938. if( rc ) return rc;
  156939. }
  156940. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  156941. if( rc ) return rc;
  156942. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  156943. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  156944. sqlite3_step(pStmt);
  156945. rc = sqlite3_reset(pStmt);
  156946. return rc;
  156947. }
  156948. /*
  156949. ** Return a 64-bit checksum for the FTS index entry specified by the
  156950. ** arguments to this function.
  156951. */
  156952. static u64 fts3ChecksumEntry(
  156953. const char *zTerm, /* Pointer to buffer containing term */
  156954. int nTerm, /* Size of zTerm in bytes */
  156955. int iLangid, /* Language id for current row */
  156956. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  156957. i64 iDocid, /* Docid for current row. */
  156958. int iCol, /* Column number */
  156959. int iPos /* Position */
  156960. ){
  156961. int i;
  156962. u64 ret = (u64)iDocid;
  156963. ret += (ret<<3) + iLangid;
  156964. ret += (ret<<3) + iIndex;
  156965. ret += (ret<<3) + iCol;
  156966. ret += (ret<<3) + iPos;
  156967. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  156968. return ret;
  156969. }
  156970. /*
  156971. ** Return a checksum of all entries in the FTS index that correspond to
  156972. ** language id iLangid. The checksum is calculated by XORing the checksums
  156973. ** of each individual entry (see fts3ChecksumEntry()) together.
  156974. **
  156975. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  156976. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  156977. ** return value is undefined in this case.
  156978. */
  156979. static u64 fts3ChecksumIndex(
  156980. Fts3Table *p, /* FTS3 table handle */
  156981. int iLangid, /* Language id to return cksum for */
  156982. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  156983. int *pRc /* OUT: Return code */
  156984. ){
  156985. Fts3SegFilter filter;
  156986. Fts3MultiSegReader csr;
  156987. int rc;
  156988. u64 cksum = 0;
  156989. assert( *pRc==SQLITE_OK );
  156990. memset(&filter, 0, sizeof(filter));
  156991. memset(&csr, 0, sizeof(csr));
  156992. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  156993. filter.flags |= FTS3_SEGMENT_SCAN;
  156994. rc = sqlite3Fts3SegReaderCursor(
  156995. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  156996. );
  156997. if( rc==SQLITE_OK ){
  156998. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  156999. }
  157000. if( rc==SQLITE_OK ){
  157001. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  157002. char *pCsr = csr.aDoclist;
  157003. char *pEnd = &pCsr[csr.nDoclist];
  157004. i64 iDocid = 0;
  157005. i64 iCol = 0;
  157006. i64 iPos = 0;
  157007. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  157008. while( pCsr<pEnd ){
  157009. i64 iVal = 0;
  157010. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  157011. if( pCsr<pEnd ){
  157012. if( iVal==0 || iVal==1 ){
  157013. iCol = 0;
  157014. iPos = 0;
  157015. if( iVal ){
  157016. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  157017. }else{
  157018. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  157019. iDocid += iVal;
  157020. }
  157021. }else{
  157022. iPos += (iVal - 2);
  157023. cksum = cksum ^ fts3ChecksumEntry(
  157024. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  157025. (int)iCol, (int)iPos
  157026. );
  157027. }
  157028. }
  157029. }
  157030. }
  157031. }
  157032. sqlite3Fts3SegReaderFinish(&csr);
  157033. *pRc = rc;
  157034. return cksum;
  157035. }
  157036. /*
  157037. ** Check if the contents of the FTS index match the current contents of the
  157038. ** content table. If no error occurs and the contents do match, set *pbOk
  157039. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  157040. ** to false before returning.
  157041. **
  157042. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  157043. ** code. The final value of *pbOk is undefined in this case.
  157044. */
  157045. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  157046. int rc = SQLITE_OK; /* Return code */
  157047. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  157048. u64 cksum2 = 0; /* Checksum based on %_content contents */
  157049. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  157050. /* This block calculates the checksum according to the FTS index. */
  157051. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  157052. if( rc==SQLITE_OK ){
  157053. int rc2;
  157054. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  157055. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  157056. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  157057. int iLangid = sqlite3_column_int(pAllLangid, 0);
  157058. int i;
  157059. for(i=0; i<p->nIndex; i++){
  157060. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  157061. }
  157062. }
  157063. rc2 = sqlite3_reset(pAllLangid);
  157064. if( rc==SQLITE_OK ) rc = rc2;
  157065. }
  157066. /* This block calculates the checksum according to the %_content table */
  157067. if( rc==SQLITE_OK ){
  157068. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  157069. sqlite3_stmt *pStmt = 0;
  157070. char *zSql;
  157071. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  157072. if( !zSql ){
  157073. rc = SQLITE_NOMEM;
  157074. }else{
  157075. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  157076. sqlite3_free(zSql);
  157077. }
  157078. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  157079. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  157080. int iLang = langidFromSelect(p, pStmt);
  157081. int iCol;
  157082. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  157083. if( p->abNotindexed[iCol]==0 ){
  157084. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  157085. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  157086. sqlite3_tokenizer_cursor *pT = 0;
  157087. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  157088. while( rc==SQLITE_OK ){
  157089. char const *zToken; /* Buffer containing token */
  157090. int nToken = 0; /* Number of bytes in token */
  157091. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  157092. int iPos = 0; /* Position of token in zText */
  157093. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  157094. if( rc==SQLITE_OK ){
  157095. int i;
  157096. cksum2 = cksum2 ^ fts3ChecksumEntry(
  157097. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  157098. );
  157099. for(i=1; i<p->nIndex; i++){
  157100. if( p->aIndex[i].nPrefix<=nToken ){
  157101. cksum2 = cksum2 ^ fts3ChecksumEntry(
  157102. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  157103. );
  157104. }
  157105. }
  157106. }
  157107. }
  157108. if( pT ) pModule->xClose(pT);
  157109. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  157110. }
  157111. }
  157112. }
  157113. sqlite3_finalize(pStmt);
  157114. }
  157115. *pbOk = (cksum1==cksum2);
  157116. return rc;
  157117. }
  157118. /*
  157119. ** Run the integrity-check. If no error occurs and the current contents of
  157120. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  157121. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  157122. **
  157123. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  157124. ** error code.
  157125. **
  157126. ** The integrity-check works as follows. For each token and indexed token
  157127. ** prefix in the document set, a 64-bit checksum is calculated (by code
  157128. ** in fts3ChecksumEntry()) based on the following:
  157129. **
  157130. ** + The index number (0 for the main index, 1 for the first prefix
  157131. ** index etc.),
  157132. ** + The token (or token prefix) text itself,
  157133. ** + The language-id of the row it appears in,
  157134. ** + The docid of the row it appears in,
  157135. ** + The column it appears in, and
  157136. ** + The tokens position within that column.
  157137. **
  157138. ** The checksums for all entries in the index are XORed together to create
  157139. ** a single checksum for the entire index.
  157140. **
  157141. ** The integrity-check code calculates the same checksum in two ways:
  157142. **
  157143. ** 1. By scanning the contents of the FTS index, and
  157144. ** 2. By scanning and tokenizing the content table.
  157145. **
  157146. ** If the two checksums are identical, the integrity-check is deemed to have
  157147. ** passed.
  157148. */
  157149. static int fts3DoIntegrityCheck(
  157150. Fts3Table *p /* FTS3 table handle */
  157151. ){
  157152. int rc;
  157153. int bOk = 0;
  157154. rc = fts3IntegrityCheck(p, &bOk);
  157155. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  157156. return rc;
  157157. }
  157158. /*
  157159. ** Handle a 'special' INSERT of the form:
  157160. **
  157161. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  157162. **
  157163. ** Argument pVal contains the result of <expr>. Currently the only
  157164. ** meaningful value to insert is the text 'optimize'.
  157165. */
  157166. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  157167. int rc; /* Return Code */
  157168. const char *zVal = (const char *)sqlite3_value_text(pVal);
  157169. int nVal = sqlite3_value_bytes(pVal);
  157170. if( !zVal ){
  157171. return SQLITE_NOMEM;
  157172. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  157173. rc = fts3DoOptimize(p, 0);
  157174. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  157175. rc = fts3DoRebuild(p);
  157176. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  157177. rc = fts3DoIntegrityCheck(p);
  157178. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  157179. rc = fts3DoIncrmerge(p, &zVal[6]);
  157180. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  157181. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  157182. #ifdef SQLITE_TEST
  157183. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  157184. p->nNodeSize = atoi(&zVal[9]);
  157185. rc = SQLITE_OK;
  157186. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  157187. p->nMaxPendingData = atoi(&zVal[11]);
  157188. rc = SQLITE_OK;
  157189. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  157190. p->bNoIncrDoclist = atoi(&zVal[21]);
  157191. rc = SQLITE_OK;
  157192. #endif
  157193. }else{
  157194. rc = SQLITE_ERROR;
  157195. }
  157196. return rc;
  157197. }
  157198. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  157199. /*
  157200. ** Delete all cached deferred doclists. Deferred doclists are cached
  157201. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  157202. */
  157203. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  157204. Fts3DeferredToken *pDef;
  157205. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  157206. fts3PendingListDelete(pDef->pList);
  157207. pDef->pList = 0;
  157208. }
  157209. }
  157210. /*
  157211. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  157212. ** this list using sqlite3Fts3DeferToken().
  157213. */
  157214. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  157215. Fts3DeferredToken *pDef;
  157216. Fts3DeferredToken *pNext;
  157217. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  157218. pNext = pDef->pNext;
  157219. fts3PendingListDelete(pDef->pList);
  157220. sqlite3_free(pDef);
  157221. }
  157222. pCsr->pDeferred = 0;
  157223. }
  157224. /*
  157225. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  157226. ** based on the row that pCsr currently points to.
  157227. **
  157228. ** A deferred-doclist is like any other doclist with position information
  157229. ** included, except that it only contains entries for a single row of the
  157230. ** table, not for all rows.
  157231. */
  157232. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  157233. int rc = SQLITE_OK; /* Return code */
  157234. if( pCsr->pDeferred ){
  157235. int i; /* Used to iterate through table columns */
  157236. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  157237. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  157238. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  157239. sqlite3_tokenizer *pT = p->pTokenizer;
  157240. sqlite3_tokenizer_module const *pModule = pT->pModule;
  157241. assert( pCsr->isRequireSeek==0 );
  157242. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  157243. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  157244. if( p->abNotindexed[i]==0 ){
  157245. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  157246. sqlite3_tokenizer_cursor *pTC = 0;
  157247. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  157248. while( rc==SQLITE_OK ){
  157249. char const *zToken; /* Buffer containing token */
  157250. int nToken = 0; /* Number of bytes in token */
  157251. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  157252. int iPos = 0; /* Position of token in zText */
  157253. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  157254. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  157255. Fts3PhraseToken *pPT = pDef->pToken;
  157256. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  157257. && (pPT->bFirst==0 || iPos==0)
  157258. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  157259. && (0==memcmp(zToken, pPT->z, pPT->n))
  157260. ){
  157261. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  157262. }
  157263. }
  157264. }
  157265. if( pTC ) pModule->xClose(pTC);
  157266. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  157267. }
  157268. }
  157269. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  157270. if( pDef->pList ){
  157271. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  157272. }
  157273. }
  157274. }
  157275. return rc;
  157276. }
  157277. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  157278. Fts3DeferredToken *p,
  157279. char **ppData,
  157280. int *pnData
  157281. ){
  157282. char *pRet;
  157283. int nSkip;
  157284. sqlite3_int64 dummy;
  157285. *ppData = 0;
  157286. *pnData = 0;
  157287. if( p->pList==0 ){
  157288. return SQLITE_OK;
  157289. }
  157290. pRet = (char *)sqlite3_malloc(p->pList->nData);
  157291. if( !pRet ) return SQLITE_NOMEM;
  157292. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  157293. *pnData = p->pList->nData - nSkip;
  157294. *ppData = pRet;
  157295. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  157296. return SQLITE_OK;
  157297. }
  157298. /*
  157299. ** Add an entry for token pToken to the pCsr->pDeferred list.
  157300. */
  157301. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  157302. Fts3Cursor *pCsr, /* Fts3 table cursor */
  157303. Fts3PhraseToken *pToken, /* Token to defer */
  157304. int iCol /* Column that token must appear in (or -1) */
  157305. ){
  157306. Fts3DeferredToken *pDeferred;
  157307. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  157308. if( !pDeferred ){
  157309. return SQLITE_NOMEM;
  157310. }
  157311. memset(pDeferred, 0, sizeof(*pDeferred));
  157312. pDeferred->pToken = pToken;
  157313. pDeferred->pNext = pCsr->pDeferred;
  157314. pDeferred->iCol = iCol;
  157315. pCsr->pDeferred = pDeferred;
  157316. assert( pToken->pDeferred==0 );
  157317. pToken->pDeferred = pDeferred;
  157318. return SQLITE_OK;
  157319. }
  157320. #endif
  157321. /*
  157322. ** SQLite value pRowid contains the rowid of a row that may or may not be
  157323. ** present in the FTS3 table. If it is, delete it and adjust the contents
  157324. ** of subsiduary data structures accordingly.
  157325. */
  157326. static int fts3DeleteByRowid(
  157327. Fts3Table *p,
  157328. sqlite3_value *pRowid,
  157329. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  157330. u32 *aSzDel
  157331. ){
  157332. int rc = SQLITE_OK; /* Return code */
  157333. int bFound = 0; /* True if *pRowid really is in the table */
  157334. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  157335. if( bFound && rc==SQLITE_OK ){
  157336. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  157337. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  157338. if( rc==SQLITE_OK ){
  157339. if( isEmpty ){
  157340. /* Deleting this row means the whole table is empty. In this case
  157341. ** delete the contents of all three tables and throw away any
  157342. ** data in the pendingTerms hash table. */
  157343. rc = fts3DeleteAll(p, 1);
  157344. *pnChng = 0;
  157345. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  157346. }else{
  157347. *pnChng = *pnChng - 1;
  157348. if( p->zContentTbl==0 ){
  157349. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  157350. }
  157351. if( p->bHasDocsize ){
  157352. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  157353. }
  157354. }
  157355. }
  157356. }
  157357. return rc;
  157358. }
  157359. /*
  157360. ** This function does the work for the xUpdate method of FTS3 virtual
  157361. ** tables. The schema of the virtual table being:
  157362. **
  157363. ** CREATE TABLE <table name>(
  157364. ** <user columns>,
  157365. ** <table name> HIDDEN,
  157366. ** docid HIDDEN,
  157367. ** <langid> HIDDEN
  157368. ** );
  157369. **
  157370. **
  157371. */
  157372. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  157373. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  157374. int nArg, /* Size of argument array */
  157375. sqlite3_value **apVal, /* Array of arguments */
  157376. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  157377. ){
  157378. Fts3Table *p = (Fts3Table *)pVtab;
  157379. int rc = SQLITE_OK; /* Return Code */
  157380. u32 *aSzIns = 0; /* Sizes of inserted documents */
  157381. u32 *aSzDel = 0; /* Sizes of deleted documents */
  157382. int nChng = 0; /* Net change in number of documents */
  157383. int bInsertDone = 0;
  157384. /* At this point it must be known if the %_stat table exists or not.
  157385. ** So bHasStat may not be 2. */
  157386. assert( p->bHasStat==0 || p->bHasStat==1 );
  157387. assert( p->pSegments==0 );
  157388. assert(
  157389. nArg==1 /* DELETE operations */
  157390. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  157391. );
  157392. /* Check for a "special" INSERT operation. One of the form:
  157393. **
  157394. ** INSERT INTO xyz(xyz) VALUES('command');
  157395. */
  157396. if( nArg>1
  157397. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  157398. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  157399. ){
  157400. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  157401. goto update_out;
  157402. }
  157403. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  157404. rc = SQLITE_CONSTRAINT;
  157405. goto update_out;
  157406. }
  157407. /* Allocate space to hold the change in document sizes */
  157408. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  157409. if( aSzDel==0 ){
  157410. rc = SQLITE_NOMEM;
  157411. goto update_out;
  157412. }
  157413. aSzIns = &aSzDel[p->nColumn+1];
  157414. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  157415. rc = fts3Writelock(p);
  157416. if( rc!=SQLITE_OK ) goto update_out;
  157417. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  157418. ** value, then this operation requires constraint handling.
  157419. **
  157420. ** If the on-conflict mode is REPLACE, this means that the existing row
  157421. ** should be deleted from the database before inserting the new row. Or,
  157422. ** if the on-conflict mode is other than REPLACE, then this method must
  157423. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  157424. ** modify the database file.
  157425. */
  157426. if( nArg>1 && p->zContentTbl==0 ){
  157427. /* Find the value object that holds the new rowid value. */
  157428. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  157429. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  157430. pNewRowid = apVal[1];
  157431. }
  157432. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  157433. sqlite3_value_type(apVal[0])==SQLITE_NULL
  157434. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  157435. )){
  157436. /* The new rowid is not NULL (in this case the rowid will be
  157437. ** automatically assigned and there is no chance of a conflict), and
  157438. ** the statement is either an INSERT or an UPDATE that modifies the
  157439. ** rowid column. So if the conflict mode is REPLACE, then delete any
  157440. ** existing row with rowid=pNewRowid.
  157441. **
  157442. ** Or, if the conflict mode is not REPLACE, insert the new record into
  157443. ** the %_content table. If we hit the duplicate rowid constraint (or any
  157444. ** other error) while doing so, return immediately.
  157445. **
  157446. ** This branch may also run if pNewRowid contains a value that cannot
  157447. ** be losslessly converted to an integer. In this case, the eventual
  157448. ** call to fts3InsertData() (either just below or further on in this
  157449. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  157450. ** invoked, it will delete zero rows (since no row will have
  157451. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  157452. */
  157453. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  157454. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  157455. }else{
  157456. rc = fts3InsertData(p, apVal, pRowid);
  157457. bInsertDone = 1;
  157458. }
  157459. }
  157460. }
  157461. if( rc!=SQLITE_OK ){
  157462. goto update_out;
  157463. }
  157464. /* If this is a DELETE or UPDATE operation, remove the old record. */
  157465. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  157466. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  157467. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  157468. }
  157469. /* If this is an INSERT or UPDATE operation, insert the new record. */
  157470. if( nArg>1 && rc==SQLITE_OK ){
  157471. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  157472. if( bInsertDone==0 ){
  157473. rc = fts3InsertData(p, apVal, pRowid);
  157474. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  157475. rc = FTS_CORRUPT_VTAB;
  157476. }
  157477. }
  157478. if( rc==SQLITE_OK ){
  157479. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  157480. }
  157481. if( rc==SQLITE_OK ){
  157482. assert( p->iPrevDocid==*pRowid );
  157483. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  157484. }
  157485. if( p->bHasDocsize ){
  157486. fts3InsertDocsize(&rc, p, aSzIns);
  157487. }
  157488. nChng++;
  157489. }
  157490. if( p->bFts4 ){
  157491. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  157492. }
  157493. update_out:
  157494. sqlite3_free(aSzDel);
  157495. sqlite3Fts3SegmentsClose(p);
  157496. return rc;
  157497. }
  157498. /*
  157499. ** Flush any data in the pending-terms hash table to disk. If successful,
  157500. ** merge all segments in the database (including the new segment, if
  157501. ** there was any data to flush) into a single segment.
  157502. */
  157503. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  157504. int rc;
  157505. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  157506. if( rc==SQLITE_OK ){
  157507. rc = fts3DoOptimize(p, 1);
  157508. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  157509. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  157510. if( rc2!=SQLITE_OK ) rc = rc2;
  157511. }else{
  157512. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  157513. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  157514. }
  157515. }
  157516. sqlite3Fts3SegmentsClose(p);
  157517. return rc;
  157518. }
  157519. #endif
  157520. /************** End of fts3_write.c ******************************************/
  157521. /************** Begin file fts3_snippet.c ************************************/
  157522. /*
  157523. ** 2009 Oct 23
  157524. **
  157525. ** The author disclaims copyright to this source code. In place of
  157526. ** a legal notice, here is a blessing:
  157527. **
  157528. ** May you do good and not evil.
  157529. ** May you find forgiveness for yourself and forgive others.
  157530. ** May you share freely, never taking more than you give.
  157531. **
  157532. ******************************************************************************
  157533. */
  157534. /* #include "fts3Int.h" */
  157535. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157536. /* #include <string.h> */
  157537. /* #include <assert.h> */
  157538. /*
  157539. ** Characters that may appear in the second argument to matchinfo().
  157540. */
  157541. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  157542. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  157543. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  157544. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  157545. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  157546. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  157547. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  157548. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  157549. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  157550. /*
  157551. ** The default value for the second argument to matchinfo().
  157552. */
  157553. #define FTS3_MATCHINFO_DEFAULT "pcx"
  157554. /*
  157555. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  157556. ** Fts3Expr.aDoclist[]/nDoclist.
  157557. */
  157558. typedef struct LoadDoclistCtx LoadDoclistCtx;
  157559. struct LoadDoclistCtx {
  157560. Fts3Cursor *pCsr; /* FTS3 Cursor */
  157561. int nPhrase; /* Number of phrases seen so far */
  157562. int nToken; /* Number of tokens seen so far */
  157563. };
  157564. /*
  157565. ** The following types are used as part of the implementation of the
  157566. ** fts3BestSnippet() routine.
  157567. */
  157568. typedef struct SnippetIter SnippetIter;
  157569. typedef struct SnippetPhrase SnippetPhrase;
  157570. typedef struct SnippetFragment SnippetFragment;
  157571. struct SnippetIter {
  157572. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  157573. int iCol; /* Extract snippet from this column */
  157574. int nSnippet; /* Requested snippet length (in tokens) */
  157575. int nPhrase; /* Number of phrases in query */
  157576. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  157577. int iCurrent; /* First token of current snippet */
  157578. };
  157579. struct SnippetPhrase {
  157580. int nToken; /* Number of tokens in phrase */
  157581. char *pList; /* Pointer to start of phrase position list */
  157582. int iHead; /* Next value in position list */
  157583. char *pHead; /* Position list data following iHead */
  157584. int iTail; /* Next value in trailing position list */
  157585. char *pTail; /* Position list data following iTail */
  157586. };
  157587. struct SnippetFragment {
  157588. int iCol; /* Column snippet is extracted from */
  157589. int iPos; /* Index of first token in snippet */
  157590. u64 covered; /* Mask of query phrases covered */
  157591. u64 hlmask; /* Mask of snippet terms to highlight */
  157592. };
  157593. /*
  157594. ** This type is used as an fts3ExprIterate() context object while
  157595. ** accumulating the data returned by the matchinfo() function.
  157596. */
  157597. typedef struct MatchInfo MatchInfo;
  157598. struct MatchInfo {
  157599. Fts3Cursor *pCursor; /* FTS3 Cursor */
  157600. int nCol; /* Number of columns in table */
  157601. int nPhrase; /* Number of matchable phrases in query */
  157602. sqlite3_int64 nDoc; /* Number of docs in database */
  157603. char flag;
  157604. u32 *aMatchinfo; /* Pre-allocated buffer */
  157605. };
  157606. /*
  157607. ** An instance of this structure is used to manage a pair of buffers, each
  157608. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  157609. ** for details.
  157610. */
  157611. struct MatchinfoBuffer {
  157612. u8 aRef[3];
  157613. int nElem;
  157614. int bGlobal; /* Set if global data is loaded */
  157615. char *zMatchinfo;
  157616. u32 aMatchinfo[1];
  157617. };
  157618. /*
  157619. ** The snippet() and offsets() functions both return text values. An instance
  157620. ** of the following structure is used to accumulate those values while the
  157621. ** functions are running. See fts3StringAppend() for details.
  157622. */
  157623. typedef struct StrBuffer StrBuffer;
  157624. struct StrBuffer {
  157625. char *z; /* Pointer to buffer containing string */
  157626. int n; /* Length of z in bytes (excl. nul-term) */
  157627. int nAlloc; /* Allocated size of buffer z in bytes */
  157628. };
  157629. /*************************************************************************
  157630. ** Start of MatchinfoBuffer code.
  157631. */
  157632. /*
  157633. ** Allocate a two-slot MatchinfoBuffer object.
  157634. */
  157635. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  157636. MatchinfoBuffer *pRet;
  157637. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  157638. int nStr = (int)strlen(zMatchinfo);
  157639. pRet = sqlite3_malloc(nByte + nStr+1);
  157640. if( pRet ){
  157641. memset(pRet, 0, nByte);
  157642. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  157643. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  157644. pRet->nElem = nElem;
  157645. pRet->zMatchinfo = ((char*)pRet) + nByte;
  157646. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  157647. pRet->aRef[0] = 1;
  157648. }
  157649. return pRet;
  157650. }
  157651. static void fts3MIBufferFree(void *p){
  157652. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  157653. assert( (u32*)p==&pBuf->aMatchinfo[1]
  157654. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  157655. );
  157656. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  157657. pBuf->aRef[1] = 0;
  157658. }else{
  157659. pBuf->aRef[2] = 0;
  157660. }
  157661. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  157662. sqlite3_free(pBuf);
  157663. }
  157664. }
  157665. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  157666. void (*xRet)(void*) = 0;
  157667. u32 *aOut = 0;
  157668. if( p->aRef[1]==0 ){
  157669. p->aRef[1] = 1;
  157670. aOut = &p->aMatchinfo[1];
  157671. xRet = fts3MIBufferFree;
  157672. }
  157673. else if( p->aRef[2]==0 ){
  157674. p->aRef[2] = 1;
  157675. aOut = &p->aMatchinfo[p->nElem+2];
  157676. xRet = fts3MIBufferFree;
  157677. }else{
  157678. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  157679. if( aOut ){
  157680. xRet = sqlite3_free;
  157681. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  157682. }
  157683. }
  157684. *paOut = aOut;
  157685. return xRet;
  157686. }
  157687. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  157688. p->bGlobal = 1;
  157689. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  157690. }
  157691. /*
  157692. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  157693. */
  157694. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  157695. if( p ){
  157696. assert( p->aRef[0]==1 );
  157697. p->aRef[0] = 0;
  157698. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  157699. sqlite3_free(p);
  157700. }
  157701. }
  157702. }
  157703. /*
  157704. ** End of MatchinfoBuffer code.
  157705. *************************************************************************/
  157706. /*
  157707. ** This function is used to help iterate through a position-list. A position
  157708. ** list is a list of unique integers, sorted from smallest to largest. Each
  157709. ** element of the list is represented by an FTS3 varint that takes the value
  157710. ** of the difference between the current element and the previous one plus
  157711. ** two. For example, to store the position-list:
  157712. **
  157713. ** 4 9 113
  157714. **
  157715. ** the three varints:
  157716. **
  157717. ** 6 7 106
  157718. **
  157719. ** are encoded.
  157720. **
  157721. ** When this function is called, *pp points to the start of an element of
  157722. ** the list. *piPos contains the value of the previous entry in the list.
  157723. ** After it returns, *piPos contains the value of the next element of the
  157724. ** list and *pp is advanced to the following varint.
  157725. */
  157726. static void fts3GetDeltaPosition(char **pp, int *piPos){
  157727. int iVal;
  157728. *pp += fts3GetVarint32(*pp, &iVal);
  157729. *piPos += (iVal-2);
  157730. }
  157731. /*
  157732. ** Helper function for fts3ExprIterate() (see below).
  157733. */
  157734. static int fts3ExprIterate2(
  157735. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  157736. int *piPhrase, /* Pointer to phrase counter */
  157737. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  157738. void *pCtx /* Second argument to pass to callback */
  157739. ){
  157740. int rc; /* Return code */
  157741. int eType = pExpr->eType; /* Type of expression node pExpr */
  157742. if( eType!=FTSQUERY_PHRASE ){
  157743. assert( pExpr->pLeft && pExpr->pRight );
  157744. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  157745. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  157746. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  157747. }
  157748. }else{
  157749. rc = x(pExpr, *piPhrase, pCtx);
  157750. (*piPhrase)++;
  157751. }
  157752. return rc;
  157753. }
  157754. /*
  157755. ** Iterate through all phrase nodes in an FTS3 query, except those that
  157756. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  157757. ** For each phrase node found, the supplied callback function is invoked.
  157758. **
  157759. ** If the callback function returns anything other than SQLITE_OK,
  157760. ** the iteration is abandoned and the error code returned immediately.
  157761. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  157762. ** all eligible phrase nodes.
  157763. */
  157764. static int fts3ExprIterate(
  157765. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  157766. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  157767. void *pCtx /* Second argument to pass to callback */
  157768. ){
  157769. int iPhrase = 0; /* Variable used as the phrase counter */
  157770. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  157771. }
  157772. /*
  157773. ** This is an fts3ExprIterate() callback used while loading the doclists
  157774. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  157775. ** fts3ExprLoadDoclists().
  157776. */
  157777. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  157778. int rc = SQLITE_OK;
  157779. Fts3Phrase *pPhrase = pExpr->pPhrase;
  157780. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  157781. UNUSED_PARAMETER(iPhrase);
  157782. p->nPhrase++;
  157783. p->nToken += pPhrase->nToken;
  157784. return rc;
  157785. }
  157786. /*
  157787. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  157788. ** pCsr.
  157789. **
  157790. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  157791. ** phrases in the expression (all phrases except those directly or
  157792. ** indirectly descended from the right-hand-side of a NOT operator). If
  157793. ** pnToken is not NULL, then it is set to the number of tokens in all
  157794. ** matchable phrases of the expression.
  157795. */
  157796. static int fts3ExprLoadDoclists(
  157797. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  157798. int *pnPhrase, /* OUT: Number of phrases in query */
  157799. int *pnToken /* OUT: Number of tokens in query */
  157800. ){
  157801. int rc; /* Return Code */
  157802. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  157803. sCtx.pCsr = pCsr;
  157804. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  157805. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  157806. if( pnToken ) *pnToken = sCtx.nToken;
  157807. return rc;
  157808. }
  157809. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  157810. (*(int *)ctx)++;
  157811. pExpr->iPhrase = iPhrase;
  157812. return SQLITE_OK;
  157813. }
  157814. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  157815. int nPhrase = 0;
  157816. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  157817. return nPhrase;
  157818. }
  157819. /*
  157820. ** Advance the position list iterator specified by the first two
  157821. ** arguments so that it points to the first element with a value greater
  157822. ** than or equal to parameter iNext.
  157823. */
  157824. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  157825. char *pIter = *ppIter;
  157826. if( pIter ){
  157827. int iIter = *piIter;
  157828. while( iIter<iNext ){
  157829. if( 0==(*pIter & 0xFE) ){
  157830. iIter = -1;
  157831. pIter = 0;
  157832. break;
  157833. }
  157834. fts3GetDeltaPosition(&pIter, &iIter);
  157835. }
  157836. *piIter = iIter;
  157837. *ppIter = pIter;
  157838. }
  157839. }
  157840. /*
  157841. ** Advance the snippet iterator to the next candidate snippet.
  157842. */
  157843. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  157844. int i; /* Loop counter */
  157845. if( pIter->iCurrent<0 ){
  157846. /* The SnippetIter object has just been initialized. The first snippet
  157847. ** candidate always starts at offset 0 (even if this candidate has a
  157848. ** score of 0.0).
  157849. */
  157850. pIter->iCurrent = 0;
  157851. /* Advance the 'head' iterator of each phrase to the first offset that
  157852. ** is greater than or equal to (iNext+nSnippet).
  157853. */
  157854. for(i=0; i<pIter->nPhrase; i++){
  157855. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  157856. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  157857. }
  157858. }else{
  157859. int iStart;
  157860. int iEnd = 0x7FFFFFFF;
  157861. for(i=0; i<pIter->nPhrase; i++){
  157862. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  157863. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  157864. iEnd = pPhrase->iHead;
  157865. }
  157866. }
  157867. if( iEnd==0x7FFFFFFF ){
  157868. return 1;
  157869. }
  157870. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  157871. for(i=0; i<pIter->nPhrase; i++){
  157872. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  157873. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  157874. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  157875. }
  157876. }
  157877. return 0;
  157878. }
  157879. /*
  157880. ** Retrieve information about the current candidate snippet of snippet
  157881. ** iterator pIter.
  157882. */
  157883. static void fts3SnippetDetails(
  157884. SnippetIter *pIter, /* Snippet iterator */
  157885. u64 mCovered, /* Bitmask of phrases already covered */
  157886. int *piToken, /* OUT: First token of proposed snippet */
  157887. int *piScore, /* OUT: "Score" for this snippet */
  157888. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  157889. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  157890. ){
  157891. int iStart = pIter->iCurrent; /* First token of snippet */
  157892. int iScore = 0; /* Score of this snippet */
  157893. int i; /* Loop counter */
  157894. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  157895. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  157896. for(i=0; i<pIter->nPhrase; i++){
  157897. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  157898. if( pPhrase->pTail ){
  157899. char *pCsr = pPhrase->pTail;
  157900. int iCsr = pPhrase->iTail;
  157901. while( iCsr<(iStart+pIter->nSnippet) ){
  157902. int j;
  157903. u64 mPhrase = (u64)1 << i;
  157904. u64 mPos = (u64)1 << (iCsr - iStart);
  157905. assert( iCsr>=iStart );
  157906. if( (mCover|mCovered)&mPhrase ){
  157907. iScore++;
  157908. }else{
  157909. iScore += 1000;
  157910. }
  157911. mCover |= mPhrase;
  157912. for(j=0; j<pPhrase->nToken; j++){
  157913. mHighlight |= (mPos>>j);
  157914. }
  157915. if( 0==(*pCsr & 0x0FE) ) break;
  157916. fts3GetDeltaPosition(&pCsr, &iCsr);
  157917. }
  157918. }
  157919. }
  157920. /* Set the output variables before returning. */
  157921. *piToken = iStart;
  157922. *piScore = iScore;
  157923. *pmCover = mCover;
  157924. *pmHighlight = mHighlight;
  157925. }
  157926. /*
  157927. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  157928. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  157929. */
  157930. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  157931. SnippetIter *p = (SnippetIter *)ctx;
  157932. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  157933. char *pCsr;
  157934. int rc;
  157935. pPhrase->nToken = pExpr->pPhrase->nToken;
  157936. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  157937. assert( rc==SQLITE_OK || pCsr==0 );
  157938. if( pCsr ){
  157939. int iFirst = 0;
  157940. pPhrase->pList = pCsr;
  157941. fts3GetDeltaPosition(&pCsr, &iFirst);
  157942. assert( iFirst>=0 );
  157943. pPhrase->pHead = pCsr;
  157944. pPhrase->pTail = pCsr;
  157945. pPhrase->iHead = iFirst;
  157946. pPhrase->iTail = iFirst;
  157947. }else{
  157948. assert( rc!=SQLITE_OK || (
  157949. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  157950. ));
  157951. }
  157952. return rc;
  157953. }
  157954. /*
  157955. ** Select the fragment of text consisting of nFragment contiguous tokens
  157956. ** from column iCol that represent the "best" snippet. The best snippet
  157957. ** is the snippet with the highest score, where scores are calculated
  157958. ** by adding:
  157959. **
  157960. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  157961. **
  157962. ** (b) +1000 points for the first occurrence of each matchable phrase in
  157963. ** the snippet for which the corresponding mCovered bit is not set.
  157964. **
  157965. ** The selected snippet parameters are stored in structure *pFragment before
  157966. ** returning. The score of the selected snippet is stored in *piScore
  157967. ** before returning.
  157968. */
  157969. static int fts3BestSnippet(
  157970. int nSnippet, /* Desired snippet length */
  157971. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  157972. int iCol, /* Index of column to create snippet from */
  157973. u64 mCovered, /* Mask of phrases already covered */
  157974. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  157975. SnippetFragment *pFragment, /* OUT: Best snippet found */
  157976. int *piScore /* OUT: Score of snippet pFragment */
  157977. ){
  157978. int rc; /* Return Code */
  157979. int nList; /* Number of phrases in expression */
  157980. SnippetIter sIter; /* Iterates through snippet candidates */
  157981. int nByte; /* Number of bytes of space to allocate */
  157982. int iBestScore = -1; /* Best snippet score found so far */
  157983. int i; /* Loop counter */
  157984. memset(&sIter, 0, sizeof(sIter));
  157985. /* Iterate through the phrases in the expression to count them. The same
  157986. ** callback makes sure the doclists are loaded for each phrase.
  157987. */
  157988. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  157989. if( rc!=SQLITE_OK ){
  157990. return rc;
  157991. }
  157992. /* Now that it is known how many phrases there are, allocate and zero
  157993. ** the required space using malloc().
  157994. */
  157995. nByte = sizeof(SnippetPhrase) * nList;
  157996. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  157997. if( !sIter.aPhrase ){
  157998. return SQLITE_NOMEM;
  157999. }
  158000. memset(sIter.aPhrase, 0, nByte);
  158001. /* Initialize the contents of the SnippetIter object. Then iterate through
  158002. ** the set of phrases in the expression to populate the aPhrase[] array.
  158003. */
  158004. sIter.pCsr = pCsr;
  158005. sIter.iCol = iCol;
  158006. sIter.nSnippet = nSnippet;
  158007. sIter.nPhrase = nList;
  158008. sIter.iCurrent = -1;
  158009. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  158010. if( rc==SQLITE_OK ){
  158011. /* Set the *pmSeen output variable. */
  158012. for(i=0; i<nList; i++){
  158013. if( sIter.aPhrase[i].pHead ){
  158014. *pmSeen |= (u64)1 << i;
  158015. }
  158016. }
  158017. /* Loop through all candidate snippets. Store the best snippet in
  158018. ** *pFragment. Store its associated 'score' in iBestScore.
  158019. */
  158020. pFragment->iCol = iCol;
  158021. while( !fts3SnippetNextCandidate(&sIter) ){
  158022. int iPos;
  158023. int iScore;
  158024. u64 mCover;
  158025. u64 mHighlite;
  158026. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  158027. assert( iScore>=0 );
  158028. if( iScore>iBestScore ){
  158029. pFragment->iPos = iPos;
  158030. pFragment->hlmask = mHighlite;
  158031. pFragment->covered = mCover;
  158032. iBestScore = iScore;
  158033. }
  158034. }
  158035. *piScore = iBestScore;
  158036. }
  158037. sqlite3_free(sIter.aPhrase);
  158038. return rc;
  158039. }
  158040. /*
  158041. ** Append a string to the string-buffer passed as the first argument.
  158042. **
  158043. ** If nAppend is negative, then the length of the string zAppend is
  158044. ** determined using strlen().
  158045. */
  158046. static int fts3StringAppend(
  158047. StrBuffer *pStr, /* Buffer to append to */
  158048. const char *zAppend, /* Pointer to data to append to buffer */
  158049. int nAppend /* Size of zAppend in bytes (or -1) */
  158050. ){
  158051. if( nAppend<0 ){
  158052. nAppend = (int)strlen(zAppend);
  158053. }
  158054. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  158055. ** to grow the buffer until so that it is big enough to accomadate the
  158056. ** appended data.
  158057. */
  158058. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  158059. int nAlloc = pStr->nAlloc+nAppend+100;
  158060. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  158061. if( !zNew ){
  158062. return SQLITE_NOMEM;
  158063. }
  158064. pStr->z = zNew;
  158065. pStr->nAlloc = nAlloc;
  158066. }
  158067. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  158068. /* Append the data to the string buffer. */
  158069. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  158070. pStr->n += nAppend;
  158071. pStr->z[pStr->n] = '\0';
  158072. return SQLITE_OK;
  158073. }
  158074. /*
  158075. ** The fts3BestSnippet() function often selects snippets that end with a
  158076. ** query term. That is, the final term of the snippet is always a term
  158077. ** that requires highlighting. For example, if 'X' is a highlighted term
  158078. ** and '.' is a non-highlighted term, BestSnippet() may select:
  158079. **
  158080. ** ........X.....X
  158081. **
  158082. ** This function "shifts" the beginning of the snippet forward in the
  158083. ** document so that there are approximately the same number of
  158084. ** non-highlighted terms to the right of the final highlighted term as there
  158085. ** are to the left of the first highlighted term. For example, to this:
  158086. **
  158087. ** ....X.....X....
  158088. **
  158089. ** This is done as part of extracting the snippet text, not when selecting
  158090. ** the snippet. Snippet selection is done based on doclists only, so there
  158091. ** is no way for fts3BestSnippet() to know whether or not the document
  158092. ** actually contains terms that follow the final highlighted term.
  158093. */
  158094. static int fts3SnippetShift(
  158095. Fts3Table *pTab, /* FTS3 table snippet comes from */
  158096. int iLangid, /* Language id to use in tokenizing */
  158097. int nSnippet, /* Number of tokens desired for snippet */
  158098. const char *zDoc, /* Document text to extract snippet from */
  158099. int nDoc, /* Size of buffer zDoc in bytes */
  158100. int *piPos, /* IN/OUT: First token of snippet */
  158101. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  158102. ){
  158103. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  158104. if( hlmask ){
  158105. int nLeft; /* Tokens to the left of first highlight */
  158106. int nRight; /* Tokens to the right of last highlight */
  158107. int nDesired; /* Ideal number of tokens to shift forward */
  158108. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  158109. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  158110. nDesired = (nLeft-nRight)/2;
  158111. /* Ideally, the start of the snippet should be pushed forward in the
  158112. ** document nDesired tokens. This block checks if there are actually
  158113. ** nDesired tokens to the right of the snippet. If so, *piPos and
  158114. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  158115. ** right. Otherwise, the snippet is shifted by the number of tokens
  158116. ** available.
  158117. */
  158118. if( nDesired>0 ){
  158119. int nShift; /* Number of tokens to shift snippet by */
  158120. int iCurrent = 0; /* Token counter */
  158121. int rc; /* Return Code */
  158122. sqlite3_tokenizer_module *pMod;
  158123. sqlite3_tokenizer_cursor *pC;
  158124. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  158125. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  158126. ** or more tokens in zDoc/nDoc.
  158127. */
  158128. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  158129. if( rc!=SQLITE_OK ){
  158130. return rc;
  158131. }
  158132. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  158133. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  158134. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  158135. }
  158136. pMod->xClose(pC);
  158137. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  158138. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  158139. assert( nShift<=nDesired );
  158140. if( nShift>0 ){
  158141. *piPos += nShift;
  158142. *pHlmask = hlmask >> nShift;
  158143. }
  158144. }
  158145. }
  158146. return SQLITE_OK;
  158147. }
  158148. /*
  158149. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  158150. ** append it to string buffer pOut.
  158151. */
  158152. static int fts3SnippetText(
  158153. Fts3Cursor *pCsr, /* FTS3 Cursor */
  158154. SnippetFragment *pFragment, /* Snippet to extract */
  158155. int iFragment, /* Fragment number */
  158156. int isLast, /* True for final fragment in snippet */
  158157. int nSnippet, /* Number of tokens in extracted snippet */
  158158. const char *zOpen, /* String inserted before highlighted term */
  158159. const char *zClose, /* String inserted after highlighted term */
  158160. const char *zEllipsis, /* String inserted between snippets */
  158161. StrBuffer *pOut /* Write output here */
  158162. ){
  158163. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  158164. int rc; /* Return code */
  158165. const char *zDoc; /* Document text to extract snippet from */
  158166. int nDoc; /* Size of zDoc in bytes */
  158167. int iCurrent = 0; /* Current token number of document */
  158168. int iEnd = 0; /* Byte offset of end of current token */
  158169. int isShiftDone = 0; /* True after snippet is shifted */
  158170. int iPos = pFragment->iPos; /* First token of snippet */
  158171. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  158172. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  158173. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  158174. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  158175. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  158176. if( zDoc==0 ){
  158177. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  158178. return SQLITE_NOMEM;
  158179. }
  158180. return SQLITE_OK;
  158181. }
  158182. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  158183. /* Open a token cursor on the document. */
  158184. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  158185. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  158186. if( rc!=SQLITE_OK ){
  158187. return rc;
  158188. }
  158189. while( rc==SQLITE_OK ){
  158190. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  158191. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  158192. int iBegin = 0; /* Offset in zDoc of start of token */
  158193. int iFin = 0; /* Offset in zDoc of end of token */
  158194. int isHighlight = 0; /* True for highlighted terms */
  158195. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  158196. ** in the FTS code the variable that the third argument to xNext points to
  158197. ** is initialized to zero before the first (*but not necessarily
  158198. ** subsequent*) call to xNext(). This is done for a particular application
  158199. ** that needs to know whether or not the tokenizer is being used for
  158200. ** snippet generation or for some other purpose.
  158201. **
  158202. ** Extreme care is required when writing code to depend on this
  158203. ** initialization. It is not a documented part of the tokenizer interface.
  158204. ** If a tokenizer is used directly by any code outside of FTS, this
  158205. ** convention might not be respected. */
  158206. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  158207. if( rc!=SQLITE_OK ){
  158208. if( rc==SQLITE_DONE ){
  158209. /* Special case - the last token of the snippet is also the last token
  158210. ** of the column. Append any punctuation that occurred between the end
  158211. ** of the previous token and the end of the document to the output.
  158212. ** Then break out of the loop. */
  158213. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  158214. }
  158215. break;
  158216. }
  158217. if( iCurrent<iPos ){ continue; }
  158218. if( !isShiftDone ){
  158219. int n = nDoc - iBegin;
  158220. rc = fts3SnippetShift(
  158221. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  158222. );
  158223. isShiftDone = 1;
  158224. /* Now that the shift has been done, check if the initial "..." are
  158225. ** required. They are required if (a) this is not the first fragment,
  158226. ** or (b) this fragment does not begin at position 0 of its column.
  158227. */
  158228. if( rc==SQLITE_OK ){
  158229. if( iPos>0 || iFragment>0 ){
  158230. rc = fts3StringAppend(pOut, zEllipsis, -1);
  158231. }else if( iBegin ){
  158232. rc = fts3StringAppend(pOut, zDoc, iBegin);
  158233. }
  158234. }
  158235. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  158236. }
  158237. if( iCurrent>=(iPos+nSnippet) ){
  158238. if( isLast ){
  158239. rc = fts3StringAppend(pOut, zEllipsis, -1);
  158240. }
  158241. break;
  158242. }
  158243. /* Set isHighlight to true if this term should be highlighted. */
  158244. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  158245. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  158246. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  158247. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  158248. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  158249. iEnd = iFin;
  158250. }
  158251. pMod->xClose(pC);
  158252. return rc;
  158253. }
  158254. /*
  158255. ** This function is used to count the entries in a column-list (a
  158256. ** delta-encoded list of term offsets within a single column of a single
  158257. ** row). When this function is called, *ppCollist should point to the
  158258. ** beginning of the first varint in the column-list (the varint that
  158259. ** contains the position of the first matching term in the column data).
  158260. ** Before returning, *ppCollist is set to point to the first byte after
  158261. ** the last varint in the column-list (either the 0x00 signifying the end
  158262. ** of the position-list, or the 0x01 that precedes the column number of
  158263. ** the next column in the position-list).
  158264. **
  158265. ** The number of elements in the column-list is returned.
  158266. */
  158267. static int fts3ColumnlistCount(char **ppCollist){
  158268. char *pEnd = *ppCollist;
  158269. char c = 0;
  158270. int nEntry = 0;
  158271. /* A column-list is terminated by either a 0x01 or 0x00. */
  158272. while( 0xFE & (*pEnd | c) ){
  158273. c = *pEnd++ & 0x80;
  158274. if( !c ) nEntry++;
  158275. }
  158276. *ppCollist = pEnd;
  158277. return nEntry;
  158278. }
  158279. /*
  158280. ** This function gathers 'y' or 'b' data for a single phrase.
  158281. */
  158282. static void fts3ExprLHits(
  158283. Fts3Expr *pExpr, /* Phrase expression node */
  158284. MatchInfo *p /* Matchinfo context */
  158285. ){
  158286. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  158287. int iStart;
  158288. Fts3Phrase *pPhrase = pExpr->pPhrase;
  158289. char *pIter = pPhrase->doclist.pList;
  158290. int iCol = 0;
  158291. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  158292. if( p->flag==FTS3_MATCHINFO_LHITS ){
  158293. iStart = pExpr->iPhrase * p->nCol;
  158294. }else{
  158295. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  158296. }
  158297. while( 1 ){
  158298. int nHit = fts3ColumnlistCount(&pIter);
  158299. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  158300. if( p->flag==FTS3_MATCHINFO_LHITS ){
  158301. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  158302. }else if( nHit ){
  158303. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  158304. }
  158305. }
  158306. assert( *pIter==0x00 || *pIter==0x01 );
  158307. if( *pIter!=0x01 ) break;
  158308. pIter++;
  158309. pIter += fts3GetVarint32(pIter, &iCol);
  158310. }
  158311. }
  158312. /*
  158313. ** Gather the results for matchinfo directives 'y' and 'b'.
  158314. */
  158315. static void fts3ExprLHitGather(
  158316. Fts3Expr *pExpr,
  158317. MatchInfo *p
  158318. ){
  158319. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  158320. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  158321. if( pExpr->pLeft ){
  158322. fts3ExprLHitGather(pExpr->pLeft, p);
  158323. fts3ExprLHitGather(pExpr->pRight, p);
  158324. }else{
  158325. fts3ExprLHits(pExpr, p);
  158326. }
  158327. }
  158328. }
  158329. /*
  158330. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  158331. ** for a single query.
  158332. **
  158333. ** fts3ExprIterate() callback to load the 'global' elements of a
  158334. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  158335. ** of the matchinfo array that are constant for all rows returned by the
  158336. ** current query.
  158337. **
  158338. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  158339. ** function populates Matchinfo.aMatchinfo[] as follows:
  158340. **
  158341. ** for(iCol=0; iCol<nCol; iCol++){
  158342. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  158343. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  158344. ** }
  158345. **
  158346. ** where X is the number of matches for phrase iPhrase is column iCol of all
  158347. ** rows of the table. Y is the number of rows for which column iCol contains
  158348. ** at least one instance of phrase iPhrase.
  158349. **
  158350. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  158351. ** Y values are set to nDoc, where nDoc is the number of documents in the
  158352. ** file system. This is done because the full-text index doclist is required
  158353. ** to calculate these values properly, and the full-text index doclist is
  158354. ** not available for deferred tokens.
  158355. */
  158356. static int fts3ExprGlobalHitsCb(
  158357. Fts3Expr *pExpr, /* Phrase expression node */
  158358. int iPhrase, /* Phrase number (numbered from zero) */
  158359. void *pCtx /* Pointer to MatchInfo structure */
  158360. ){
  158361. MatchInfo *p = (MatchInfo *)pCtx;
  158362. return sqlite3Fts3EvalPhraseStats(
  158363. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  158364. );
  158365. }
  158366. /*
  158367. ** fts3ExprIterate() callback used to collect the "local" part of the
  158368. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  158369. ** array that are different for each row returned by the query.
  158370. */
  158371. static int fts3ExprLocalHitsCb(
  158372. Fts3Expr *pExpr, /* Phrase expression node */
  158373. int iPhrase, /* Phrase number */
  158374. void *pCtx /* Pointer to MatchInfo structure */
  158375. ){
  158376. int rc = SQLITE_OK;
  158377. MatchInfo *p = (MatchInfo *)pCtx;
  158378. int iStart = iPhrase * p->nCol * 3;
  158379. int i;
  158380. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  158381. char *pCsr;
  158382. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  158383. if( pCsr ){
  158384. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  158385. }else{
  158386. p->aMatchinfo[iStart+i*3] = 0;
  158387. }
  158388. }
  158389. return rc;
  158390. }
  158391. static int fts3MatchinfoCheck(
  158392. Fts3Table *pTab,
  158393. char cArg,
  158394. char **pzErr
  158395. ){
  158396. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  158397. || (cArg==FTS3_MATCHINFO_NCOL)
  158398. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  158399. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  158400. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  158401. || (cArg==FTS3_MATCHINFO_LCS)
  158402. || (cArg==FTS3_MATCHINFO_HITS)
  158403. || (cArg==FTS3_MATCHINFO_LHITS)
  158404. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  158405. ){
  158406. return SQLITE_OK;
  158407. }
  158408. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  158409. return SQLITE_ERROR;
  158410. }
  158411. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  158412. int nVal; /* Number of integers output by cArg */
  158413. switch( cArg ){
  158414. case FTS3_MATCHINFO_NDOC:
  158415. case FTS3_MATCHINFO_NPHRASE:
  158416. case FTS3_MATCHINFO_NCOL:
  158417. nVal = 1;
  158418. break;
  158419. case FTS3_MATCHINFO_AVGLENGTH:
  158420. case FTS3_MATCHINFO_LENGTH:
  158421. case FTS3_MATCHINFO_LCS:
  158422. nVal = pInfo->nCol;
  158423. break;
  158424. case FTS3_MATCHINFO_LHITS:
  158425. nVal = pInfo->nCol * pInfo->nPhrase;
  158426. break;
  158427. case FTS3_MATCHINFO_LHITS_BM:
  158428. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  158429. break;
  158430. default:
  158431. assert( cArg==FTS3_MATCHINFO_HITS );
  158432. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  158433. break;
  158434. }
  158435. return nVal;
  158436. }
  158437. static int fts3MatchinfoSelectDoctotal(
  158438. Fts3Table *pTab,
  158439. sqlite3_stmt **ppStmt,
  158440. sqlite3_int64 *pnDoc,
  158441. const char **paLen
  158442. ){
  158443. sqlite3_stmt *pStmt;
  158444. const char *a;
  158445. sqlite3_int64 nDoc;
  158446. if( !*ppStmt ){
  158447. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  158448. if( rc!=SQLITE_OK ) return rc;
  158449. }
  158450. pStmt = *ppStmt;
  158451. assert( sqlite3_data_count(pStmt)==1 );
  158452. a = sqlite3_column_blob(pStmt, 0);
  158453. a += sqlite3Fts3GetVarint(a, &nDoc);
  158454. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  158455. *pnDoc = (u32)nDoc;
  158456. if( paLen ) *paLen = a;
  158457. return SQLITE_OK;
  158458. }
  158459. /*
  158460. ** An instance of the following structure is used to store state while
  158461. ** iterating through a multi-column position-list corresponding to the
  158462. ** hits for a single phrase on a single row in order to calculate the
  158463. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  158464. */
  158465. typedef struct LcsIterator LcsIterator;
  158466. struct LcsIterator {
  158467. Fts3Expr *pExpr; /* Pointer to phrase expression */
  158468. int iPosOffset; /* Tokens count up to end of this phrase */
  158469. char *pRead; /* Cursor used to iterate through aDoclist */
  158470. int iPos; /* Current position */
  158471. };
  158472. /*
  158473. ** If LcsIterator.iCol is set to the following value, the iterator has
  158474. ** finished iterating through all offsets for all columns.
  158475. */
  158476. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  158477. static int fts3MatchinfoLcsCb(
  158478. Fts3Expr *pExpr, /* Phrase expression node */
  158479. int iPhrase, /* Phrase number (numbered from zero) */
  158480. void *pCtx /* Pointer to MatchInfo structure */
  158481. ){
  158482. LcsIterator *aIter = (LcsIterator *)pCtx;
  158483. aIter[iPhrase].pExpr = pExpr;
  158484. return SQLITE_OK;
  158485. }
  158486. /*
  158487. ** Advance the iterator passed as an argument to the next position. Return
  158488. ** 1 if the iterator is at EOF or if it now points to the start of the
  158489. ** position list for the next column.
  158490. */
  158491. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  158492. char *pRead = pIter->pRead;
  158493. sqlite3_int64 iRead;
  158494. int rc = 0;
  158495. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  158496. if( iRead==0 || iRead==1 ){
  158497. pRead = 0;
  158498. rc = 1;
  158499. }else{
  158500. pIter->iPos += (int)(iRead-2);
  158501. }
  158502. pIter->pRead = pRead;
  158503. return rc;
  158504. }
  158505. /*
  158506. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  158507. **
  158508. ** If the call is successful, the longest-common-substring lengths for each
  158509. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  158510. ** array before returning. SQLITE_OK is returned in this case.
  158511. **
  158512. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  158513. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  158514. ** undefined.
  158515. */
  158516. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  158517. LcsIterator *aIter;
  158518. int i;
  158519. int iCol;
  158520. int nToken = 0;
  158521. /* Allocate and populate the array of LcsIterator objects. The array
  158522. ** contains one element for each matchable phrase in the query.
  158523. **/
  158524. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  158525. if( !aIter ) return SQLITE_NOMEM;
  158526. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  158527. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  158528. for(i=0; i<pInfo->nPhrase; i++){
  158529. LcsIterator *pIter = &aIter[i];
  158530. nToken -= pIter->pExpr->pPhrase->nToken;
  158531. pIter->iPosOffset = nToken;
  158532. }
  158533. for(iCol=0; iCol<pInfo->nCol; iCol++){
  158534. int nLcs = 0; /* LCS value for this column */
  158535. int nLive = 0; /* Number of iterators in aIter not at EOF */
  158536. for(i=0; i<pInfo->nPhrase; i++){
  158537. int rc;
  158538. LcsIterator *pIt = &aIter[i];
  158539. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  158540. if( rc!=SQLITE_OK ) return rc;
  158541. if( pIt->pRead ){
  158542. pIt->iPos = pIt->iPosOffset;
  158543. fts3LcsIteratorAdvance(&aIter[i]);
  158544. nLive++;
  158545. }
  158546. }
  158547. while( nLive>0 ){
  158548. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  158549. int nThisLcs = 0; /* LCS for the current iterator positions */
  158550. for(i=0; i<pInfo->nPhrase; i++){
  158551. LcsIterator *pIter = &aIter[i];
  158552. if( pIter->pRead==0 ){
  158553. /* This iterator is already at EOF for this column. */
  158554. nThisLcs = 0;
  158555. }else{
  158556. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  158557. pAdv = pIter;
  158558. }
  158559. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  158560. nThisLcs++;
  158561. }else{
  158562. nThisLcs = 1;
  158563. }
  158564. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  158565. }
  158566. }
  158567. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  158568. }
  158569. pInfo->aMatchinfo[iCol] = nLcs;
  158570. }
  158571. sqlite3_free(aIter);
  158572. return SQLITE_OK;
  158573. }
  158574. /*
  158575. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  158576. ** be returned by the matchinfo() function. Argument zArg contains the
  158577. ** format string passed as the second argument to matchinfo (or the
  158578. ** default value "pcx" if no second argument was specified). The format
  158579. ** string has already been validated and the pInfo->aMatchinfo[] array
  158580. ** is guaranteed to be large enough for the output.
  158581. **
  158582. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  158583. ** If it is false, then assume that those fields that do not change between
  158584. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  158585. ** have already been populated.
  158586. **
  158587. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  158588. ** occurs. If a value other than SQLITE_OK is returned, the state the
  158589. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  158590. */
  158591. static int fts3MatchinfoValues(
  158592. Fts3Cursor *pCsr, /* FTS3 cursor object */
  158593. int bGlobal, /* True to grab the global stats */
  158594. MatchInfo *pInfo, /* Matchinfo context object */
  158595. const char *zArg /* Matchinfo format string */
  158596. ){
  158597. int rc = SQLITE_OK;
  158598. int i;
  158599. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  158600. sqlite3_stmt *pSelect = 0;
  158601. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  158602. pInfo->flag = zArg[i];
  158603. switch( zArg[i] ){
  158604. case FTS3_MATCHINFO_NPHRASE:
  158605. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  158606. break;
  158607. case FTS3_MATCHINFO_NCOL:
  158608. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  158609. break;
  158610. case FTS3_MATCHINFO_NDOC:
  158611. if( bGlobal ){
  158612. sqlite3_int64 nDoc = 0;
  158613. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  158614. pInfo->aMatchinfo[0] = (u32)nDoc;
  158615. }
  158616. break;
  158617. case FTS3_MATCHINFO_AVGLENGTH:
  158618. if( bGlobal ){
  158619. sqlite3_int64 nDoc; /* Number of rows in table */
  158620. const char *a; /* Aggregate column length array */
  158621. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  158622. if( rc==SQLITE_OK ){
  158623. int iCol;
  158624. for(iCol=0; iCol<pInfo->nCol; iCol++){
  158625. u32 iVal;
  158626. sqlite3_int64 nToken;
  158627. a += sqlite3Fts3GetVarint(a, &nToken);
  158628. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  158629. pInfo->aMatchinfo[iCol] = iVal;
  158630. }
  158631. }
  158632. }
  158633. break;
  158634. case FTS3_MATCHINFO_LENGTH: {
  158635. sqlite3_stmt *pSelectDocsize = 0;
  158636. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  158637. if( rc==SQLITE_OK ){
  158638. int iCol;
  158639. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  158640. for(iCol=0; iCol<pInfo->nCol; iCol++){
  158641. sqlite3_int64 nToken;
  158642. a += sqlite3Fts3GetVarint(a, &nToken);
  158643. pInfo->aMatchinfo[iCol] = (u32)nToken;
  158644. }
  158645. }
  158646. sqlite3_reset(pSelectDocsize);
  158647. break;
  158648. }
  158649. case FTS3_MATCHINFO_LCS:
  158650. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  158651. if( rc==SQLITE_OK ){
  158652. rc = fts3MatchinfoLcs(pCsr, pInfo);
  158653. }
  158654. break;
  158655. case FTS3_MATCHINFO_LHITS_BM:
  158656. case FTS3_MATCHINFO_LHITS: {
  158657. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  158658. memset(pInfo->aMatchinfo, 0, nZero);
  158659. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  158660. break;
  158661. }
  158662. default: {
  158663. Fts3Expr *pExpr;
  158664. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  158665. pExpr = pCsr->pExpr;
  158666. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  158667. if( rc!=SQLITE_OK ) break;
  158668. if( bGlobal ){
  158669. if( pCsr->pDeferred ){
  158670. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  158671. if( rc!=SQLITE_OK ) break;
  158672. }
  158673. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  158674. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  158675. if( rc!=SQLITE_OK ) break;
  158676. }
  158677. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  158678. break;
  158679. }
  158680. }
  158681. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  158682. }
  158683. sqlite3_reset(pSelect);
  158684. return rc;
  158685. }
  158686. /*
  158687. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  158688. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  158689. */
  158690. static void fts3GetMatchinfo(
  158691. sqlite3_context *pCtx, /* Return results here */
  158692. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  158693. const char *zArg /* Second argument to matchinfo() function */
  158694. ){
  158695. MatchInfo sInfo;
  158696. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  158697. int rc = SQLITE_OK;
  158698. int bGlobal = 0; /* Collect 'global' stats as well as local */
  158699. u32 *aOut = 0;
  158700. void (*xDestroyOut)(void*) = 0;
  158701. memset(&sInfo, 0, sizeof(MatchInfo));
  158702. sInfo.pCursor = pCsr;
  158703. sInfo.nCol = pTab->nColumn;
  158704. /* If there is cached matchinfo() data, but the format string for the
  158705. ** cache does not match the format string for this request, discard
  158706. ** the cached data. */
  158707. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  158708. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  158709. pCsr->pMIBuffer = 0;
  158710. }
  158711. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  158712. ** matchinfo function has been called for this query. In this case
  158713. ** allocate the array used to accumulate the matchinfo data and
  158714. ** initialize those elements that are constant for every row.
  158715. */
  158716. if( pCsr->pMIBuffer==0 ){
  158717. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  158718. int i; /* Used to iterate through zArg */
  158719. /* Determine the number of phrases in the query */
  158720. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  158721. sInfo.nPhrase = pCsr->nPhrase;
  158722. /* Determine the number of integers in the buffer returned by this call. */
  158723. for(i=0; zArg[i]; i++){
  158724. char *zErr = 0;
  158725. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  158726. sqlite3_result_error(pCtx, zErr, -1);
  158727. sqlite3_free(zErr);
  158728. return;
  158729. }
  158730. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  158731. }
  158732. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  158733. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  158734. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  158735. pCsr->isMatchinfoNeeded = 1;
  158736. bGlobal = 1;
  158737. }
  158738. if( rc==SQLITE_OK ){
  158739. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  158740. if( xDestroyOut==0 ){
  158741. rc = SQLITE_NOMEM;
  158742. }
  158743. }
  158744. if( rc==SQLITE_OK ){
  158745. sInfo.aMatchinfo = aOut;
  158746. sInfo.nPhrase = pCsr->nPhrase;
  158747. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  158748. if( bGlobal ){
  158749. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  158750. }
  158751. }
  158752. if( rc!=SQLITE_OK ){
  158753. sqlite3_result_error_code(pCtx, rc);
  158754. if( xDestroyOut ) xDestroyOut(aOut);
  158755. }else{
  158756. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  158757. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  158758. }
  158759. }
  158760. /*
  158761. ** Implementation of snippet() function.
  158762. */
  158763. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  158764. sqlite3_context *pCtx, /* SQLite function call context */
  158765. Fts3Cursor *pCsr, /* Cursor object */
  158766. const char *zStart, /* Snippet start text - "<b>" */
  158767. const char *zEnd, /* Snippet end text - "</b>" */
  158768. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  158769. int iCol, /* Extract snippet from this column */
  158770. int nToken /* Approximate number of tokens in snippet */
  158771. ){
  158772. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  158773. int rc = SQLITE_OK;
  158774. int i;
  158775. StrBuffer res = {0, 0, 0};
  158776. /* The returned text includes up to four fragments of text extracted from
  158777. ** the data in the current row. The first iteration of the for(...) loop
  158778. ** below attempts to locate a single fragment of text nToken tokens in
  158779. ** size that contains at least one instance of all phrases in the query
  158780. ** expression that appear in the current row. If such a fragment of text
  158781. ** cannot be found, the second iteration of the loop attempts to locate
  158782. ** a pair of fragments, and so on.
  158783. */
  158784. int nSnippet = 0; /* Number of fragments in this snippet */
  158785. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  158786. int nFToken = -1; /* Number of tokens in each fragment */
  158787. if( !pCsr->pExpr ){
  158788. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  158789. return;
  158790. }
  158791. for(nSnippet=1; 1; nSnippet++){
  158792. int iSnip; /* Loop counter 0..nSnippet-1 */
  158793. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  158794. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  158795. if( nToken>=0 ){
  158796. nFToken = (nToken+nSnippet-1) / nSnippet;
  158797. }else{
  158798. nFToken = -1 * nToken;
  158799. }
  158800. for(iSnip=0; iSnip<nSnippet; iSnip++){
  158801. int iBestScore = -1; /* Best score of columns checked so far */
  158802. int iRead; /* Used to iterate through columns */
  158803. SnippetFragment *pFragment = &aSnippet[iSnip];
  158804. memset(pFragment, 0, sizeof(*pFragment));
  158805. /* Loop through all columns of the table being considered for snippets.
  158806. ** If the iCol argument to this function was negative, this means all
  158807. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  158808. */
  158809. for(iRead=0; iRead<pTab->nColumn; iRead++){
  158810. SnippetFragment sF = {0, 0, 0, 0};
  158811. int iS = 0;
  158812. if( iCol>=0 && iRead!=iCol ) continue;
  158813. /* Find the best snippet of nFToken tokens in column iRead. */
  158814. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  158815. if( rc!=SQLITE_OK ){
  158816. goto snippet_out;
  158817. }
  158818. if( iS>iBestScore ){
  158819. *pFragment = sF;
  158820. iBestScore = iS;
  158821. }
  158822. }
  158823. mCovered |= pFragment->covered;
  158824. }
  158825. /* If all query phrases seen by fts3BestSnippet() are present in at least
  158826. ** one of the nSnippet snippet fragments, break out of the loop.
  158827. */
  158828. assert( (mCovered&mSeen)==mCovered );
  158829. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  158830. }
  158831. assert( nFToken>0 );
  158832. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  158833. rc = fts3SnippetText(pCsr, &aSnippet[i],
  158834. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  158835. );
  158836. }
  158837. snippet_out:
  158838. sqlite3Fts3SegmentsClose(pTab);
  158839. if( rc!=SQLITE_OK ){
  158840. sqlite3_result_error_code(pCtx, rc);
  158841. sqlite3_free(res.z);
  158842. }else{
  158843. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  158844. }
  158845. }
  158846. typedef struct TermOffset TermOffset;
  158847. typedef struct TermOffsetCtx TermOffsetCtx;
  158848. struct TermOffset {
  158849. char *pList; /* Position-list */
  158850. int iPos; /* Position just read from pList */
  158851. int iOff; /* Offset of this term from read positions */
  158852. };
  158853. struct TermOffsetCtx {
  158854. Fts3Cursor *pCsr;
  158855. int iCol; /* Column of table to populate aTerm for */
  158856. int iTerm;
  158857. sqlite3_int64 iDocid;
  158858. TermOffset *aTerm;
  158859. };
  158860. /*
  158861. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  158862. */
  158863. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  158864. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  158865. int nTerm; /* Number of tokens in phrase */
  158866. int iTerm; /* For looping through nTerm phrase terms */
  158867. char *pList; /* Pointer to position list for phrase */
  158868. int iPos = 0; /* First position in position-list */
  158869. int rc;
  158870. UNUSED_PARAMETER(iPhrase);
  158871. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  158872. nTerm = pExpr->pPhrase->nToken;
  158873. if( pList ){
  158874. fts3GetDeltaPosition(&pList, &iPos);
  158875. assert( iPos>=0 );
  158876. }
  158877. for(iTerm=0; iTerm<nTerm; iTerm++){
  158878. TermOffset *pT = &p->aTerm[p->iTerm++];
  158879. pT->iOff = nTerm-iTerm-1;
  158880. pT->pList = pList;
  158881. pT->iPos = iPos;
  158882. }
  158883. return rc;
  158884. }
  158885. /*
  158886. ** Implementation of offsets() function.
  158887. */
  158888. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  158889. sqlite3_context *pCtx, /* SQLite function call context */
  158890. Fts3Cursor *pCsr /* Cursor object */
  158891. ){
  158892. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  158893. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  158894. int rc; /* Return Code */
  158895. int nToken; /* Number of tokens in query */
  158896. int iCol; /* Column currently being processed */
  158897. StrBuffer res = {0, 0, 0}; /* Result string */
  158898. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  158899. if( !pCsr->pExpr ){
  158900. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  158901. return;
  158902. }
  158903. memset(&sCtx, 0, sizeof(sCtx));
  158904. assert( pCsr->isRequireSeek==0 );
  158905. /* Count the number of terms in the query */
  158906. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  158907. if( rc!=SQLITE_OK ) goto offsets_out;
  158908. /* Allocate the array of TermOffset iterators. */
  158909. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  158910. if( 0==sCtx.aTerm ){
  158911. rc = SQLITE_NOMEM;
  158912. goto offsets_out;
  158913. }
  158914. sCtx.iDocid = pCsr->iPrevId;
  158915. sCtx.pCsr = pCsr;
  158916. /* Loop through the table columns, appending offset information to
  158917. ** string-buffer res for each column.
  158918. */
  158919. for(iCol=0; iCol<pTab->nColumn; iCol++){
  158920. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  158921. const char *ZDUMMY; /* Dummy argument used with xNext() */
  158922. int NDUMMY = 0; /* Dummy argument used with xNext() */
  158923. int iStart = 0;
  158924. int iEnd = 0;
  158925. int iCurrent = 0;
  158926. const char *zDoc;
  158927. int nDoc;
  158928. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  158929. ** no way that this operation can fail, so the return code from
  158930. ** fts3ExprIterate() can be discarded.
  158931. */
  158932. sCtx.iCol = iCol;
  158933. sCtx.iTerm = 0;
  158934. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  158935. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  158936. ** in column iCol, jump immediately to the next iteration of the loop.
  158937. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  158938. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  158939. ** to the caller.
  158940. */
  158941. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  158942. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  158943. if( zDoc==0 ){
  158944. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  158945. continue;
  158946. }
  158947. rc = SQLITE_NOMEM;
  158948. goto offsets_out;
  158949. }
  158950. /* Initialize a tokenizer iterator to iterate through column iCol. */
  158951. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  158952. zDoc, nDoc, &pC
  158953. );
  158954. if( rc!=SQLITE_OK ) goto offsets_out;
  158955. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  158956. while( rc==SQLITE_OK ){
  158957. int i; /* Used to loop through terms */
  158958. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  158959. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  158960. for(i=0; i<nToken; i++){
  158961. TermOffset *pT = &sCtx.aTerm[i];
  158962. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  158963. iMinPos = pT->iPos-pT->iOff;
  158964. pTerm = pT;
  158965. }
  158966. }
  158967. if( !pTerm ){
  158968. /* All offsets for this column have been gathered. */
  158969. rc = SQLITE_DONE;
  158970. }else{
  158971. assert( iCurrent<=iMinPos );
  158972. if( 0==(0xFE&*pTerm->pList) ){
  158973. pTerm->pList = 0;
  158974. }else{
  158975. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  158976. }
  158977. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  158978. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  158979. }
  158980. if( rc==SQLITE_OK ){
  158981. char aBuffer[64];
  158982. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  158983. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  158984. );
  158985. rc = fts3StringAppend(&res, aBuffer, -1);
  158986. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  158987. rc = FTS_CORRUPT_VTAB;
  158988. }
  158989. }
  158990. }
  158991. if( rc==SQLITE_DONE ){
  158992. rc = SQLITE_OK;
  158993. }
  158994. pMod->xClose(pC);
  158995. if( rc!=SQLITE_OK ) goto offsets_out;
  158996. }
  158997. offsets_out:
  158998. sqlite3_free(sCtx.aTerm);
  158999. assert( rc!=SQLITE_DONE );
  159000. sqlite3Fts3SegmentsClose(pTab);
  159001. if( rc!=SQLITE_OK ){
  159002. sqlite3_result_error_code(pCtx, rc);
  159003. sqlite3_free(res.z);
  159004. }else{
  159005. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  159006. }
  159007. return;
  159008. }
  159009. /*
  159010. ** Implementation of matchinfo() function.
  159011. */
  159012. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  159013. sqlite3_context *pContext, /* Function call context */
  159014. Fts3Cursor *pCsr, /* FTS3 table cursor */
  159015. const char *zArg /* Second arg to matchinfo() function */
  159016. ){
  159017. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  159018. const char *zFormat;
  159019. if( zArg ){
  159020. zFormat = zArg;
  159021. }else{
  159022. zFormat = FTS3_MATCHINFO_DEFAULT;
  159023. }
  159024. if( !pCsr->pExpr ){
  159025. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  159026. return;
  159027. }else{
  159028. /* Retrieve matchinfo() data. */
  159029. fts3GetMatchinfo(pContext, pCsr, zFormat);
  159030. sqlite3Fts3SegmentsClose(pTab);
  159031. }
  159032. }
  159033. #endif
  159034. /************** End of fts3_snippet.c ****************************************/
  159035. /************** Begin file fts3_unicode.c ************************************/
  159036. /*
  159037. ** 2012 May 24
  159038. **
  159039. ** The author disclaims copyright to this source code. In place of
  159040. ** a legal notice, here is a blessing:
  159041. **
  159042. ** May you do good and not evil.
  159043. ** May you find forgiveness for yourself and forgive others.
  159044. ** May you share freely, never taking more than you give.
  159045. **
  159046. ******************************************************************************
  159047. **
  159048. ** Implementation of the "unicode" full-text-search tokenizer.
  159049. */
  159050. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  159051. /* #include "fts3Int.h" */
  159052. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  159053. /* #include <assert.h> */
  159054. /* #include <stdlib.h> */
  159055. /* #include <stdio.h> */
  159056. /* #include <string.h> */
  159057. /* #include "fts3_tokenizer.h" */
  159058. /*
  159059. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  159060. ** from the sqlite3 source file utf.c. If this file is compiled as part
  159061. ** of the amalgamation, they are not required.
  159062. */
  159063. #ifndef SQLITE_AMALGAMATION
  159064. static const unsigned char sqlite3Utf8Trans1[] = {
  159065. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  159066. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  159067. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  159068. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  159069. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  159070. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  159071. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  159072. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  159073. };
  159074. #define READ_UTF8(zIn, zTerm, c) \
  159075. c = *(zIn++); \
  159076. if( c>=0xc0 ){ \
  159077. c = sqlite3Utf8Trans1[c-0xc0]; \
  159078. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  159079. c = (c<<6) + (0x3f & *(zIn++)); \
  159080. } \
  159081. if( c<0x80 \
  159082. || (c&0xFFFFF800)==0xD800 \
  159083. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  159084. }
  159085. #define WRITE_UTF8(zOut, c) { \
  159086. if( c<0x00080 ){ \
  159087. *zOut++ = (u8)(c&0xFF); \
  159088. } \
  159089. else if( c<0x00800 ){ \
  159090. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  159091. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  159092. } \
  159093. else if( c<0x10000 ){ \
  159094. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  159095. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  159096. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  159097. }else{ \
  159098. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  159099. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  159100. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  159101. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  159102. } \
  159103. }
  159104. #endif /* ifndef SQLITE_AMALGAMATION */
  159105. typedef struct unicode_tokenizer unicode_tokenizer;
  159106. typedef struct unicode_cursor unicode_cursor;
  159107. struct unicode_tokenizer {
  159108. sqlite3_tokenizer base;
  159109. int bRemoveDiacritic;
  159110. int nException;
  159111. int *aiException;
  159112. };
  159113. struct unicode_cursor {
  159114. sqlite3_tokenizer_cursor base;
  159115. const unsigned char *aInput; /* Input text being tokenized */
  159116. int nInput; /* Size of aInput[] in bytes */
  159117. int iOff; /* Current offset within aInput[] */
  159118. int iToken; /* Index of next token to be returned */
  159119. char *zToken; /* storage for current token */
  159120. int nAlloc; /* space allocated at zToken */
  159121. };
  159122. /*
  159123. ** Destroy a tokenizer allocated by unicodeCreate().
  159124. */
  159125. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  159126. if( pTokenizer ){
  159127. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  159128. sqlite3_free(p->aiException);
  159129. sqlite3_free(p);
  159130. }
  159131. return SQLITE_OK;
  159132. }
  159133. /*
  159134. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  159135. ** statement has specified that the tokenizer for this table shall consider
  159136. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  159137. ** token characters (if bAlnum==1).
  159138. **
  159139. ** For each codepoint in the zIn/nIn string, this function checks if the
  159140. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  159141. ** If so, no action is taken. Otherwise, the codepoint is added to the
  159142. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  159143. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  159144. ** codepoints in the aiException[] array.
  159145. **
  159146. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  159147. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  159148. ** It is not possible to change the behavior of the tokenizer with respect
  159149. ** to these codepoints.
  159150. */
  159151. static int unicodeAddExceptions(
  159152. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  159153. int bAlnum, /* Replace Isalnum() return value with this */
  159154. const char *zIn, /* Array of characters to make exceptions */
  159155. int nIn /* Length of z in bytes */
  159156. ){
  159157. const unsigned char *z = (const unsigned char *)zIn;
  159158. const unsigned char *zTerm = &z[nIn];
  159159. unsigned int iCode;
  159160. int nEntry = 0;
  159161. assert( bAlnum==0 || bAlnum==1 );
  159162. while( z<zTerm ){
  159163. READ_UTF8(z, zTerm, iCode);
  159164. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  159165. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  159166. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  159167. ){
  159168. nEntry++;
  159169. }
  159170. }
  159171. if( nEntry ){
  159172. int *aNew; /* New aiException[] array */
  159173. int nNew; /* Number of valid entries in array aNew[] */
  159174. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  159175. if( aNew==0 ) return SQLITE_NOMEM;
  159176. nNew = p->nException;
  159177. z = (const unsigned char *)zIn;
  159178. while( z<zTerm ){
  159179. READ_UTF8(z, zTerm, iCode);
  159180. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  159181. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  159182. ){
  159183. int i, j;
  159184. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  159185. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  159186. aNew[i] = (int)iCode;
  159187. nNew++;
  159188. }
  159189. }
  159190. p->aiException = aNew;
  159191. p->nException = nNew;
  159192. }
  159193. return SQLITE_OK;
  159194. }
  159195. /*
  159196. ** Return true if the p->aiException[] array contains the value iCode.
  159197. */
  159198. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  159199. if( p->nException>0 ){
  159200. int *a = p->aiException;
  159201. int iLo = 0;
  159202. int iHi = p->nException-1;
  159203. while( iHi>=iLo ){
  159204. int iTest = (iHi + iLo) / 2;
  159205. if( iCode==a[iTest] ){
  159206. return 1;
  159207. }else if( iCode>a[iTest] ){
  159208. iLo = iTest+1;
  159209. }else{
  159210. iHi = iTest-1;
  159211. }
  159212. }
  159213. }
  159214. return 0;
  159215. }
  159216. /*
  159217. ** Return true if, for the purposes of tokenization, codepoint iCode is
  159218. ** considered a token character (not a separator).
  159219. */
  159220. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  159221. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  159222. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  159223. }
  159224. /*
  159225. ** Create a new tokenizer instance.
  159226. */
  159227. static int unicodeCreate(
  159228. int nArg, /* Size of array argv[] */
  159229. const char * const *azArg, /* Tokenizer creation arguments */
  159230. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  159231. ){
  159232. unicode_tokenizer *pNew; /* New tokenizer object */
  159233. int i;
  159234. int rc = SQLITE_OK;
  159235. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  159236. if( pNew==NULL ) return SQLITE_NOMEM;
  159237. memset(pNew, 0, sizeof(unicode_tokenizer));
  159238. pNew->bRemoveDiacritic = 1;
  159239. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  159240. const char *z = azArg[i];
  159241. int n = (int)strlen(z);
  159242. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  159243. pNew->bRemoveDiacritic = 1;
  159244. }
  159245. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  159246. pNew->bRemoveDiacritic = 0;
  159247. }
  159248. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  159249. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  159250. }
  159251. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  159252. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  159253. }
  159254. else{
  159255. /* Unrecognized argument */
  159256. rc = SQLITE_ERROR;
  159257. }
  159258. }
  159259. if( rc!=SQLITE_OK ){
  159260. unicodeDestroy((sqlite3_tokenizer *)pNew);
  159261. pNew = 0;
  159262. }
  159263. *pp = (sqlite3_tokenizer *)pNew;
  159264. return rc;
  159265. }
  159266. /*
  159267. ** Prepare to begin tokenizing a particular string. The input
  159268. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  159269. ** used to incrementally tokenize this string is returned in
  159270. ** *ppCursor.
  159271. */
  159272. static int unicodeOpen(
  159273. sqlite3_tokenizer *p, /* The tokenizer */
  159274. const char *aInput, /* Input string */
  159275. int nInput, /* Size of string aInput in bytes */
  159276. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  159277. ){
  159278. unicode_cursor *pCsr;
  159279. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  159280. if( pCsr==0 ){
  159281. return SQLITE_NOMEM;
  159282. }
  159283. memset(pCsr, 0, sizeof(unicode_cursor));
  159284. pCsr->aInput = (const unsigned char *)aInput;
  159285. if( aInput==0 ){
  159286. pCsr->nInput = 0;
  159287. }else if( nInput<0 ){
  159288. pCsr->nInput = (int)strlen(aInput);
  159289. }else{
  159290. pCsr->nInput = nInput;
  159291. }
  159292. *pp = &pCsr->base;
  159293. UNUSED_PARAMETER(p);
  159294. return SQLITE_OK;
  159295. }
  159296. /*
  159297. ** Close a tokenization cursor previously opened by a call to
  159298. ** simpleOpen() above.
  159299. */
  159300. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  159301. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  159302. sqlite3_free(pCsr->zToken);
  159303. sqlite3_free(pCsr);
  159304. return SQLITE_OK;
  159305. }
  159306. /*
  159307. ** Extract the next token from a tokenization cursor. The cursor must
  159308. ** have been opened by a prior call to simpleOpen().
  159309. */
  159310. static int unicodeNext(
  159311. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  159312. const char **paToken, /* OUT: Token text */
  159313. int *pnToken, /* OUT: Number of bytes at *paToken */
  159314. int *piStart, /* OUT: Starting offset of token */
  159315. int *piEnd, /* OUT: Ending offset of token */
  159316. int *piPos /* OUT: Position integer of token */
  159317. ){
  159318. unicode_cursor *pCsr = (unicode_cursor *)pC;
  159319. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  159320. unsigned int iCode = 0;
  159321. char *zOut;
  159322. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  159323. const unsigned char *zStart = z;
  159324. const unsigned char *zEnd;
  159325. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  159326. /* Scan past any delimiter characters before the start of the next token.
  159327. ** Return SQLITE_DONE early if this takes us all the way to the end of
  159328. ** the input. */
  159329. while( z<zTerm ){
  159330. READ_UTF8(z, zTerm, iCode);
  159331. if( unicodeIsAlnum(p, (int)iCode) ) break;
  159332. zStart = z;
  159333. }
  159334. if( zStart>=zTerm ) return SQLITE_DONE;
  159335. zOut = pCsr->zToken;
  159336. do {
  159337. int iOut;
  159338. /* Grow the output buffer if required. */
  159339. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  159340. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  159341. if( !zNew ) return SQLITE_NOMEM;
  159342. zOut = &zNew[zOut - pCsr->zToken];
  159343. pCsr->zToken = zNew;
  159344. pCsr->nAlloc += 64;
  159345. }
  159346. /* Write the folded case of the last character read to the output */
  159347. zEnd = z;
  159348. iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
  159349. if( iOut ){
  159350. WRITE_UTF8(zOut, iOut);
  159351. }
  159352. /* If the cursor is not at EOF, read the next character */
  159353. if( z>=zTerm ) break;
  159354. READ_UTF8(z, zTerm, iCode);
  159355. }while( unicodeIsAlnum(p, (int)iCode)
  159356. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  159357. );
  159358. /* Set the output variables and return. */
  159359. pCsr->iOff = (int)(z - pCsr->aInput);
  159360. *paToken = pCsr->zToken;
  159361. *pnToken = (int)(zOut - pCsr->zToken);
  159362. *piStart = (int)(zStart - pCsr->aInput);
  159363. *piEnd = (int)(zEnd - pCsr->aInput);
  159364. *piPos = pCsr->iToken++;
  159365. return SQLITE_OK;
  159366. }
  159367. /*
  159368. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  159369. ** structure for the unicode tokenizer.
  159370. */
  159371. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  159372. static const sqlite3_tokenizer_module module = {
  159373. 0,
  159374. unicodeCreate,
  159375. unicodeDestroy,
  159376. unicodeOpen,
  159377. unicodeClose,
  159378. unicodeNext,
  159379. 0,
  159380. };
  159381. *ppModule = &module;
  159382. }
  159383. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  159384. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  159385. /************** End of fts3_unicode.c ****************************************/
  159386. /************** Begin file fts3_unicode2.c ***********************************/
  159387. /*
  159388. ** 2012 May 25
  159389. **
  159390. ** The author disclaims copyright to this source code. In place of
  159391. ** a legal notice, here is a blessing:
  159392. **
  159393. ** May you do good and not evil.
  159394. ** May you find forgiveness for yourself and forgive others.
  159395. ** May you share freely, never taking more than you give.
  159396. **
  159397. ******************************************************************************
  159398. */
  159399. /*
  159400. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  159401. */
  159402. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  159403. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  159404. /* #include <assert.h> */
  159405. /*
  159406. ** Return true if the argument corresponds to a unicode codepoint
  159407. ** classified as either a letter or a number. Otherwise false.
  159408. **
  159409. ** The results are undefined if the value passed to this function
  159410. ** is less than zero.
  159411. */
  159412. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  159413. /* Each unsigned integer in the following array corresponds to a contiguous
  159414. ** range of unicode codepoints that are not either letters or numbers (i.e.
  159415. ** codepoints for which this function should return 0).
  159416. **
  159417. ** The most significant 22 bits in each 32-bit value contain the first
  159418. ** codepoint in the range. The least significant 10 bits are used to store
  159419. ** the size of the range (always at least 1). In other words, the value
  159420. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  159421. ** C. It is not possible to represent a range larger than 1023 codepoints
  159422. ** using this format.
  159423. */
  159424. static const unsigned int aEntry[] = {
  159425. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  159426. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  159427. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  159428. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  159429. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  159430. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  159431. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  159432. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  159433. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  159434. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  159435. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  159436. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  159437. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  159438. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  159439. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  159440. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  159441. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  159442. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  159443. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  159444. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  159445. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  159446. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  159447. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  159448. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  159449. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  159450. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  159451. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  159452. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  159453. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  159454. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  159455. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  159456. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  159457. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  159458. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  159459. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  159460. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  159461. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  159462. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  159463. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  159464. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  159465. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  159466. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  159467. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  159468. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  159469. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  159470. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  159471. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  159472. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  159473. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  159474. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  159475. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  159476. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  159477. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  159478. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  159479. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  159480. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  159481. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  159482. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  159483. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  159484. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  159485. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  159486. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  159487. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  159488. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  159489. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  159490. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  159491. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  159492. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  159493. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  159494. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  159495. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  159496. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  159497. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  159498. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  159499. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  159500. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  159501. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  159502. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  159503. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  159504. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  159505. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  159506. 0x380400F0,
  159507. };
  159508. static const unsigned int aAscii[4] = {
  159509. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  159510. };
  159511. if( (unsigned int)c<128 ){
  159512. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  159513. }else if( (unsigned int)c<(1<<22) ){
  159514. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  159515. int iRes = 0;
  159516. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  159517. int iLo = 0;
  159518. while( iHi>=iLo ){
  159519. int iTest = (iHi + iLo) / 2;
  159520. if( key >= aEntry[iTest] ){
  159521. iRes = iTest;
  159522. iLo = iTest+1;
  159523. }else{
  159524. iHi = iTest-1;
  159525. }
  159526. }
  159527. assert( aEntry[0]<key );
  159528. assert( key>=aEntry[iRes] );
  159529. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  159530. }
  159531. return 1;
  159532. }
  159533. /*
  159534. ** If the argument is a codepoint corresponding to a lowercase letter
  159535. ** in the ASCII range with a diacritic added, return the codepoint
  159536. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  159537. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  159538. ** E"). The resuls of passing a codepoint that corresponds to an
  159539. ** uppercase letter are undefined.
  159540. */
  159541. static int remove_diacritic(int c){
  159542. unsigned short aDia[] = {
  159543. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  159544. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  159545. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  159546. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  159547. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  159548. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  159549. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  159550. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  159551. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  159552. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  159553. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  159554. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  159555. 62924, 63050, 63082, 63274, 63390,
  159556. };
  159557. char aChar[] = {
  159558. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  159559. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  159560. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  159561. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  159562. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  159563. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  159564. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  159565. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  159566. 'e', 'i', 'o', 'u', 'y',
  159567. };
  159568. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  159569. int iRes = 0;
  159570. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  159571. int iLo = 0;
  159572. while( iHi>=iLo ){
  159573. int iTest = (iHi + iLo) / 2;
  159574. if( key >= aDia[iTest] ){
  159575. iRes = iTest;
  159576. iLo = iTest+1;
  159577. }else{
  159578. iHi = iTest-1;
  159579. }
  159580. }
  159581. assert( key>=aDia[iRes] );
  159582. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  159583. }
  159584. /*
  159585. ** Return true if the argument interpreted as a unicode codepoint
  159586. ** is a diacritical modifier character.
  159587. */
  159588. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  159589. unsigned int mask0 = 0x08029FDF;
  159590. unsigned int mask1 = 0x000361F8;
  159591. if( c<768 || c>817 ) return 0;
  159592. return (c < 768+32) ?
  159593. (mask0 & (1 << (c-768))) :
  159594. (mask1 & (1 << (c-768-32)));
  159595. }
  159596. /*
  159597. ** Interpret the argument as a unicode codepoint. If the codepoint
  159598. ** is an upper case character that has a lower case equivalent,
  159599. ** return the codepoint corresponding to the lower case version.
  159600. ** Otherwise, return a copy of the argument.
  159601. **
  159602. ** The results are undefined if the value passed to this function
  159603. ** is less than zero.
  159604. */
  159605. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  159606. /* Each entry in the following array defines a rule for folding a range
  159607. ** of codepoints to lower case. The rule applies to a range of nRange
  159608. ** codepoints starting at codepoint iCode.
  159609. **
  159610. ** If the least significant bit in flags is clear, then the rule applies
  159611. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  159612. ** need to be folded). Or, if it is set, then the rule only applies to
  159613. ** every second codepoint in the range, starting with codepoint C.
  159614. **
  159615. ** The 7 most significant bits in flags are an index into the aiOff[]
  159616. ** array. If a specific codepoint C does require folding, then its lower
  159617. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  159618. **
  159619. ** The contents of this array are generated by parsing the CaseFolding.txt
  159620. ** file distributed as part of the "Unicode Character Database". See
  159621. ** http://www.unicode.org for details.
  159622. */
  159623. static const struct TableEntry {
  159624. unsigned short iCode;
  159625. unsigned char flags;
  159626. unsigned char nRange;
  159627. } aEntry[] = {
  159628. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  159629. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  159630. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  159631. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  159632. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  159633. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  159634. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  159635. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  159636. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  159637. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  159638. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  159639. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  159640. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  159641. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  159642. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  159643. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  159644. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  159645. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  159646. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  159647. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  159648. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  159649. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  159650. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  159651. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  159652. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  159653. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  159654. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  159655. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  159656. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  159657. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  159658. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  159659. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  159660. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  159661. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  159662. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  159663. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  159664. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  159665. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  159666. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  159667. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  159668. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  159669. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  159670. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  159671. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  159672. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  159673. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  159674. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  159675. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  159676. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  159677. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  159678. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  159679. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  159680. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  159681. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  159682. {65313, 14, 26},
  159683. };
  159684. static const unsigned short aiOff[] = {
  159685. 1, 2, 8, 15, 16, 26, 28, 32,
  159686. 37, 38, 40, 48, 63, 64, 69, 71,
  159687. 79, 80, 116, 202, 203, 205, 206, 207,
  159688. 209, 210, 211, 213, 214, 217, 218, 219,
  159689. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  159690. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  159691. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  159692. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  159693. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  159694. 65514, 65521, 65527, 65528, 65529,
  159695. };
  159696. int ret = c;
  159697. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  159698. if( c<128 ){
  159699. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  159700. }else if( c<65536 ){
  159701. const struct TableEntry *p;
  159702. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  159703. int iLo = 0;
  159704. int iRes = -1;
  159705. assert( c>aEntry[0].iCode );
  159706. while( iHi>=iLo ){
  159707. int iTest = (iHi + iLo) / 2;
  159708. int cmp = (c - aEntry[iTest].iCode);
  159709. if( cmp>=0 ){
  159710. iRes = iTest;
  159711. iLo = iTest+1;
  159712. }else{
  159713. iHi = iTest-1;
  159714. }
  159715. }
  159716. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  159717. p = &aEntry[iRes];
  159718. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  159719. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  159720. assert( ret>0 );
  159721. }
  159722. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  159723. }
  159724. else if( c>=66560 && c<66600 ){
  159725. ret = c + 40;
  159726. }
  159727. return ret;
  159728. }
  159729. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  159730. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  159731. /************** End of fts3_unicode2.c ***************************************/
  159732. /************** Begin file rtree.c *******************************************/
  159733. /*
  159734. ** 2001 September 15
  159735. **
  159736. ** The author disclaims copyright to this source code. In place of
  159737. ** a legal notice, here is a blessing:
  159738. **
  159739. ** May you do good and not evil.
  159740. ** May you find forgiveness for yourself and forgive others.
  159741. ** May you share freely, never taking more than you give.
  159742. **
  159743. *************************************************************************
  159744. ** This file contains code for implementations of the r-tree and r*-tree
  159745. ** algorithms packaged as an SQLite virtual table module.
  159746. */
  159747. /*
  159748. ** Database Format of R-Tree Tables
  159749. ** --------------------------------
  159750. **
  159751. ** The data structure for a single virtual r-tree table is stored in three
  159752. ** native SQLite tables declared as follows. In each case, the '%' character
  159753. ** in the table name is replaced with the user-supplied name of the r-tree
  159754. ** table.
  159755. **
  159756. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  159757. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  159758. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  159759. **
  159760. ** The data for each node of the r-tree structure is stored in the %_node
  159761. ** table. For each node that is not the root node of the r-tree, there is
  159762. ** an entry in the %_parent table associating the node with its parent.
  159763. ** And for each row of data in the table, there is an entry in the %_rowid
  159764. ** table that maps from the entries rowid to the id of the node that it
  159765. ** is stored on. If the r-tree contains auxiliary columns, those are stored
  159766. ** on the end of the %_rowid table.
  159767. **
  159768. ** The root node of an r-tree always exists, even if the r-tree table is
  159769. ** empty. The nodeno of the root node is always 1. All other nodes in the
  159770. ** table must be the same size as the root node. The content of each node
  159771. ** is formatted as follows:
  159772. **
  159773. ** 1. If the node is the root node (node 1), then the first 2 bytes
  159774. ** of the node contain the tree depth as a big-endian integer.
  159775. ** For non-root nodes, the first 2 bytes are left unused.
  159776. **
  159777. ** 2. The next 2 bytes contain the number of entries currently
  159778. ** stored in the node.
  159779. **
  159780. ** 3. The remainder of the node contains the node entries. Each entry
  159781. ** consists of a single 8-byte integer followed by an even number
  159782. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  159783. ** of a record. For internal nodes it is the node number of a
  159784. ** child page.
  159785. */
  159786. #if !defined(SQLITE_CORE) \
  159787. || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
  159788. #ifndef SQLITE_CORE
  159789. /* #include "sqlite3ext.h" */
  159790. SQLITE_EXTENSION_INIT1
  159791. #else
  159792. /* #include "sqlite3.h" */
  159793. #endif
  159794. /* #include <string.h> */
  159795. /* #include <assert.h> */
  159796. /* #include <stdio.h> */
  159797. #ifndef SQLITE_AMALGAMATION
  159798. #include "sqlite3rtree.h"
  159799. typedef sqlite3_int64 i64;
  159800. typedef sqlite3_uint64 u64;
  159801. typedef unsigned char u8;
  159802. typedef unsigned short u16;
  159803. typedef unsigned int u32;
  159804. #endif
  159805. /* The following macro is used to suppress compiler warnings.
  159806. */
  159807. #ifndef UNUSED_PARAMETER
  159808. # define UNUSED_PARAMETER(x) (void)(x)
  159809. #endif
  159810. typedef struct Rtree Rtree;
  159811. typedef struct RtreeCursor RtreeCursor;
  159812. typedef struct RtreeNode RtreeNode;
  159813. typedef struct RtreeCell RtreeCell;
  159814. typedef struct RtreeConstraint RtreeConstraint;
  159815. typedef struct RtreeMatchArg RtreeMatchArg;
  159816. typedef struct RtreeGeomCallback RtreeGeomCallback;
  159817. typedef union RtreeCoord RtreeCoord;
  159818. typedef struct RtreeSearchPoint RtreeSearchPoint;
  159819. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  159820. #define RTREE_MAX_DIMENSIONS 5
  159821. /* Maximum number of auxiliary columns */
  159822. #define RTREE_MAX_AUX_COLUMN 100
  159823. /* Size of hash table Rtree.aHash. This hash table is not expected to
  159824. ** ever contain very many entries, so a fixed number of buckets is
  159825. ** used.
  159826. */
  159827. #define HASHSIZE 97
  159828. /* The xBestIndex method of this virtual table requires an estimate of
  159829. ** the number of rows in the virtual table to calculate the costs of
  159830. ** various strategies. If possible, this estimate is loaded from the
  159831. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  159832. ** Otherwise, if no sqlite_stat1 entry is available, use
  159833. ** RTREE_DEFAULT_ROWEST.
  159834. */
  159835. #define RTREE_DEFAULT_ROWEST 1048576
  159836. #define RTREE_MIN_ROWEST 100
  159837. /*
  159838. ** An rtree virtual-table object.
  159839. */
  159840. struct Rtree {
  159841. sqlite3_vtab base; /* Base class. Must be first */
  159842. sqlite3 *db; /* Host database connection */
  159843. int iNodeSize; /* Size in bytes of each node in the node table */
  159844. u8 nDim; /* Number of dimensions */
  159845. u8 nDim2; /* Twice the number of dimensions */
  159846. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  159847. u8 nBytesPerCell; /* Bytes consumed per cell */
  159848. u8 inWrTrans; /* True if inside write transaction */
  159849. u8 nAux; /* # of auxiliary columns in %_rowid */
  159850. int iDepth; /* Current depth of the r-tree structure */
  159851. char *zDb; /* Name of database containing r-tree table */
  159852. char *zName; /* Name of r-tree table */
  159853. u32 nBusy; /* Current number of users of this structure */
  159854. i64 nRowEst; /* Estimated number of rows in this table */
  159855. u32 nCursor; /* Number of open cursors */
  159856. u32 nNodeRef; /* Number RtreeNodes with positive nRef */
  159857. char *zReadAuxSql; /* SQL for statement to read aux data */
  159858. /* List of nodes removed during a CondenseTree operation. List is
  159859. ** linked together via the pointer normally used for hash chains -
  159860. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  159861. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  159862. */
  159863. RtreeNode *pDeleted;
  159864. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  159865. /* Blob I/O on xxx_node */
  159866. sqlite3_blob *pNodeBlob;
  159867. /* Statements to read/write/delete a record from xxx_node */
  159868. sqlite3_stmt *pWriteNode;
  159869. sqlite3_stmt *pDeleteNode;
  159870. /* Statements to read/write/delete a record from xxx_rowid */
  159871. sqlite3_stmt *pReadRowid;
  159872. sqlite3_stmt *pWriteRowid;
  159873. sqlite3_stmt *pDeleteRowid;
  159874. /* Statements to read/write/delete a record from xxx_parent */
  159875. sqlite3_stmt *pReadParent;
  159876. sqlite3_stmt *pWriteParent;
  159877. sqlite3_stmt *pDeleteParent;
  159878. /* Statement for writing to the "aux:" fields, if there are any */
  159879. sqlite3_stmt *pWriteAux;
  159880. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  159881. };
  159882. /* Possible values for Rtree.eCoordType: */
  159883. #define RTREE_COORD_REAL32 0
  159884. #define RTREE_COORD_INT32 1
  159885. /*
  159886. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  159887. ** only deal with integer coordinates. No floating point operations
  159888. ** will be done.
  159889. */
  159890. #ifdef SQLITE_RTREE_INT_ONLY
  159891. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  159892. typedef int RtreeValue; /* Low accuracy coordinate */
  159893. # define RTREE_ZERO 0
  159894. #else
  159895. typedef double RtreeDValue; /* High accuracy coordinate */
  159896. typedef float RtreeValue; /* Low accuracy coordinate */
  159897. # define RTREE_ZERO 0.0
  159898. #endif
  159899. /*
  159900. ** When doing a search of an r-tree, instances of the following structure
  159901. ** record intermediate results from the tree walk.
  159902. **
  159903. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  159904. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  159905. ** the id is of the parent node and the cell that RtreeSearchPoint
  159906. ** represents is the iCell-th entry in the parent node.
  159907. */
  159908. struct RtreeSearchPoint {
  159909. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  159910. sqlite3_int64 id; /* Node ID */
  159911. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  159912. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  159913. u8 iCell; /* Cell index within the node */
  159914. };
  159915. /*
  159916. ** The minimum number of cells allowed for a node is a third of the
  159917. ** maximum. In Gutman's notation:
  159918. **
  159919. ** m = M/3
  159920. **
  159921. ** If an R*-tree "Reinsert" operation is required, the same number of
  159922. ** cells are removed from the overfull node and reinserted into the tree.
  159923. */
  159924. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  159925. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  159926. #define RTREE_MAXCELLS 51
  159927. /*
  159928. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  159929. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  159930. ** Therefore all non-root nodes must contain at least 3 entries. Since
  159931. ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
  159932. ** 40 or less.
  159933. */
  159934. #define RTREE_MAX_DEPTH 40
  159935. /*
  159936. ** Number of entries in the cursor RtreeNode cache. The first entry is
  159937. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  159938. ** entries cache the RtreeNode for the first elements of the priority queue.
  159939. */
  159940. #define RTREE_CACHE_SZ 5
  159941. /*
  159942. ** An rtree cursor object.
  159943. */
  159944. struct RtreeCursor {
  159945. sqlite3_vtab_cursor base; /* Base class. Must be first */
  159946. u8 atEOF; /* True if at end of search */
  159947. u8 bPoint; /* True if sPoint is valid */
  159948. u8 bAuxValid; /* True if pReadAux is valid */
  159949. int iStrategy; /* Copy of idxNum search parameter */
  159950. int nConstraint; /* Number of entries in aConstraint */
  159951. RtreeConstraint *aConstraint; /* Search constraints. */
  159952. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  159953. int nPoint; /* Number of slots used in aPoint[] */
  159954. int mxLevel; /* iLevel value for root of the tree */
  159955. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  159956. sqlite3_stmt *pReadAux; /* Statement to read aux-data */
  159957. RtreeSearchPoint sPoint; /* Cached next search point */
  159958. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  159959. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  159960. };
  159961. /* Return the Rtree of a RtreeCursor */
  159962. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  159963. /*
  159964. ** A coordinate can be either a floating point number or a integer. All
  159965. ** coordinates within a single R-Tree are always of the same time.
  159966. */
  159967. union RtreeCoord {
  159968. RtreeValue f; /* Floating point value */
  159969. int i; /* Integer value */
  159970. u32 u; /* Unsigned for byte-order conversions */
  159971. };
  159972. /*
  159973. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  159974. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  159975. ** variable pRtree points to the Rtree structure associated with the
  159976. ** RtreeCoord.
  159977. */
  159978. #ifdef SQLITE_RTREE_INT_ONLY
  159979. # define DCOORD(coord) ((RtreeDValue)coord.i)
  159980. #else
  159981. # define DCOORD(coord) ( \
  159982. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  159983. ((double)coord.f) : \
  159984. ((double)coord.i) \
  159985. )
  159986. #endif
  159987. /*
  159988. ** A search constraint.
  159989. */
  159990. struct RtreeConstraint {
  159991. int iCoord; /* Index of constrained coordinate */
  159992. int op; /* Constraining operation */
  159993. union {
  159994. RtreeDValue rValue; /* Constraint value. */
  159995. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  159996. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  159997. } u;
  159998. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  159999. };
  160000. /* Possible values for RtreeConstraint.op */
  160001. #define RTREE_EQ 0x41 /* A */
  160002. #define RTREE_LE 0x42 /* B */
  160003. #define RTREE_LT 0x43 /* C */
  160004. #define RTREE_GE 0x44 /* D */
  160005. #define RTREE_GT 0x45 /* E */
  160006. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  160007. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  160008. /*
  160009. ** An rtree structure node.
  160010. */
  160011. struct RtreeNode {
  160012. RtreeNode *pParent; /* Parent node */
  160013. i64 iNode; /* The node number */
  160014. int nRef; /* Number of references to this node */
  160015. int isDirty; /* True if the node needs to be written to disk */
  160016. u8 *zData; /* Content of the node, as should be on disk */
  160017. RtreeNode *pNext; /* Next node in this hash collision chain */
  160018. };
  160019. /* Return the number of cells in a node */
  160020. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  160021. /*
  160022. ** A single cell from a node, deserialized
  160023. */
  160024. struct RtreeCell {
  160025. i64 iRowid; /* Node or entry ID */
  160026. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  160027. };
  160028. /*
  160029. ** This object becomes the sqlite3_user_data() for the SQL functions
  160030. ** that are created by sqlite3_rtree_geometry_callback() and
  160031. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  160032. ** operators in order to constrain a search.
  160033. **
  160034. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  160035. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  160036. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  160037. ** sqlite3_rtree_query_callback().
  160038. **
  160039. ** This object is deleted automatically by the destructor mechanism in
  160040. ** sqlite3_create_function_v2().
  160041. */
  160042. struct RtreeGeomCallback {
  160043. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  160044. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  160045. void (*xDestructor)(void*);
  160046. void *pContext;
  160047. };
  160048. /*
  160049. ** An instance of this structure (in the form of a BLOB) is returned by
  160050. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  160051. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  160052. ** operand to the MATCH operator of an R-Tree.
  160053. */
  160054. struct RtreeMatchArg {
  160055. u32 iSize; /* Size of this object */
  160056. RtreeGeomCallback cb; /* Info about the callback functions */
  160057. int nParam; /* Number of parameters to the SQL function */
  160058. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  160059. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  160060. };
  160061. #ifndef MAX
  160062. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  160063. #endif
  160064. #ifndef MIN
  160065. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  160066. #endif
  160067. /* What version of GCC is being used. 0 means GCC is not being used .
  160068. ** Note that the GCC_VERSION macro will also be set correctly when using
  160069. ** clang, since clang works hard to be gcc compatible. So the gcc
  160070. ** optimizations will also work when compiling with clang.
  160071. */
  160072. #ifndef GCC_VERSION
  160073. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  160074. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  160075. #else
  160076. # define GCC_VERSION 0
  160077. #endif
  160078. #endif
  160079. /* The testcase() macro should already be defined in the amalgamation. If
  160080. ** it is not, make it a no-op.
  160081. */
  160082. #ifndef SQLITE_AMALGAMATION
  160083. # define testcase(X)
  160084. #endif
  160085. /*
  160086. ** Macros to determine whether the machine is big or little endian,
  160087. ** and whether or not that determination is run-time or compile-time.
  160088. **
  160089. ** For best performance, an attempt is made to guess at the byte-order
  160090. ** using C-preprocessor macros. If that is unsuccessful, or if
  160091. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  160092. ** at run-time.
  160093. */
  160094. #ifndef SQLITE_BYTEORDER
  160095. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  160096. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  160097. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  160098. defined(__arm__)
  160099. # define SQLITE_BYTEORDER 1234
  160100. #elif defined(sparc) || defined(__ppc__)
  160101. # define SQLITE_BYTEORDER 4321
  160102. #else
  160103. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  160104. #endif
  160105. #endif
  160106. /* What version of MSVC is being used. 0 means MSVC is not being used */
  160107. #ifndef MSVC_VERSION
  160108. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  160109. # define MSVC_VERSION _MSC_VER
  160110. #else
  160111. # define MSVC_VERSION 0
  160112. #endif
  160113. #endif
  160114. /*
  160115. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  160116. ** 64 bit integer. The deserialized value is returned.
  160117. */
  160118. static int readInt16(u8 *p){
  160119. return (p[0]<<8) + p[1];
  160120. }
  160121. static void readCoord(u8 *p, RtreeCoord *pCoord){
  160122. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  160123. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  160124. pCoord->u = _byteswap_ulong(*(u32*)p);
  160125. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  160126. pCoord->u = __builtin_bswap32(*(u32*)p);
  160127. #elif SQLITE_BYTEORDER==4321
  160128. pCoord->u = *(u32*)p;
  160129. #else
  160130. pCoord->u = (
  160131. (((u32)p[0]) << 24) +
  160132. (((u32)p[1]) << 16) +
  160133. (((u32)p[2]) << 8) +
  160134. (((u32)p[3]) << 0)
  160135. );
  160136. #endif
  160137. }
  160138. static i64 readInt64(u8 *p){
  160139. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  160140. u64 x;
  160141. memcpy(&x, p, 8);
  160142. return (i64)_byteswap_uint64(x);
  160143. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  160144. u64 x;
  160145. memcpy(&x, p, 8);
  160146. return (i64)__builtin_bswap64(x);
  160147. #elif SQLITE_BYTEORDER==4321
  160148. i64 x;
  160149. memcpy(&x, p, 8);
  160150. return x;
  160151. #else
  160152. return (i64)(
  160153. (((u64)p[0]) << 56) +
  160154. (((u64)p[1]) << 48) +
  160155. (((u64)p[2]) << 40) +
  160156. (((u64)p[3]) << 32) +
  160157. (((u64)p[4]) << 24) +
  160158. (((u64)p[5]) << 16) +
  160159. (((u64)p[6]) << 8) +
  160160. (((u64)p[7]) << 0)
  160161. );
  160162. #endif
  160163. }
  160164. /*
  160165. ** Functions to serialize a 16 bit integer, 32 bit real number and
  160166. ** 64 bit integer. The value returned is the number of bytes written
  160167. ** to the argument buffer (always 2, 4 and 8 respectively).
  160168. */
  160169. static void writeInt16(u8 *p, int i){
  160170. p[0] = (i>> 8)&0xFF;
  160171. p[1] = (i>> 0)&0xFF;
  160172. }
  160173. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  160174. u32 i;
  160175. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  160176. assert( sizeof(RtreeCoord)==4 );
  160177. assert( sizeof(u32)==4 );
  160178. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  160179. i = __builtin_bswap32(pCoord->u);
  160180. memcpy(p, &i, 4);
  160181. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  160182. i = _byteswap_ulong(pCoord->u);
  160183. memcpy(p, &i, 4);
  160184. #elif SQLITE_BYTEORDER==4321
  160185. i = pCoord->u;
  160186. memcpy(p, &i, 4);
  160187. #else
  160188. i = pCoord->u;
  160189. p[0] = (i>>24)&0xFF;
  160190. p[1] = (i>>16)&0xFF;
  160191. p[2] = (i>> 8)&0xFF;
  160192. p[3] = (i>> 0)&0xFF;
  160193. #endif
  160194. return 4;
  160195. }
  160196. static int writeInt64(u8 *p, i64 i){
  160197. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  160198. i = (i64)__builtin_bswap64((u64)i);
  160199. memcpy(p, &i, 8);
  160200. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  160201. i = (i64)_byteswap_uint64((u64)i);
  160202. memcpy(p, &i, 8);
  160203. #elif SQLITE_BYTEORDER==4321
  160204. memcpy(p, &i, 8);
  160205. #else
  160206. p[0] = (i>>56)&0xFF;
  160207. p[1] = (i>>48)&0xFF;
  160208. p[2] = (i>>40)&0xFF;
  160209. p[3] = (i>>32)&0xFF;
  160210. p[4] = (i>>24)&0xFF;
  160211. p[5] = (i>>16)&0xFF;
  160212. p[6] = (i>> 8)&0xFF;
  160213. p[7] = (i>> 0)&0xFF;
  160214. #endif
  160215. return 8;
  160216. }
  160217. /*
  160218. ** Increment the reference count of node p.
  160219. */
  160220. static void nodeReference(RtreeNode *p){
  160221. if( p ){
  160222. assert( p->nRef>0 );
  160223. p->nRef++;
  160224. }
  160225. }
  160226. /*
  160227. ** Clear the content of node p (set all bytes to 0x00).
  160228. */
  160229. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  160230. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  160231. p->isDirty = 1;
  160232. }
  160233. /*
  160234. ** Given a node number iNode, return the corresponding key to use
  160235. ** in the Rtree.aHash table.
  160236. */
  160237. static int nodeHash(i64 iNode){
  160238. return iNode % HASHSIZE;
  160239. }
  160240. /*
  160241. ** Search the node hash table for node iNode. If found, return a pointer
  160242. ** to it. Otherwise, return 0.
  160243. */
  160244. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  160245. RtreeNode *p;
  160246. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  160247. return p;
  160248. }
  160249. /*
  160250. ** Add node pNode to the node hash table.
  160251. */
  160252. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  160253. int iHash;
  160254. assert( pNode->pNext==0 );
  160255. iHash = nodeHash(pNode->iNode);
  160256. pNode->pNext = pRtree->aHash[iHash];
  160257. pRtree->aHash[iHash] = pNode;
  160258. }
  160259. /*
  160260. ** Remove node pNode from the node hash table.
  160261. */
  160262. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  160263. RtreeNode **pp;
  160264. if( pNode->iNode!=0 ){
  160265. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  160266. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  160267. *pp = pNode->pNext;
  160268. pNode->pNext = 0;
  160269. }
  160270. }
  160271. /*
  160272. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  160273. ** indicating that node has not yet been assigned a node number. It is
  160274. ** assigned a node number when nodeWrite() is called to write the
  160275. ** node contents out to the database.
  160276. */
  160277. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  160278. RtreeNode *pNode;
  160279. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  160280. if( pNode ){
  160281. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  160282. pNode->zData = (u8 *)&pNode[1];
  160283. pNode->nRef = 1;
  160284. pRtree->nNodeRef++;
  160285. pNode->pParent = pParent;
  160286. pNode->isDirty = 1;
  160287. nodeReference(pParent);
  160288. }
  160289. return pNode;
  160290. }
  160291. /*
  160292. ** Clear the Rtree.pNodeBlob object
  160293. */
  160294. static void nodeBlobReset(Rtree *pRtree){
  160295. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  160296. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  160297. pRtree->pNodeBlob = 0;
  160298. sqlite3_blob_close(pBlob);
  160299. }
  160300. }
  160301. /*
  160302. ** Obtain a reference to an r-tree node.
  160303. */
  160304. static int nodeAcquire(
  160305. Rtree *pRtree, /* R-tree structure */
  160306. i64 iNode, /* Node number to load */
  160307. RtreeNode *pParent, /* Either the parent node or NULL */
  160308. RtreeNode **ppNode /* OUT: Acquired node */
  160309. ){
  160310. int rc = SQLITE_OK;
  160311. RtreeNode *pNode = 0;
  160312. /* Check if the requested node is already in the hash table. If so,
  160313. ** increase its reference count and return it.
  160314. */
  160315. if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
  160316. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  160317. if( pParent && !pNode->pParent ){
  160318. pParent->nRef++;
  160319. pNode->pParent = pParent;
  160320. }
  160321. pNode->nRef++;
  160322. *ppNode = pNode;
  160323. return SQLITE_OK;
  160324. }
  160325. if( pRtree->pNodeBlob ){
  160326. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  160327. pRtree->pNodeBlob = 0;
  160328. rc = sqlite3_blob_reopen(pBlob, iNode);
  160329. pRtree->pNodeBlob = pBlob;
  160330. if( rc ){
  160331. nodeBlobReset(pRtree);
  160332. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  160333. }
  160334. }
  160335. if( pRtree->pNodeBlob==0 ){
  160336. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  160337. if( zTab==0 ) return SQLITE_NOMEM;
  160338. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  160339. &pRtree->pNodeBlob);
  160340. sqlite3_free(zTab);
  160341. }
  160342. if( rc ){
  160343. nodeBlobReset(pRtree);
  160344. *ppNode = 0;
  160345. /* If unable to open an sqlite3_blob on the desired row, that can only
  160346. ** be because the shadow tables hold erroneous data. */
  160347. if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
  160348. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  160349. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  160350. if( !pNode ){
  160351. rc = SQLITE_NOMEM;
  160352. }else{
  160353. pNode->pParent = pParent;
  160354. pNode->zData = (u8 *)&pNode[1];
  160355. pNode->nRef = 1;
  160356. pRtree->nNodeRef++;
  160357. pNode->iNode = iNode;
  160358. pNode->isDirty = 0;
  160359. pNode->pNext = 0;
  160360. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  160361. pRtree->iNodeSize, 0);
  160362. nodeReference(pParent);
  160363. }
  160364. }
  160365. /* If the root node was just loaded, set pRtree->iDepth to the height
  160366. ** of the r-tree structure. A height of zero means all data is stored on
  160367. ** the root node. A height of one means the children of the root node
  160368. ** are the leaves, and so on. If the depth as specified on the root node
  160369. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  160370. */
  160371. if( pNode && iNode==1 ){
  160372. pRtree->iDepth = readInt16(pNode->zData);
  160373. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  160374. rc = SQLITE_CORRUPT_VTAB;
  160375. }
  160376. }
  160377. /* If no error has occurred so far, check if the "number of entries"
  160378. ** field on the node is too large. If so, set the return code to
  160379. ** SQLITE_CORRUPT_VTAB.
  160380. */
  160381. if( pNode && rc==SQLITE_OK ){
  160382. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  160383. rc = SQLITE_CORRUPT_VTAB;
  160384. }
  160385. }
  160386. if( rc==SQLITE_OK ){
  160387. if( pNode!=0 ){
  160388. nodeHashInsert(pRtree, pNode);
  160389. }else{
  160390. rc = SQLITE_CORRUPT_VTAB;
  160391. }
  160392. *ppNode = pNode;
  160393. }else{
  160394. if( pNode ){
  160395. pRtree->nNodeRef--;
  160396. sqlite3_free(pNode);
  160397. }
  160398. *ppNode = 0;
  160399. }
  160400. return rc;
  160401. }
  160402. /*
  160403. ** Overwrite cell iCell of node pNode with the contents of pCell.
  160404. */
  160405. static void nodeOverwriteCell(
  160406. Rtree *pRtree, /* The overall R-Tree */
  160407. RtreeNode *pNode, /* The node into which the cell is to be written */
  160408. RtreeCell *pCell, /* The cell to write */
  160409. int iCell /* Index into pNode into which pCell is written */
  160410. ){
  160411. int ii;
  160412. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  160413. p += writeInt64(p, pCell->iRowid);
  160414. for(ii=0; ii<pRtree->nDim2; ii++){
  160415. p += writeCoord(p, &pCell->aCoord[ii]);
  160416. }
  160417. pNode->isDirty = 1;
  160418. }
  160419. /*
  160420. ** Remove the cell with index iCell from node pNode.
  160421. */
  160422. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  160423. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  160424. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  160425. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  160426. memmove(pDst, pSrc, nByte);
  160427. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  160428. pNode->isDirty = 1;
  160429. }
  160430. /*
  160431. ** Insert the contents of cell pCell into node pNode. If the insert
  160432. ** is successful, return SQLITE_OK.
  160433. **
  160434. ** If there is not enough free space in pNode, return SQLITE_FULL.
  160435. */
  160436. static int nodeInsertCell(
  160437. Rtree *pRtree, /* The overall R-Tree */
  160438. RtreeNode *pNode, /* Write new cell into this node */
  160439. RtreeCell *pCell /* The cell to be inserted */
  160440. ){
  160441. int nCell; /* Current number of cells in pNode */
  160442. int nMaxCell; /* Maximum number of cells for pNode */
  160443. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  160444. nCell = NCELL(pNode);
  160445. assert( nCell<=nMaxCell );
  160446. if( nCell<nMaxCell ){
  160447. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  160448. writeInt16(&pNode->zData[2], nCell+1);
  160449. pNode->isDirty = 1;
  160450. }
  160451. return (nCell==nMaxCell);
  160452. }
  160453. /*
  160454. ** If the node is dirty, write it out to the database.
  160455. */
  160456. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  160457. int rc = SQLITE_OK;
  160458. if( pNode->isDirty ){
  160459. sqlite3_stmt *p = pRtree->pWriteNode;
  160460. if( pNode->iNode ){
  160461. sqlite3_bind_int64(p, 1, pNode->iNode);
  160462. }else{
  160463. sqlite3_bind_null(p, 1);
  160464. }
  160465. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  160466. sqlite3_step(p);
  160467. pNode->isDirty = 0;
  160468. rc = sqlite3_reset(p);
  160469. sqlite3_bind_null(p, 2);
  160470. if( pNode->iNode==0 && rc==SQLITE_OK ){
  160471. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  160472. nodeHashInsert(pRtree, pNode);
  160473. }
  160474. }
  160475. return rc;
  160476. }
  160477. /*
  160478. ** Release a reference to a node. If the node is dirty and the reference
  160479. ** count drops to zero, the node data is written to the database.
  160480. */
  160481. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  160482. int rc = SQLITE_OK;
  160483. if( pNode ){
  160484. assert( pNode->nRef>0 );
  160485. assert( pRtree->nNodeRef>0 );
  160486. pNode->nRef--;
  160487. if( pNode->nRef==0 ){
  160488. pRtree->nNodeRef--;
  160489. if( pNode->iNode==1 ){
  160490. pRtree->iDepth = -1;
  160491. }
  160492. if( pNode->pParent ){
  160493. rc = nodeRelease(pRtree, pNode->pParent);
  160494. }
  160495. if( rc==SQLITE_OK ){
  160496. rc = nodeWrite(pRtree, pNode);
  160497. }
  160498. nodeHashDelete(pRtree, pNode);
  160499. sqlite3_free(pNode);
  160500. }
  160501. }
  160502. return rc;
  160503. }
  160504. /*
  160505. ** Return the 64-bit integer value associated with cell iCell of
  160506. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  160507. ** an internal node, then the 64-bit integer is a child page number.
  160508. */
  160509. static i64 nodeGetRowid(
  160510. Rtree *pRtree, /* The overall R-Tree */
  160511. RtreeNode *pNode, /* The node from which to extract the ID */
  160512. int iCell /* The cell index from which to extract the ID */
  160513. ){
  160514. assert( iCell<NCELL(pNode) );
  160515. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  160516. }
  160517. /*
  160518. ** Return coordinate iCoord from cell iCell in node pNode.
  160519. */
  160520. static void nodeGetCoord(
  160521. Rtree *pRtree, /* The overall R-Tree */
  160522. RtreeNode *pNode, /* The node from which to extract a coordinate */
  160523. int iCell, /* The index of the cell within the node */
  160524. int iCoord, /* Which coordinate to extract */
  160525. RtreeCoord *pCoord /* OUT: Space to write result to */
  160526. ){
  160527. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  160528. }
  160529. /*
  160530. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  160531. ** to by pCell with the results.
  160532. */
  160533. static void nodeGetCell(
  160534. Rtree *pRtree, /* The overall R-Tree */
  160535. RtreeNode *pNode, /* The node containing the cell to be read */
  160536. int iCell, /* Index of the cell within the node */
  160537. RtreeCell *pCell /* OUT: Write the cell contents here */
  160538. ){
  160539. u8 *pData;
  160540. RtreeCoord *pCoord;
  160541. int ii = 0;
  160542. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  160543. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  160544. pCoord = pCell->aCoord;
  160545. do{
  160546. readCoord(pData, &pCoord[ii]);
  160547. readCoord(pData+4, &pCoord[ii+1]);
  160548. pData += 8;
  160549. ii += 2;
  160550. }while( ii<pRtree->nDim2 );
  160551. }
  160552. /* Forward declaration for the function that does the work of
  160553. ** the virtual table module xCreate() and xConnect() methods.
  160554. */
  160555. static int rtreeInit(
  160556. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  160557. );
  160558. /*
  160559. ** Rtree virtual table module xCreate method.
  160560. */
  160561. static int rtreeCreate(
  160562. sqlite3 *db,
  160563. void *pAux,
  160564. int argc, const char *const*argv,
  160565. sqlite3_vtab **ppVtab,
  160566. char **pzErr
  160567. ){
  160568. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  160569. }
  160570. /*
  160571. ** Rtree virtual table module xConnect method.
  160572. */
  160573. static int rtreeConnect(
  160574. sqlite3 *db,
  160575. void *pAux,
  160576. int argc, const char *const*argv,
  160577. sqlite3_vtab **ppVtab,
  160578. char **pzErr
  160579. ){
  160580. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  160581. }
  160582. /*
  160583. ** Increment the r-tree reference count.
  160584. */
  160585. static void rtreeReference(Rtree *pRtree){
  160586. pRtree->nBusy++;
  160587. }
  160588. /*
  160589. ** Decrement the r-tree reference count. When the reference count reaches
  160590. ** zero the structure is deleted.
  160591. */
  160592. static void rtreeRelease(Rtree *pRtree){
  160593. pRtree->nBusy--;
  160594. if( pRtree->nBusy==0 ){
  160595. pRtree->inWrTrans = 0;
  160596. assert( pRtree->nCursor==0 );
  160597. nodeBlobReset(pRtree);
  160598. assert( pRtree->nNodeRef==0 );
  160599. sqlite3_finalize(pRtree->pWriteNode);
  160600. sqlite3_finalize(pRtree->pDeleteNode);
  160601. sqlite3_finalize(pRtree->pReadRowid);
  160602. sqlite3_finalize(pRtree->pWriteRowid);
  160603. sqlite3_finalize(pRtree->pDeleteRowid);
  160604. sqlite3_finalize(pRtree->pReadParent);
  160605. sqlite3_finalize(pRtree->pWriteParent);
  160606. sqlite3_finalize(pRtree->pDeleteParent);
  160607. sqlite3_finalize(pRtree->pWriteAux);
  160608. sqlite3_free(pRtree->zReadAuxSql);
  160609. sqlite3_free(pRtree);
  160610. }
  160611. }
  160612. /*
  160613. ** Rtree virtual table module xDisconnect method.
  160614. */
  160615. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  160616. rtreeRelease((Rtree *)pVtab);
  160617. return SQLITE_OK;
  160618. }
  160619. /*
  160620. ** Rtree virtual table module xDestroy method.
  160621. */
  160622. static int rtreeDestroy(sqlite3_vtab *pVtab){
  160623. Rtree *pRtree = (Rtree *)pVtab;
  160624. int rc;
  160625. char *zCreate = sqlite3_mprintf(
  160626. "DROP TABLE '%q'.'%q_node';"
  160627. "DROP TABLE '%q'.'%q_rowid';"
  160628. "DROP TABLE '%q'.'%q_parent';",
  160629. pRtree->zDb, pRtree->zName,
  160630. pRtree->zDb, pRtree->zName,
  160631. pRtree->zDb, pRtree->zName
  160632. );
  160633. if( !zCreate ){
  160634. rc = SQLITE_NOMEM;
  160635. }else{
  160636. nodeBlobReset(pRtree);
  160637. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  160638. sqlite3_free(zCreate);
  160639. }
  160640. if( rc==SQLITE_OK ){
  160641. rtreeRelease(pRtree);
  160642. }
  160643. return rc;
  160644. }
  160645. /*
  160646. ** Rtree virtual table module xOpen method.
  160647. */
  160648. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  160649. int rc = SQLITE_NOMEM;
  160650. Rtree *pRtree = (Rtree *)pVTab;
  160651. RtreeCursor *pCsr;
  160652. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  160653. if( pCsr ){
  160654. memset(pCsr, 0, sizeof(RtreeCursor));
  160655. pCsr->base.pVtab = pVTab;
  160656. rc = SQLITE_OK;
  160657. pRtree->nCursor++;
  160658. }
  160659. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  160660. return rc;
  160661. }
  160662. /*
  160663. ** Free the RtreeCursor.aConstraint[] array and its contents.
  160664. */
  160665. static void freeCursorConstraints(RtreeCursor *pCsr){
  160666. if( pCsr->aConstraint ){
  160667. int i; /* Used to iterate through constraint array */
  160668. for(i=0; i<pCsr->nConstraint; i++){
  160669. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  160670. if( pInfo ){
  160671. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  160672. sqlite3_free(pInfo);
  160673. }
  160674. }
  160675. sqlite3_free(pCsr->aConstraint);
  160676. pCsr->aConstraint = 0;
  160677. }
  160678. }
  160679. /*
  160680. ** Rtree virtual table module xClose method.
  160681. */
  160682. static int rtreeClose(sqlite3_vtab_cursor *cur){
  160683. Rtree *pRtree = (Rtree *)(cur->pVtab);
  160684. int ii;
  160685. RtreeCursor *pCsr = (RtreeCursor *)cur;
  160686. assert( pRtree->nCursor>0 );
  160687. freeCursorConstraints(pCsr);
  160688. sqlite3_finalize(pCsr->pReadAux);
  160689. sqlite3_free(pCsr->aPoint);
  160690. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  160691. sqlite3_free(pCsr);
  160692. pRtree->nCursor--;
  160693. nodeBlobReset(pRtree);
  160694. return SQLITE_OK;
  160695. }
  160696. /*
  160697. ** Rtree virtual table module xEof method.
  160698. **
  160699. ** Return non-zero if the cursor does not currently point to a valid
  160700. ** record (i.e if the scan has finished), or zero otherwise.
  160701. */
  160702. static int rtreeEof(sqlite3_vtab_cursor *cur){
  160703. RtreeCursor *pCsr = (RtreeCursor *)cur;
  160704. return pCsr->atEOF;
  160705. }
  160706. /*
  160707. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  160708. ** The on-disk format is big-endian and needs to be converted for little-
  160709. ** endian platforms. The on-disk record stores integer coordinates if
  160710. ** eInt is true and it stores 32-bit floating point records if eInt is
  160711. ** false. a[] is the four bytes of the on-disk record to be decoded.
  160712. ** Store the results in "r".
  160713. **
  160714. ** There are five versions of this macro. The last one is generic. The
  160715. ** other four are various architectures-specific optimizations.
  160716. */
  160717. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  160718. #define RTREE_DECODE_COORD(eInt, a, r) { \
  160719. RtreeCoord c; /* Coordinate decoded */ \
  160720. c.u = _byteswap_ulong(*(u32*)a); \
  160721. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  160722. }
  160723. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  160724. #define RTREE_DECODE_COORD(eInt, a, r) { \
  160725. RtreeCoord c; /* Coordinate decoded */ \
  160726. c.u = __builtin_bswap32(*(u32*)a); \
  160727. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  160728. }
  160729. #elif SQLITE_BYTEORDER==1234
  160730. #define RTREE_DECODE_COORD(eInt, a, r) { \
  160731. RtreeCoord c; /* Coordinate decoded */ \
  160732. memcpy(&c.u,a,4); \
  160733. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  160734. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  160735. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  160736. }
  160737. #elif SQLITE_BYTEORDER==4321
  160738. #define RTREE_DECODE_COORD(eInt, a, r) { \
  160739. RtreeCoord c; /* Coordinate decoded */ \
  160740. memcpy(&c.u,a,4); \
  160741. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  160742. }
  160743. #else
  160744. #define RTREE_DECODE_COORD(eInt, a, r) { \
  160745. RtreeCoord c; /* Coordinate decoded */ \
  160746. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  160747. +((u32)a[2]<<8) + a[3]; \
  160748. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  160749. }
  160750. #endif
  160751. /*
  160752. ** Check the RTree node or entry given by pCellData and p against the MATCH
  160753. ** constraint pConstraint.
  160754. */
  160755. static int rtreeCallbackConstraint(
  160756. RtreeConstraint *pConstraint, /* The constraint to test */
  160757. int eInt, /* True if RTree holding integer coordinates */
  160758. u8 *pCellData, /* Raw cell content */
  160759. RtreeSearchPoint *pSearch, /* Container of this cell */
  160760. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  160761. int *peWithin /* OUT: visibility of the cell */
  160762. ){
  160763. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  160764. int nCoord = pInfo->nCoord; /* No. of coordinates */
  160765. int rc; /* Callback return code */
  160766. RtreeCoord c; /* Translator union */
  160767. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  160768. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  160769. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  160770. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  160771. pInfo->iRowid = readInt64(pCellData);
  160772. }
  160773. pCellData += 8;
  160774. #ifndef SQLITE_RTREE_INT_ONLY
  160775. if( eInt==0 ){
  160776. switch( nCoord ){
  160777. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  160778. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  160779. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  160780. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  160781. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  160782. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  160783. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  160784. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  160785. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  160786. readCoord(pCellData, &c); aCoord[0] = c.f;
  160787. }
  160788. }else
  160789. #endif
  160790. {
  160791. switch( nCoord ){
  160792. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  160793. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  160794. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  160795. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  160796. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  160797. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  160798. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  160799. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  160800. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  160801. readCoord(pCellData, &c); aCoord[0] = c.i;
  160802. }
  160803. }
  160804. if( pConstraint->op==RTREE_MATCH ){
  160805. int eWithin = 0;
  160806. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  160807. nCoord, aCoord, &eWithin);
  160808. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  160809. *prScore = RTREE_ZERO;
  160810. }else{
  160811. pInfo->aCoord = aCoord;
  160812. pInfo->iLevel = pSearch->iLevel - 1;
  160813. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  160814. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  160815. rc = pConstraint->u.xQueryFunc(pInfo);
  160816. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  160817. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  160818. *prScore = pInfo->rScore;
  160819. }
  160820. }
  160821. return rc;
  160822. }
  160823. /*
  160824. ** Check the internal RTree node given by pCellData against constraint p.
  160825. ** If this constraint cannot be satisfied by any child within the node,
  160826. ** set *peWithin to NOT_WITHIN.
  160827. */
  160828. static void rtreeNonleafConstraint(
  160829. RtreeConstraint *p, /* The constraint to test */
  160830. int eInt, /* True if RTree holds integer coordinates */
  160831. u8 *pCellData, /* Raw cell content as appears on disk */
  160832. int *peWithin /* Adjust downward, as appropriate */
  160833. ){
  160834. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  160835. /* p->iCoord might point to either a lower or upper bound coordinate
  160836. ** in a coordinate pair. But make pCellData point to the lower bound.
  160837. */
  160838. pCellData += 8 + 4*(p->iCoord&0xfe);
  160839. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  160840. || p->op==RTREE_GT || p->op==RTREE_EQ );
  160841. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  160842. switch( p->op ){
  160843. case RTREE_LE:
  160844. case RTREE_LT:
  160845. case RTREE_EQ:
  160846. RTREE_DECODE_COORD(eInt, pCellData, val);
  160847. /* val now holds the lower bound of the coordinate pair */
  160848. if( p->u.rValue>=val ) return;
  160849. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  160850. /* Fall through for the RTREE_EQ case */
  160851. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  160852. pCellData += 4;
  160853. RTREE_DECODE_COORD(eInt, pCellData, val);
  160854. /* val now holds the upper bound of the coordinate pair */
  160855. if( p->u.rValue<=val ) return;
  160856. }
  160857. *peWithin = NOT_WITHIN;
  160858. }
  160859. /*
  160860. ** Check the leaf RTree cell given by pCellData against constraint p.
  160861. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  160862. ** If the constraint is satisfied, leave *peWithin unchanged.
  160863. **
  160864. ** The constraint is of the form: xN op $val
  160865. **
  160866. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  160867. ** pCellData. $val is given by p->u.rValue.
  160868. */
  160869. static void rtreeLeafConstraint(
  160870. RtreeConstraint *p, /* The constraint to test */
  160871. int eInt, /* True if RTree holds integer coordinates */
  160872. u8 *pCellData, /* Raw cell content as appears on disk */
  160873. int *peWithin /* Adjust downward, as appropriate */
  160874. ){
  160875. RtreeDValue xN; /* Coordinate value converted to a double */
  160876. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  160877. || p->op==RTREE_GT || p->op==RTREE_EQ );
  160878. pCellData += 8 + p->iCoord*4;
  160879. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  160880. RTREE_DECODE_COORD(eInt, pCellData, xN);
  160881. switch( p->op ){
  160882. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  160883. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  160884. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  160885. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  160886. default: if( xN == p->u.rValue ) return; break;
  160887. }
  160888. *peWithin = NOT_WITHIN;
  160889. }
  160890. /*
  160891. ** One of the cells in node pNode is guaranteed to have a 64-bit
  160892. ** integer value equal to iRowid. Return the index of this cell.
  160893. */
  160894. static int nodeRowidIndex(
  160895. Rtree *pRtree,
  160896. RtreeNode *pNode,
  160897. i64 iRowid,
  160898. int *piIndex
  160899. ){
  160900. int ii;
  160901. int nCell = NCELL(pNode);
  160902. assert( nCell<200 );
  160903. for(ii=0; ii<nCell; ii++){
  160904. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  160905. *piIndex = ii;
  160906. return SQLITE_OK;
  160907. }
  160908. }
  160909. return SQLITE_CORRUPT_VTAB;
  160910. }
  160911. /*
  160912. ** Return the index of the cell containing a pointer to node pNode
  160913. ** in its parent. If pNode is the root node, return -1.
  160914. */
  160915. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  160916. RtreeNode *pParent = pNode->pParent;
  160917. if( pParent ){
  160918. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  160919. }
  160920. *piIndex = -1;
  160921. return SQLITE_OK;
  160922. }
  160923. /*
  160924. ** Compare two search points. Return negative, zero, or positive if the first
  160925. ** is less than, equal to, or greater than the second.
  160926. **
  160927. ** The rScore is the primary key. Smaller rScore values come first.
  160928. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  160929. ** iLevel values coming first. In this way, if rScore is the same for all
  160930. ** SearchPoints, then iLevel becomes the deciding factor and the result
  160931. ** is a depth-first search, which is the desired default behavior.
  160932. */
  160933. static int rtreeSearchPointCompare(
  160934. const RtreeSearchPoint *pA,
  160935. const RtreeSearchPoint *pB
  160936. ){
  160937. if( pA->rScore<pB->rScore ) return -1;
  160938. if( pA->rScore>pB->rScore ) return +1;
  160939. if( pA->iLevel<pB->iLevel ) return -1;
  160940. if( pA->iLevel>pB->iLevel ) return +1;
  160941. return 0;
  160942. }
  160943. /*
  160944. ** Interchange two search points in a cursor.
  160945. */
  160946. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  160947. RtreeSearchPoint t = p->aPoint[i];
  160948. assert( i<j );
  160949. p->aPoint[i] = p->aPoint[j];
  160950. p->aPoint[j] = t;
  160951. i++; j++;
  160952. if( i<RTREE_CACHE_SZ ){
  160953. if( j>=RTREE_CACHE_SZ ){
  160954. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  160955. p->aNode[i] = 0;
  160956. }else{
  160957. RtreeNode *pTemp = p->aNode[i];
  160958. p->aNode[i] = p->aNode[j];
  160959. p->aNode[j] = pTemp;
  160960. }
  160961. }
  160962. }
  160963. /*
  160964. ** Return the search point with the lowest current score.
  160965. */
  160966. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  160967. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  160968. }
  160969. /*
  160970. ** Get the RtreeNode for the search point with the lowest score.
  160971. */
  160972. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  160973. sqlite3_int64 id;
  160974. int ii = 1 - pCur->bPoint;
  160975. assert( ii==0 || ii==1 );
  160976. assert( pCur->bPoint || pCur->nPoint );
  160977. if( pCur->aNode[ii]==0 ){
  160978. assert( pRC!=0 );
  160979. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  160980. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  160981. }
  160982. return pCur->aNode[ii];
  160983. }
  160984. /*
  160985. ** Push a new element onto the priority queue
  160986. */
  160987. static RtreeSearchPoint *rtreeEnqueue(
  160988. RtreeCursor *pCur, /* The cursor */
  160989. RtreeDValue rScore, /* Score for the new search point */
  160990. u8 iLevel /* Level for the new search point */
  160991. ){
  160992. int i, j;
  160993. RtreeSearchPoint *pNew;
  160994. if( pCur->nPoint>=pCur->nPointAlloc ){
  160995. int nNew = pCur->nPointAlloc*2 + 8;
  160996. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  160997. if( pNew==0 ) return 0;
  160998. pCur->aPoint = pNew;
  160999. pCur->nPointAlloc = nNew;
  161000. }
  161001. i = pCur->nPoint++;
  161002. pNew = pCur->aPoint + i;
  161003. pNew->rScore = rScore;
  161004. pNew->iLevel = iLevel;
  161005. assert( iLevel<=RTREE_MAX_DEPTH );
  161006. while( i>0 ){
  161007. RtreeSearchPoint *pParent;
  161008. j = (i-1)/2;
  161009. pParent = pCur->aPoint + j;
  161010. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  161011. rtreeSearchPointSwap(pCur, j, i);
  161012. i = j;
  161013. pNew = pParent;
  161014. }
  161015. return pNew;
  161016. }
  161017. /*
  161018. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  161019. ** NULL if malloc fails.
  161020. */
  161021. static RtreeSearchPoint *rtreeSearchPointNew(
  161022. RtreeCursor *pCur, /* The cursor */
  161023. RtreeDValue rScore, /* Score for the new search point */
  161024. u8 iLevel /* Level for the new search point */
  161025. ){
  161026. RtreeSearchPoint *pNew, *pFirst;
  161027. pFirst = rtreeSearchPointFirst(pCur);
  161028. pCur->anQueue[iLevel]++;
  161029. if( pFirst==0
  161030. || pFirst->rScore>rScore
  161031. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  161032. ){
  161033. if( pCur->bPoint ){
  161034. int ii;
  161035. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  161036. if( pNew==0 ) return 0;
  161037. ii = (int)(pNew - pCur->aPoint) + 1;
  161038. if( ii<RTREE_CACHE_SZ ){
  161039. assert( pCur->aNode[ii]==0 );
  161040. pCur->aNode[ii] = pCur->aNode[0];
  161041. }else{
  161042. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  161043. }
  161044. pCur->aNode[0] = 0;
  161045. *pNew = pCur->sPoint;
  161046. }
  161047. pCur->sPoint.rScore = rScore;
  161048. pCur->sPoint.iLevel = iLevel;
  161049. pCur->bPoint = 1;
  161050. return &pCur->sPoint;
  161051. }else{
  161052. return rtreeEnqueue(pCur, rScore, iLevel);
  161053. }
  161054. }
  161055. #if 0
  161056. /* Tracing routines for the RtreeSearchPoint queue */
  161057. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  161058. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  161059. printf(" %d.%05lld.%02d %g %d",
  161060. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  161061. );
  161062. idx++;
  161063. if( idx<RTREE_CACHE_SZ ){
  161064. printf(" %p\n", pCur->aNode[idx]);
  161065. }else{
  161066. printf("\n");
  161067. }
  161068. }
  161069. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  161070. int ii;
  161071. printf("=== %9s ", zPrefix);
  161072. if( pCur->bPoint ){
  161073. tracePoint(&pCur->sPoint, -1, pCur);
  161074. }
  161075. for(ii=0; ii<pCur->nPoint; ii++){
  161076. if( ii>0 || pCur->bPoint ) printf(" ");
  161077. tracePoint(&pCur->aPoint[ii], ii, pCur);
  161078. }
  161079. }
  161080. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  161081. #else
  161082. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  161083. #endif
  161084. /* Remove the search point with the lowest current score.
  161085. */
  161086. static void rtreeSearchPointPop(RtreeCursor *p){
  161087. int i, j, k, n;
  161088. i = 1 - p->bPoint;
  161089. assert( i==0 || i==1 );
  161090. if( p->aNode[i] ){
  161091. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  161092. p->aNode[i] = 0;
  161093. }
  161094. if( p->bPoint ){
  161095. p->anQueue[p->sPoint.iLevel]--;
  161096. p->bPoint = 0;
  161097. }else if( p->nPoint ){
  161098. p->anQueue[p->aPoint[0].iLevel]--;
  161099. n = --p->nPoint;
  161100. p->aPoint[0] = p->aPoint[n];
  161101. if( n<RTREE_CACHE_SZ-1 ){
  161102. p->aNode[1] = p->aNode[n+1];
  161103. p->aNode[n+1] = 0;
  161104. }
  161105. i = 0;
  161106. while( (j = i*2+1)<n ){
  161107. k = j+1;
  161108. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  161109. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  161110. rtreeSearchPointSwap(p, i, k);
  161111. i = k;
  161112. }else{
  161113. break;
  161114. }
  161115. }else{
  161116. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  161117. rtreeSearchPointSwap(p, i, j);
  161118. i = j;
  161119. }else{
  161120. break;
  161121. }
  161122. }
  161123. }
  161124. }
  161125. }
  161126. /*
  161127. ** Continue the search on cursor pCur until the front of the queue
  161128. ** contains an entry suitable for returning as a result-set row,
  161129. ** or until the RtreeSearchPoint queue is empty, indicating that the
  161130. ** query has completed.
  161131. */
  161132. static int rtreeStepToLeaf(RtreeCursor *pCur){
  161133. RtreeSearchPoint *p;
  161134. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  161135. RtreeNode *pNode;
  161136. int eWithin;
  161137. int rc = SQLITE_OK;
  161138. int nCell;
  161139. int nConstraint = pCur->nConstraint;
  161140. int ii;
  161141. int eInt;
  161142. RtreeSearchPoint x;
  161143. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  161144. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  161145. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  161146. if( rc ) return rc;
  161147. nCell = NCELL(pNode);
  161148. assert( nCell<200 );
  161149. while( p->iCell<nCell ){
  161150. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  161151. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  161152. eWithin = FULLY_WITHIN;
  161153. for(ii=0; ii<nConstraint; ii++){
  161154. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  161155. if( pConstraint->op>=RTREE_MATCH ){
  161156. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  161157. &rScore, &eWithin);
  161158. if( rc ) return rc;
  161159. }else if( p->iLevel==1 ){
  161160. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  161161. }else{
  161162. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  161163. }
  161164. if( eWithin==NOT_WITHIN ) break;
  161165. }
  161166. p->iCell++;
  161167. if( eWithin==NOT_WITHIN ) continue;
  161168. x.iLevel = p->iLevel - 1;
  161169. if( x.iLevel ){
  161170. x.id = readInt64(pCellData);
  161171. x.iCell = 0;
  161172. }else{
  161173. x.id = p->id;
  161174. x.iCell = p->iCell - 1;
  161175. }
  161176. if( p->iCell>=nCell ){
  161177. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  161178. rtreeSearchPointPop(pCur);
  161179. }
  161180. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  161181. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  161182. if( p==0 ) return SQLITE_NOMEM;
  161183. p->eWithin = (u8)eWithin;
  161184. p->id = x.id;
  161185. p->iCell = x.iCell;
  161186. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  161187. break;
  161188. }
  161189. if( p->iCell>=nCell ){
  161190. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  161191. rtreeSearchPointPop(pCur);
  161192. }
  161193. }
  161194. pCur->atEOF = p==0;
  161195. return SQLITE_OK;
  161196. }
  161197. /*
  161198. ** Rtree virtual table module xNext method.
  161199. */
  161200. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  161201. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  161202. int rc = SQLITE_OK;
  161203. /* Move to the next entry that matches the configured constraints. */
  161204. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  161205. if( pCsr->bAuxValid ){
  161206. pCsr->bAuxValid = 0;
  161207. sqlite3_reset(pCsr->pReadAux);
  161208. }
  161209. rtreeSearchPointPop(pCsr);
  161210. rc = rtreeStepToLeaf(pCsr);
  161211. return rc;
  161212. }
  161213. /*
  161214. ** Rtree virtual table module xRowid method.
  161215. */
  161216. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  161217. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  161218. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  161219. int rc = SQLITE_OK;
  161220. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  161221. if( rc==SQLITE_OK && p ){
  161222. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  161223. }
  161224. return rc;
  161225. }
  161226. /*
  161227. ** Rtree virtual table module xColumn method.
  161228. */
  161229. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  161230. Rtree *pRtree = (Rtree *)cur->pVtab;
  161231. RtreeCursor *pCsr = (RtreeCursor *)cur;
  161232. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  161233. RtreeCoord c;
  161234. int rc = SQLITE_OK;
  161235. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  161236. if( rc ) return rc;
  161237. if( p==0 ) return SQLITE_OK;
  161238. if( i==0 ){
  161239. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  161240. }else if( i<=pRtree->nDim2 ){
  161241. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  161242. #ifndef SQLITE_RTREE_INT_ONLY
  161243. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  161244. sqlite3_result_double(ctx, c.f);
  161245. }else
  161246. #endif
  161247. {
  161248. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  161249. sqlite3_result_int(ctx, c.i);
  161250. }
  161251. }else{
  161252. if( !pCsr->bAuxValid ){
  161253. if( pCsr->pReadAux==0 ){
  161254. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  161255. &pCsr->pReadAux, 0);
  161256. if( rc ) return rc;
  161257. }
  161258. sqlite3_bind_int64(pCsr->pReadAux, 1,
  161259. nodeGetRowid(pRtree, pNode, p->iCell));
  161260. rc = sqlite3_step(pCsr->pReadAux);
  161261. if( rc==SQLITE_ROW ){
  161262. pCsr->bAuxValid = 1;
  161263. }else{
  161264. sqlite3_reset(pCsr->pReadAux);
  161265. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  161266. return rc;
  161267. }
  161268. }
  161269. sqlite3_result_value(ctx,
  161270. sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
  161271. }
  161272. return SQLITE_OK;
  161273. }
  161274. /*
  161275. ** Use nodeAcquire() to obtain the leaf node containing the record with
  161276. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  161277. ** return SQLITE_OK. If there is no such record in the table, set
  161278. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  161279. ** to zero and return an SQLite error code.
  161280. */
  161281. static int findLeafNode(
  161282. Rtree *pRtree, /* RTree to search */
  161283. i64 iRowid, /* The rowid searching for */
  161284. RtreeNode **ppLeaf, /* Write the node here */
  161285. sqlite3_int64 *piNode /* Write the node-id here */
  161286. ){
  161287. int rc;
  161288. *ppLeaf = 0;
  161289. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  161290. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  161291. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  161292. if( piNode ) *piNode = iNode;
  161293. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  161294. sqlite3_reset(pRtree->pReadRowid);
  161295. }else{
  161296. rc = sqlite3_reset(pRtree->pReadRowid);
  161297. }
  161298. return rc;
  161299. }
  161300. /*
  161301. ** This function is called to configure the RtreeConstraint object passed
  161302. ** as the second argument for a MATCH constraint. The value passed as the
  161303. ** first argument to this function is the right-hand operand to the MATCH
  161304. ** operator.
  161305. */
  161306. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  161307. RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
  161308. sqlite3_rtree_query_info *pInfo; /* Callback information */
  161309. pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
  161310. if( pSrc==0 ) return SQLITE_ERROR;
  161311. pInfo = (sqlite3_rtree_query_info*)
  161312. sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
  161313. if( !pInfo ) return SQLITE_NOMEM;
  161314. memset(pInfo, 0, sizeof(*pInfo));
  161315. pBlob = (RtreeMatchArg*)&pInfo[1];
  161316. memcpy(pBlob, pSrc, pSrc->iSize);
  161317. pInfo->pContext = pBlob->cb.pContext;
  161318. pInfo->nParam = pBlob->nParam;
  161319. pInfo->aParam = pBlob->aParam;
  161320. pInfo->apSqlParam = pBlob->apSqlParam;
  161321. if( pBlob->cb.xGeom ){
  161322. pCons->u.xGeom = pBlob->cb.xGeom;
  161323. }else{
  161324. pCons->op = RTREE_QUERY;
  161325. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  161326. }
  161327. pCons->pInfo = pInfo;
  161328. return SQLITE_OK;
  161329. }
  161330. /*
  161331. ** Rtree virtual table module xFilter method.
  161332. */
  161333. static int rtreeFilter(
  161334. sqlite3_vtab_cursor *pVtabCursor,
  161335. int idxNum, const char *idxStr,
  161336. int argc, sqlite3_value **argv
  161337. ){
  161338. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  161339. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  161340. RtreeNode *pRoot = 0;
  161341. int ii;
  161342. int rc = SQLITE_OK;
  161343. int iCell = 0;
  161344. sqlite3_stmt *pStmt;
  161345. rtreeReference(pRtree);
  161346. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  161347. freeCursorConstraints(pCsr);
  161348. sqlite3_free(pCsr->aPoint);
  161349. pStmt = pCsr->pReadAux;
  161350. memset(pCsr, 0, sizeof(RtreeCursor));
  161351. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  161352. pCsr->pReadAux = pStmt;
  161353. pCsr->iStrategy = idxNum;
  161354. if( idxNum==1 ){
  161355. /* Special case - lookup by rowid. */
  161356. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  161357. RtreeSearchPoint *p; /* Search point for the leaf */
  161358. i64 iRowid = sqlite3_value_int64(argv[0]);
  161359. i64 iNode = 0;
  161360. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  161361. if( rc==SQLITE_OK && pLeaf!=0 ){
  161362. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  161363. assert( p!=0 ); /* Always returns pCsr->sPoint */
  161364. pCsr->aNode[0] = pLeaf;
  161365. p->id = iNode;
  161366. p->eWithin = PARTLY_WITHIN;
  161367. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  161368. p->iCell = (u8)iCell;
  161369. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  161370. }else{
  161371. pCsr->atEOF = 1;
  161372. }
  161373. }else{
  161374. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  161375. ** with the configured constraints.
  161376. */
  161377. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  161378. if( rc==SQLITE_OK && argc>0 ){
  161379. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  161380. pCsr->nConstraint = argc;
  161381. if( !pCsr->aConstraint ){
  161382. rc = SQLITE_NOMEM;
  161383. }else{
  161384. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  161385. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  161386. assert( (idxStr==0 && argc==0)
  161387. || (idxStr && (int)strlen(idxStr)==argc*2) );
  161388. for(ii=0; ii<argc; ii++){
  161389. RtreeConstraint *p = &pCsr->aConstraint[ii];
  161390. p->op = idxStr[ii*2];
  161391. p->iCoord = idxStr[ii*2+1]-'0';
  161392. if( p->op>=RTREE_MATCH ){
  161393. /* A MATCH operator. The right-hand-side must be a blob that
  161394. ** can be cast into an RtreeMatchArg object. One created using
  161395. ** an sqlite3_rtree_geometry_callback() SQL user function.
  161396. */
  161397. rc = deserializeGeometry(argv[ii], p);
  161398. if( rc!=SQLITE_OK ){
  161399. break;
  161400. }
  161401. p->pInfo->nCoord = pRtree->nDim2;
  161402. p->pInfo->anQueue = pCsr->anQueue;
  161403. p->pInfo->mxLevel = pRtree->iDepth + 1;
  161404. }else{
  161405. #ifdef SQLITE_RTREE_INT_ONLY
  161406. p->u.rValue = sqlite3_value_int64(argv[ii]);
  161407. #else
  161408. p->u.rValue = sqlite3_value_double(argv[ii]);
  161409. #endif
  161410. }
  161411. }
  161412. }
  161413. }
  161414. if( rc==SQLITE_OK ){
  161415. RtreeSearchPoint *pNew;
  161416. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  161417. if( pNew==0 ) return SQLITE_NOMEM;
  161418. pNew->id = 1;
  161419. pNew->iCell = 0;
  161420. pNew->eWithin = PARTLY_WITHIN;
  161421. assert( pCsr->bPoint==1 );
  161422. pCsr->aNode[0] = pRoot;
  161423. pRoot = 0;
  161424. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  161425. rc = rtreeStepToLeaf(pCsr);
  161426. }
  161427. }
  161428. nodeRelease(pRtree, pRoot);
  161429. rtreeRelease(pRtree);
  161430. return rc;
  161431. }
  161432. /*
  161433. ** Rtree virtual table module xBestIndex method. There are three
  161434. ** table scan strategies to choose from (in order from most to
  161435. ** least desirable):
  161436. **
  161437. ** idxNum idxStr Strategy
  161438. ** ------------------------------------------------
  161439. ** 1 Unused Direct lookup by rowid.
  161440. ** 2 See below R-tree query or full-table scan.
  161441. ** ------------------------------------------------
  161442. **
  161443. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  161444. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  161445. ** constraint used. The first two bytes of idxStr correspond to
  161446. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  161447. ** (argvIndex==1) etc.
  161448. **
  161449. ** The first of each pair of bytes in idxStr identifies the constraint
  161450. ** operator as follows:
  161451. **
  161452. ** Operator Byte Value
  161453. ** ----------------------
  161454. ** = 0x41 ('A')
  161455. ** <= 0x42 ('B')
  161456. ** < 0x43 ('C')
  161457. ** >= 0x44 ('D')
  161458. ** > 0x45 ('E')
  161459. ** MATCH 0x46 ('F')
  161460. ** ----------------------
  161461. **
  161462. ** The second of each pair of bytes identifies the coordinate column
  161463. ** to which the constraint applies. The leftmost coordinate column
  161464. ** is 'a', the second from the left 'b' etc.
  161465. */
  161466. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  161467. Rtree *pRtree = (Rtree*)tab;
  161468. int rc = SQLITE_OK;
  161469. int ii;
  161470. int bMatch = 0; /* True if there exists a MATCH constraint */
  161471. i64 nRow; /* Estimated rows returned by this scan */
  161472. int iIdx = 0;
  161473. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  161474. memset(zIdxStr, 0, sizeof(zIdxStr));
  161475. /* Check if there exists a MATCH constraint - even an unusable one. If there
  161476. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  161477. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  161478. ** possible. */
  161479. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  161480. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  161481. bMatch = 1;
  161482. }
  161483. }
  161484. assert( pIdxInfo->idxStr==0 );
  161485. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  161486. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  161487. if( bMatch==0 && p->usable
  161488. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  161489. ){
  161490. /* We have an equality constraint on the rowid. Use strategy 1. */
  161491. int jj;
  161492. for(jj=0; jj<ii; jj++){
  161493. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  161494. pIdxInfo->aConstraintUsage[jj].omit = 0;
  161495. }
  161496. pIdxInfo->idxNum = 1;
  161497. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  161498. pIdxInfo->aConstraintUsage[jj].omit = 1;
  161499. /* This strategy involves a two rowid lookups on an B-Tree structures
  161500. ** and then a linear search of an R-Tree node. This should be
  161501. ** considered almost as quick as a direct rowid lookup (for which
  161502. ** sqlite uses an internal cost of 0.0). It is expected to return
  161503. ** a single row.
  161504. */
  161505. pIdxInfo->estimatedCost = 30.0;
  161506. pIdxInfo->estimatedRows = 1;
  161507. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  161508. return SQLITE_OK;
  161509. }
  161510. if( p->usable
  161511. && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
  161512. || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
  161513. ){
  161514. u8 op;
  161515. switch( p->op ){
  161516. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  161517. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  161518. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  161519. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  161520. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  161521. default:
  161522. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  161523. op = RTREE_MATCH;
  161524. break;
  161525. }
  161526. zIdxStr[iIdx++] = op;
  161527. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  161528. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  161529. pIdxInfo->aConstraintUsage[ii].omit = 1;
  161530. }
  161531. }
  161532. pIdxInfo->idxNum = 2;
  161533. pIdxInfo->needToFreeIdxStr = 1;
  161534. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  161535. return SQLITE_NOMEM;
  161536. }
  161537. nRow = pRtree->nRowEst >> (iIdx/2);
  161538. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  161539. pIdxInfo->estimatedRows = nRow;
  161540. return rc;
  161541. }
  161542. /*
  161543. ** Return the N-dimensional volumn of the cell stored in *p.
  161544. */
  161545. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  161546. RtreeDValue area = (RtreeDValue)1;
  161547. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  161548. #ifndef SQLITE_RTREE_INT_ONLY
  161549. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  161550. switch( pRtree->nDim ){
  161551. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  161552. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  161553. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  161554. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  161555. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  161556. }
  161557. }else
  161558. #endif
  161559. {
  161560. switch( pRtree->nDim ){
  161561. case 5: area = p->aCoord[9].i - p->aCoord[8].i;
  161562. case 4: area *= p->aCoord[7].i - p->aCoord[6].i;
  161563. case 3: area *= p->aCoord[5].i - p->aCoord[4].i;
  161564. case 2: area *= p->aCoord[3].i - p->aCoord[2].i;
  161565. default: area *= p->aCoord[1].i - p->aCoord[0].i;
  161566. }
  161567. }
  161568. return area;
  161569. }
  161570. /*
  161571. ** Return the margin length of cell p. The margin length is the sum
  161572. ** of the objects size in each dimension.
  161573. */
  161574. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  161575. RtreeDValue margin = 0;
  161576. int ii = pRtree->nDim2 - 2;
  161577. do{
  161578. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  161579. ii -= 2;
  161580. }while( ii>=0 );
  161581. return margin;
  161582. }
  161583. /*
  161584. ** Store the union of cells p1 and p2 in p1.
  161585. */
  161586. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  161587. int ii = 0;
  161588. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  161589. do{
  161590. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  161591. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  161592. ii += 2;
  161593. }while( ii<pRtree->nDim2 );
  161594. }else{
  161595. do{
  161596. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  161597. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  161598. ii += 2;
  161599. }while( ii<pRtree->nDim2 );
  161600. }
  161601. }
  161602. /*
  161603. ** Return true if the area covered by p2 is a subset of the area covered
  161604. ** by p1. False otherwise.
  161605. */
  161606. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  161607. int ii;
  161608. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  161609. for(ii=0; ii<pRtree->nDim2; ii+=2){
  161610. RtreeCoord *a1 = &p1->aCoord[ii];
  161611. RtreeCoord *a2 = &p2->aCoord[ii];
  161612. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  161613. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  161614. ){
  161615. return 0;
  161616. }
  161617. }
  161618. return 1;
  161619. }
  161620. /*
  161621. ** Return the amount cell p would grow by if it were unioned with pCell.
  161622. */
  161623. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  161624. RtreeDValue area;
  161625. RtreeCell cell;
  161626. memcpy(&cell, p, sizeof(RtreeCell));
  161627. area = cellArea(pRtree, &cell);
  161628. cellUnion(pRtree, &cell, pCell);
  161629. return (cellArea(pRtree, &cell)-area);
  161630. }
  161631. static RtreeDValue cellOverlap(
  161632. Rtree *pRtree,
  161633. RtreeCell *p,
  161634. RtreeCell *aCell,
  161635. int nCell
  161636. ){
  161637. int ii;
  161638. RtreeDValue overlap = RTREE_ZERO;
  161639. for(ii=0; ii<nCell; ii++){
  161640. int jj;
  161641. RtreeDValue o = (RtreeDValue)1;
  161642. for(jj=0; jj<pRtree->nDim2; jj+=2){
  161643. RtreeDValue x1, x2;
  161644. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  161645. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  161646. if( x2<x1 ){
  161647. o = (RtreeDValue)0;
  161648. break;
  161649. }else{
  161650. o = o * (x2-x1);
  161651. }
  161652. }
  161653. overlap += o;
  161654. }
  161655. return overlap;
  161656. }
  161657. /*
  161658. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  161659. ** ChooseSubTree in r*tree terminology.
  161660. */
  161661. static int ChooseLeaf(
  161662. Rtree *pRtree, /* Rtree table */
  161663. RtreeCell *pCell, /* Cell to insert into rtree */
  161664. int iHeight, /* Height of sub-tree rooted at pCell */
  161665. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  161666. ){
  161667. int rc;
  161668. int ii;
  161669. RtreeNode *pNode = 0;
  161670. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  161671. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  161672. int iCell;
  161673. sqlite3_int64 iBest = 0;
  161674. RtreeDValue fMinGrowth = RTREE_ZERO;
  161675. RtreeDValue fMinArea = RTREE_ZERO;
  161676. int nCell = NCELL(pNode);
  161677. RtreeCell cell;
  161678. RtreeNode *pChild;
  161679. RtreeCell *aCell = 0;
  161680. /* Select the child node which will be enlarged the least if pCell
  161681. ** is inserted into it. Resolve ties by choosing the entry with
  161682. ** the smallest area.
  161683. */
  161684. for(iCell=0; iCell<nCell; iCell++){
  161685. int bBest = 0;
  161686. RtreeDValue growth;
  161687. RtreeDValue area;
  161688. nodeGetCell(pRtree, pNode, iCell, &cell);
  161689. growth = cellGrowth(pRtree, &cell, pCell);
  161690. area = cellArea(pRtree, &cell);
  161691. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  161692. bBest = 1;
  161693. }
  161694. if( bBest ){
  161695. fMinGrowth = growth;
  161696. fMinArea = area;
  161697. iBest = cell.iRowid;
  161698. }
  161699. }
  161700. sqlite3_free(aCell);
  161701. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  161702. nodeRelease(pRtree, pNode);
  161703. pNode = pChild;
  161704. }
  161705. *ppLeaf = pNode;
  161706. return rc;
  161707. }
  161708. /*
  161709. ** A cell with the same content as pCell has just been inserted into
  161710. ** the node pNode. This function updates the bounding box cells in
  161711. ** all ancestor elements.
  161712. */
  161713. static int AdjustTree(
  161714. Rtree *pRtree, /* Rtree table */
  161715. RtreeNode *pNode, /* Adjust ancestry of this node. */
  161716. RtreeCell *pCell /* This cell was just inserted */
  161717. ){
  161718. RtreeNode *p = pNode;
  161719. while( p->pParent ){
  161720. RtreeNode *pParent = p->pParent;
  161721. RtreeCell cell;
  161722. int iCell;
  161723. if( nodeParentIndex(pRtree, p, &iCell) ){
  161724. return SQLITE_CORRUPT_VTAB;
  161725. }
  161726. nodeGetCell(pRtree, pParent, iCell, &cell);
  161727. if( !cellContains(pRtree, &cell, pCell) ){
  161728. cellUnion(pRtree, &cell, pCell);
  161729. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  161730. }
  161731. p = pParent;
  161732. }
  161733. return SQLITE_OK;
  161734. }
  161735. /*
  161736. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  161737. */
  161738. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  161739. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  161740. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  161741. sqlite3_step(pRtree->pWriteRowid);
  161742. return sqlite3_reset(pRtree->pWriteRowid);
  161743. }
  161744. /*
  161745. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  161746. */
  161747. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  161748. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  161749. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  161750. sqlite3_step(pRtree->pWriteParent);
  161751. return sqlite3_reset(pRtree->pWriteParent);
  161752. }
  161753. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  161754. /*
  161755. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  161756. ** nIdx. The aIdx array contains the set of integers from 0 to
  161757. ** (nIdx-1) in no particular order. This function sorts the values
  161758. ** in aIdx according to the indexed values in aDistance. For
  161759. ** example, assuming the inputs:
  161760. **
  161761. ** aIdx = { 0, 1, 2, 3 }
  161762. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  161763. **
  161764. ** this function sets the aIdx array to contain:
  161765. **
  161766. ** aIdx = { 0, 1, 2, 3 }
  161767. **
  161768. ** The aSpare array is used as temporary working space by the
  161769. ** sorting algorithm.
  161770. */
  161771. static void SortByDistance(
  161772. int *aIdx,
  161773. int nIdx,
  161774. RtreeDValue *aDistance,
  161775. int *aSpare
  161776. ){
  161777. if( nIdx>1 ){
  161778. int iLeft = 0;
  161779. int iRight = 0;
  161780. int nLeft = nIdx/2;
  161781. int nRight = nIdx-nLeft;
  161782. int *aLeft = aIdx;
  161783. int *aRight = &aIdx[nLeft];
  161784. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  161785. SortByDistance(aRight, nRight, aDistance, aSpare);
  161786. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  161787. aLeft = aSpare;
  161788. while( iLeft<nLeft || iRight<nRight ){
  161789. if( iLeft==nLeft ){
  161790. aIdx[iLeft+iRight] = aRight[iRight];
  161791. iRight++;
  161792. }else if( iRight==nRight ){
  161793. aIdx[iLeft+iRight] = aLeft[iLeft];
  161794. iLeft++;
  161795. }else{
  161796. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  161797. RtreeDValue fRight = aDistance[aRight[iRight]];
  161798. if( fLeft<fRight ){
  161799. aIdx[iLeft+iRight] = aLeft[iLeft];
  161800. iLeft++;
  161801. }else{
  161802. aIdx[iLeft+iRight] = aRight[iRight];
  161803. iRight++;
  161804. }
  161805. }
  161806. }
  161807. #if 0
  161808. /* Check that the sort worked */
  161809. {
  161810. int jj;
  161811. for(jj=1; jj<nIdx; jj++){
  161812. RtreeDValue left = aDistance[aIdx[jj-1]];
  161813. RtreeDValue right = aDistance[aIdx[jj]];
  161814. assert( left<=right );
  161815. }
  161816. }
  161817. #endif
  161818. }
  161819. }
  161820. /*
  161821. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  161822. ** nIdx. The aIdx array contains the set of integers from 0 to
  161823. ** (nIdx-1) in no particular order. This function sorts the values
  161824. ** in aIdx according to dimension iDim of the cells in aCell. The
  161825. ** minimum value of dimension iDim is considered first, the
  161826. ** maximum used to break ties.
  161827. **
  161828. ** The aSpare array is used as temporary working space by the
  161829. ** sorting algorithm.
  161830. */
  161831. static void SortByDimension(
  161832. Rtree *pRtree,
  161833. int *aIdx,
  161834. int nIdx,
  161835. int iDim,
  161836. RtreeCell *aCell,
  161837. int *aSpare
  161838. ){
  161839. if( nIdx>1 ){
  161840. int iLeft = 0;
  161841. int iRight = 0;
  161842. int nLeft = nIdx/2;
  161843. int nRight = nIdx-nLeft;
  161844. int *aLeft = aIdx;
  161845. int *aRight = &aIdx[nLeft];
  161846. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  161847. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  161848. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  161849. aLeft = aSpare;
  161850. while( iLeft<nLeft || iRight<nRight ){
  161851. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  161852. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  161853. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  161854. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  161855. if( (iLeft!=nLeft) && ((iRight==nRight)
  161856. || (xleft1<xright1)
  161857. || (xleft1==xright1 && xleft2<xright2)
  161858. )){
  161859. aIdx[iLeft+iRight] = aLeft[iLeft];
  161860. iLeft++;
  161861. }else{
  161862. aIdx[iLeft+iRight] = aRight[iRight];
  161863. iRight++;
  161864. }
  161865. }
  161866. #if 0
  161867. /* Check that the sort worked */
  161868. {
  161869. int jj;
  161870. for(jj=1; jj<nIdx; jj++){
  161871. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  161872. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  161873. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  161874. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  161875. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  161876. }
  161877. }
  161878. #endif
  161879. }
  161880. }
  161881. /*
  161882. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  161883. */
  161884. static int splitNodeStartree(
  161885. Rtree *pRtree,
  161886. RtreeCell *aCell,
  161887. int nCell,
  161888. RtreeNode *pLeft,
  161889. RtreeNode *pRight,
  161890. RtreeCell *pBboxLeft,
  161891. RtreeCell *pBboxRight
  161892. ){
  161893. int **aaSorted;
  161894. int *aSpare;
  161895. int ii;
  161896. int iBestDim = 0;
  161897. int iBestSplit = 0;
  161898. RtreeDValue fBestMargin = RTREE_ZERO;
  161899. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  161900. aaSorted = (int **)sqlite3_malloc(nByte);
  161901. if( !aaSorted ){
  161902. return SQLITE_NOMEM;
  161903. }
  161904. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  161905. memset(aaSorted, 0, nByte);
  161906. for(ii=0; ii<pRtree->nDim; ii++){
  161907. int jj;
  161908. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  161909. for(jj=0; jj<nCell; jj++){
  161910. aaSorted[ii][jj] = jj;
  161911. }
  161912. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  161913. }
  161914. for(ii=0; ii<pRtree->nDim; ii++){
  161915. RtreeDValue margin = RTREE_ZERO;
  161916. RtreeDValue fBestOverlap = RTREE_ZERO;
  161917. RtreeDValue fBestArea = RTREE_ZERO;
  161918. int iBestLeft = 0;
  161919. int nLeft;
  161920. for(
  161921. nLeft=RTREE_MINCELLS(pRtree);
  161922. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  161923. nLeft++
  161924. ){
  161925. RtreeCell left;
  161926. RtreeCell right;
  161927. int kk;
  161928. RtreeDValue overlap;
  161929. RtreeDValue area;
  161930. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  161931. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  161932. for(kk=1; kk<(nCell-1); kk++){
  161933. if( kk<nLeft ){
  161934. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  161935. }else{
  161936. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  161937. }
  161938. }
  161939. margin += cellMargin(pRtree, &left);
  161940. margin += cellMargin(pRtree, &right);
  161941. overlap = cellOverlap(pRtree, &left, &right, 1);
  161942. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  161943. if( (nLeft==RTREE_MINCELLS(pRtree))
  161944. || (overlap<fBestOverlap)
  161945. || (overlap==fBestOverlap && area<fBestArea)
  161946. ){
  161947. iBestLeft = nLeft;
  161948. fBestOverlap = overlap;
  161949. fBestArea = area;
  161950. }
  161951. }
  161952. if( ii==0 || margin<fBestMargin ){
  161953. iBestDim = ii;
  161954. fBestMargin = margin;
  161955. iBestSplit = iBestLeft;
  161956. }
  161957. }
  161958. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  161959. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  161960. for(ii=0; ii<nCell; ii++){
  161961. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  161962. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  161963. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  161964. nodeInsertCell(pRtree, pTarget, pCell);
  161965. cellUnion(pRtree, pBbox, pCell);
  161966. }
  161967. sqlite3_free(aaSorted);
  161968. return SQLITE_OK;
  161969. }
  161970. static int updateMapping(
  161971. Rtree *pRtree,
  161972. i64 iRowid,
  161973. RtreeNode *pNode,
  161974. int iHeight
  161975. ){
  161976. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  161977. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  161978. if( iHeight>0 ){
  161979. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  161980. if( pChild ){
  161981. nodeRelease(pRtree, pChild->pParent);
  161982. nodeReference(pNode);
  161983. pChild->pParent = pNode;
  161984. }
  161985. }
  161986. return xSetMapping(pRtree, iRowid, pNode->iNode);
  161987. }
  161988. static int SplitNode(
  161989. Rtree *pRtree,
  161990. RtreeNode *pNode,
  161991. RtreeCell *pCell,
  161992. int iHeight
  161993. ){
  161994. int i;
  161995. int newCellIsRight = 0;
  161996. int rc = SQLITE_OK;
  161997. int nCell = NCELL(pNode);
  161998. RtreeCell *aCell;
  161999. int *aiUsed;
  162000. RtreeNode *pLeft = 0;
  162001. RtreeNode *pRight = 0;
  162002. RtreeCell leftbbox;
  162003. RtreeCell rightbbox;
  162004. /* Allocate an array and populate it with a copy of pCell and
  162005. ** all cells from node pLeft. Then zero the original node.
  162006. */
  162007. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  162008. if( !aCell ){
  162009. rc = SQLITE_NOMEM;
  162010. goto splitnode_out;
  162011. }
  162012. aiUsed = (int *)&aCell[nCell+1];
  162013. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  162014. for(i=0; i<nCell; i++){
  162015. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  162016. }
  162017. nodeZero(pRtree, pNode);
  162018. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  162019. nCell++;
  162020. if( pNode->iNode==1 ){
  162021. pRight = nodeNew(pRtree, pNode);
  162022. pLeft = nodeNew(pRtree, pNode);
  162023. pRtree->iDepth++;
  162024. pNode->isDirty = 1;
  162025. writeInt16(pNode->zData, pRtree->iDepth);
  162026. }else{
  162027. pLeft = pNode;
  162028. pRight = nodeNew(pRtree, pLeft->pParent);
  162029. pLeft->nRef++;
  162030. }
  162031. if( !pLeft || !pRight ){
  162032. rc = SQLITE_NOMEM;
  162033. goto splitnode_out;
  162034. }
  162035. memset(pLeft->zData, 0, pRtree->iNodeSize);
  162036. memset(pRight->zData, 0, pRtree->iNodeSize);
  162037. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  162038. &leftbbox, &rightbbox);
  162039. if( rc!=SQLITE_OK ){
  162040. goto splitnode_out;
  162041. }
  162042. /* Ensure both child nodes have node numbers assigned to them by calling
  162043. ** nodeWrite(). Node pRight always needs a node number, as it was created
  162044. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  162045. ** In this case avoid the all to nodeWrite().
  162046. */
  162047. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  162048. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  162049. ){
  162050. goto splitnode_out;
  162051. }
  162052. rightbbox.iRowid = pRight->iNode;
  162053. leftbbox.iRowid = pLeft->iNode;
  162054. if( pNode->iNode==1 ){
  162055. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  162056. if( rc!=SQLITE_OK ){
  162057. goto splitnode_out;
  162058. }
  162059. }else{
  162060. RtreeNode *pParent = pLeft->pParent;
  162061. int iCell;
  162062. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  162063. if( rc==SQLITE_OK ){
  162064. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  162065. rc = AdjustTree(pRtree, pParent, &leftbbox);
  162066. }
  162067. if( rc!=SQLITE_OK ){
  162068. goto splitnode_out;
  162069. }
  162070. }
  162071. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  162072. goto splitnode_out;
  162073. }
  162074. for(i=0; i<NCELL(pRight); i++){
  162075. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  162076. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  162077. if( iRowid==pCell->iRowid ){
  162078. newCellIsRight = 1;
  162079. }
  162080. if( rc!=SQLITE_OK ){
  162081. goto splitnode_out;
  162082. }
  162083. }
  162084. if( pNode->iNode==1 ){
  162085. for(i=0; i<NCELL(pLeft); i++){
  162086. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  162087. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  162088. if( rc!=SQLITE_OK ){
  162089. goto splitnode_out;
  162090. }
  162091. }
  162092. }else if( newCellIsRight==0 ){
  162093. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  162094. }
  162095. if( rc==SQLITE_OK ){
  162096. rc = nodeRelease(pRtree, pRight);
  162097. pRight = 0;
  162098. }
  162099. if( rc==SQLITE_OK ){
  162100. rc = nodeRelease(pRtree, pLeft);
  162101. pLeft = 0;
  162102. }
  162103. splitnode_out:
  162104. nodeRelease(pRtree, pRight);
  162105. nodeRelease(pRtree, pLeft);
  162106. sqlite3_free(aCell);
  162107. return rc;
  162108. }
  162109. /*
  162110. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  162111. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  162112. ** the pLeaf->pParent chain all the way up to the root node.
  162113. **
  162114. ** This operation is required when a row is deleted (or updated - an update
  162115. ** is implemented as a delete followed by an insert). SQLite provides the
  162116. ** rowid of the row to delete, which can be used to find the leaf on which
  162117. ** the entry resides (argument pLeaf). Once the leaf is located, this
  162118. ** function is called to determine its ancestry.
  162119. */
  162120. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  162121. int rc = SQLITE_OK;
  162122. RtreeNode *pChild = pLeaf;
  162123. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  162124. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  162125. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  162126. rc = sqlite3_step(pRtree->pReadParent);
  162127. if( rc==SQLITE_ROW ){
  162128. RtreeNode *pTest; /* Used to test for reference loops */
  162129. i64 iNode; /* Node number of parent node */
  162130. /* Before setting pChild->pParent, test that we are not creating a
  162131. ** loop of references (as we would if, say, pChild==pParent). We don't
  162132. ** want to do this as it leads to a memory leak when trying to delete
  162133. ** the referenced counted node structures.
  162134. */
  162135. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  162136. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  162137. if( !pTest ){
  162138. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  162139. }
  162140. }
  162141. rc = sqlite3_reset(pRtree->pReadParent);
  162142. if( rc==SQLITE_OK ) rc = rc2;
  162143. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  162144. pChild = pChild->pParent;
  162145. }
  162146. return rc;
  162147. }
  162148. static int deleteCell(Rtree *, RtreeNode *, int, int);
  162149. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  162150. int rc;
  162151. int rc2;
  162152. RtreeNode *pParent = 0;
  162153. int iCell;
  162154. assert( pNode->nRef==1 );
  162155. /* Remove the entry in the parent cell. */
  162156. rc = nodeParentIndex(pRtree, pNode, &iCell);
  162157. if( rc==SQLITE_OK ){
  162158. pParent = pNode->pParent;
  162159. pNode->pParent = 0;
  162160. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  162161. }
  162162. rc2 = nodeRelease(pRtree, pParent);
  162163. if( rc==SQLITE_OK ){
  162164. rc = rc2;
  162165. }
  162166. if( rc!=SQLITE_OK ){
  162167. return rc;
  162168. }
  162169. /* Remove the xxx_node entry. */
  162170. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  162171. sqlite3_step(pRtree->pDeleteNode);
  162172. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  162173. return rc;
  162174. }
  162175. /* Remove the xxx_parent entry. */
  162176. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  162177. sqlite3_step(pRtree->pDeleteParent);
  162178. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  162179. return rc;
  162180. }
  162181. /* Remove the node from the in-memory hash table and link it into
  162182. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  162183. */
  162184. nodeHashDelete(pRtree, pNode);
  162185. pNode->iNode = iHeight;
  162186. pNode->pNext = pRtree->pDeleted;
  162187. pNode->nRef++;
  162188. pRtree->pDeleted = pNode;
  162189. return SQLITE_OK;
  162190. }
  162191. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  162192. RtreeNode *pParent = pNode->pParent;
  162193. int rc = SQLITE_OK;
  162194. if( pParent ){
  162195. int ii;
  162196. int nCell = NCELL(pNode);
  162197. RtreeCell box; /* Bounding box for pNode */
  162198. nodeGetCell(pRtree, pNode, 0, &box);
  162199. for(ii=1; ii<nCell; ii++){
  162200. RtreeCell cell;
  162201. nodeGetCell(pRtree, pNode, ii, &cell);
  162202. cellUnion(pRtree, &box, &cell);
  162203. }
  162204. box.iRowid = pNode->iNode;
  162205. rc = nodeParentIndex(pRtree, pNode, &ii);
  162206. if( rc==SQLITE_OK ){
  162207. nodeOverwriteCell(pRtree, pParent, &box, ii);
  162208. rc = fixBoundingBox(pRtree, pParent);
  162209. }
  162210. }
  162211. return rc;
  162212. }
  162213. /*
  162214. ** Delete the cell at index iCell of node pNode. After removing the
  162215. ** cell, adjust the r-tree data structure if required.
  162216. */
  162217. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  162218. RtreeNode *pParent;
  162219. int rc;
  162220. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  162221. return rc;
  162222. }
  162223. /* Remove the cell from the node. This call just moves bytes around
  162224. ** the in-memory node image, so it cannot fail.
  162225. */
  162226. nodeDeleteCell(pRtree, pNode, iCell);
  162227. /* If the node is not the tree root and now has less than the minimum
  162228. ** number of cells, remove it from the tree. Otherwise, update the
  162229. ** cell in the parent node so that it tightly contains the updated
  162230. ** node.
  162231. */
  162232. pParent = pNode->pParent;
  162233. assert( pParent || pNode->iNode==1 );
  162234. if( pParent ){
  162235. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  162236. rc = removeNode(pRtree, pNode, iHeight);
  162237. }else{
  162238. rc = fixBoundingBox(pRtree, pNode);
  162239. }
  162240. }
  162241. return rc;
  162242. }
  162243. static int Reinsert(
  162244. Rtree *pRtree,
  162245. RtreeNode *pNode,
  162246. RtreeCell *pCell,
  162247. int iHeight
  162248. ){
  162249. int *aOrder;
  162250. int *aSpare;
  162251. RtreeCell *aCell;
  162252. RtreeDValue *aDistance;
  162253. int nCell;
  162254. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  162255. int iDim;
  162256. int ii;
  162257. int rc = SQLITE_OK;
  162258. int n;
  162259. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  162260. nCell = NCELL(pNode)+1;
  162261. n = (nCell+1)&(~1);
  162262. /* Allocate the buffers used by this operation. The allocation is
  162263. ** relinquished before this function returns.
  162264. */
  162265. aCell = (RtreeCell *)sqlite3_malloc(n * (
  162266. sizeof(RtreeCell) + /* aCell array */
  162267. sizeof(int) + /* aOrder array */
  162268. sizeof(int) + /* aSpare array */
  162269. sizeof(RtreeDValue) /* aDistance array */
  162270. ));
  162271. if( !aCell ){
  162272. return SQLITE_NOMEM;
  162273. }
  162274. aOrder = (int *)&aCell[n];
  162275. aSpare = (int *)&aOrder[n];
  162276. aDistance = (RtreeDValue *)&aSpare[n];
  162277. for(ii=0; ii<nCell; ii++){
  162278. if( ii==(nCell-1) ){
  162279. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  162280. }else{
  162281. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  162282. }
  162283. aOrder[ii] = ii;
  162284. for(iDim=0; iDim<pRtree->nDim; iDim++){
  162285. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  162286. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  162287. }
  162288. }
  162289. for(iDim=0; iDim<pRtree->nDim; iDim++){
  162290. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  162291. }
  162292. for(ii=0; ii<nCell; ii++){
  162293. aDistance[ii] = RTREE_ZERO;
  162294. for(iDim=0; iDim<pRtree->nDim; iDim++){
  162295. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  162296. DCOORD(aCell[ii].aCoord[iDim*2]));
  162297. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  162298. }
  162299. }
  162300. SortByDistance(aOrder, nCell, aDistance, aSpare);
  162301. nodeZero(pRtree, pNode);
  162302. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  162303. RtreeCell *p = &aCell[aOrder[ii]];
  162304. nodeInsertCell(pRtree, pNode, p);
  162305. if( p->iRowid==pCell->iRowid ){
  162306. if( iHeight==0 ){
  162307. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  162308. }else{
  162309. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  162310. }
  162311. }
  162312. }
  162313. if( rc==SQLITE_OK ){
  162314. rc = fixBoundingBox(pRtree, pNode);
  162315. }
  162316. for(; rc==SQLITE_OK && ii<nCell; ii++){
  162317. /* Find a node to store this cell in. pNode->iNode currently contains
  162318. ** the height of the sub-tree headed by the cell.
  162319. */
  162320. RtreeNode *pInsert;
  162321. RtreeCell *p = &aCell[aOrder[ii]];
  162322. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  162323. if( rc==SQLITE_OK ){
  162324. int rc2;
  162325. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  162326. rc2 = nodeRelease(pRtree, pInsert);
  162327. if( rc==SQLITE_OK ){
  162328. rc = rc2;
  162329. }
  162330. }
  162331. }
  162332. sqlite3_free(aCell);
  162333. return rc;
  162334. }
  162335. /*
  162336. ** Insert cell pCell into node pNode. Node pNode is the head of a
  162337. ** subtree iHeight high (leaf nodes have iHeight==0).
  162338. */
  162339. static int rtreeInsertCell(
  162340. Rtree *pRtree,
  162341. RtreeNode *pNode,
  162342. RtreeCell *pCell,
  162343. int iHeight
  162344. ){
  162345. int rc = SQLITE_OK;
  162346. if( iHeight>0 ){
  162347. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  162348. if( pChild ){
  162349. nodeRelease(pRtree, pChild->pParent);
  162350. nodeReference(pNode);
  162351. pChild->pParent = pNode;
  162352. }
  162353. }
  162354. if( nodeInsertCell(pRtree, pNode, pCell) ){
  162355. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  162356. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  162357. }else{
  162358. pRtree->iReinsertHeight = iHeight;
  162359. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  162360. }
  162361. }else{
  162362. rc = AdjustTree(pRtree, pNode, pCell);
  162363. if( rc==SQLITE_OK ){
  162364. if( iHeight==0 ){
  162365. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  162366. }else{
  162367. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  162368. }
  162369. }
  162370. }
  162371. return rc;
  162372. }
  162373. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  162374. int ii;
  162375. int rc = SQLITE_OK;
  162376. int nCell = NCELL(pNode);
  162377. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  162378. RtreeNode *pInsert;
  162379. RtreeCell cell;
  162380. nodeGetCell(pRtree, pNode, ii, &cell);
  162381. /* Find a node to store this cell in. pNode->iNode currently contains
  162382. ** the height of the sub-tree headed by the cell.
  162383. */
  162384. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  162385. if( rc==SQLITE_OK ){
  162386. int rc2;
  162387. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  162388. rc2 = nodeRelease(pRtree, pInsert);
  162389. if( rc==SQLITE_OK ){
  162390. rc = rc2;
  162391. }
  162392. }
  162393. }
  162394. return rc;
  162395. }
  162396. /*
  162397. ** Select a currently unused rowid for a new r-tree record.
  162398. */
  162399. static int newRowid(Rtree *pRtree, i64 *piRowid){
  162400. int rc;
  162401. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  162402. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  162403. sqlite3_step(pRtree->pWriteRowid);
  162404. rc = sqlite3_reset(pRtree->pWriteRowid);
  162405. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  162406. return rc;
  162407. }
  162408. /*
  162409. ** Remove the entry with rowid=iDelete from the r-tree structure.
  162410. */
  162411. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  162412. int rc; /* Return code */
  162413. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  162414. int iCell; /* Index of iDelete cell in pLeaf */
  162415. RtreeNode *pRoot = 0; /* Root node of rtree structure */
  162416. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  162417. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  162418. /* Obtain a reference to the leaf node that contains the entry
  162419. ** about to be deleted.
  162420. */
  162421. if( rc==SQLITE_OK ){
  162422. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  162423. }
  162424. /* Delete the cell in question from the leaf node. */
  162425. if( rc==SQLITE_OK ){
  162426. int rc2;
  162427. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  162428. if( rc==SQLITE_OK ){
  162429. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  162430. }
  162431. rc2 = nodeRelease(pRtree, pLeaf);
  162432. if( rc==SQLITE_OK ){
  162433. rc = rc2;
  162434. }
  162435. }
  162436. /* Delete the corresponding entry in the <rtree>_rowid table. */
  162437. if( rc==SQLITE_OK ){
  162438. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  162439. sqlite3_step(pRtree->pDeleteRowid);
  162440. rc = sqlite3_reset(pRtree->pDeleteRowid);
  162441. }
  162442. /* Check if the root node now has exactly one child. If so, remove
  162443. ** it, schedule the contents of the child for reinsertion and
  162444. ** reduce the tree height by one.
  162445. **
  162446. ** This is equivalent to copying the contents of the child into
  162447. ** the root node (the operation that Gutman's paper says to perform
  162448. ** in this scenario).
  162449. */
  162450. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  162451. int rc2;
  162452. RtreeNode *pChild = 0;
  162453. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  162454. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  162455. if( rc==SQLITE_OK ){
  162456. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  162457. }
  162458. rc2 = nodeRelease(pRtree, pChild);
  162459. if( rc==SQLITE_OK ) rc = rc2;
  162460. if( rc==SQLITE_OK ){
  162461. pRtree->iDepth--;
  162462. writeInt16(pRoot->zData, pRtree->iDepth);
  162463. pRoot->isDirty = 1;
  162464. }
  162465. }
  162466. /* Re-insert the contents of any underfull nodes removed from the tree. */
  162467. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  162468. if( rc==SQLITE_OK ){
  162469. rc = reinsertNodeContent(pRtree, pLeaf);
  162470. }
  162471. pRtree->pDeleted = pLeaf->pNext;
  162472. pRtree->nNodeRef--;
  162473. sqlite3_free(pLeaf);
  162474. }
  162475. /* Release the reference to the root node. */
  162476. if( rc==SQLITE_OK ){
  162477. rc = nodeRelease(pRtree, pRoot);
  162478. }else{
  162479. nodeRelease(pRtree, pRoot);
  162480. }
  162481. return rc;
  162482. }
  162483. /*
  162484. ** Rounding constants for float->double conversion.
  162485. */
  162486. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  162487. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  162488. #if !defined(SQLITE_RTREE_INT_ONLY)
  162489. /*
  162490. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  162491. ** while taking care to round toward negative or positive, respectively.
  162492. */
  162493. static RtreeValue rtreeValueDown(sqlite3_value *v){
  162494. double d = sqlite3_value_double(v);
  162495. float f = (float)d;
  162496. if( f>d ){
  162497. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  162498. }
  162499. return f;
  162500. }
  162501. static RtreeValue rtreeValueUp(sqlite3_value *v){
  162502. double d = sqlite3_value_double(v);
  162503. float f = (float)d;
  162504. if( f<d ){
  162505. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  162506. }
  162507. return f;
  162508. }
  162509. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  162510. /*
  162511. ** A constraint has failed while inserting a row into an rtree table.
  162512. ** Assuming no OOM error occurs, this function sets the error message
  162513. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  162514. ** SQLITE_CONSTRAINT.
  162515. **
  162516. ** Parameter iCol is the index of the leftmost column involved in the
  162517. ** constraint failure. If it is 0, then the constraint that failed is
  162518. ** the unique constraint on the id column. Otherwise, it is the rtree
  162519. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  162520. **
  162521. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  162522. */
  162523. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  162524. sqlite3_stmt *pStmt = 0;
  162525. char *zSql;
  162526. int rc;
  162527. assert( iCol==0 || iCol%2 );
  162528. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  162529. if( zSql ){
  162530. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  162531. }else{
  162532. rc = SQLITE_NOMEM;
  162533. }
  162534. sqlite3_free(zSql);
  162535. if( rc==SQLITE_OK ){
  162536. if( iCol==0 ){
  162537. const char *zCol = sqlite3_column_name(pStmt, 0);
  162538. pRtree->base.zErrMsg = sqlite3_mprintf(
  162539. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  162540. );
  162541. }else{
  162542. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  162543. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  162544. pRtree->base.zErrMsg = sqlite3_mprintf(
  162545. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  162546. );
  162547. }
  162548. }
  162549. sqlite3_finalize(pStmt);
  162550. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  162551. }
  162552. /*
  162553. ** The xUpdate method for rtree module virtual tables.
  162554. */
  162555. static int rtreeUpdate(
  162556. sqlite3_vtab *pVtab,
  162557. int nData,
  162558. sqlite3_value **aData,
  162559. sqlite_int64 *pRowid
  162560. ){
  162561. Rtree *pRtree = (Rtree *)pVtab;
  162562. int rc = SQLITE_OK;
  162563. RtreeCell cell; /* New cell to insert if nData>1 */
  162564. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  162565. if( pRtree->nNodeRef ){
  162566. /* Unable to write to the btree while another cursor is reading from it,
  162567. ** since the write might do a rebalance which would disrupt the read
  162568. ** cursor. */
  162569. return SQLITE_LOCKED_VTAB;
  162570. }
  162571. rtreeReference(pRtree);
  162572. assert(nData>=1);
  162573. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  162574. /* Constraint handling. A write operation on an r-tree table may return
  162575. ** SQLITE_CONSTRAINT for two reasons:
  162576. **
  162577. ** 1. A duplicate rowid value, or
  162578. ** 2. The supplied data violates the "x2>=x1" constraint.
  162579. **
  162580. ** In the first case, if the conflict-handling mode is REPLACE, then
  162581. ** the conflicting row can be removed before proceeding. In the second
  162582. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  162583. ** conflict-handling mode specified by the user.
  162584. */
  162585. if( nData>1 ){
  162586. int ii;
  162587. int nn = nData - 4;
  162588. if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
  162589. /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
  162590. **
  162591. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  162592. ** with "column" that are interpreted as table constraints.
  162593. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  162594. ** This problem was discovered after years of use, so we silently ignore
  162595. ** these kinds of misdeclared tables to avoid breaking any legacy.
  162596. */
  162597. #ifndef SQLITE_RTREE_INT_ONLY
  162598. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  162599. for(ii=0; ii<nn; ii+=2){
  162600. cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
  162601. cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
  162602. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  162603. rc = rtreeConstraintError(pRtree, ii+1);
  162604. goto constraint;
  162605. }
  162606. }
  162607. }else
  162608. #endif
  162609. {
  162610. for(ii=0; ii<nn; ii+=2){
  162611. cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
  162612. cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
  162613. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  162614. rc = rtreeConstraintError(pRtree, ii+1);
  162615. goto constraint;
  162616. }
  162617. }
  162618. }
  162619. /* If a rowid value was supplied, check if it is already present in
  162620. ** the table. If so, the constraint has failed. */
  162621. if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
  162622. cell.iRowid = sqlite3_value_int64(aData[2]);
  162623. if( sqlite3_value_type(aData[0])==SQLITE_NULL
  162624. || sqlite3_value_int64(aData[0])!=cell.iRowid
  162625. ){
  162626. int steprc;
  162627. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  162628. steprc = sqlite3_step(pRtree->pReadRowid);
  162629. rc = sqlite3_reset(pRtree->pReadRowid);
  162630. if( SQLITE_ROW==steprc ){
  162631. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  162632. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  162633. }else{
  162634. rc = rtreeConstraintError(pRtree, 0);
  162635. goto constraint;
  162636. }
  162637. }
  162638. }
  162639. bHaveRowid = 1;
  162640. }
  162641. }
  162642. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  162643. ** record to delete from the r-tree table. The following block does
  162644. ** just that.
  162645. */
  162646. if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
  162647. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
  162648. }
  162649. /* If the aData[] array contains more than one element, elements
  162650. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  162651. ** the r-tree structure.
  162652. */
  162653. if( rc==SQLITE_OK && nData>1 ){
  162654. /* Insert the new record into the r-tree */
  162655. RtreeNode *pLeaf = 0;
  162656. /* Figure out the rowid of the new row. */
  162657. if( bHaveRowid==0 ){
  162658. rc = newRowid(pRtree, &cell.iRowid);
  162659. }
  162660. *pRowid = cell.iRowid;
  162661. if( rc==SQLITE_OK ){
  162662. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  162663. }
  162664. if( rc==SQLITE_OK ){
  162665. int rc2;
  162666. pRtree->iReinsertHeight = -1;
  162667. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  162668. rc2 = nodeRelease(pRtree, pLeaf);
  162669. if( rc==SQLITE_OK ){
  162670. rc = rc2;
  162671. }
  162672. }
  162673. if( pRtree->nAux ){
  162674. sqlite3_stmt *pUp = pRtree->pWriteAux;
  162675. int jj;
  162676. sqlite3_bind_int64(pUp, 1, *pRowid);
  162677. for(jj=0; jj<pRtree->nAux; jj++){
  162678. sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
  162679. }
  162680. sqlite3_step(pUp);
  162681. rc = sqlite3_reset(pUp);
  162682. }
  162683. }
  162684. constraint:
  162685. rtreeRelease(pRtree);
  162686. return rc;
  162687. }
  162688. /*
  162689. ** Called when a transaction starts.
  162690. */
  162691. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  162692. Rtree *pRtree = (Rtree *)pVtab;
  162693. assert( pRtree->inWrTrans==0 );
  162694. pRtree->inWrTrans++;
  162695. return SQLITE_OK;
  162696. }
  162697. /*
  162698. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  162699. ** The sqlite3_blob object should be released at this point.
  162700. */
  162701. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  162702. Rtree *pRtree = (Rtree *)pVtab;
  162703. pRtree->inWrTrans = 0;
  162704. nodeBlobReset(pRtree);
  162705. return SQLITE_OK;
  162706. }
  162707. /*
  162708. ** The xRename method for rtree module virtual tables.
  162709. */
  162710. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  162711. Rtree *pRtree = (Rtree *)pVtab;
  162712. int rc = SQLITE_NOMEM;
  162713. char *zSql = sqlite3_mprintf(
  162714. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  162715. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  162716. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  162717. , pRtree->zDb, pRtree->zName, zNewName
  162718. , pRtree->zDb, pRtree->zName, zNewName
  162719. , pRtree->zDb, pRtree->zName, zNewName
  162720. );
  162721. if( zSql ){
  162722. nodeBlobReset(pRtree);
  162723. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  162724. sqlite3_free(zSql);
  162725. }
  162726. return rc;
  162727. }
  162728. /*
  162729. ** The xSavepoint method.
  162730. **
  162731. ** This module does not need to do anything to support savepoints. However,
  162732. ** it uses this hook to close any open blob handle. This is done because a
  162733. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  162734. ** succeed if there are any open blob handles. i.e. if the blob handle were
  162735. ** not closed here, the following would fail:
  162736. **
  162737. ** BEGIN;
  162738. ** INSERT INTO rtree...
  162739. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  162740. ** COMMIT;
  162741. */
  162742. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  162743. Rtree *pRtree = (Rtree *)pVtab;
  162744. int iwt = pRtree->inWrTrans;
  162745. UNUSED_PARAMETER(iSavepoint);
  162746. pRtree->inWrTrans = 0;
  162747. nodeBlobReset(pRtree);
  162748. pRtree->inWrTrans = iwt;
  162749. return SQLITE_OK;
  162750. }
  162751. /*
  162752. ** This function populates the pRtree->nRowEst variable with an estimate
  162753. ** of the number of rows in the virtual table. If possible, this is based
  162754. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  162755. */
  162756. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  162757. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  162758. char *zSql;
  162759. sqlite3_stmt *p;
  162760. int rc;
  162761. i64 nRow = 0;
  162762. rc = sqlite3_table_column_metadata(
  162763. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  162764. );
  162765. if( rc!=SQLITE_OK ){
  162766. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  162767. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  162768. }
  162769. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  162770. if( zSql==0 ){
  162771. rc = SQLITE_NOMEM;
  162772. }else{
  162773. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  162774. if( rc==SQLITE_OK ){
  162775. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  162776. rc = sqlite3_finalize(p);
  162777. }else if( rc!=SQLITE_NOMEM ){
  162778. rc = SQLITE_OK;
  162779. }
  162780. if( rc==SQLITE_OK ){
  162781. if( nRow==0 ){
  162782. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  162783. }else{
  162784. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  162785. }
  162786. }
  162787. sqlite3_free(zSql);
  162788. }
  162789. return rc;
  162790. }
  162791. static sqlite3_module rtreeModule = {
  162792. 2, /* iVersion */
  162793. rtreeCreate, /* xCreate - create a table */
  162794. rtreeConnect, /* xConnect - connect to an existing table */
  162795. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  162796. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  162797. rtreeDestroy, /* xDestroy - Drop a table */
  162798. rtreeOpen, /* xOpen - open a cursor */
  162799. rtreeClose, /* xClose - close a cursor */
  162800. rtreeFilter, /* xFilter - configure scan constraints */
  162801. rtreeNext, /* xNext - advance a cursor */
  162802. rtreeEof, /* xEof */
  162803. rtreeColumn, /* xColumn - read data */
  162804. rtreeRowid, /* xRowid - read data */
  162805. rtreeUpdate, /* xUpdate - write data */
  162806. rtreeBeginTransaction, /* xBegin - begin transaction */
  162807. rtreeEndTransaction, /* xSync - sync transaction */
  162808. rtreeEndTransaction, /* xCommit - commit transaction */
  162809. rtreeEndTransaction, /* xRollback - rollback transaction */
  162810. 0, /* xFindFunction - function overloading */
  162811. rtreeRename, /* xRename - rename the table */
  162812. rtreeSavepoint, /* xSavepoint */
  162813. 0, /* xRelease */
  162814. 0, /* xRollbackTo */
  162815. };
  162816. static int rtreeSqlInit(
  162817. Rtree *pRtree,
  162818. sqlite3 *db,
  162819. const char *zDb,
  162820. const char *zPrefix,
  162821. int isCreate
  162822. ){
  162823. int rc = SQLITE_OK;
  162824. #define N_STATEMENT 8
  162825. static const char *azSql[N_STATEMENT] = {
  162826. /* Write the xxx_node table */
  162827. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
  162828. "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
  162829. /* Read and write the xxx_rowid table */
  162830. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  162831. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
  162832. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  162833. /* Read and write the xxx_parent table */
  162834. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
  162835. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
  162836. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
  162837. };
  162838. sqlite3_stmt **appStmt[N_STATEMENT];
  162839. int i;
  162840. pRtree->db = db;
  162841. if( isCreate ){
  162842. char *zCreate;
  162843. sqlite3_str *p = sqlite3_str_new(db);
  162844. int ii;
  162845. sqlite3_str_appendf(p,
  162846. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
  162847. zDb, zPrefix);
  162848. for(ii=0; ii<pRtree->nAux; ii++){
  162849. sqlite3_str_appendf(p,",a%d",ii);
  162850. }
  162851. sqlite3_str_appendf(p,
  162852. ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
  162853. zDb, zPrefix);
  162854. sqlite3_str_appendf(p,
  162855. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
  162856. zDb, zPrefix);
  162857. sqlite3_str_appendf(p,
  162858. "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
  162859. zDb, zPrefix, pRtree->iNodeSize);
  162860. zCreate = sqlite3_str_finish(p);
  162861. if( !zCreate ){
  162862. return SQLITE_NOMEM;
  162863. }
  162864. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  162865. sqlite3_free(zCreate);
  162866. if( rc!=SQLITE_OK ){
  162867. return rc;
  162868. }
  162869. }
  162870. appStmt[0] = &pRtree->pWriteNode;
  162871. appStmt[1] = &pRtree->pDeleteNode;
  162872. appStmt[2] = &pRtree->pReadRowid;
  162873. appStmt[3] = &pRtree->pWriteRowid;
  162874. appStmt[4] = &pRtree->pDeleteRowid;
  162875. appStmt[5] = &pRtree->pReadParent;
  162876. appStmt[6] = &pRtree->pWriteParent;
  162877. appStmt[7] = &pRtree->pDeleteParent;
  162878. rc = rtreeQueryStat1(db, pRtree);
  162879. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  162880. char *zSql;
  162881. const char *zFormat;
  162882. if( i!=3 || pRtree->nAux==0 ){
  162883. zFormat = azSql[i];
  162884. }else {
  162885. /* An UPSERT is very slightly slower than REPLACE, but it is needed
  162886. ** if there are auxiliary columns */
  162887. zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
  162888. "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
  162889. }
  162890. zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
  162891. if( zSql ){
  162892. rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  162893. appStmt[i], 0);
  162894. }else{
  162895. rc = SQLITE_NOMEM;
  162896. }
  162897. sqlite3_free(zSql);
  162898. }
  162899. if( pRtree->nAux ){
  162900. pRtree->zReadAuxSql = sqlite3_mprintf(
  162901. "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
  162902. zDb, zPrefix);
  162903. if( pRtree->zReadAuxSql==0 ){
  162904. rc = SQLITE_NOMEM;
  162905. }else{
  162906. sqlite3_str *p = sqlite3_str_new(db);
  162907. int ii;
  162908. char *zSql;
  162909. sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
  162910. for(ii=0; ii<pRtree->nAux; ii++){
  162911. if( ii ) sqlite3_str_append(p, ",", 1);
  162912. sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
  162913. }
  162914. sqlite3_str_appendf(p, " WHERE rowid=?1");
  162915. zSql = sqlite3_str_finish(p);
  162916. if( zSql==0 ){
  162917. rc = SQLITE_NOMEM;
  162918. }else{
  162919. rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  162920. &pRtree->pWriteAux, 0);
  162921. sqlite3_free(zSql);
  162922. }
  162923. }
  162924. }
  162925. return rc;
  162926. }
  162927. /*
  162928. ** The second argument to this function contains the text of an SQL statement
  162929. ** that returns a single integer value. The statement is compiled and executed
  162930. ** using database connection db. If successful, the integer value returned
  162931. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  162932. ** code is returned and the value of *piVal after returning is not defined.
  162933. */
  162934. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  162935. int rc = SQLITE_NOMEM;
  162936. if( zSql ){
  162937. sqlite3_stmt *pStmt = 0;
  162938. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  162939. if( rc==SQLITE_OK ){
  162940. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162941. *piVal = sqlite3_column_int(pStmt, 0);
  162942. }
  162943. rc = sqlite3_finalize(pStmt);
  162944. }
  162945. }
  162946. return rc;
  162947. }
  162948. /*
  162949. ** This function is called from within the xConnect() or xCreate() method to
  162950. ** determine the node-size used by the rtree table being created or connected
  162951. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  162952. ** Otherwise, an SQLite error code is returned.
  162953. **
  162954. ** If this function is being called as part of an xConnect(), then the rtree
  162955. ** table already exists. In this case the node-size is determined by inspecting
  162956. ** the root node of the tree.
  162957. **
  162958. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  162959. ** This ensures that each node is stored on a single database page. If the
  162960. ** database page-size is so large that more than RTREE_MAXCELLS entries
  162961. ** would fit in a single node, use a smaller node-size.
  162962. */
  162963. static int getNodeSize(
  162964. sqlite3 *db, /* Database handle */
  162965. Rtree *pRtree, /* Rtree handle */
  162966. int isCreate, /* True for xCreate, false for xConnect */
  162967. char **pzErr /* OUT: Error message, if any */
  162968. ){
  162969. int rc;
  162970. char *zSql;
  162971. if( isCreate ){
  162972. int iPageSize = 0;
  162973. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  162974. rc = getIntFromStmt(db, zSql, &iPageSize);
  162975. if( rc==SQLITE_OK ){
  162976. pRtree->iNodeSize = iPageSize-64;
  162977. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  162978. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  162979. }
  162980. }else{
  162981. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  162982. }
  162983. }else{
  162984. zSql = sqlite3_mprintf(
  162985. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  162986. pRtree->zDb, pRtree->zName
  162987. );
  162988. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  162989. if( rc!=SQLITE_OK ){
  162990. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  162991. }else if( pRtree->iNodeSize<(512-64) ){
  162992. rc = SQLITE_CORRUPT_VTAB;
  162993. *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
  162994. pRtree->zName);
  162995. }
  162996. }
  162997. sqlite3_free(zSql);
  162998. return rc;
  162999. }
  163000. /*
  163001. ** This function is the implementation of both the xConnect and xCreate
  163002. ** methods of the r-tree virtual table.
  163003. **
  163004. ** argv[0] -> module name
  163005. ** argv[1] -> database name
  163006. ** argv[2] -> table name
  163007. ** argv[...] -> column names...
  163008. */
  163009. static int rtreeInit(
  163010. sqlite3 *db, /* Database connection */
  163011. void *pAux, /* One of the RTREE_COORD_* constants */
  163012. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  163013. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  163014. char **pzErr, /* OUT: Error message, if any */
  163015. int isCreate /* True for xCreate, false for xConnect */
  163016. ){
  163017. int rc = SQLITE_OK;
  163018. Rtree *pRtree;
  163019. int nDb; /* Length of string argv[1] */
  163020. int nName; /* Length of string argv[2] */
  163021. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  163022. sqlite3_str *pSql;
  163023. char *zSql;
  163024. int ii = 4;
  163025. int iErr;
  163026. const char *aErrMsg[] = {
  163027. 0, /* 0 */
  163028. "Wrong number of columns for an rtree table", /* 1 */
  163029. "Too few columns for an rtree table", /* 2 */
  163030. "Too many columns for an rtree table", /* 3 */
  163031. "Auxiliary rtree columns must be last" /* 4 */
  163032. };
  163033. assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
  163034. if( argc>RTREE_MAX_AUX_COLUMN+3 ){
  163035. *pzErr = sqlite3_mprintf("%s", aErrMsg[3]);
  163036. return SQLITE_ERROR;
  163037. }
  163038. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  163039. /* Allocate the sqlite3_vtab structure */
  163040. nDb = (int)strlen(argv[1]);
  163041. nName = (int)strlen(argv[2]);
  163042. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  163043. if( !pRtree ){
  163044. return SQLITE_NOMEM;
  163045. }
  163046. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  163047. pRtree->nBusy = 1;
  163048. pRtree->base.pModule = &rtreeModule;
  163049. pRtree->zDb = (char *)&pRtree[1];
  163050. pRtree->zName = &pRtree->zDb[nDb+1];
  163051. pRtree->eCoordType = (u8)eCoordType;
  163052. memcpy(pRtree->zDb, argv[1], nDb);
  163053. memcpy(pRtree->zName, argv[2], nName);
  163054. /* Create/Connect to the underlying relational database schema. If
  163055. ** that is successful, call sqlite3_declare_vtab() to configure
  163056. ** the r-tree table schema.
  163057. */
  163058. pSql = sqlite3_str_new(db);
  163059. sqlite3_str_appendf(pSql, "CREATE TABLE x(%s", argv[3]);
  163060. for(ii=4; ii<argc; ii++){
  163061. if( argv[ii][0]=='+' ){
  163062. pRtree->nAux++;
  163063. sqlite3_str_appendf(pSql, ",%s", argv[ii]+1);
  163064. }else if( pRtree->nAux>0 ){
  163065. break;
  163066. }else{
  163067. pRtree->nDim2++;
  163068. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  163069. }
  163070. }
  163071. sqlite3_str_appendf(pSql, ");");
  163072. zSql = sqlite3_str_finish(pSql);
  163073. if( !zSql ){
  163074. rc = SQLITE_NOMEM;
  163075. }else if( ii<argc ){
  163076. *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
  163077. rc = SQLITE_ERROR;
  163078. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  163079. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  163080. }
  163081. sqlite3_free(zSql);
  163082. if( rc ) goto rtreeInit_fail;
  163083. pRtree->nDim = pRtree->nDim2/2;
  163084. if( pRtree->nDim<1 ){
  163085. iErr = 2;
  163086. }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
  163087. iErr = 3;
  163088. }else if( pRtree->nDim2 % 2 ){
  163089. iErr = 1;
  163090. }else{
  163091. iErr = 0;
  163092. }
  163093. if( iErr ){
  163094. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  163095. goto rtreeInit_fail;
  163096. }
  163097. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  163098. /* Figure out the node size to use. */
  163099. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  163100. if( rc ) goto rtreeInit_fail;
  163101. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  163102. if( rc ){
  163103. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  163104. goto rtreeInit_fail;
  163105. }
  163106. *ppVtab = (sqlite3_vtab *)pRtree;
  163107. return SQLITE_OK;
  163108. rtreeInit_fail:
  163109. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  163110. assert( *ppVtab==0 );
  163111. assert( pRtree->nBusy==1 );
  163112. rtreeRelease(pRtree);
  163113. return rc;
  163114. }
  163115. /*
  163116. ** Implementation of a scalar function that decodes r-tree nodes to
  163117. ** human readable strings. This can be used for debugging and analysis.
  163118. **
  163119. ** The scalar function takes two arguments: (1) the number of dimensions
  163120. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  163121. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  163122. ** deserialize all nodes, a statement like:
  163123. **
  163124. ** SELECT rtreenode(2, data) FROM rt_node;
  163125. **
  163126. ** The human readable string takes the form of a Tcl list with one
  163127. ** entry for each cell in the r-tree node. Each entry is itself a
  163128. ** list, containing the 8-byte rowid/pageno followed by the
  163129. ** <num-dimension>*2 coordinates.
  163130. */
  163131. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  163132. char *zText = 0;
  163133. RtreeNode node;
  163134. Rtree tree;
  163135. int ii;
  163136. UNUSED_PARAMETER(nArg);
  163137. memset(&node, 0, sizeof(RtreeNode));
  163138. memset(&tree, 0, sizeof(Rtree));
  163139. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  163140. tree.nDim2 = tree.nDim*2;
  163141. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  163142. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  163143. for(ii=0; ii<NCELL(&node); ii++){
  163144. char zCell[512];
  163145. int nCell = 0;
  163146. RtreeCell cell;
  163147. int jj;
  163148. nodeGetCell(&tree, &node, ii, &cell);
  163149. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  163150. nCell = (int)strlen(zCell);
  163151. for(jj=0; jj<tree.nDim2; jj++){
  163152. #ifndef SQLITE_RTREE_INT_ONLY
  163153. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  163154. (double)cell.aCoord[jj].f);
  163155. #else
  163156. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  163157. cell.aCoord[jj].i);
  163158. #endif
  163159. nCell = (int)strlen(zCell);
  163160. }
  163161. if( zText ){
  163162. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  163163. sqlite3_free(zText);
  163164. zText = zTextNew;
  163165. }else{
  163166. zText = sqlite3_mprintf("{%s}", zCell);
  163167. }
  163168. }
  163169. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  163170. }
  163171. /* This routine implements an SQL function that returns the "depth" parameter
  163172. ** from the front of a blob that is an r-tree node. For example:
  163173. **
  163174. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  163175. **
  163176. ** The depth value is 0 for all nodes other than the root node, and the root
  163177. ** node always has nodeno=1, so the example above is the primary use for this
  163178. ** routine. This routine is intended for testing and analysis only.
  163179. */
  163180. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  163181. UNUSED_PARAMETER(nArg);
  163182. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  163183. || sqlite3_value_bytes(apArg[0])<2
  163184. ){
  163185. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  163186. }else{
  163187. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  163188. sqlite3_result_int(ctx, readInt16(zBlob));
  163189. }
  163190. }
  163191. /*
  163192. ** Context object passed between the various routines that make up the
  163193. ** implementation of integrity-check function rtreecheck().
  163194. */
  163195. typedef struct RtreeCheck RtreeCheck;
  163196. struct RtreeCheck {
  163197. sqlite3 *db; /* Database handle */
  163198. const char *zDb; /* Database containing rtree table */
  163199. const char *zTab; /* Name of rtree table */
  163200. int bInt; /* True for rtree_i32 table */
  163201. int nDim; /* Number of dimensions for this rtree tbl */
  163202. sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
  163203. sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
  163204. int nLeaf; /* Number of leaf cells in table */
  163205. int nNonLeaf; /* Number of non-leaf cells in table */
  163206. int rc; /* Return code */
  163207. char *zReport; /* Message to report */
  163208. int nErr; /* Number of lines in zReport */
  163209. };
  163210. #define RTREE_CHECK_MAX_ERROR 100
  163211. /*
  163212. ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
  163213. ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
  163214. */
  163215. static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
  163216. int rc = sqlite3_reset(pStmt);
  163217. if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
  163218. }
  163219. /*
  163220. ** The second and subsequent arguments to this function are a format string
  163221. ** and printf style arguments. This function formats the string and attempts
  163222. ** to compile it as an SQL statement.
  163223. **
  163224. ** If successful, a pointer to the new SQL statement is returned. Otherwise,
  163225. ** NULL is returned and an error code left in RtreeCheck.rc.
  163226. */
  163227. static sqlite3_stmt *rtreeCheckPrepare(
  163228. RtreeCheck *pCheck, /* RtreeCheck object */
  163229. const char *zFmt, ... /* Format string and trailing args */
  163230. ){
  163231. va_list ap;
  163232. char *z;
  163233. sqlite3_stmt *pRet = 0;
  163234. va_start(ap, zFmt);
  163235. z = sqlite3_vmprintf(zFmt, ap);
  163236. if( pCheck->rc==SQLITE_OK ){
  163237. if( z==0 ){
  163238. pCheck->rc = SQLITE_NOMEM;
  163239. }else{
  163240. pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
  163241. }
  163242. }
  163243. sqlite3_free(z);
  163244. va_end(ap);
  163245. return pRet;
  163246. }
  163247. /*
  163248. ** The second and subsequent arguments to this function are a printf()
  163249. ** style format string and arguments. This function formats the string and
  163250. ** appends it to the report being accumuated in pCheck.
  163251. */
  163252. static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
  163253. va_list ap;
  163254. va_start(ap, zFmt);
  163255. if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
  163256. char *z = sqlite3_vmprintf(zFmt, ap);
  163257. if( z==0 ){
  163258. pCheck->rc = SQLITE_NOMEM;
  163259. }else{
  163260. pCheck->zReport = sqlite3_mprintf("%z%s%z",
  163261. pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
  163262. );
  163263. if( pCheck->zReport==0 ){
  163264. pCheck->rc = SQLITE_NOMEM;
  163265. }
  163266. }
  163267. pCheck->nErr++;
  163268. }
  163269. va_end(ap);
  163270. }
  163271. /*
  163272. ** This function is a no-op if there is already an error code stored
  163273. ** in the RtreeCheck object indicated by the first argument. NULL is
  163274. ** returned in this case.
  163275. **
  163276. ** Otherwise, the contents of rtree table node iNode are loaded from
  163277. ** the database and copied into a buffer obtained from sqlite3_malloc().
  163278. ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
  163279. ** is set to the size of the buffer in bytes.
  163280. **
  163281. ** Or, if an error does occur, NULL is returned and an error code left
  163282. ** in the RtreeCheck object. The final value of *pnNode is undefined in
  163283. ** this case.
  163284. */
  163285. static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
  163286. u8 *pRet = 0; /* Return value */
  163287. assert( pCheck->rc==SQLITE_OK );
  163288. if( pCheck->pGetNode==0 ){
  163289. pCheck->pGetNode = rtreeCheckPrepare(pCheck,
  163290. "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
  163291. pCheck->zDb, pCheck->zTab
  163292. );
  163293. }
  163294. if( pCheck->rc==SQLITE_OK ){
  163295. sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
  163296. if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
  163297. int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
  163298. const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
  163299. pRet = sqlite3_malloc(nNode);
  163300. if( pRet==0 ){
  163301. pCheck->rc = SQLITE_NOMEM;
  163302. }else{
  163303. memcpy(pRet, pNode, nNode);
  163304. *pnNode = nNode;
  163305. }
  163306. }
  163307. rtreeCheckReset(pCheck, pCheck->pGetNode);
  163308. if( pCheck->rc==SQLITE_OK && pRet==0 ){
  163309. rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
  163310. }
  163311. }
  163312. return pRet;
  163313. }
  163314. /*
  163315. ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
  163316. ** (if bLeaf==1) table contains a specified entry. The schemas of the
  163317. ** two tables are:
  163318. **
  163319. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  163320. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  163321. **
  163322. ** In both cases, this function checks that there exists an entry with
  163323. ** IPK value iKey and the second column set to iVal.
  163324. **
  163325. */
  163326. static void rtreeCheckMapping(
  163327. RtreeCheck *pCheck, /* RtreeCheck object */
  163328. int bLeaf, /* True for a leaf cell, false for interior */
  163329. i64 iKey, /* Key for mapping */
  163330. i64 iVal /* Expected value for mapping */
  163331. ){
  163332. int rc;
  163333. sqlite3_stmt *pStmt;
  163334. const char *azSql[2] = {
  163335. "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
  163336. "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
  163337. };
  163338. assert( bLeaf==0 || bLeaf==1 );
  163339. if( pCheck->aCheckMapping[bLeaf]==0 ){
  163340. pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
  163341. azSql[bLeaf], pCheck->zDb, pCheck->zTab
  163342. );
  163343. }
  163344. if( pCheck->rc!=SQLITE_OK ) return;
  163345. pStmt = pCheck->aCheckMapping[bLeaf];
  163346. sqlite3_bind_int64(pStmt, 1, iKey);
  163347. rc = sqlite3_step(pStmt);
  163348. if( rc==SQLITE_DONE ){
  163349. rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
  163350. iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
  163351. );
  163352. }else if( rc==SQLITE_ROW ){
  163353. i64 ii = sqlite3_column_int64(pStmt, 0);
  163354. if( ii!=iVal ){
  163355. rtreeCheckAppendMsg(pCheck,
  163356. "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
  163357. iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
  163358. );
  163359. }
  163360. }
  163361. rtreeCheckReset(pCheck, pStmt);
  163362. }
  163363. /*
  163364. ** Argument pCell points to an array of coordinates stored on an rtree page.
  163365. ** This function checks that the coordinates are internally consistent (no
  163366. ** x1>x2 conditions) and adds an error message to the RtreeCheck object
  163367. ** if they are not.
  163368. **
  163369. ** Additionally, if pParent is not NULL, then it is assumed to point to
  163370. ** the array of coordinates on the parent page that bound the page
  163371. ** containing pCell. In this case it is also verified that the two
  163372. ** sets of coordinates are mutually consistent and an error message added
  163373. ** to the RtreeCheck object if they are not.
  163374. */
  163375. static void rtreeCheckCellCoord(
  163376. RtreeCheck *pCheck,
  163377. i64 iNode, /* Node id to use in error messages */
  163378. int iCell, /* Cell number to use in error messages */
  163379. u8 *pCell, /* Pointer to cell coordinates */
  163380. u8 *pParent /* Pointer to parent coordinates */
  163381. ){
  163382. RtreeCoord c1, c2;
  163383. RtreeCoord p1, p2;
  163384. int i;
  163385. for(i=0; i<pCheck->nDim; i++){
  163386. readCoord(&pCell[4*2*i], &c1);
  163387. readCoord(&pCell[4*(2*i + 1)], &c2);
  163388. /* printf("%e, %e\n", c1.u.f, c2.u.f); */
  163389. if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
  163390. rtreeCheckAppendMsg(pCheck,
  163391. "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
  163392. );
  163393. }
  163394. if( pParent ){
  163395. readCoord(&pParent[4*2*i], &p1);
  163396. readCoord(&pParent[4*(2*i + 1)], &p2);
  163397. if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
  163398. || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
  163399. ){
  163400. rtreeCheckAppendMsg(pCheck,
  163401. "Dimension %d of cell %d on node %lld is corrupt relative to parent"
  163402. , i, iCell, iNode
  163403. );
  163404. }
  163405. }
  163406. }
  163407. }
  163408. /*
  163409. ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
  163410. ** the r-tree structure. Argument aParent points to the array of coordinates
  163411. ** that bound node iNode on the parent node.
  163412. **
  163413. ** If any problems are discovered, an error message is appended to the
  163414. ** report accumulated in the RtreeCheck object.
  163415. */
  163416. static void rtreeCheckNode(
  163417. RtreeCheck *pCheck,
  163418. int iDepth, /* Depth of iNode (0==leaf) */
  163419. u8 *aParent, /* Buffer containing parent coords */
  163420. i64 iNode /* Node to check */
  163421. ){
  163422. u8 *aNode = 0;
  163423. int nNode = 0;
  163424. assert( iNode==1 || aParent!=0 );
  163425. assert( pCheck->nDim>0 );
  163426. aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
  163427. if( aNode ){
  163428. if( nNode<4 ){
  163429. rtreeCheckAppendMsg(pCheck,
  163430. "Node %lld is too small (%d bytes)", iNode, nNode
  163431. );
  163432. }else{
  163433. int nCell; /* Number of cells on page */
  163434. int i; /* Used to iterate through cells */
  163435. if( aParent==0 ){
  163436. iDepth = readInt16(aNode);
  163437. if( iDepth>RTREE_MAX_DEPTH ){
  163438. rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
  163439. sqlite3_free(aNode);
  163440. return;
  163441. }
  163442. }
  163443. nCell = readInt16(&aNode[2]);
  163444. if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
  163445. rtreeCheckAppendMsg(pCheck,
  163446. "Node %lld is too small for cell count of %d (%d bytes)",
  163447. iNode, nCell, nNode
  163448. );
  163449. }else{
  163450. for(i=0; i<nCell; i++){
  163451. u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
  163452. i64 iVal = readInt64(pCell);
  163453. rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
  163454. if( iDepth>0 ){
  163455. rtreeCheckMapping(pCheck, 0, iVal, iNode);
  163456. rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
  163457. pCheck->nNonLeaf++;
  163458. }else{
  163459. rtreeCheckMapping(pCheck, 1, iVal, iNode);
  163460. pCheck->nLeaf++;
  163461. }
  163462. }
  163463. }
  163464. }
  163465. sqlite3_free(aNode);
  163466. }
  163467. }
  163468. /*
  163469. ** The second argument to this function must be either "_rowid" or
  163470. ** "_parent". This function checks that the number of entries in the
  163471. ** %_rowid or %_parent table is exactly nExpect. If not, it adds
  163472. ** an error message to the report in the RtreeCheck object indicated
  163473. ** by the first argument.
  163474. */
  163475. static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
  163476. if( pCheck->rc==SQLITE_OK ){
  163477. sqlite3_stmt *pCount;
  163478. pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
  163479. pCheck->zDb, pCheck->zTab, zTbl
  163480. );
  163481. if( pCount ){
  163482. if( sqlite3_step(pCount)==SQLITE_ROW ){
  163483. i64 nActual = sqlite3_column_int64(pCount, 0);
  163484. if( nActual!=nExpect ){
  163485. rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
  163486. " - expected %lld, actual %lld" , zTbl, nExpect, nActual
  163487. );
  163488. }
  163489. }
  163490. pCheck->rc = sqlite3_finalize(pCount);
  163491. }
  163492. }
  163493. }
  163494. /*
  163495. ** This function does the bulk of the work for the rtree integrity-check.
  163496. ** It is called by rtreecheck(), which is the SQL function implementation.
  163497. */
  163498. static int rtreeCheckTable(
  163499. sqlite3 *db, /* Database handle to access db through */
  163500. const char *zDb, /* Name of db ("main", "temp" etc.) */
  163501. const char *zTab, /* Name of rtree table to check */
  163502. char **pzReport /* OUT: sqlite3_malloc'd report text */
  163503. ){
  163504. RtreeCheck check; /* Common context for various routines */
  163505. sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
  163506. int bEnd = 0; /* True if transaction should be closed */
  163507. int nAux = 0; /* Number of extra columns. */
  163508. /* Initialize the context object */
  163509. memset(&check, 0, sizeof(check));
  163510. check.db = db;
  163511. check.zDb = zDb;
  163512. check.zTab = zTab;
  163513. /* If there is not already an open transaction, open one now. This is
  163514. ** to ensure that the queries run as part of this integrity-check operate
  163515. ** on a consistent snapshot. */
  163516. if( sqlite3_get_autocommit(db) ){
  163517. check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
  163518. bEnd = 1;
  163519. }
  163520. /* Find the number of auxiliary columns */
  163521. if( check.rc==SQLITE_OK ){
  163522. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
  163523. if( pStmt ){
  163524. nAux = sqlite3_column_count(pStmt) - 2;
  163525. sqlite3_finalize(pStmt);
  163526. }
  163527. check.rc = SQLITE_OK;
  163528. }
  163529. /* Find number of dimensions in the rtree table. */
  163530. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
  163531. if( pStmt ){
  163532. int rc;
  163533. check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
  163534. if( check.nDim<1 ){
  163535. rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
  163536. }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
  163537. check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
  163538. }
  163539. rc = sqlite3_finalize(pStmt);
  163540. if( rc!=SQLITE_CORRUPT ) check.rc = rc;
  163541. }
  163542. /* Do the actual integrity-check */
  163543. if( check.nDim>=1 ){
  163544. if( check.rc==SQLITE_OK ){
  163545. rtreeCheckNode(&check, 0, 0, 1);
  163546. }
  163547. rtreeCheckCount(&check, "_rowid", check.nLeaf);
  163548. rtreeCheckCount(&check, "_parent", check.nNonLeaf);
  163549. }
  163550. /* Finalize SQL statements used by the integrity-check */
  163551. sqlite3_finalize(check.pGetNode);
  163552. sqlite3_finalize(check.aCheckMapping[0]);
  163553. sqlite3_finalize(check.aCheckMapping[1]);
  163554. /* If one was opened, close the transaction */
  163555. if( bEnd ){
  163556. int rc = sqlite3_exec(db, "END", 0, 0, 0);
  163557. if( check.rc==SQLITE_OK ) check.rc = rc;
  163558. }
  163559. *pzReport = check.zReport;
  163560. return check.rc;
  163561. }
  163562. /*
  163563. ** Usage:
  163564. **
  163565. ** rtreecheck(<rtree-table>);
  163566. ** rtreecheck(<database>, <rtree-table>);
  163567. **
  163568. ** Invoking this SQL function runs an integrity-check on the named rtree
  163569. ** table. The integrity-check verifies the following:
  163570. **
  163571. ** 1. For each cell in the r-tree structure (%_node table), that:
  163572. **
  163573. ** a) for each dimension, (coord1 <= coord2).
  163574. **
  163575. ** b) unless the cell is on the root node, that the cell is bounded
  163576. ** by the parent cell on the parent node.
  163577. **
  163578. ** c) for leaf nodes, that there is an entry in the %_rowid
  163579. ** table corresponding to the cell's rowid value that
  163580. ** points to the correct node.
  163581. **
  163582. ** d) for cells on non-leaf nodes, that there is an entry in the
  163583. ** %_parent table mapping from the cell's child node to the
  163584. ** node that it resides on.
  163585. **
  163586. ** 2. That there are the same number of entries in the %_rowid table
  163587. ** as there are leaf cells in the r-tree structure, and that there
  163588. ** is a leaf cell that corresponds to each entry in the %_rowid table.
  163589. **
  163590. ** 3. That there are the same number of entries in the %_parent table
  163591. ** as there are non-leaf cells in the r-tree structure, and that
  163592. ** there is a non-leaf cell that corresponds to each entry in the
  163593. ** %_parent table.
  163594. */
  163595. static void rtreecheck(
  163596. sqlite3_context *ctx,
  163597. int nArg,
  163598. sqlite3_value **apArg
  163599. ){
  163600. if( nArg!=1 && nArg!=2 ){
  163601. sqlite3_result_error(ctx,
  163602. "wrong number of arguments to function rtreecheck()", -1
  163603. );
  163604. }else{
  163605. int rc;
  163606. char *zReport = 0;
  163607. const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
  163608. const char *zTab;
  163609. if( nArg==1 ){
  163610. zTab = zDb;
  163611. zDb = "main";
  163612. }else{
  163613. zTab = (const char*)sqlite3_value_text(apArg[1]);
  163614. }
  163615. rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
  163616. if( rc==SQLITE_OK ){
  163617. sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
  163618. }else{
  163619. sqlite3_result_error_code(ctx, rc);
  163620. }
  163621. sqlite3_free(zReport);
  163622. }
  163623. }
  163624. /*
  163625. ** Register the r-tree module with database handle db. This creates the
  163626. ** virtual table module "rtree" and the debugging/analysis scalar
  163627. ** function "rtreenode".
  163628. */
  163629. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  163630. const int utf8 = SQLITE_UTF8;
  163631. int rc;
  163632. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  163633. if( rc==SQLITE_OK ){
  163634. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  163635. }
  163636. if( rc==SQLITE_OK ){
  163637. rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
  163638. }
  163639. if( rc==SQLITE_OK ){
  163640. #ifdef SQLITE_RTREE_INT_ONLY
  163641. void *c = (void *)RTREE_COORD_INT32;
  163642. #else
  163643. void *c = (void *)RTREE_COORD_REAL32;
  163644. #endif
  163645. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  163646. }
  163647. if( rc==SQLITE_OK ){
  163648. void *c = (void *)RTREE_COORD_INT32;
  163649. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  163650. }
  163651. return rc;
  163652. }
  163653. /*
  163654. ** This routine deletes the RtreeGeomCallback object that was attached
  163655. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  163656. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  163657. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  163658. ** the corresponding SQL function is deleted.
  163659. */
  163660. static void rtreeFreeCallback(void *p){
  163661. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  163662. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  163663. sqlite3_free(p);
  163664. }
  163665. /*
  163666. ** This routine frees the BLOB that is returned by geomCallback().
  163667. */
  163668. static void rtreeMatchArgFree(void *pArg){
  163669. int i;
  163670. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  163671. for(i=0; i<p->nParam; i++){
  163672. sqlite3_value_free(p->apSqlParam[i]);
  163673. }
  163674. sqlite3_free(p);
  163675. }
  163676. /*
  163677. ** Each call to sqlite3_rtree_geometry_callback() or
  163678. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  163679. ** scalar function that is implemented by this routine.
  163680. **
  163681. ** All this function does is construct an RtreeMatchArg object that
  163682. ** contains the geometry-checking callback routines and a list of
  163683. ** parameters to this function, then return that RtreeMatchArg object
  163684. ** as a BLOB.
  163685. **
  163686. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  163687. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  163688. ** out which elements of the R-Tree should be returned by the query.
  163689. */
  163690. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  163691. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  163692. RtreeMatchArg *pBlob;
  163693. int nBlob;
  163694. int memErr = 0;
  163695. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  163696. + nArg*sizeof(sqlite3_value*);
  163697. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  163698. if( !pBlob ){
  163699. sqlite3_result_error_nomem(ctx);
  163700. }else{
  163701. int i;
  163702. pBlob->iSize = nBlob;
  163703. pBlob->cb = pGeomCtx[0];
  163704. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  163705. pBlob->nParam = nArg;
  163706. for(i=0; i<nArg; i++){
  163707. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  163708. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  163709. #ifdef SQLITE_RTREE_INT_ONLY
  163710. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  163711. #else
  163712. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  163713. #endif
  163714. }
  163715. if( memErr ){
  163716. sqlite3_result_error_nomem(ctx);
  163717. rtreeMatchArgFree(pBlob);
  163718. }else{
  163719. sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
  163720. }
  163721. }
  163722. }
  163723. /*
  163724. ** Register a new geometry function for use with the r-tree MATCH operator.
  163725. */
  163726. SQLITE_API int sqlite3_rtree_geometry_callback(
  163727. sqlite3 *db, /* Register SQL function on this connection */
  163728. const char *zGeom, /* Name of the new SQL function */
  163729. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  163730. void *pContext /* Extra data associated with the callback */
  163731. ){
  163732. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  163733. /* Allocate and populate the context object. */
  163734. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  163735. if( !pGeomCtx ) return SQLITE_NOMEM;
  163736. pGeomCtx->xGeom = xGeom;
  163737. pGeomCtx->xQueryFunc = 0;
  163738. pGeomCtx->xDestructor = 0;
  163739. pGeomCtx->pContext = pContext;
  163740. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  163741. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  163742. );
  163743. }
  163744. /*
  163745. ** Register a new 2nd-generation geometry function for use with the
  163746. ** r-tree MATCH operator.
  163747. */
  163748. SQLITE_API int sqlite3_rtree_query_callback(
  163749. sqlite3 *db, /* Register SQL function on this connection */
  163750. const char *zQueryFunc, /* Name of new SQL function */
  163751. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  163752. void *pContext, /* Extra data passed into the callback */
  163753. void (*xDestructor)(void*) /* Destructor for the extra data */
  163754. ){
  163755. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  163756. /* Allocate and populate the context object. */
  163757. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  163758. if( !pGeomCtx ) return SQLITE_NOMEM;
  163759. pGeomCtx->xGeom = 0;
  163760. pGeomCtx->xQueryFunc = xQueryFunc;
  163761. pGeomCtx->xDestructor = xDestructor;
  163762. pGeomCtx->pContext = pContext;
  163763. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  163764. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  163765. );
  163766. }
  163767. #if !SQLITE_CORE
  163768. #ifdef _WIN32
  163769. __declspec(dllexport)
  163770. #endif
  163771. SQLITE_API int sqlite3_rtree_init(
  163772. sqlite3 *db,
  163773. char **pzErrMsg,
  163774. const sqlite3_api_routines *pApi
  163775. ){
  163776. SQLITE_EXTENSION_INIT2(pApi)
  163777. return sqlite3RtreeInit(db);
  163778. }
  163779. #endif
  163780. #endif
  163781. /************** End of rtree.c ***********************************************/
  163782. /************** Begin file icu.c *********************************************/
  163783. /*
  163784. ** 2007 May 6
  163785. **
  163786. ** The author disclaims copyright to this source code. In place of
  163787. ** a legal notice, here is a blessing:
  163788. **
  163789. ** May you do good and not evil.
  163790. ** May you find forgiveness for yourself and forgive others.
  163791. ** May you share freely, never taking more than you give.
  163792. **
  163793. *************************************************************************
  163794. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  163795. **
  163796. ** This file implements an integration between the ICU library
  163797. ** ("International Components for Unicode", an open-source library
  163798. ** for handling unicode data) and SQLite. The integration uses
  163799. ** ICU to provide the following to SQLite:
  163800. **
  163801. ** * An implementation of the SQL regexp() function (and hence REGEXP
  163802. ** operator) using the ICU uregex_XX() APIs.
  163803. **
  163804. ** * Implementations of the SQL scalar upper() and lower() functions
  163805. ** for case mapping.
  163806. **
  163807. ** * Integration of ICU and SQLite collation sequences.
  163808. **
  163809. ** * An implementation of the LIKE operator that uses ICU to
  163810. ** provide case-independent matching.
  163811. */
  163812. #if !defined(SQLITE_CORE) \
  163813. || defined(SQLITE_ENABLE_ICU) \
  163814. || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  163815. /* Include ICU headers */
  163816. #include <unicode/utypes.h>
  163817. #include <unicode/uregex.h>
  163818. #include <unicode/ustring.h>
  163819. #include <unicode/ucol.h>
  163820. /* #include <assert.h> */
  163821. #ifndef SQLITE_CORE
  163822. /* #include "sqlite3ext.h" */
  163823. SQLITE_EXTENSION_INIT1
  163824. #else
  163825. /* #include "sqlite3.h" */
  163826. #endif
  163827. /*
  163828. ** This function is called when an ICU function called from within
  163829. ** the implementation of an SQL scalar function returns an error.
  163830. **
  163831. ** The scalar function context passed as the first argument is
  163832. ** loaded with an error message based on the following two args.
  163833. */
  163834. static void icuFunctionError(
  163835. sqlite3_context *pCtx, /* SQLite scalar function context */
  163836. const char *zName, /* Name of ICU function that failed */
  163837. UErrorCode e /* Error code returned by ICU function */
  163838. ){
  163839. char zBuf[128];
  163840. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  163841. zBuf[127] = '\0';
  163842. sqlite3_result_error(pCtx, zBuf, -1);
  163843. }
  163844. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  163845. /*
  163846. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  163847. ** operator.
  163848. */
  163849. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  163850. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  163851. #endif
  163852. /*
  163853. ** Version of sqlite3_free() that is always a function, never a macro.
  163854. */
  163855. static void xFree(void *p){
  163856. sqlite3_free(p);
  163857. }
  163858. /*
  163859. ** This lookup table is used to help decode the first byte of
  163860. ** a multi-byte UTF8 character. It is copied here from SQLite source
  163861. ** code file utf8.c.
  163862. */
  163863. static const unsigned char icuUtf8Trans1[] = {
  163864. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  163865. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  163866. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  163867. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  163868. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  163869. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  163870. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  163871. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  163872. };
  163873. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  163874. c = *(zIn++); \
  163875. if( c>=0xc0 ){ \
  163876. c = icuUtf8Trans1[c-0xc0]; \
  163877. while( (*zIn & 0xc0)==0x80 ){ \
  163878. c = (c<<6) + (0x3f & *(zIn++)); \
  163879. } \
  163880. }
  163881. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  163882. assert( *zIn ); \
  163883. if( *(zIn++)>=0xc0 ){ \
  163884. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  163885. }
  163886. /*
  163887. ** Compare two UTF-8 strings for equality where the first string is
  163888. ** a "LIKE" expression. Return true (1) if they are the same and
  163889. ** false (0) if they are different.
  163890. */
  163891. static int icuLikeCompare(
  163892. const uint8_t *zPattern, /* LIKE pattern */
  163893. const uint8_t *zString, /* The UTF-8 string to compare against */
  163894. const UChar32 uEsc /* The escape character */
  163895. ){
  163896. static const uint32_t MATCH_ONE = (uint32_t)'_';
  163897. static const uint32_t MATCH_ALL = (uint32_t)'%';
  163898. int prevEscape = 0; /* True if the previous character was uEsc */
  163899. while( 1 ){
  163900. /* Read (and consume) the next character from the input pattern. */
  163901. uint32_t uPattern;
  163902. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  163903. if( uPattern==0 ) break;
  163904. /* There are now 4 possibilities:
  163905. **
  163906. ** 1. uPattern is an unescaped match-all character "%",
  163907. ** 2. uPattern is an unescaped match-one character "_",
  163908. ** 3. uPattern is an unescaped escape character, or
  163909. ** 4. uPattern is to be handled as an ordinary character
  163910. */
  163911. if( !prevEscape && uPattern==MATCH_ALL ){
  163912. /* Case 1. */
  163913. uint8_t c;
  163914. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  163915. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  163916. ** test string.
  163917. */
  163918. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  163919. if( c==MATCH_ONE ){
  163920. if( *zString==0 ) return 0;
  163921. SQLITE_ICU_SKIP_UTF8(zString);
  163922. }
  163923. zPattern++;
  163924. }
  163925. if( *zPattern==0 ) return 1;
  163926. while( *zString ){
  163927. if( icuLikeCompare(zPattern, zString, uEsc) ){
  163928. return 1;
  163929. }
  163930. SQLITE_ICU_SKIP_UTF8(zString);
  163931. }
  163932. return 0;
  163933. }else if( !prevEscape && uPattern==MATCH_ONE ){
  163934. /* Case 2. */
  163935. if( *zString==0 ) return 0;
  163936. SQLITE_ICU_SKIP_UTF8(zString);
  163937. }else if( !prevEscape && uPattern==(uint32_t)uEsc){
  163938. /* Case 3. */
  163939. prevEscape = 1;
  163940. }else{
  163941. /* Case 4. */
  163942. uint32_t uString;
  163943. SQLITE_ICU_READ_UTF8(zString, uString);
  163944. uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
  163945. uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
  163946. if( uString!=uPattern ){
  163947. return 0;
  163948. }
  163949. prevEscape = 0;
  163950. }
  163951. }
  163952. return *zString==0;
  163953. }
  163954. /*
  163955. ** Implementation of the like() SQL function. This function implements
  163956. ** the build-in LIKE operator. The first argument to the function is the
  163957. ** pattern and the second argument is the string. So, the SQL statements:
  163958. **
  163959. ** A LIKE B
  163960. **
  163961. ** is implemented as like(B, A). If there is an escape character E,
  163962. **
  163963. ** A LIKE B ESCAPE E
  163964. **
  163965. ** is mapped to like(B, A, E).
  163966. */
  163967. static void icuLikeFunc(
  163968. sqlite3_context *context,
  163969. int argc,
  163970. sqlite3_value **argv
  163971. ){
  163972. const unsigned char *zA = sqlite3_value_text(argv[0]);
  163973. const unsigned char *zB = sqlite3_value_text(argv[1]);
  163974. UChar32 uEsc = 0;
  163975. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  163976. ** of deep recursion and N*N behavior in patternCompare().
  163977. */
  163978. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  163979. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  163980. return;
  163981. }
  163982. if( argc==3 ){
  163983. /* The escape character string must consist of a single UTF-8 character.
  163984. ** Otherwise, return an error.
  163985. */
  163986. int nE= sqlite3_value_bytes(argv[2]);
  163987. const unsigned char *zE = sqlite3_value_text(argv[2]);
  163988. int i = 0;
  163989. if( zE==0 ) return;
  163990. U8_NEXT(zE, i, nE, uEsc);
  163991. if( i!=nE){
  163992. sqlite3_result_error(context,
  163993. "ESCAPE expression must be a single character", -1);
  163994. return;
  163995. }
  163996. }
  163997. if( zA && zB ){
  163998. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  163999. }
  164000. }
  164001. /*
  164002. ** Function to delete compiled regexp objects. Registered as
  164003. ** a destructor function with sqlite3_set_auxdata().
  164004. */
  164005. static void icuRegexpDelete(void *p){
  164006. URegularExpression *pExpr = (URegularExpression *)p;
  164007. uregex_close(pExpr);
  164008. }
  164009. /*
  164010. ** Implementation of SQLite REGEXP operator. This scalar function takes
  164011. ** two arguments. The first is a regular expression pattern to compile
  164012. ** the second is a string to match against that pattern. If either
  164013. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  164014. ** is 1 if the string matches the pattern, or 0 otherwise.
  164015. **
  164016. ** SQLite maps the regexp() function to the regexp() operator such
  164017. ** that the following two are equivalent:
  164018. **
  164019. ** zString REGEXP zPattern
  164020. ** regexp(zPattern, zString)
  164021. **
  164022. ** Uses the following ICU regexp APIs:
  164023. **
  164024. ** uregex_open()
  164025. ** uregex_matches()
  164026. ** uregex_close()
  164027. */
  164028. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  164029. UErrorCode status = U_ZERO_ERROR;
  164030. URegularExpression *pExpr;
  164031. UBool res;
  164032. const UChar *zString = sqlite3_value_text16(apArg[1]);
  164033. (void)nArg; /* Unused parameter */
  164034. /* If the left hand side of the regexp operator is NULL,
  164035. ** then the result is also NULL.
  164036. */
  164037. if( !zString ){
  164038. return;
  164039. }
  164040. pExpr = sqlite3_get_auxdata(p, 0);
  164041. if( !pExpr ){
  164042. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  164043. if( !zPattern ){
  164044. return;
  164045. }
  164046. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  164047. if( U_SUCCESS(status) ){
  164048. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  164049. }else{
  164050. assert(!pExpr);
  164051. icuFunctionError(p, "uregex_open", status);
  164052. return;
  164053. }
  164054. }
  164055. /* Configure the text that the regular expression operates on. */
  164056. uregex_setText(pExpr, zString, -1, &status);
  164057. if( !U_SUCCESS(status) ){
  164058. icuFunctionError(p, "uregex_setText", status);
  164059. return;
  164060. }
  164061. /* Attempt the match */
  164062. res = uregex_matches(pExpr, 0, &status);
  164063. if( !U_SUCCESS(status) ){
  164064. icuFunctionError(p, "uregex_matches", status);
  164065. return;
  164066. }
  164067. /* Set the text that the regular expression operates on to a NULL
  164068. ** pointer. This is not really necessary, but it is tidier than
  164069. ** leaving the regular expression object configured with an invalid
  164070. ** pointer after this function returns.
  164071. */
  164072. uregex_setText(pExpr, 0, 0, &status);
  164073. /* Return 1 or 0. */
  164074. sqlite3_result_int(p, res ? 1 : 0);
  164075. }
  164076. /*
  164077. ** Implementations of scalar functions for case mapping - upper() and
  164078. ** lower(). Function upper() converts its input to upper-case (ABC).
  164079. ** Function lower() converts to lower-case (abc).
  164080. **
  164081. ** ICU provides two types of case mapping, "general" case mapping and
  164082. ** "language specific". Refer to ICU documentation for the differences
  164083. ** between the two.
  164084. **
  164085. ** To utilise "general" case mapping, the upper() or lower() scalar
  164086. ** functions are invoked with one argument:
  164087. **
  164088. ** upper('ABC') -> 'abc'
  164089. ** lower('abc') -> 'ABC'
  164090. **
  164091. ** To access ICU "language specific" case mapping, upper() or lower()
  164092. ** should be invoked with two arguments. The second argument is the name
  164093. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  164094. ** as the second argument is the same as invoking the 1 argument version
  164095. ** of upper() or lower().
  164096. **
  164097. ** lower('I', 'en_us') -> 'i'
  164098. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  164099. **
  164100. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  164101. */
  164102. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  164103. const UChar *zInput; /* Pointer to input string */
  164104. UChar *zOutput = 0; /* Pointer to output buffer */
  164105. int nInput; /* Size of utf-16 input string in bytes */
  164106. int nOut; /* Size of output buffer in bytes */
  164107. int cnt;
  164108. int bToUpper; /* True for toupper(), false for tolower() */
  164109. UErrorCode status;
  164110. const char *zLocale = 0;
  164111. assert(nArg==1 || nArg==2);
  164112. bToUpper = (sqlite3_user_data(p)!=0);
  164113. if( nArg==2 ){
  164114. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  164115. }
  164116. zInput = sqlite3_value_text16(apArg[0]);
  164117. if( !zInput ){
  164118. return;
  164119. }
  164120. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  164121. if( nOut==0 ){
  164122. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  164123. return;
  164124. }
  164125. for(cnt=0; cnt<2; cnt++){
  164126. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  164127. if( zNew==0 ){
  164128. sqlite3_free(zOutput);
  164129. sqlite3_result_error_nomem(p);
  164130. return;
  164131. }
  164132. zOutput = zNew;
  164133. status = U_ZERO_ERROR;
  164134. if( bToUpper ){
  164135. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  164136. }else{
  164137. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  164138. }
  164139. if( U_SUCCESS(status) ){
  164140. sqlite3_result_text16(p, zOutput, nOut, xFree);
  164141. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  164142. assert( cnt==0 );
  164143. continue;
  164144. }else{
  164145. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  164146. }
  164147. return;
  164148. }
  164149. assert( 0 ); /* Unreachable */
  164150. }
  164151. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  164152. /*
  164153. ** Collation sequence destructor function. The pCtx argument points to
  164154. ** a UCollator structure previously allocated using ucol_open().
  164155. */
  164156. static void icuCollationDel(void *pCtx){
  164157. UCollator *p = (UCollator *)pCtx;
  164158. ucol_close(p);
  164159. }
  164160. /*
  164161. ** Collation sequence comparison function. The pCtx argument points to
  164162. ** a UCollator structure previously allocated using ucol_open().
  164163. */
  164164. static int icuCollationColl(
  164165. void *pCtx,
  164166. int nLeft,
  164167. const void *zLeft,
  164168. int nRight,
  164169. const void *zRight
  164170. ){
  164171. UCollationResult res;
  164172. UCollator *p = (UCollator *)pCtx;
  164173. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  164174. switch( res ){
  164175. case UCOL_LESS: return -1;
  164176. case UCOL_GREATER: return +1;
  164177. case UCOL_EQUAL: return 0;
  164178. }
  164179. assert(!"Unexpected return value from ucol_strcoll()");
  164180. return 0;
  164181. }
  164182. /*
  164183. ** Implementation of the scalar function icu_load_collation().
  164184. **
  164185. ** This scalar function is used to add ICU collation based collation
  164186. ** types to an SQLite database connection. It is intended to be called
  164187. ** as follows:
  164188. **
  164189. ** SELECT icu_load_collation(<locale>, <collation-name>);
  164190. **
  164191. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  164192. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  164193. ** collation sequence to create.
  164194. */
  164195. static void icuLoadCollation(
  164196. sqlite3_context *p,
  164197. int nArg,
  164198. sqlite3_value **apArg
  164199. ){
  164200. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  164201. UErrorCode status = U_ZERO_ERROR;
  164202. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  164203. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  164204. UCollator *pUCollator; /* ICU library collation object */
  164205. int rc; /* Return code from sqlite3_create_collation_x() */
  164206. assert(nArg==2);
  164207. (void)nArg; /* Unused parameter */
  164208. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  164209. zName = (const char *)sqlite3_value_text(apArg[1]);
  164210. if( !zLocale || !zName ){
  164211. return;
  164212. }
  164213. pUCollator = ucol_open(zLocale, &status);
  164214. if( !U_SUCCESS(status) ){
  164215. icuFunctionError(p, "ucol_open", status);
  164216. return;
  164217. }
  164218. assert(p);
  164219. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  164220. icuCollationColl, icuCollationDel
  164221. );
  164222. if( rc!=SQLITE_OK ){
  164223. ucol_close(pUCollator);
  164224. sqlite3_result_error(p, "Error registering collation function", -1);
  164225. }
  164226. }
  164227. /*
  164228. ** Register the ICU extension functions with database db.
  164229. */
  164230. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  164231. static const struct IcuScalar {
  164232. const char *zName; /* Function name */
  164233. unsigned char nArg; /* Number of arguments */
  164234. unsigned short enc; /* Optimal text encoding */
  164235. unsigned char iContext; /* sqlite3_user_data() context */
  164236. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  164237. } scalars[] = {
  164238. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  164239. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  164240. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  164241. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  164242. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  164243. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  164244. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  164245. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  164246. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  164247. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  164248. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  164249. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  164250. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  164251. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  164252. };
  164253. int rc = SQLITE_OK;
  164254. int i;
  164255. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  164256. const struct IcuScalar *p = &scalars[i];
  164257. rc = sqlite3_create_function(
  164258. db, p->zName, p->nArg, p->enc,
  164259. p->iContext ? (void*)db : (void*)0,
  164260. p->xFunc, 0, 0
  164261. );
  164262. }
  164263. return rc;
  164264. }
  164265. #if !SQLITE_CORE
  164266. #ifdef _WIN32
  164267. __declspec(dllexport)
  164268. #endif
  164269. SQLITE_API int sqlite3_icu_init(
  164270. sqlite3 *db,
  164271. char **pzErrMsg,
  164272. const sqlite3_api_routines *pApi
  164273. ){
  164274. SQLITE_EXTENSION_INIT2(pApi)
  164275. return sqlite3IcuInit(db);
  164276. }
  164277. #endif
  164278. #endif
  164279. /************** End of icu.c *************************************************/
  164280. /************** Begin file fts3_icu.c ****************************************/
  164281. /*
  164282. ** 2007 June 22
  164283. **
  164284. ** The author disclaims copyright to this source code. In place of
  164285. ** a legal notice, here is a blessing:
  164286. **
  164287. ** May you do good and not evil.
  164288. ** May you find forgiveness for yourself and forgive others.
  164289. ** May you share freely, never taking more than you give.
  164290. **
  164291. *************************************************************************
  164292. ** This file implements a tokenizer for fts3 based on the ICU library.
  164293. */
  164294. /* #include "fts3Int.h" */
  164295. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  164296. #ifdef SQLITE_ENABLE_ICU
  164297. /* #include <assert.h> */
  164298. /* #include <string.h> */
  164299. /* #include "fts3_tokenizer.h" */
  164300. #include <unicode/ubrk.h>
  164301. /* #include <unicode/ucol.h> */
  164302. /* #include <unicode/ustring.h> */
  164303. #include <unicode/utf16.h>
  164304. typedef struct IcuTokenizer IcuTokenizer;
  164305. typedef struct IcuCursor IcuCursor;
  164306. struct IcuTokenizer {
  164307. sqlite3_tokenizer base;
  164308. char *zLocale;
  164309. };
  164310. struct IcuCursor {
  164311. sqlite3_tokenizer_cursor base;
  164312. UBreakIterator *pIter; /* ICU break-iterator object */
  164313. int nChar; /* Number of UChar elements in pInput */
  164314. UChar *aChar; /* Copy of input using utf-16 encoding */
  164315. int *aOffset; /* Offsets of each character in utf-8 input */
  164316. int nBuffer;
  164317. char *zBuffer;
  164318. int iToken;
  164319. };
  164320. /*
  164321. ** Create a new tokenizer instance.
  164322. */
  164323. static int icuCreate(
  164324. int argc, /* Number of entries in argv[] */
  164325. const char * const *argv, /* Tokenizer creation arguments */
  164326. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  164327. ){
  164328. IcuTokenizer *p;
  164329. int n = 0;
  164330. if( argc>0 ){
  164331. n = strlen(argv[0])+1;
  164332. }
  164333. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  164334. if( !p ){
  164335. return SQLITE_NOMEM;
  164336. }
  164337. memset(p, 0, sizeof(IcuTokenizer));
  164338. if( n ){
  164339. p->zLocale = (char *)&p[1];
  164340. memcpy(p->zLocale, argv[0], n);
  164341. }
  164342. *ppTokenizer = (sqlite3_tokenizer *)p;
  164343. return SQLITE_OK;
  164344. }
  164345. /*
  164346. ** Destroy a tokenizer
  164347. */
  164348. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  164349. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  164350. sqlite3_free(p);
  164351. return SQLITE_OK;
  164352. }
  164353. /*
  164354. ** Prepare to begin tokenizing a particular string. The input
  164355. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  164356. ** used to incrementally tokenize this string is returned in
  164357. ** *ppCursor.
  164358. */
  164359. static int icuOpen(
  164360. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  164361. const char *zInput, /* Input string */
  164362. int nInput, /* Length of zInput in bytes */
  164363. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  164364. ){
  164365. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  164366. IcuCursor *pCsr;
  164367. const int32_t opt = U_FOLD_CASE_DEFAULT;
  164368. UErrorCode status = U_ZERO_ERROR;
  164369. int nChar;
  164370. UChar32 c;
  164371. int iInput = 0;
  164372. int iOut = 0;
  164373. *ppCursor = 0;
  164374. if( zInput==0 ){
  164375. nInput = 0;
  164376. zInput = "";
  164377. }else if( nInput<0 ){
  164378. nInput = strlen(zInput);
  164379. }
  164380. nChar = nInput+1;
  164381. pCsr = (IcuCursor *)sqlite3_malloc(
  164382. sizeof(IcuCursor) + /* IcuCursor */
  164383. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  164384. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  164385. );
  164386. if( !pCsr ){
  164387. return SQLITE_NOMEM;
  164388. }
  164389. memset(pCsr, 0, sizeof(IcuCursor));
  164390. pCsr->aChar = (UChar *)&pCsr[1];
  164391. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  164392. pCsr->aOffset[iOut] = iInput;
  164393. U8_NEXT(zInput, iInput, nInput, c);
  164394. while( c>0 ){
  164395. int isError = 0;
  164396. c = u_foldCase(c, opt);
  164397. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  164398. if( isError ){
  164399. sqlite3_free(pCsr);
  164400. return SQLITE_ERROR;
  164401. }
  164402. pCsr->aOffset[iOut] = iInput;
  164403. if( iInput<nInput ){
  164404. U8_NEXT(zInput, iInput, nInput, c);
  164405. }else{
  164406. c = 0;
  164407. }
  164408. }
  164409. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  164410. if( !U_SUCCESS(status) ){
  164411. sqlite3_free(pCsr);
  164412. return SQLITE_ERROR;
  164413. }
  164414. pCsr->nChar = iOut;
  164415. ubrk_first(pCsr->pIter);
  164416. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  164417. return SQLITE_OK;
  164418. }
  164419. /*
  164420. ** Close a tokenization cursor previously opened by a call to icuOpen().
  164421. */
  164422. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  164423. IcuCursor *pCsr = (IcuCursor *)pCursor;
  164424. ubrk_close(pCsr->pIter);
  164425. sqlite3_free(pCsr->zBuffer);
  164426. sqlite3_free(pCsr);
  164427. return SQLITE_OK;
  164428. }
  164429. /*
  164430. ** Extract the next token from a tokenization cursor.
  164431. */
  164432. static int icuNext(
  164433. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  164434. const char **ppToken, /* OUT: *ppToken is the token text */
  164435. int *pnBytes, /* OUT: Number of bytes in token */
  164436. int *piStartOffset, /* OUT: Starting offset of token */
  164437. int *piEndOffset, /* OUT: Ending offset of token */
  164438. int *piPosition /* OUT: Position integer of token */
  164439. ){
  164440. IcuCursor *pCsr = (IcuCursor *)pCursor;
  164441. int iStart = 0;
  164442. int iEnd = 0;
  164443. int nByte = 0;
  164444. while( iStart==iEnd ){
  164445. UChar32 c;
  164446. iStart = ubrk_current(pCsr->pIter);
  164447. iEnd = ubrk_next(pCsr->pIter);
  164448. if( iEnd==UBRK_DONE ){
  164449. return SQLITE_DONE;
  164450. }
  164451. while( iStart<iEnd ){
  164452. int iWhite = iStart;
  164453. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  164454. if( u_isspace(c) ){
  164455. iStart = iWhite;
  164456. }else{
  164457. break;
  164458. }
  164459. }
  164460. assert(iStart<=iEnd);
  164461. }
  164462. do {
  164463. UErrorCode status = U_ZERO_ERROR;
  164464. if( nByte ){
  164465. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  164466. if( !zNew ){
  164467. return SQLITE_NOMEM;
  164468. }
  164469. pCsr->zBuffer = zNew;
  164470. pCsr->nBuffer = nByte;
  164471. }
  164472. u_strToUTF8(
  164473. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  164474. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  164475. &status /* Output success/failure */
  164476. );
  164477. } while( nByte>pCsr->nBuffer );
  164478. *ppToken = pCsr->zBuffer;
  164479. *pnBytes = nByte;
  164480. *piStartOffset = pCsr->aOffset[iStart];
  164481. *piEndOffset = pCsr->aOffset[iEnd];
  164482. *piPosition = pCsr->iToken++;
  164483. return SQLITE_OK;
  164484. }
  164485. /*
  164486. ** The set of routines that implement the simple tokenizer
  164487. */
  164488. static const sqlite3_tokenizer_module icuTokenizerModule = {
  164489. 0, /* iVersion */
  164490. icuCreate, /* xCreate */
  164491. icuDestroy, /* xCreate */
  164492. icuOpen, /* xOpen */
  164493. icuClose, /* xClose */
  164494. icuNext, /* xNext */
  164495. 0, /* xLanguageid */
  164496. };
  164497. /*
  164498. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  164499. */
  164500. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  164501. sqlite3_tokenizer_module const**ppModule
  164502. ){
  164503. *ppModule = &icuTokenizerModule;
  164504. }
  164505. #endif /* defined(SQLITE_ENABLE_ICU) */
  164506. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  164507. /************** End of fts3_icu.c ********************************************/
  164508. /************** Begin file sqlite3rbu.c **************************************/
  164509. /*
  164510. ** 2014 August 30
  164511. **
  164512. ** The author disclaims copyright to this source code. In place of
  164513. ** a legal notice, here is a blessing:
  164514. **
  164515. ** May you do good and not evil.
  164516. ** May you find forgiveness for yourself and forgive others.
  164517. ** May you share freely, never taking more than you give.
  164518. **
  164519. *************************************************************************
  164520. **
  164521. **
  164522. ** OVERVIEW
  164523. **
  164524. ** The RBU extension requires that the RBU update be packaged as an
  164525. ** SQLite database. The tables it expects to find are described in
  164526. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  164527. ** that the user wishes to write to, a corresponding data_xyz table is
  164528. ** created in the RBU database and populated with one row for each row to
  164529. ** update, insert or delete from the target table.
  164530. **
  164531. ** The update proceeds in three stages:
  164532. **
  164533. ** 1) The database is updated. The modified database pages are written
  164534. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  164535. ** that it is named "<database>-oal" instead of "<database>-wal".
  164536. ** Because regular SQLite clients do not look for file named
  164537. ** "<database>-oal", they go on using the original database in
  164538. ** rollback mode while the *-oal file is being generated.
  164539. **
  164540. ** During this stage RBU does not update the database by writing
  164541. ** directly to the target tables. Instead it creates "imposter"
  164542. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  164543. ** to update each b-tree individually. All updates required by each
  164544. ** b-tree are completed before moving on to the next, and all
  164545. ** updates are done in sorted key order.
  164546. **
  164547. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  164548. ** location using a call to rename(2). Before doing this the RBU
  164549. ** module takes an EXCLUSIVE lock on the database file, ensuring
  164550. ** that there are no other active readers.
  164551. **
  164552. ** Once the EXCLUSIVE lock is released, any other database readers
  164553. ** detect the new *-wal file and read the database in wal mode. At
  164554. ** this point they see the new version of the database - including
  164555. ** the updates made as part of the RBU update.
  164556. **
  164557. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  164558. ** as a regular database checkpoint, except that a single frame is
  164559. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  164560. ** handle is closed before the entire *-wal file is checkpointed,
  164561. ** the checkpoint progress is saved in the RBU database and the
  164562. ** checkpoint can be resumed by another RBU client at some point in
  164563. ** the future.
  164564. **
  164565. ** POTENTIAL PROBLEMS
  164566. **
  164567. ** The rename() call might not be portable. And RBU is not currently
  164568. ** syncing the directory after renaming the file.
  164569. **
  164570. ** When state is saved, any commit to the *-oal file and the commit to
  164571. ** the RBU update database are not atomic. So if the power fails at the
  164572. ** wrong moment they might get out of sync. As the main database will be
  164573. ** committed before the RBU update database this will likely either just
  164574. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  164575. ** constraint violations).
  164576. **
  164577. ** If some client does modify the target database mid RBU update, or some
  164578. ** other error occurs, the RBU extension will keep throwing errors. It's
  164579. ** not really clear how to get out of this state. The system could just
  164580. ** by delete the RBU update database and *-oal file and have the device
  164581. ** download the update again and start over.
  164582. **
  164583. ** At present, for an UPDATE, both the new.* and old.* records are
  164584. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  164585. ** fields are collected. This means we're probably writing a lot more
  164586. ** data to disk when saving the state of an ongoing update to the RBU
  164587. ** update database than is strictly necessary.
  164588. **
  164589. */
  164590. /* #include <assert.h> */
  164591. /* #include <string.h> */
  164592. /* #include <stdio.h> */
  164593. /* #include "sqlite3.h" */
  164594. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  164595. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  164596. /************** Begin file sqlite3rbu.h **************************************/
  164597. /*
  164598. ** 2014 August 30
  164599. **
  164600. ** The author disclaims copyright to this source code. In place of
  164601. ** a legal notice, here is a blessing:
  164602. **
  164603. ** May you do good and not evil.
  164604. ** May you find forgiveness for yourself and forgive others.
  164605. ** May you share freely, never taking more than you give.
  164606. **
  164607. *************************************************************************
  164608. **
  164609. ** This file contains the public interface for the RBU extension.
  164610. */
  164611. /*
  164612. ** SUMMARY
  164613. **
  164614. ** Writing a transaction containing a large number of operations on
  164615. ** b-tree indexes that are collectively larger than the available cache
  164616. ** memory can be very inefficient.
  164617. **
  164618. ** The problem is that in order to update a b-tree, the leaf page (at least)
  164619. ** containing the entry being inserted or deleted must be modified. If the
  164620. ** working set of leaves is larger than the available cache memory, then a
  164621. ** single leaf that is modified more than once as part of the transaction
  164622. ** may be loaded from or written to the persistent media multiple times.
  164623. ** Additionally, because the index updates are likely to be applied in
  164624. ** random order, access to pages within the database is also likely to be in
  164625. ** random order, which is itself quite inefficient.
  164626. **
  164627. ** One way to improve the situation is to sort the operations on each index
  164628. ** by index key before applying them to the b-tree. This leads to an IO
  164629. ** pattern that resembles a single linear scan through the index b-tree,
  164630. ** and all but guarantees each modified leaf page is loaded and stored
  164631. ** exactly once. SQLite uses this trick to improve the performance of
  164632. ** CREATE INDEX commands. This extension allows it to be used to improve
  164633. ** the performance of large transactions on existing databases.
  164634. **
  164635. ** Additionally, this extension allows the work involved in writing the
  164636. ** large transaction to be broken down into sub-transactions performed
  164637. ** sequentially by separate processes. This is useful if the system cannot
  164638. ** guarantee that a single update process will run for long enough to apply
  164639. ** the entire update, for example because the update is being applied on a
  164640. ** mobile device that is frequently rebooted. Even after the writer process
  164641. ** has committed one or more sub-transactions, other database clients continue
  164642. ** to read from the original database snapshot. In other words, partially
  164643. ** applied transactions are not visible to other clients.
  164644. **
  164645. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  164646. ** transmitted via a wireless network to a mobile device. A transaction
  164647. ** applied using this extension is hence refered to as an "RBU update".
  164648. **
  164649. **
  164650. ** LIMITATIONS
  164651. **
  164652. ** An "RBU update" transaction is subject to the following limitations:
  164653. **
  164654. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  164655. ** only.
  164656. **
  164657. ** * INSERT statements may not use any default values.
  164658. **
  164659. ** * UPDATE and DELETE statements must identify their target rows by
  164660. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  164661. ** KEY fields may not be updated or deleted. If the table being written
  164662. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  164663. **
  164664. ** * UPDATE statements may not modify PRIMARY KEY columns.
  164665. **
  164666. ** * No triggers will be fired.
  164667. **
  164668. ** * No foreign key violations are detected or reported.
  164669. **
  164670. ** * CHECK constraints are not enforced.
  164671. **
  164672. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  164673. **
  164674. **
  164675. ** PREPARATION
  164676. **
  164677. ** An "RBU update" is stored as a separate SQLite database. A database
  164678. ** containing an RBU update is an "RBU database". For each table in the
  164679. ** target database to be updated, the RBU database should contain a table
  164680. ** named "data_<target name>" containing the same set of columns as the
  164681. ** target table, and one more - "rbu_control". The data_% table should
  164682. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  164683. ** the same type as the corresponding column in the target database.
  164684. ** The "rbu_control" column should have no type at all. For example, if
  164685. ** the target database contains:
  164686. **
  164687. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  164688. **
  164689. ** Then the RBU database should contain:
  164690. **
  164691. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  164692. **
  164693. ** The order of the columns in the data_% table does not matter.
  164694. **
  164695. ** Instead of a regular table, the RBU database may also contain virtual
  164696. ** tables or view named using the data_<target> naming scheme.
  164697. **
  164698. ** Instead of the plain data_<target> naming scheme, RBU database tables
  164699. ** may also be named data<integer>_<target>, where <integer> is any sequence
  164700. ** of zero or more numeric characters (0-9). This can be significant because
  164701. ** tables within the RBU database are always processed in order sorted by
  164702. ** name. By judicious selection of the <integer> portion of the names
  164703. ** of the RBU tables the user can therefore control the order in which they
  164704. ** are processed. This can be useful, for example, to ensure that "external
  164705. ** content" FTS4 tables are updated before their underlying content tables.
  164706. **
  164707. ** If the target database table is a virtual table or a table that has no
  164708. ** PRIMARY KEY declaration, the data_% table must also contain a column
  164709. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  164710. ** key column - "rowid". Virtual tables for which the "rowid" column does
  164711. ** not function like a primary key value cannot be updated using RBU. For
  164712. ** example, if the target db contains either of the following:
  164713. **
  164714. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  164715. ** CREATE TABLE x1(a, b)
  164716. **
  164717. ** then the RBU database should contain:
  164718. **
  164719. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  164720. **
  164721. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  164722. ** target table must be present in the input table. For virtual tables,
  164723. ** hidden columns are optional - they are updated by RBU if present in
  164724. ** the input table, or not otherwise. For example, to write to an fts4
  164725. ** table with a hidden languageid column such as:
  164726. **
  164727. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  164728. **
  164729. ** Either of the following input table schemas may be used:
  164730. **
  164731. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  164732. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  164733. **
  164734. ** For each row to INSERT into the target database as part of the RBU
  164735. ** update, the corresponding data_% table should contain a single record
  164736. ** with the "rbu_control" column set to contain integer value 0. The
  164737. ** other columns should be set to the values that make up the new record
  164738. ** to insert.
  164739. **
  164740. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  164741. ** possible to insert a NULL value into the IPK column. Attempting to
  164742. ** do so results in an SQLITE_MISMATCH error.
  164743. **
  164744. ** For each row to DELETE from the target database as part of the RBU
  164745. ** update, the corresponding data_% table should contain a single record
  164746. ** with the "rbu_control" column set to contain integer value 1. The
  164747. ** real primary key values of the row to delete should be stored in the
  164748. ** corresponding columns of the data_% table. The values stored in the
  164749. ** other columns are not used.
  164750. **
  164751. ** For each row to UPDATE from the target database as part of the RBU
  164752. ** update, the corresponding data_% table should contain a single record
  164753. ** with the "rbu_control" column set to contain a value of type text.
  164754. ** The real primary key values identifying the row to update should be
  164755. ** stored in the corresponding columns of the data_% table row, as should
  164756. ** the new values of all columns being update. The text value in the
  164757. ** "rbu_control" column must contain the same number of characters as
  164758. ** there are columns in the target database table, and must consist entirely
  164759. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  164760. ** each column that is being updated, the corresponding character is set to
  164761. ** 'x'. For those that remain as they are, the corresponding character of the
  164762. ** rbu_control value should be set to '.'. For example, given the tables
  164763. ** above, the update statement:
  164764. **
  164765. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  164766. **
  164767. ** is represented by the data_t1 row created by:
  164768. **
  164769. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  164770. **
  164771. ** Instead of an 'x' character, characters of the rbu_control value specified
  164772. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  164773. ** target table with the value stored in the corresponding data_% column, the
  164774. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  164775. ** the target table column. rbu_delta() is invoked with two arguments - the
  164776. ** original value currently stored in the target table column and the
  164777. ** value specified in the data_xxx table.
  164778. **
  164779. ** For example, this row:
  164780. **
  164781. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  164782. **
  164783. ** is similar to an UPDATE statement such as:
  164784. **
  164785. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  164786. **
  164787. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  164788. ** ota_control string, the contents of the data_xxx table column is assumed
  164789. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  164790. ** format used by the fossil source-code management system. In this case
  164791. ** the existing value within the target database table must be of type BLOB.
  164792. ** It is replaced by the result of applying the specified fossil delta to
  164793. ** itself.
  164794. **
  164795. ** If the target database table is a virtual table or a table with no PRIMARY
  164796. ** KEY, the rbu_control value should not include a character corresponding
  164797. ** to the rbu_rowid value. For example, this:
  164798. **
  164799. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  164800. ** VALUES(NULL, 'usa', 12, '.x');
  164801. **
  164802. ** causes a result similar to:
  164803. **
  164804. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  164805. **
  164806. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  164807. ** However, RBU is more efficient if reading the rows in from each data_xxx
  164808. ** table in "rowid" order is roughly the same as reading them sorted by
  164809. ** the PRIMARY KEY of the corresponding target database table. In other
  164810. ** words, rows should be sorted using the destination table PRIMARY KEY
  164811. ** fields before they are inserted into the data_xxx tables.
  164812. **
  164813. ** USAGE
  164814. **
  164815. ** The API declared below allows an application to apply an RBU update
  164816. ** stored on disk to an existing target database. Essentially, the
  164817. ** application:
  164818. **
  164819. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  164820. **
  164821. ** 2) Registers any required virtual table modules with the database
  164822. ** handle returned by sqlite3rbu_db(). Also, if required, register
  164823. ** the rbu_delta() implementation.
  164824. **
  164825. ** 3) Calls the sqlite3rbu_step() function one or more times on
  164826. ** the new handle. Each call to sqlite3rbu_step() performs a single
  164827. ** b-tree operation, so thousands of calls may be required to apply
  164828. ** a complete update.
  164829. **
  164830. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  164831. ** sqlite3rbu_step() has been called enough times to completely
  164832. ** apply the update to the target database, then the RBU database
  164833. ** is marked as fully applied. Otherwise, the state of the RBU
  164834. ** update application is saved in the RBU database for later
  164835. ** resumption.
  164836. **
  164837. ** See comments below for more detail on APIs.
  164838. **
  164839. ** If an update is only partially applied to the target database by the
  164840. ** time sqlite3rbu_close() is called, various state information is saved
  164841. ** within the RBU database. This allows subsequent processes to automatically
  164842. ** resume the RBU update from where it left off.
  164843. **
  164844. ** To remove all RBU extension state information, returning an RBU database
  164845. ** to its original contents, it is sufficient to drop all tables that begin
  164846. ** with the prefix "rbu_"
  164847. **
  164848. ** DATABASE LOCKING
  164849. **
  164850. ** An RBU update may not be applied to a database in WAL mode. Attempting
  164851. ** to do so is an error (SQLITE_ERROR).
  164852. **
  164853. ** While an RBU handle is open, a SHARED lock may be held on the target
  164854. ** database file. This means it is possible for other clients to read the
  164855. ** database, but not to write it.
  164856. **
  164857. ** If an RBU update is started and then suspended before it is completed,
  164858. ** then an external client writes to the database, then attempting to resume
  164859. ** the suspended RBU update is also an error (SQLITE_BUSY).
  164860. */
  164861. #ifndef _SQLITE3RBU_H
  164862. #define _SQLITE3RBU_H
  164863. /* #include "sqlite3.h" ** Required for error code definitions ** */
  164864. #if 0
  164865. extern "C" {
  164866. #endif
  164867. typedef struct sqlite3rbu sqlite3rbu;
  164868. /*
  164869. ** Open an RBU handle.
  164870. **
  164871. ** Argument zTarget is the path to the target database. Argument zRbu is
  164872. ** the path to the RBU database. Each call to this function must be matched
  164873. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  164874. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  164875. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  164876. ** database URI, not a regular file name.
  164877. **
  164878. ** If the zState argument is passed a NULL value, the RBU extension stores
  164879. ** the current state of the update (how many rows have been updated, which
  164880. ** indexes are yet to be updated etc.) within the RBU database itself. This
  164881. ** can be convenient, as it means that the RBU application does not need to
  164882. ** organize removing a separate state file after the update is concluded.
  164883. ** Or, if zState is non-NULL, it must be a path to a database file in which
  164884. ** the RBU extension can store the state of the update.
  164885. **
  164886. ** When resuming an RBU update, the zState argument must be passed the same
  164887. ** value as when the RBU update was started.
  164888. **
  164889. ** Once the RBU update is finished, the RBU extension does not
  164890. ** automatically remove any zState database file, even if it created it.
  164891. **
  164892. ** By default, RBU uses the default VFS to access the files on disk. To
  164893. ** use a VFS other than the default, an SQLite "file:" URI containing a
  164894. ** "vfs=..." option may be passed as the zTarget option.
  164895. **
  164896. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  164897. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  164898. ** not work out of the box with zipvfs. Refer to the comment describing
  164899. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  164900. */
  164901. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  164902. const char *zTarget,
  164903. const char *zRbu,
  164904. const char *zState
  164905. );
  164906. /*
  164907. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  164908. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  164909. ** that it can be suspended and resumed like an RBU update.
  164910. **
  164911. ** The second argument to this function identifies a database in which
  164912. ** to store the state of the RBU vacuum operation if it is suspended. The
  164913. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  164914. ** operation, the state database should either not exist or be empty
  164915. ** (contain no tables). If an RBU vacuum is suspended by calling
  164916. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  164917. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  164918. ** The vacuum can be resumed by calling this function to open a new RBU
  164919. ** handle specifying the same target and state databases.
  164920. **
  164921. ** If the second argument passed to this function is NULL, then the
  164922. ** name of the state database is "<database>-vacuum", where <database>
  164923. ** is the name of the target database file. In this case, on UNIX, if the
  164924. ** state database is not already present in the file-system, it is created
  164925. ** with the same permissions as the target db is made.
  164926. **
  164927. ** This function does not delete the state database after an RBU vacuum
  164928. ** is completed, even if it created it. However, if the call to
  164929. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  164930. ** of the state tables within the state database are zeroed. This way,
  164931. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  164932. ** new RBU vacuum operation.
  164933. **
  164934. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  164935. ** describing the sqlite3rbu_create_vfs() API function below for
  164936. ** a description of the complications associated with using RBU with
  164937. ** zipvfs databases.
  164938. */
  164939. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  164940. const char *zTarget,
  164941. const char *zState
  164942. );
  164943. /*
  164944. ** Configure a limit for the amount of temp space that may be used by
  164945. ** the RBU handle passed as the first argument. The new limit is specified
  164946. ** in bytes by the second parameter. If it is positive, the limit is updated.
  164947. ** If the second parameter to this function is passed zero, then the limit
  164948. ** is removed entirely. If the second parameter is negative, the limit is
  164949. ** not modified (this is useful for querying the current limit).
  164950. **
  164951. ** In all cases the returned value is the current limit in bytes (zero
  164952. ** indicates unlimited).
  164953. **
  164954. ** If the temp space limit is exceeded during operation, an SQLITE_FULL
  164955. ** error is returned.
  164956. */
  164957. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
  164958. /*
  164959. ** Return the current amount of temp file space, in bytes, currently used by
  164960. ** the RBU handle passed as the only argument.
  164961. */
  164962. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
  164963. /*
  164964. ** Internally, each RBU connection uses a separate SQLite database
  164965. ** connection to access the target and rbu update databases. This
  164966. ** API allows the application direct access to these database handles.
  164967. **
  164968. ** The first argument passed to this function must be a valid, open, RBU
  164969. ** handle. The second argument should be passed zero to access the target
  164970. ** database handle, or non-zero to access the rbu update database handle.
  164971. ** Accessing the underlying database handles may be useful in the
  164972. ** following scenarios:
  164973. **
  164974. ** * If any target tables are virtual tables, it may be necessary to
  164975. ** call sqlite3_create_module() on the target database handle to
  164976. ** register the required virtual table implementations.
  164977. **
  164978. ** * If the data_xxx tables in the RBU source database are virtual
  164979. ** tables, the application may need to call sqlite3_create_module() on
  164980. ** the rbu update db handle to any required virtual table
  164981. ** implementations.
  164982. **
  164983. ** * If the application uses the "rbu_delta()" feature described above,
  164984. ** it must use sqlite3_create_function() or similar to register the
  164985. ** rbu_delta() implementation with the target database handle.
  164986. **
  164987. ** If an error has occurred, either while opening or stepping the RBU object,
  164988. ** this function may return NULL. The error code and message may be collected
  164989. ** when sqlite3rbu_close() is called.
  164990. **
  164991. ** Database handles returned by this function remain valid until the next
  164992. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  164993. */
  164994. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  164995. /*
  164996. ** Do some work towards applying the RBU update to the target db.
  164997. **
  164998. ** Return SQLITE_DONE if the update has been completely applied, or
  164999. ** SQLITE_OK if no error occurs but there remains work to do to apply
  165000. ** the RBU update. If an error does occur, some other error code is
  165001. ** returned.
  165002. **
  165003. ** Once a call to sqlite3rbu_step() has returned a value other than
  165004. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  165005. ** that immediately return the same value.
  165006. */
  165007. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  165008. /*
  165009. ** Force RBU to save its state to disk.
  165010. **
  165011. ** If a power failure or application crash occurs during an update, following
  165012. ** system recovery RBU may resume the update from the point at which the state
  165013. ** was last saved. In other words, from the most recent successful call to
  165014. ** sqlite3rbu_close() or this function.
  165015. **
  165016. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  165017. */
  165018. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  165019. /*
  165020. ** Close an RBU handle.
  165021. **
  165022. ** If the RBU update has been completely applied, mark the RBU database
  165023. ** as fully applied. Otherwise, assuming no error has occurred, save the
  165024. ** current state of the RBU update appliation to the RBU database.
  165025. **
  165026. ** If an error has already occurred as part of an sqlite3rbu_step()
  165027. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  165028. ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
  165029. ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
  165030. ** English language error message. It is the responsibility of the caller to
  165031. ** eventually free any such buffer using sqlite3_free().
  165032. **
  165033. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  165034. ** update has been partially applied, or SQLITE_DONE if it has been
  165035. ** completely applied.
  165036. */
  165037. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  165038. /*
  165039. ** Return the total number of key-value operations (inserts, deletes or
  165040. ** updates) that have been performed on the target database since the
  165041. ** current RBU update was started.
  165042. */
  165043. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  165044. /*
  165045. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  165046. ** progress indications for the two stages of an RBU update. This API may
  165047. ** be useful for driving GUI progress indicators and similar.
  165048. **
  165049. ** An RBU update is divided into two stages:
  165050. **
  165051. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  165052. ** * Stage 2, in which the contents of the wal file are copied into the
  165053. ** main database.
  165054. **
  165055. ** The update is visible to non-RBU clients during stage 2. During stage 1
  165056. ** non-RBU reader clients may see the original database.
  165057. **
  165058. ** If this API is called during stage 2 of the update, output variable
  165059. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  165060. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  165061. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  165062. ** 9000 indicates that it is 90% finished, and so on.
  165063. **
  165064. ** If this API is called during stage 1 of the update, output variable
  165065. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  165066. ** value to which (*pnOne) is set depends on whether or not the RBU
  165067. ** database contains an "rbu_count" table. The rbu_count table, if it
  165068. ** exists, must contain the same columns as the following:
  165069. **
  165070. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  165071. **
  165072. ** There must be one row in the table for each source (data_xxx) table within
  165073. ** the RBU database. The 'tbl' column should contain the name of the source
  165074. ** table. The 'cnt' column should contain the number of rows within the
  165075. ** source table.
  165076. **
  165077. ** If the rbu_count table is present and populated correctly and this
  165078. ** API is called during stage 1, the *pnOne output variable is set to the
  165079. ** permyriadage progress of the same stage. If the rbu_count table does
  165080. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  165081. ** table exists but is not correctly populated, the value of the *pnOne
  165082. ** output variable during stage 1 is undefined.
  165083. */
  165084. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
  165085. /*
  165086. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  165087. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  165088. ** defined in this file. Return values should be interpreted as follows:
  165089. **
  165090. ** SQLITE_RBU_STATE_OAL:
  165091. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  165092. ** may either add further data to the *-oal file, or compute data that will
  165093. ** be added by a subsequent call.
  165094. **
  165095. ** SQLITE_RBU_STATE_MOVE:
  165096. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  165097. ** will move the *-oal file to the equivalent *-wal path. If the current
  165098. ** operation is an RBU update, then the updated version of the database
  165099. ** file will become visible to ordinary SQLite clients following the next
  165100. ** call to sqlite3rbu_step().
  165101. **
  165102. ** SQLITE_RBU_STATE_CHECKPOINT:
  165103. ** RBU is currently performing an incremental checkpoint. The next call to
  165104. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  165105. ** the target database file.
  165106. **
  165107. ** SQLITE_RBU_STATE_DONE:
  165108. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  165109. ** will immediately return SQLITE_DONE.
  165110. **
  165111. ** SQLITE_RBU_STATE_ERROR:
  165112. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  165113. ** immediately return the SQLite error code associated with the error.
  165114. */
  165115. #define SQLITE_RBU_STATE_OAL 1
  165116. #define SQLITE_RBU_STATE_MOVE 2
  165117. #define SQLITE_RBU_STATE_CHECKPOINT 3
  165118. #define SQLITE_RBU_STATE_DONE 4
  165119. #define SQLITE_RBU_STATE_ERROR 5
  165120. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  165121. /*
  165122. ** Create an RBU VFS named zName that accesses the underlying file-system
  165123. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  165124. ** then the new RBU VFS uses the default system VFS to access the file-system.
  165125. ** The new object is registered as a non-default VFS with SQLite before
  165126. ** returning.
  165127. **
  165128. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  165129. ** object is created and deleted automatically by RBU.
  165130. **
  165131. ** The exception is for applications that also use zipvfs. In this case,
  165132. ** the custom VFS must be explicitly created by the user before the RBU
  165133. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  165134. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  165135. ** (for example multiplexor) to access the file-system. For example,
  165136. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  165137. ** multiplexor (error checking omitted):
  165138. **
  165139. ** // Create a VFS named "multiplex" (not the default).
  165140. ** sqlite3_multiplex_initialize(0, 0);
  165141. **
  165142. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  165143. ** // second argument were replaced with NULL, the "rbu" VFS would
  165144. ** // access the file-system via the system default VFS, bypassing the
  165145. ** // multiplexor.
  165146. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  165147. **
  165148. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  165149. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  165150. **
  165151. ** // Make zipvfs the default VFS.
  165152. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  165153. **
  165154. ** Because the default VFS created above includes a RBU functionality, it
  165155. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  165156. ** that does not include the RBU layer results in an error.
  165157. **
  165158. ** The overhead of adding the "rbu" VFS to the system is negligible for
  165159. ** non-RBU users. There is no harm in an application accessing the
  165160. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  165161. ** occasionally.
  165162. */
  165163. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  165164. /*
  165165. ** Deregister and destroy an RBU vfs created by an earlier call to
  165166. ** sqlite3rbu_create_vfs().
  165167. **
  165168. ** VFS objects are not reference counted. If a VFS object is destroyed
  165169. ** before all database handles that use it have been closed, the results
  165170. ** are undefined.
  165171. */
  165172. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  165173. #if 0
  165174. } /* end of the 'extern "C"' block */
  165175. #endif
  165176. #endif /* _SQLITE3RBU_H */
  165177. /************** End of sqlite3rbu.h ******************************************/
  165178. /************** Continuing where we left off in sqlite3rbu.c *****************/
  165179. #if defined(_WIN32_WCE)
  165180. /* #include "windows.h" */
  165181. #endif
  165182. /* Maximum number of prepared UPDATE statements held by this module */
  165183. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  165184. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  165185. ** to enable checksum verification.
  165186. */
  165187. #ifndef RBU_ENABLE_DELTA_CKSUM
  165188. # define RBU_ENABLE_DELTA_CKSUM 0
  165189. #endif
  165190. /*
  165191. ** Swap two objects of type TYPE.
  165192. */
  165193. #if !defined(SQLITE_AMALGAMATION)
  165194. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  165195. #endif
  165196. /*
  165197. ** The rbu_state table is used to save the state of a partially applied
  165198. ** update so that it can be resumed later. The table consists of integer
  165199. ** keys mapped to values as follows:
  165200. **
  165201. ** RBU_STATE_STAGE:
  165202. ** May be set to integer values 1, 2, 4 or 5. As follows:
  165203. ** 1: the *-rbu file is currently under construction.
  165204. ** 2: the *-rbu file has been constructed, but not yet moved
  165205. ** to the *-wal path.
  165206. ** 4: the checkpoint is underway.
  165207. ** 5: the rbu update has been checkpointed.
  165208. **
  165209. ** RBU_STATE_TBL:
  165210. ** Only valid if STAGE==1. The target database name of the table
  165211. ** currently being written.
  165212. **
  165213. ** RBU_STATE_IDX:
  165214. ** Only valid if STAGE==1. The target database name of the index
  165215. ** currently being written, or NULL if the main table is currently being
  165216. ** updated.
  165217. **
  165218. ** RBU_STATE_ROW:
  165219. ** Only valid if STAGE==1. Number of rows already processed for the current
  165220. ** table/index.
  165221. **
  165222. ** RBU_STATE_PROGRESS:
  165223. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  165224. ** rbu update.
  165225. **
  165226. ** RBU_STATE_CKPT:
  165227. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  165228. ** header created by recovering the *-wal file. This is used to detect
  165229. ** cases when another client appends frames to the *-wal file in the
  165230. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  165231. ** be continued if this happens).
  165232. **
  165233. ** RBU_STATE_COOKIE:
  165234. ** Valid if STAGE==1. The current change-counter cookie value in the
  165235. ** target db file.
  165236. **
  165237. ** RBU_STATE_OALSZ:
  165238. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  165239. **
  165240. ** RBU_STATE_DATATBL:
  165241. ** Only valid if STAGE==1. The RBU database name of the table
  165242. ** currently being read.
  165243. */
  165244. #define RBU_STATE_STAGE 1
  165245. #define RBU_STATE_TBL 2
  165246. #define RBU_STATE_IDX 3
  165247. #define RBU_STATE_ROW 4
  165248. #define RBU_STATE_PROGRESS 5
  165249. #define RBU_STATE_CKPT 6
  165250. #define RBU_STATE_COOKIE 7
  165251. #define RBU_STATE_OALSZ 8
  165252. #define RBU_STATE_PHASEONESTEP 9
  165253. #define RBU_STATE_DATATBL 10
  165254. #define RBU_STAGE_OAL 1
  165255. #define RBU_STAGE_MOVE 2
  165256. #define RBU_STAGE_CAPTURE 3
  165257. #define RBU_STAGE_CKPT 4
  165258. #define RBU_STAGE_DONE 5
  165259. #define RBU_CREATE_STATE \
  165260. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  165261. typedef struct RbuFrame RbuFrame;
  165262. typedef struct RbuObjIter RbuObjIter;
  165263. typedef struct RbuState RbuState;
  165264. typedef struct rbu_vfs rbu_vfs;
  165265. typedef struct rbu_file rbu_file;
  165266. typedef struct RbuUpdateStmt RbuUpdateStmt;
  165267. #if !defined(SQLITE_AMALGAMATION)
  165268. typedef unsigned int u32;
  165269. typedef unsigned short u16;
  165270. typedef unsigned char u8;
  165271. typedef sqlite3_int64 i64;
  165272. #endif
  165273. /*
  165274. ** These values must match the values defined in wal.c for the equivalent
  165275. ** locks. These are not magic numbers as they are part of the SQLite file
  165276. ** format.
  165277. */
  165278. #define WAL_LOCK_WRITE 0
  165279. #define WAL_LOCK_CKPT 1
  165280. #define WAL_LOCK_READ0 3
  165281. #define SQLITE_FCNTL_RBUCNT 5149216
  165282. /*
  165283. ** A structure to store values read from the rbu_state table in memory.
  165284. */
  165285. struct RbuState {
  165286. int eStage;
  165287. char *zTbl;
  165288. char *zDataTbl;
  165289. char *zIdx;
  165290. i64 iWalCksum;
  165291. int nRow;
  165292. i64 nProgress;
  165293. u32 iCookie;
  165294. i64 iOalSz;
  165295. i64 nPhaseOneStep;
  165296. };
  165297. struct RbuUpdateStmt {
  165298. char *zMask; /* Copy of update mask used with pUpdate */
  165299. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  165300. RbuUpdateStmt *pNext;
  165301. };
  165302. /*
  165303. ** An iterator of this type is used to iterate through all objects in
  165304. ** the target database that require updating. For each such table, the
  165305. ** iterator visits, in order:
  165306. **
  165307. ** * the table itself,
  165308. ** * each index of the table (zero or more points to visit), and
  165309. ** * a special "cleanup table" state.
  165310. **
  165311. ** abIndexed:
  165312. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  165313. ** it points to an array of flags nTblCol elements in size. The flag is
  165314. ** set for each column that is either a part of the PK or a part of an
  165315. ** index. Or clear otherwise.
  165316. **
  165317. */
  165318. struct RbuObjIter {
  165319. sqlite3_stmt *pTblIter; /* Iterate through tables */
  165320. sqlite3_stmt *pIdxIter; /* Index iterator */
  165321. int nTblCol; /* Size of azTblCol[] array */
  165322. char **azTblCol; /* Array of unquoted target column names */
  165323. char **azTblType; /* Array of target column types */
  165324. int *aiSrcOrder; /* src table col -> target table col */
  165325. u8 *abTblPk; /* Array of flags, set on target PK columns */
  165326. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  165327. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  165328. int eType; /* Table type - an RBU_PK_XXX value */
  165329. /* Output variables. zTbl==0 implies EOF. */
  165330. int bCleanup; /* True in "cleanup" state */
  165331. const char *zTbl; /* Name of target db table */
  165332. const char *zDataTbl; /* Name of rbu db table (or null) */
  165333. const char *zIdx; /* Name of target db index (or null) */
  165334. int iTnum; /* Root page of current object */
  165335. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  165336. int bUnique; /* Current index is unique */
  165337. int nIndex; /* Number of aux. indexes on table zTbl */
  165338. /* Statements created by rbuObjIterPrepareAll() */
  165339. int nCol; /* Number of columns in current object */
  165340. sqlite3_stmt *pSelect; /* Source data */
  165341. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  165342. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  165343. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  165344. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  165345. RbuUpdateStmt *pRbuUpdate;
  165346. };
  165347. /*
  165348. ** Values for RbuObjIter.eType
  165349. **
  165350. ** 0: Table does not exist (error)
  165351. ** 1: Table has an implicit rowid.
  165352. ** 2: Table has an explicit IPK column.
  165353. ** 3: Table has an external PK index.
  165354. ** 4: Table is WITHOUT ROWID.
  165355. ** 5: Table is a virtual table.
  165356. */
  165357. #define RBU_PK_NOTABLE 0
  165358. #define RBU_PK_NONE 1
  165359. #define RBU_PK_IPK 2
  165360. #define RBU_PK_EXTERNAL 3
  165361. #define RBU_PK_WITHOUT_ROWID 4
  165362. #define RBU_PK_VTAB 5
  165363. /*
  165364. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  165365. ** one of the following operations.
  165366. */
  165367. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  165368. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  165369. #define RBU_REPLACE 3 /* Delete and then insert a row */
  165370. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  165371. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  165372. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  165373. /*
  165374. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  165375. ** file should be copied to page iDbPage of the database file.
  165376. */
  165377. struct RbuFrame {
  165378. u32 iDbPage;
  165379. u32 iWalFrame;
  165380. };
  165381. /*
  165382. ** RBU handle.
  165383. **
  165384. ** nPhaseOneStep:
  165385. ** If the RBU database contains an rbu_count table, this value is set to
  165386. ** a running estimate of the number of b-tree operations required to
  165387. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  165388. ** API to calculate the permyriadage progress of populating the *-oal file
  165389. ** using the formula:
  165390. **
  165391. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  165392. **
  165393. ** nPhaseOneStep is initialized to the sum of:
  165394. **
  165395. ** nRow * (nIndex + 1)
  165396. **
  165397. ** for all source tables in the RBU database, where nRow is the number
  165398. ** of rows in the source table and nIndex the number of indexes on the
  165399. ** corresponding target database table.
  165400. **
  165401. ** This estimate is accurate if the RBU update consists entirely of
  165402. ** INSERT operations. However, it is inaccurate if:
  165403. **
  165404. ** * the RBU update contains any UPDATE operations. If the PK specified
  165405. ** for an UPDATE operation does not exist in the target table, then
  165406. ** no b-tree operations are required on index b-trees. Or if the
  165407. ** specified PK does exist, then (nIndex*2) such operations are
  165408. ** required (one delete and one insert on each index b-tree).
  165409. **
  165410. ** * the RBU update contains any DELETE operations for which the specified
  165411. ** PK does not exist. In this case no operations are required on index
  165412. ** b-trees.
  165413. **
  165414. ** * the RBU update contains REPLACE operations. These are similar to
  165415. ** UPDATE operations.
  165416. **
  165417. ** nPhaseOneStep is updated to account for the conditions above during the
  165418. ** first pass of each source table. The updated nPhaseOneStep value is
  165419. ** stored in the rbu_state table if the RBU update is suspended.
  165420. */
  165421. struct sqlite3rbu {
  165422. int eStage; /* Value of RBU_STATE_STAGE field */
  165423. sqlite3 *dbMain; /* target database handle */
  165424. sqlite3 *dbRbu; /* rbu database handle */
  165425. char *zTarget; /* Path to target db */
  165426. char *zRbu; /* Path to rbu db */
  165427. char *zState; /* Path to state db (or NULL if zRbu) */
  165428. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  165429. int rc; /* Value returned by last rbu_step() call */
  165430. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  165431. int nStep; /* Rows processed for current object */
  165432. int nProgress; /* Rows processed for all objects */
  165433. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  165434. const char *zVfsName; /* Name of automatically created rbu vfs */
  165435. rbu_file *pTargetFd; /* File handle open on target db */
  165436. int nPagePerSector; /* Pages per sector for pTargetFd */
  165437. i64 iOalSz;
  165438. i64 nPhaseOneStep;
  165439. /* The following state variables are used as part of the incremental
  165440. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  165441. ** function rbuSetupCheckpoint() for details. */
  165442. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  165443. u32 mLock;
  165444. int nFrame; /* Entries in aFrame[] array */
  165445. int nFrameAlloc; /* Allocated size of aFrame[] array */
  165446. RbuFrame *aFrame;
  165447. int pgsz;
  165448. u8 *aBuf;
  165449. i64 iWalCksum;
  165450. i64 szTemp; /* Current size of all temp files in use */
  165451. i64 szTempLimit; /* Total size limit for temp files */
  165452. /* Used in RBU vacuum mode only */
  165453. int nRbu; /* Number of RBU VFS in the stack */
  165454. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  165455. };
  165456. /*
  165457. ** An rbu VFS is implemented using an instance of this structure.
  165458. **
  165459. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  165460. ** It is NULL for RBU VFS objects created explicitly using
  165461. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  165462. ** space used by the RBU handle.
  165463. */
  165464. struct rbu_vfs {
  165465. sqlite3_vfs base; /* rbu VFS shim methods */
  165466. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  165467. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  165468. sqlite3rbu *pRbu; /* Owner RBU object */
  165469. rbu_file *pMain; /* Linked list of main db files */
  165470. };
  165471. /*
  165472. ** Each file opened by an rbu VFS is represented by an instance of
  165473. ** the following structure.
  165474. **
  165475. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  165476. ** "sz" is set to the current size of the database file.
  165477. */
  165478. struct rbu_file {
  165479. sqlite3_file base; /* sqlite3_file methods */
  165480. sqlite3_file *pReal; /* Underlying file handle */
  165481. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  165482. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  165483. i64 sz; /* Size of file in bytes (temp only) */
  165484. int openFlags; /* Flags this file was opened with */
  165485. u32 iCookie; /* Cookie value for main db files */
  165486. u8 iWriteVer; /* "write-version" value for main db files */
  165487. u8 bNolock; /* True to fail EXCLUSIVE locks */
  165488. int nShm; /* Number of entries in apShm[] array */
  165489. char **apShm; /* Array of mmap'd *-shm regions */
  165490. char *zDel; /* Delete this when closing file */
  165491. const char *zWal; /* Wal filename for this main db file */
  165492. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  165493. rbu_file *pMainNext; /* Next MAIN_DB file */
  165494. };
  165495. /*
  165496. ** True for an RBU vacuum handle, or false otherwise.
  165497. */
  165498. #define rbuIsVacuum(p) ((p)->zTarget==0)
  165499. /*************************************************************************
  165500. ** The following three functions, found below:
  165501. **
  165502. ** rbuDeltaGetInt()
  165503. ** rbuDeltaChecksum()
  165504. ** rbuDeltaApply()
  165505. **
  165506. ** are lifted from the fossil source code (http://fossil-scm.org). They
  165507. ** are used to implement the scalar SQL function rbu_fossil_delta().
  165508. */
  165509. /*
  165510. ** Read bytes from *pz and convert them into a positive integer. When
  165511. ** finished, leave *pz pointing to the first character past the end of
  165512. ** the integer. The *pLen parameter holds the length of the string
  165513. ** in *pz and is decremented once for each character in the integer.
  165514. */
  165515. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  165516. static const signed char zValue[] = {
  165517. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  165518. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  165519. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  165520. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  165521. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  165522. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  165523. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  165524. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  165525. };
  165526. unsigned int v = 0;
  165527. int c;
  165528. unsigned char *z = (unsigned char*)*pz;
  165529. unsigned char *zStart = z;
  165530. while( (c = zValue[0x7f&*(z++)])>=0 ){
  165531. v = (v<<6) + c;
  165532. }
  165533. z--;
  165534. *pLen -= z - zStart;
  165535. *pz = (char*)z;
  165536. return v;
  165537. }
  165538. #if RBU_ENABLE_DELTA_CKSUM
  165539. /*
  165540. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  165541. */
  165542. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  165543. const unsigned char *z = (const unsigned char *)zIn;
  165544. unsigned sum0 = 0;
  165545. unsigned sum1 = 0;
  165546. unsigned sum2 = 0;
  165547. unsigned sum3 = 0;
  165548. while(N >= 16){
  165549. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  165550. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  165551. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  165552. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  165553. z += 16;
  165554. N -= 16;
  165555. }
  165556. while(N >= 4){
  165557. sum0 += z[0];
  165558. sum1 += z[1];
  165559. sum2 += z[2];
  165560. sum3 += z[3];
  165561. z += 4;
  165562. N -= 4;
  165563. }
  165564. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  165565. switch(N){
  165566. case 3: sum3 += (z[2] << 8);
  165567. case 2: sum3 += (z[1] << 16);
  165568. case 1: sum3 += (z[0] << 24);
  165569. default: ;
  165570. }
  165571. return sum3;
  165572. }
  165573. #endif
  165574. /*
  165575. ** Apply a delta.
  165576. **
  165577. ** The output buffer should be big enough to hold the whole output
  165578. ** file and a NUL terminator at the end. The delta_output_size()
  165579. ** routine will determine this size for you.
  165580. **
  165581. ** The delta string should be null-terminated. But the delta string
  165582. ** may contain embedded NUL characters (if the input and output are
  165583. ** binary files) so we also have to pass in the length of the delta in
  165584. ** the lenDelta parameter.
  165585. **
  165586. ** This function returns the size of the output file in bytes (excluding
  165587. ** the final NUL terminator character). Except, if the delta string is
  165588. ** malformed or intended for use with a source file other than zSrc,
  165589. ** then this routine returns -1.
  165590. **
  165591. ** Refer to the delta_create() documentation above for a description
  165592. ** of the delta file format.
  165593. */
  165594. static int rbuDeltaApply(
  165595. const char *zSrc, /* The source or pattern file */
  165596. int lenSrc, /* Length of the source file */
  165597. const char *zDelta, /* Delta to apply to the pattern */
  165598. int lenDelta, /* Length of the delta */
  165599. char *zOut /* Write the output into this preallocated buffer */
  165600. ){
  165601. unsigned int limit;
  165602. unsigned int total = 0;
  165603. #if RBU_ENABLE_DELTA_CKSUM
  165604. char *zOrigOut = zOut;
  165605. #endif
  165606. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  165607. if( *zDelta!='\n' ){
  165608. /* ERROR: size integer not terminated by "\n" */
  165609. return -1;
  165610. }
  165611. zDelta++; lenDelta--;
  165612. while( *zDelta && lenDelta>0 ){
  165613. unsigned int cnt, ofst;
  165614. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  165615. switch( zDelta[0] ){
  165616. case '@': {
  165617. zDelta++; lenDelta--;
  165618. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  165619. if( lenDelta>0 && zDelta[0]!=',' ){
  165620. /* ERROR: copy command not terminated by ',' */
  165621. return -1;
  165622. }
  165623. zDelta++; lenDelta--;
  165624. total += cnt;
  165625. if( total>limit ){
  165626. /* ERROR: copy exceeds output file size */
  165627. return -1;
  165628. }
  165629. if( (int)(ofst+cnt) > lenSrc ){
  165630. /* ERROR: copy extends past end of input */
  165631. return -1;
  165632. }
  165633. memcpy(zOut, &zSrc[ofst], cnt);
  165634. zOut += cnt;
  165635. break;
  165636. }
  165637. case ':': {
  165638. zDelta++; lenDelta--;
  165639. total += cnt;
  165640. if( total>limit ){
  165641. /* ERROR: insert command gives an output larger than predicted */
  165642. return -1;
  165643. }
  165644. if( (int)cnt>lenDelta ){
  165645. /* ERROR: insert count exceeds size of delta */
  165646. return -1;
  165647. }
  165648. memcpy(zOut, zDelta, cnt);
  165649. zOut += cnt;
  165650. zDelta += cnt;
  165651. lenDelta -= cnt;
  165652. break;
  165653. }
  165654. case ';': {
  165655. zDelta++; lenDelta--;
  165656. zOut[0] = 0;
  165657. #if RBU_ENABLE_DELTA_CKSUM
  165658. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  165659. /* ERROR: bad checksum */
  165660. return -1;
  165661. }
  165662. #endif
  165663. if( total!=limit ){
  165664. /* ERROR: generated size does not match predicted size */
  165665. return -1;
  165666. }
  165667. return total;
  165668. }
  165669. default: {
  165670. /* ERROR: unknown delta operator */
  165671. return -1;
  165672. }
  165673. }
  165674. }
  165675. /* ERROR: unterminated delta */
  165676. return -1;
  165677. }
  165678. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  165679. int size;
  165680. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  165681. if( *zDelta!='\n' ){
  165682. /* ERROR: size integer not terminated by "\n" */
  165683. return -1;
  165684. }
  165685. return size;
  165686. }
  165687. /*
  165688. ** End of code taken from fossil.
  165689. *************************************************************************/
  165690. /*
  165691. ** Implementation of SQL scalar function rbu_fossil_delta().
  165692. **
  165693. ** This function applies a fossil delta patch to a blob. Exactly two
  165694. ** arguments must be passed to this function. The first is the blob to
  165695. ** patch and the second the patch to apply. If no error occurs, this
  165696. ** function returns the patched blob.
  165697. */
  165698. static void rbuFossilDeltaFunc(
  165699. sqlite3_context *context,
  165700. int argc,
  165701. sqlite3_value **argv
  165702. ){
  165703. const char *aDelta;
  165704. int nDelta;
  165705. const char *aOrig;
  165706. int nOrig;
  165707. int nOut;
  165708. int nOut2;
  165709. char *aOut;
  165710. assert( argc==2 );
  165711. nOrig = sqlite3_value_bytes(argv[0]);
  165712. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  165713. nDelta = sqlite3_value_bytes(argv[1]);
  165714. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  165715. /* Figure out the size of the output */
  165716. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  165717. if( nOut<0 ){
  165718. sqlite3_result_error(context, "corrupt fossil delta", -1);
  165719. return;
  165720. }
  165721. aOut = sqlite3_malloc(nOut+1);
  165722. if( aOut==0 ){
  165723. sqlite3_result_error_nomem(context);
  165724. }else{
  165725. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  165726. if( nOut2!=nOut ){
  165727. sqlite3_result_error(context, "corrupt fossil delta", -1);
  165728. }else{
  165729. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  165730. }
  165731. }
  165732. }
  165733. /*
  165734. ** Prepare the SQL statement in buffer zSql against database handle db.
  165735. ** If successful, set *ppStmt to point to the new statement and return
  165736. ** SQLITE_OK.
  165737. **
  165738. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  165739. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  165740. ** point to a buffer containing an error message. It is the responsibility
  165741. ** of the caller to (eventually) free this buffer using sqlite3_free().
  165742. */
  165743. static int prepareAndCollectError(
  165744. sqlite3 *db,
  165745. sqlite3_stmt **ppStmt,
  165746. char **pzErrmsg,
  165747. const char *zSql
  165748. ){
  165749. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  165750. if( rc!=SQLITE_OK ){
  165751. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  165752. *ppStmt = 0;
  165753. }
  165754. return rc;
  165755. }
  165756. /*
  165757. ** Reset the SQL statement passed as the first argument. Return a copy
  165758. ** of the value returned by sqlite3_reset().
  165759. **
  165760. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  165761. ** containing an error message. It is the responsibility of the caller
  165762. ** to eventually free this buffer using sqlite3_free().
  165763. */
  165764. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  165765. int rc = sqlite3_reset(pStmt);
  165766. if( rc!=SQLITE_OK ){
  165767. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  165768. }
  165769. return rc;
  165770. }
  165771. /*
  165772. ** Unless it is NULL, argument zSql points to a buffer allocated using
  165773. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  165774. ** statement against database db and frees the buffer. If statement
  165775. ** compilation is successful, *ppStmt is set to point to the new statement
  165776. ** handle and SQLITE_OK is returned.
  165777. **
  165778. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  165779. ** returned. In this case, *pzErrmsg may also be set to point to an error
  165780. ** message. It is the responsibility of the caller to free this error message
  165781. ** buffer using sqlite3_free().
  165782. **
  165783. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  165784. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  165785. */
  165786. static int prepareFreeAndCollectError(
  165787. sqlite3 *db,
  165788. sqlite3_stmt **ppStmt,
  165789. char **pzErrmsg,
  165790. char *zSql
  165791. ){
  165792. int rc;
  165793. assert( *pzErrmsg==0 );
  165794. if( zSql==0 ){
  165795. rc = SQLITE_NOMEM;
  165796. *ppStmt = 0;
  165797. }else{
  165798. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  165799. sqlite3_free(zSql);
  165800. }
  165801. return rc;
  165802. }
  165803. /*
  165804. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  165805. ** by an earlier call to rbuObjIterCacheTableInfo().
  165806. */
  165807. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  165808. int i;
  165809. for(i=0; i<pIter->nTblCol; i++){
  165810. sqlite3_free(pIter->azTblCol[i]);
  165811. sqlite3_free(pIter->azTblType[i]);
  165812. }
  165813. sqlite3_free(pIter->azTblCol);
  165814. pIter->azTblCol = 0;
  165815. pIter->azTblType = 0;
  165816. pIter->aiSrcOrder = 0;
  165817. pIter->abTblPk = 0;
  165818. pIter->abNotNull = 0;
  165819. pIter->nTblCol = 0;
  165820. pIter->eType = 0; /* Invalid value */
  165821. }
  165822. /*
  165823. ** Finalize all statements and free all allocations that are specific to
  165824. ** the current object (table/index pair).
  165825. */
  165826. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  165827. RbuUpdateStmt *pUp;
  165828. sqlite3_finalize(pIter->pSelect);
  165829. sqlite3_finalize(pIter->pInsert);
  165830. sqlite3_finalize(pIter->pDelete);
  165831. sqlite3_finalize(pIter->pTmpInsert);
  165832. pUp = pIter->pRbuUpdate;
  165833. while( pUp ){
  165834. RbuUpdateStmt *pTmp = pUp->pNext;
  165835. sqlite3_finalize(pUp->pUpdate);
  165836. sqlite3_free(pUp);
  165837. pUp = pTmp;
  165838. }
  165839. pIter->pSelect = 0;
  165840. pIter->pInsert = 0;
  165841. pIter->pDelete = 0;
  165842. pIter->pRbuUpdate = 0;
  165843. pIter->pTmpInsert = 0;
  165844. pIter->nCol = 0;
  165845. }
  165846. /*
  165847. ** Clean up any resources allocated as part of the iterator object passed
  165848. ** as the only argument.
  165849. */
  165850. static void rbuObjIterFinalize(RbuObjIter *pIter){
  165851. rbuObjIterClearStatements(pIter);
  165852. sqlite3_finalize(pIter->pTblIter);
  165853. sqlite3_finalize(pIter->pIdxIter);
  165854. rbuObjIterFreeCols(pIter);
  165855. memset(pIter, 0, sizeof(RbuObjIter));
  165856. }
  165857. /*
  165858. ** Advance the iterator to the next position.
  165859. **
  165860. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  165861. ** pointing to the next entry. Otherwise, an error code and message is
  165862. ** left in the RBU handle passed as the first argument. A copy of the
  165863. ** error code is returned.
  165864. */
  165865. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  165866. int rc = p->rc;
  165867. if( rc==SQLITE_OK ){
  165868. /* Free any SQLite statements used while processing the previous object */
  165869. rbuObjIterClearStatements(pIter);
  165870. if( pIter->zIdx==0 ){
  165871. rc = sqlite3_exec(p->dbMain,
  165872. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  165873. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  165874. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  165875. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  165876. , 0, 0, &p->zErrmsg
  165877. );
  165878. }
  165879. if( rc==SQLITE_OK ){
  165880. if( pIter->bCleanup ){
  165881. rbuObjIterFreeCols(pIter);
  165882. pIter->bCleanup = 0;
  165883. rc = sqlite3_step(pIter->pTblIter);
  165884. if( rc!=SQLITE_ROW ){
  165885. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  165886. pIter->zTbl = 0;
  165887. }else{
  165888. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  165889. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  165890. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  165891. }
  165892. }else{
  165893. if( pIter->zIdx==0 ){
  165894. sqlite3_stmt *pIdx = pIter->pIdxIter;
  165895. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  165896. }
  165897. if( rc==SQLITE_OK ){
  165898. rc = sqlite3_step(pIter->pIdxIter);
  165899. if( rc!=SQLITE_ROW ){
  165900. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  165901. pIter->bCleanup = 1;
  165902. pIter->zIdx = 0;
  165903. }else{
  165904. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  165905. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  165906. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  165907. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  165908. }
  165909. }
  165910. }
  165911. }
  165912. }
  165913. if( rc!=SQLITE_OK ){
  165914. rbuObjIterFinalize(pIter);
  165915. p->rc = rc;
  165916. }
  165917. return rc;
  165918. }
  165919. /*
  165920. ** The implementation of the rbu_target_name() SQL function. This function
  165921. ** accepts one or two arguments. The first argument is the name of a table -
  165922. ** the name of a table in the RBU database. The second, if it is present, is 1
  165923. ** for a view or 0 for a table.
  165924. **
  165925. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  165926. **
  165927. ** data[0-9]_<name>
  165928. **
  165929. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  165930. ** Otherwise, if the only argument does not match the above pattern, an SQL
  165931. ** NULL is returned.
  165932. **
  165933. ** "data_t1" -> "t1"
  165934. ** "data0123_t2" -> "t2"
  165935. ** "dataAB_t3" -> NULL
  165936. **
  165937. ** For an rbu vacuum handle, a copy of the first argument is returned if
  165938. ** the second argument is either missing or 0 (not a view).
  165939. */
  165940. static void rbuTargetNameFunc(
  165941. sqlite3_context *pCtx,
  165942. int argc,
  165943. sqlite3_value **argv
  165944. ){
  165945. sqlite3rbu *p = sqlite3_user_data(pCtx);
  165946. const char *zIn;
  165947. assert( argc==1 || argc==2 );
  165948. zIn = (const char*)sqlite3_value_text(argv[0]);
  165949. if( zIn ){
  165950. if( rbuIsVacuum(p) ){
  165951. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  165952. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  165953. }
  165954. }else{
  165955. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  165956. int i;
  165957. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  165958. if( zIn[i]=='_' && zIn[i+1] ){
  165959. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  165960. }
  165961. }
  165962. }
  165963. }
  165964. }
  165965. /*
  165966. ** Initialize the iterator structure passed as the second argument.
  165967. **
  165968. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  165969. ** pointing to the first entry. Otherwise, an error code and message is
  165970. ** left in the RBU handle passed as the first argument. A copy of the
  165971. ** error code is returned.
  165972. */
  165973. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  165974. int rc;
  165975. memset(pIter, 0, sizeof(RbuObjIter));
  165976. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  165977. sqlite3_mprintf(
  165978. "SELECT rbu_target_name(name, type='view') AS target, name "
  165979. "FROM sqlite_master "
  165980. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  165981. " %s "
  165982. "ORDER BY name"
  165983. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  165984. if( rc==SQLITE_OK ){
  165985. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  165986. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  165987. " FROM main.sqlite_master "
  165988. " WHERE type='index' AND tbl_name = ?"
  165989. );
  165990. }
  165991. pIter->bCleanup = 1;
  165992. p->rc = rc;
  165993. return rbuObjIterNext(p, pIter);
  165994. }
  165995. /*
  165996. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  165997. ** an error code is stored in the RBU handle passed as the first argument.
  165998. **
  165999. ** If an error has already occurred (p->rc is already set to something other
  166000. ** than SQLITE_OK), then this function returns NULL without modifying the
  166001. ** stored error code. In this case it still calls sqlite3_free() on any
  166002. ** printf() parameters associated with %z conversions.
  166003. */
  166004. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  166005. char *zSql = 0;
  166006. va_list ap;
  166007. va_start(ap, zFmt);
  166008. zSql = sqlite3_vmprintf(zFmt, ap);
  166009. if( p->rc==SQLITE_OK ){
  166010. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  166011. }else{
  166012. sqlite3_free(zSql);
  166013. zSql = 0;
  166014. }
  166015. va_end(ap);
  166016. return zSql;
  166017. }
  166018. /*
  166019. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  166020. ** arguments are the usual subsitution values. This function performs
  166021. ** the printf() style substitutions and executes the result as an SQL
  166022. ** statement on the RBU handles database.
  166023. **
  166024. ** If an error occurs, an error code and error message is stored in the
  166025. ** RBU handle. If an error has already occurred when this function is
  166026. ** called, it is a no-op.
  166027. */
  166028. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  166029. va_list ap;
  166030. char *zSql;
  166031. va_start(ap, zFmt);
  166032. zSql = sqlite3_vmprintf(zFmt, ap);
  166033. if( p->rc==SQLITE_OK ){
  166034. if( zSql==0 ){
  166035. p->rc = SQLITE_NOMEM;
  166036. }else{
  166037. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  166038. }
  166039. }
  166040. sqlite3_free(zSql);
  166041. va_end(ap);
  166042. return p->rc;
  166043. }
  166044. /*
  166045. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  166046. ** bytes.
  166047. **
  166048. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  166049. ** error code in the rbu handle passed as the first argument. Or, if an
  166050. ** error has already occurred when this function is called, return NULL
  166051. ** immediately without attempting the allocation or modifying the stored
  166052. ** error code.
  166053. */
  166054. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  166055. void *pRet = 0;
  166056. if( p->rc==SQLITE_OK ){
  166057. assert( nByte>0 );
  166058. pRet = sqlite3_malloc64(nByte);
  166059. if( pRet==0 ){
  166060. p->rc = SQLITE_NOMEM;
  166061. }else{
  166062. memset(pRet, 0, nByte);
  166063. }
  166064. }
  166065. return pRet;
  166066. }
  166067. /*
  166068. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  166069. ** there is room for at least nCol elements. If an OOM occurs, store an
  166070. ** error code in the RBU handle passed as the first argument.
  166071. */
  166072. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  166073. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  166074. char **azNew;
  166075. azNew = (char**)rbuMalloc(p, nByte);
  166076. if( azNew ){
  166077. pIter->azTblCol = azNew;
  166078. pIter->azTblType = &azNew[nCol];
  166079. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  166080. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  166081. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  166082. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  166083. }
  166084. }
  166085. /*
  166086. ** The first argument must be a nul-terminated string. This function
  166087. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  166088. ** It is the responsibility of the caller to eventually free this memory
  166089. ** using sqlite3_free().
  166090. **
  166091. ** If an OOM condition is encountered when attempting to allocate memory,
  166092. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  166093. ** if the allocation succeeds, (*pRc) is left unchanged.
  166094. */
  166095. static char *rbuStrndup(const char *zStr, int *pRc){
  166096. char *zRet = 0;
  166097. assert( *pRc==SQLITE_OK );
  166098. if( zStr ){
  166099. size_t nCopy = strlen(zStr) + 1;
  166100. zRet = (char*)sqlite3_malloc64(nCopy);
  166101. if( zRet ){
  166102. memcpy(zRet, zStr, nCopy);
  166103. }else{
  166104. *pRc = SQLITE_NOMEM;
  166105. }
  166106. }
  166107. return zRet;
  166108. }
  166109. /*
  166110. ** Finalize the statement passed as the second argument.
  166111. **
  166112. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  166113. ** rbu handle error code is not already set, set the error code and error
  166114. ** message accordingly.
  166115. */
  166116. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  166117. sqlite3 *db = sqlite3_db_handle(pStmt);
  166118. int rc = sqlite3_finalize(pStmt);
  166119. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  166120. p->rc = rc;
  166121. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  166122. }
  166123. }
  166124. /* Determine the type of a table.
  166125. **
  166126. ** peType is of type (int*), a pointer to an output parameter of type
  166127. ** (int). This call sets the output parameter as follows, depending
  166128. ** on the type of the table specified by parameters dbName and zTbl.
  166129. **
  166130. ** RBU_PK_NOTABLE: No such table.
  166131. ** RBU_PK_NONE: Table has an implicit rowid.
  166132. ** RBU_PK_IPK: Table has an explicit IPK column.
  166133. ** RBU_PK_EXTERNAL: Table has an external PK index.
  166134. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  166135. ** RBU_PK_VTAB: Table is a virtual table.
  166136. **
  166137. ** Argument *piPk is also of type (int*), and also points to an output
  166138. ** parameter. Unless the table has an external primary key index
  166139. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  166140. ** if the table does have an external primary key index, then *piPk
  166141. ** is set to the root page number of the primary key index before
  166142. ** returning.
  166143. **
  166144. ** ALGORITHM:
  166145. **
  166146. ** if( no entry exists in sqlite_master ){
  166147. ** return RBU_PK_NOTABLE
  166148. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  166149. ** return RBU_PK_VTAB
  166150. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  166151. ** if( the index that is the pk exists in sqlite_master ){
  166152. ** *piPK = rootpage of that index.
  166153. ** return RBU_PK_EXTERNAL
  166154. ** }else{
  166155. ** return RBU_PK_WITHOUT_ROWID
  166156. ** }
  166157. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  166158. ** return RBU_PK_IPK
  166159. ** }else{
  166160. ** return RBU_PK_NONE
  166161. ** }
  166162. */
  166163. static void rbuTableType(
  166164. sqlite3rbu *p,
  166165. const char *zTab,
  166166. int *peType,
  166167. int *piTnum,
  166168. int *piPk
  166169. ){
  166170. /*
  166171. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  166172. ** 1) PRAGMA index_list = ?
  166173. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  166174. ** 3) PRAGMA table_info = ?
  166175. */
  166176. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  166177. *peType = RBU_PK_NOTABLE;
  166178. *piPk = 0;
  166179. assert( p->rc==SQLITE_OK );
  166180. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  166181. sqlite3_mprintf(
  166182. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  166183. " FROM sqlite_master"
  166184. " WHERE name=%Q", zTab
  166185. ));
  166186. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  166187. /* Either an error, or no such table. */
  166188. goto rbuTableType_end;
  166189. }
  166190. if( sqlite3_column_int(aStmt[0], 0) ){
  166191. *peType = RBU_PK_VTAB; /* virtual table */
  166192. goto rbuTableType_end;
  166193. }
  166194. *piTnum = sqlite3_column_int(aStmt[0], 1);
  166195. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  166196. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  166197. );
  166198. if( p->rc ) goto rbuTableType_end;
  166199. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  166200. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  166201. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  166202. if( zOrig && zIdx && zOrig[0]=='p' ){
  166203. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  166204. sqlite3_mprintf(
  166205. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  166206. ));
  166207. if( p->rc==SQLITE_OK ){
  166208. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  166209. *piPk = sqlite3_column_int(aStmt[2], 0);
  166210. *peType = RBU_PK_EXTERNAL;
  166211. }else{
  166212. *peType = RBU_PK_WITHOUT_ROWID;
  166213. }
  166214. }
  166215. goto rbuTableType_end;
  166216. }
  166217. }
  166218. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  166219. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  166220. );
  166221. if( p->rc==SQLITE_OK ){
  166222. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  166223. if( sqlite3_column_int(aStmt[3],5)>0 ){
  166224. *peType = RBU_PK_IPK; /* explicit IPK column */
  166225. goto rbuTableType_end;
  166226. }
  166227. }
  166228. *peType = RBU_PK_NONE;
  166229. }
  166230. rbuTableType_end: {
  166231. unsigned int i;
  166232. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  166233. rbuFinalize(p, aStmt[i]);
  166234. }
  166235. }
  166236. }
  166237. /*
  166238. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  166239. ** the pIter->abIndexed[] array.
  166240. */
  166241. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  166242. sqlite3_stmt *pList = 0;
  166243. int bIndex = 0;
  166244. if( p->rc==SQLITE_OK ){
  166245. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  166246. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  166247. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  166248. );
  166249. }
  166250. pIter->nIndex = 0;
  166251. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  166252. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  166253. sqlite3_stmt *pXInfo = 0;
  166254. if( zIdx==0 ) break;
  166255. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  166256. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  166257. );
  166258. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  166259. int iCid = sqlite3_column_int(pXInfo, 1);
  166260. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  166261. }
  166262. rbuFinalize(p, pXInfo);
  166263. bIndex = 1;
  166264. pIter->nIndex++;
  166265. }
  166266. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  166267. /* "PRAGMA index_list" includes the main PK b-tree */
  166268. pIter->nIndex--;
  166269. }
  166270. rbuFinalize(p, pList);
  166271. if( bIndex==0 ) pIter->abIndexed = 0;
  166272. }
  166273. /*
  166274. ** If they are not already populated, populate the pIter->azTblCol[],
  166275. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  166276. ** the table (not index) that the iterator currently points to.
  166277. **
  166278. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  166279. ** an error does occur, an error code and error message are also left in
  166280. ** the RBU handle.
  166281. */
  166282. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  166283. if( pIter->azTblCol==0 ){
  166284. sqlite3_stmt *pStmt = 0;
  166285. int nCol = 0;
  166286. int i; /* for() loop iterator variable */
  166287. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  166288. int iOrder = 0;
  166289. int iTnum = 0;
  166290. /* Figure out the type of table this step will deal with. */
  166291. assert( pIter->eType==0 );
  166292. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  166293. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  166294. p->rc = SQLITE_ERROR;
  166295. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  166296. }
  166297. if( p->rc ) return p->rc;
  166298. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  166299. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  166300. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  166301. || pIter->eType==RBU_PK_VTAB
  166302. );
  166303. /* Populate the azTblCol[] and nTblCol variables based on the columns
  166304. ** of the input table. Ignore any input table columns that begin with
  166305. ** "rbu_". */
  166306. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  166307. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  166308. );
  166309. if( p->rc==SQLITE_OK ){
  166310. nCol = sqlite3_column_count(pStmt);
  166311. rbuAllocateIterArrays(p, pIter, nCol);
  166312. }
  166313. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  166314. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  166315. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  166316. char *zCopy = rbuStrndup(zName, &p->rc);
  166317. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  166318. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  166319. }
  166320. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  166321. bRbuRowid = 1;
  166322. }
  166323. }
  166324. sqlite3_finalize(pStmt);
  166325. pStmt = 0;
  166326. if( p->rc==SQLITE_OK
  166327. && rbuIsVacuum(p)==0
  166328. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  166329. ){
  166330. p->rc = SQLITE_ERROR;
  166331. p->zErrmsg = sqlite3_mprintf(
  166332. "table %q %s rbu_rowid column", pIter->zDataTbl,
  166333. (bRbuRowid ? "may not have" : "requires")
  166334. );
  166335. }
  166336. /* Check that all non-HIDDEN columns in the destination table are also
  166337. ** present in the input table. Populate the abTblPk[], azTblType[] and
  166338. ** aiTblOrder[] arrays at the same time. */
  166339. if( p->rc==SQLITE_OK ){
  166340. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  166341. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  166342. );
  166343. }
  166344. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  166345. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  166346. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  166347. for(i=iOrder; i<pIter->nTblCol; i++){
  166348. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  166349. }
  166350. if( i==pIter->nTblCol ){
  166351. p->rc = SQLITE_ERROR;
  166352. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  166353. pIter->zDataTbl, zName
  166354. );
  166355. }else{
  166356. int iPk = sqlite3_column_int(pStmt, 5);
  166357. int bNotNull = sqlite3_column_int(pStmt, 3);
  166358. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  166359. if( i!=iOrder ){
  166360. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  166361. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  166362. }
  166363. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  166364. pIter->abTblPk[iOrder] = (iPk!=0);
  166365. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  166366. iOrder++;
  166367. }
  166368. }
  166369. rbuFinalize(p, pStmt);
  166370. rbuObjIterCacheIndexedCols(p, pIter);
  166371. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  166372. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  166373. }
  166374. return p->rc;
  166375. }
  166376. /*
  166377. ** This function constructs and returns a pointer to a nul-terminated
  166378. ** string containing some SQL clause or list based on one or more of the
  166379. ** column names currently stored in the pIter->azTblCol[] array.
  166380. */
  166381. static char *rbuObjIterGetCollist(
  166382. sqlite3rbu *p, /* RBU object */
  166383. RbuObjIter *pIter /* Object iterator for column names */
  166384. ){
  166385. char *zList = 0;
  166386. const char *zSep = "";
  166387. int i;
  166388. for(i=0; i<pIter->nTblCol; i++){
  166389. const char *z = pIter->azTblCol[i];
  166390. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  166391. zSep = ", ";
  166392. }
  166393. return zList;
  166394. }
  166395. /*
  166396. ** This function is used to create a SELECT list (the list of SQL
  166397. ** expressions that follows a SELECT keyword) for a SELECT statement
  166398. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  166399. ** index object currently indicated by the iterator object passed as the
  166400. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  166401. ** to obtain the required information.
  166402. **
  166403. ** If the index is of the following form:
  166404. **
  166405. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  166406. **
  166407. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  166408. ** "ipk", the returned string is:
  166409. **
  166410. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  166411. **
  166412. ** As well as the returned string, three other malloc'd strings are
  166413. ** returned via output parameters. As follows:
  166414. **
  166415. ** pzImposterCols: ...
  166416. ** pzImposterPk: ...
  166417. ** pzWhere: ...
  166418. */
  166419. static char *rbuObjIterGetIndexCols(
  166420. sqlite3rbu *p, /* RBU object */
  166421. RbuObjIter *pIter, /* Object iterator for column names */
  166422. char **pzImposterCols, /* OUT: Columns for imposter table */
  166423. char **pzImposterPk, /* OUT: Imposter PK clause */
  166424. char **pzWhere, /* OUT: WHERE clause */
  166425. int *pnBind /* OUT: Trbul number of columns */
  166426. ){
  166427. int rc = p->rc; /* Error code */
  166428. int rc2; /* sqlite3_finalize() return code */
  166429. char *zRet = 0; /* String to return */
  166430. char *zImpCols = 0; /* String to return via *pzImposterCols */
  166431. char *zImpPK = 0; /* String to return via *pzImposterPK */
  166432. char *zWhere = 0; /* String to return via *pzWhere */
  166433. int nBind = 0; /* Value to return via *pnBind */
  166434. const char *zCom = ""; /* Set to ", " later on */
  166435. const char *zAnd = ""; /* Set to " AND " later on */
  166436. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  166437. if( rc==SQLITE_OK ){
  166438. assert( p->zErrmsg==0 );
  166439. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  166440. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  166441. );
  166442. }
  166443. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  166444. int iCid = sqlite3_column_int(pXInfo, 1);
  166445. int bDesc = sqlite3_column_int(pXInfo, 3);
  166446. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  166447. const char *zCol;
  166448. const char *zType;
  166449. if( iCid<0 ){
  166450. /* An integer primary key. If the table has an explicit IPK, use
  166451. ** its name. Otherwise, use "rbu_rowid". */
  166452. if( pIter->eType==RBU_PK_IPK ){
  166453. int i;
  166454. for(i=0; pIter->abTblPk[i]==0; i++);
  166455. assert( i<pIter->nTblCol );
  166456. zCol = pIter->azTblCol[i];
  166457. }else if( rbuIsVacuum(p) ){
  166458. zCol = "_rowid_";
  166459. }else{
  166460. zCol = "rbu_rowid";
  166461. }
  166462. zType = "INTEGER";
  166463. }else{
  166464. zCol = pIter->azTblCol[iCid];
  166465. zType = pIter->azTblType[iCid];
  166466. }
  166467. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  166468. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  166469. const char *zOrder = (bDesc ? " DESC" : "");
  166470. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  166471. zImpPK, zCom, nBind, zCol, zOrder
  166472. );
  166473. }
  166474. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  166475. zImpCols, zCom, nBind, zCol, zType, zCollate
  166476. );
  166477. zWhere = sqlite3_mprintf(
  166478. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  166479. );
  166480. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  166481. zCom = ", ";
  166482. zAnd = " AND ";
  166483. nBind++;
  166484. }
  166485. rc2 = sqlite3_finalize(pXInfo);
  166486. if( rc==SQLITE_OK ) rc = rc2;
  166487. if( rc!=SQLITE_OK ){
  166488. sqlite3_free(zRet);
  166489. sqlite3_free(zImpCols);
  166490. sqlite3_free(zImpPK);
  166491. sqlite3_free(zWhere);
  166492. zRet = 0;
  166493. zImpCols = 0;
  166494. zImpPK = 0;
  166495. zWhere = 0;
  166496. p->rc = rc;
  166497. }
  166498. *pzImposterCols = zImpCols;
  166499. *pzImposterPk = zImpPK;
  166500. *pzWhere = zWhere;
  166501. *pnBind = nBind;
  166502. return zRet;
  166503. }
  166504. /*
  166505. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  166506. ** paramter is passed "old", return a string of the form:
  166507. **
  166508. ** "old.a, old.b, old.b"
  166509. **
  166510. ** With the column names escaped.
  166511. **
  166512. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  166513. ** the text ", old._rowid_" to the returned value.
  166514. */
  166515. static char *rbuObjIterGetOldlist(
  166516. sqlite3rbu *p,
  166517. RbuObjIter *pIter,
  166518. const char *zObj
  166519. ){
  166520. char *zList = 0;
  166521. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  166522. const char *zS = "";
  166523. int i;
  166524. for(i=0; i<pIter->nTblCol; i++){
  166525. if( pIter->abIndexed[i] ){
  166526. const char *zCol = pIter->azTblCol[i];
  166527. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  166528. }else{
  166529. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  166530. }
  166531. zS = ", ";
  166532. if( zList==0 ){
  166533. p->rc = SQLITE_NOMEM;
  166534. break;
  166535. }
  166536. }
  166537. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  166538. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  166539. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  166540. }
  166541. }
  166542. return zList;
  166543. }
  166544. /*
  166545. ** Return an expression that can be used in a WHERE clause to match the
  166546. ** primary key of the current table. For example, if the table is:
  166547. **
  166548. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  166549. **
  166550. ** Return the string:
  166551. **
  166552. ** "b = ?1 AND c = ?2"
  166553. */
  166554. static char *rbuObjIterGetWhere(
  166555. sqlite3rbu *p,
  166556. RbuObjIter *pIter
  166557. ){
  166558. char *zList = 0;
  166559. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  166560. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  166561. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  166562. const char *zSep = "";
  166563. int i;
  166564. for(i=0; i<pIter->nTblCol; i++){
  166565. if( pIter->abTblPk[i] ){
  166566. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  166567. zSep = " AND ";
  166568. }
  166569. }
  166570. zList = rbuMPrintf(p,
  166571. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  166572. );
  166573. }else{
  166574. const char *zSep = "";
  166575. int i;
  166576. for(i=0; i<pIter->nTblCol; i++){
  166577. if( pIter->abTblPk[i] ){
  166578. const char *zCol = pIter->azTblCol[i];
  166579. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  166580. zSep = " AND ";
  166581. }
  166582. }
  166583. }
  166584. return zList;
  166585. }
  166586. /*
  166587. ** The SELECT statement iterating through the keys for the current object
  166588. ** (p->objiter.pSelect) currently points to a valid row. However, there
  166589. ** is something wrong with the rbu_control value in the rbu_control value
  166590. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  166591. ** of the RBU handle to something reflecting this.
  166592. */
  166593. static void rbuBadControlError(sqlite3rbu *p){
  166594. p->rc = SQLITE_ERROR;
  166595. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  166596. }
  166597. /*
  166598. ** Return a nul-terminated string containing the comma separated list of
  166599. ** assignments that should be included following the "SET" keyword of
  166600. ** an UPDATE statement used to update the table object that the iterator
  166601. ** passed as the second argument currently points to if the rbu_control
  166602. ** column of the data_xxx table entry is set to zMask.
  166603. **
  166604. ** The memory for the returned string is obtained from sqlite3_malloc().
  166605. ** It is the responsibility of the caller to eventually free it using
  166606. ** sqlite3_free().
  166607. **
  166608. ** If an OOM error is encountered when allocating space for the new
  166609. ** string, an error code is left in the rbu handle passed as the first
  166610. ** argument and NULL is returned. Or, if an error has already occurred
  166611. ** when this function is called, NULL is returned immediately, without
  166612. ** attempting the allocation or modifying the stored error code.
  166613. */
  166614. static char *rbuObjIterGetSetlist(
  166615. sqlite3rbu *p,
  166616. RbuObjIter *pIter,
  166617. const char *zMask
  166618. ){
  166619. char *zList = 0;
  166620. if( p->rc==SQLITE_OK ){
  166621. int i;
  166622. if( (int)strlen(zMask)!=pIter->nTblCol ){
  166623. rbuBadControlError(p);
  166624. }else{
  166625. const char *zSep = "";
  166626. for(i=0; i<pIter->nTblCol; i++){
  166627. char c = zMask[pIter->aiSrcOrder[i]];
  166628. if( c=='x' ){
  166629. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  166630. zList, zSep, pIter->azTblCol[i], i+1
  166631. );
  166632. zSep = ", ";
  166633. }
  166634. else if( c=='d' ){
  166635. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  166636. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  166637. );
  166638. zSep = ", ";
  166639. }
  166640. else if( c=='f' ){
  166641. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  166642. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  166643. );
  166644. zSep = ", ";
  166645. }
  166646. }
  166647. }
  166648. }
  166649. return zList;
  166650. }
  166651. /*
  166652. ** Return a nul-terminated string consisting of nByte comma separated
  166653. ** "?" expressions. For example, if nByte is 3, return a pointer to
  166654. ** a buffer containing the string "?,?,?".
  166655. **
  166656. ** The memory for the returned string is obtained from sqlite3_malloc().
  166657. ** It is the responsibility of the caller to eventually free it using
  166658. ** sqlite3_free().
  166659. **
  166660. ** If an OOM error is encountered when allocating space for the new
  166661. ** string, an error code is left in the rbu handle passed as the first
  166662. ** argument and NULL is returned. Or, if an error has already occurred
  166663. ** when this function is called, NULL is returned immediately, without
  166664. ** attempting the allocation or modifying the stored error code.
  166665. */
  166666. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  166667. char *zRet = 0;
  166668. int nByte = nBind*2 + 1;
  166669. zRet = (char*)rbuMalloc(p, nByte);
  166670. if( zRet ){
  166671. int i;
  166672. for(i=0; i<nBind; i++){
  166673. zRet[i*2] = '?';
  166674. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  166675. }
  166676. }
  166677. return zRet;
  166678. }
  166679. /*
  166680. ** The iterator currently points to a table (not index) of type
  166681. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  166682. ** declaration for the corresponding imposter table. For example,
  166683. ** if the iterator points to a table created as:
  166684. **
  166685. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  166686. **
  166687. ** this function returns:
  166688. **
  166689. ** PRIMARY KEY("b", "a" DESC)
  166690. */
  166691. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  166692. char *z = 0;
  166693. assert( pIter->zIdx==0 );
  166694. if( p->rc==SQLITE_OK ){
  166695. const char *zSep = "PRIMARY KEY(";
  166696. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  166697. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  166698. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  166699. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  166700. );
  166701. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  166702. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  166703. if( zOrig && strcmp(zOrig, "pk")==0 ){
  166704. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  166705. if( zIdx ){
  166706. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  166707. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  166708. );
  166709. }
  166710. break;
  166711. }
  166712. }
  166713. rbuFinalize(p, pXList);
  166714. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  166715. if( sqlite3_column_int(pXInfo, 5) ){
  166716. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  166717. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  166718. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  166719. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  166720. zSep = ", ";
  166721. }
  166722. }
  166723. z = rbuMPrintf(p, "%z)", z);
  166724. rbuFinalize(p, pXInfo);
  166725. }
  166726. return z;
  166727. }
  166728. /*
  166729. ** This function creates the second imposter table used when writing to
  166730. ** a table b-tree where the table has an external primary key. If the
  166731. ** iterator passed as the second argument does not currently point to
  166732. ** a table (not index) with an external primary key, this function is a
  166733. ** no-op.
  166734. **
  166735. ** Assuming the iterator does point to a table with an external PK, this
  166736. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  166737. ** used to access that PK index. For example, if the target table is
  166738. ** declared as follows:
  166739. **
  166740. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  166741. **
  166742. ** then the imposter table schema is:
  166743. **
  166744. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  166745. **
  166746. */
  166747. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  166748. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  166749. int tnum = pIter->iPkTnum; /* Root page of PK index */
  166750. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  166751. const char *zIdx = 0; /* Name of PK index */
  166752. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  166753. const char *zComma = "";
  166754. char *zCols = 0; /* Used to build up list of table cols */
  166755. char *zPk = 0; /* Used to build up table PK declaration */
  166756. /* Figure out the name of the primary key index for the current table.
  166757. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  166758. ** zIdx to point to a nul-terminated string containing this name. */
  166759. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  166760. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  166761. );
  166762. if( p->rc==SQLITE_OK ){
  166763. sqlite3_bind_int(pQuery, 1, tnum);
  166764. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  166765. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  166766. }
  166767. }
  166768. if( zIdx ){
  166769. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  166770. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  166771. );
  166772. }
  166773. rbuFinalize(p, pQuery);
  166774. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  166775. int bKey = sqlite3_column_int(pXInfo, 5);
  166776. if( bKey ){
  166777. int iCid = sqlite3_column_int(pXInfo, 1);
  166778. int bDesc = sqlite3_column_int(pXInfo, 3);
  166779. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  166780. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
  166781. iCid, pIter->azTblType[iCid], zCollate
  166782. );
  166783. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  166784. zComma = ", ";
  166785. }
  166786. }
  166787. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  166788. rbuFinalize(p, pXInfo);
  166789. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  166790. rbuMPrintfExec(p, p->dbMain,
  166791. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  166792. zCols, zPk
  166793. );
  166794. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  166795. }
  166796. }
  166797. /*
  166798. ** If an error has already occurred when this function is called, it
  166799. ** immediately returns zero (without doing any work). Or, if an error
  166800. ** occurs during the execution of this function, it sets the error code
  166801. ** in the sqlite3rbu object indicated by the first argument and returns
  166802. ** zero.
  166803. **
  166804. ** The iterator passed as the second argument is guaranteed to point to
  166805. ** a table (not an index) when this function is called. This function
  166806. ** attempts to create any imposter table required to write to the main
  166807. ** table b-tree of the table before returning. Non-zero is returned if
  166808. ** an imposter table are created, or zero otherwise.
  166809. **
  166810. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  166811. ** virtual tables are written to directly. The imposter table has the
  166812. ** same schema as the actual target table (less any UNIQUE constraints).
  166813. ** More precisely, the "same schema" means the same columns, types,
  166814. ** collation sequences. For tables that do not have an external PRIMARY
  166815. ** KEY, it also means the same PRIMARY KEY declaration.
  166816. */
  166817. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  166818. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  166819. int tnum = pIter->iTnum;
  166820. const char *zComma = "";
  166821. char *zSql = 0;
  166822. int iCol;
  166823. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  166824. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  166825. const char *zPk = "";
  166826. const char *zCol = pIter->azTblCol[iCol];
  166827. const char *zColl = 0;
  166828. p->rc = sqlite3_table_column_metadata(
  166829. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  166830. );
  166831. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  166832. /* If the target table column is an "INTEGER PRIMARY KEY", add
  166833. ** "PRIMARY KEY" to the imposter table column declaration. */
  166834. zPk = "PRIMARY KEY ";
  166835. }
  166836. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
  166837. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  166838. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  166839. );
  166840. zComma = ", ";
  166841. }
  166842. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  166843. char *zPk = rbuWithoutRowidPK(p, pIter);
  166844. if( zPk ){
  166845. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  166846. }
  166847. }
  166848. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  166849. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  166850. pIter->zTbl, zSql,
  166851. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  166852. );
  166853. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  166854. }
  166855. }
  166856. /*
  166857. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  166858. ** Specifically a statement of the form:
  166859. **
  166860. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  166861. **
  166862. ** The number of bound variables is equal to the number of columns in
  166863. ** the target table, plus one (for the rbu_control column), plus one more
  166864. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  166865. ** virtual table.
  166866. */
  166867. static void rbuObjIterPrepareTmpInsert(
  166868. sqlite3rbu *p,
  166869. RbuObjIter *pIter,
  166870. const char *zCollist,
  166871. const char *zRbuRowid
  166872. ){
  166873. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  166874. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  166875. if( zBind ){
  166876. assert( pIter->pTmpInsert==0 );
  166877. p->rc = prepareFreeAndCollectError(
  166878. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  166879. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  166880. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  166881. ));
  166882. }
  166883. }
  166884. static void rbuTmpInsertFunc(
  166885. sqlite3_context *pCtx,
  166886. int nVal,
  166887. sqlite3_value **apVal
  166888. ){
  166889. sqlite3rbu *p = sqlite3_user_data(pCtx);
  166890. int rc = SQLITE_OK;
  166891. int i;
  166892. assert( sqlite3_value_int(apVal[0])!=0
  166893. || p->objiter.eType==RBU_PK_EXTERNAL
  166894. || p->objiter.eType==RBU_PK_NONE
  166895. );
  166896. if( sqlite3_value_int(apVal[0])!=0 ){
  166897. p->nPhaseOneStep += p->objiter.nIndex;
  166898. }
  166899. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  166900. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  166901. }
  166902. if( rc==SQLITE_OK ){
  166903. sqlite3_step(p->objiter.pTmpInsert);
  166904. rc = sqlite3_reset(p->objiter.pTmpInsert);
  166905. }
  166906. if( rc!=SQLITE_OK ){
  166907. sqlite3_result_error_code(pCtx, rc);
  166908. }
  166909. }
  166910. /*
  166911. ** Ensure that the SQLite statement handles required to update the
  166912. ** target database object currently indicated by the iterator passed
  166913. ** as the second argument are available.
  166914. */
  166915. static int rbuObjIterPrepareAll(
  166916. sqlite3rbu *p,
  166917. RbuObjIter *pIter,
  166918. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  166919. ){
  166920. assert( pIter->bCleanup==0 );
  166921. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  166922. const int tnum = pIter->iTnum;
  166923. char *zCollist = 0; /* List of indexed columns */
  166924. char **pz = &p->zErrmsg;
  166925. const char *zIdx = pIter->zIdx;
  166926. char *zLimit = 0;
  166927. if( nOffset ){
  166928. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  166929. if( !zLimit ) p->rc = SQLITE_NOMEM;
  166930. }
  166931. if( zIdx ){
  166932. const char *zTbl = pIter->zTbl;
  166933. char *zImposterCols = 0; /* Columns for imposter table */
  166934. char *zImposterPK = 0; /* Primary key declaration for imposter */
  166935. char *zWhere = 0; /* WHERE clause on PK columns */
  166936. char *zBind = 0;
  166937. int nBind = 0;
  166938. assert( pIter->eType!=RBU_PK_VTAB );
  166939. zCollist = rbuObjIterGetIndexCols(
  166940. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  166941. );
  166942. zBind = rbuObjIterGetBindlist(p, nBind);
  166943. /* Create the imposter table used to write to this index. */
  166944. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  166945. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  166946. rbuMPrintfExec(p, p->dbMain,
  166947. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  166948. zTbl, zImposterCols, zImposterPK
  166949. );
  166950. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  166951. /* Create the statement to insert index entries */
  166952. pIter->nCol = nBind;
  166953. if( p->rc==SQLITE_OK ){
  166954. p->rc = prepareFreeAndCollectError(
  166955. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  166956. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  166957. );
  166958. }
  166959. /* And to delete index entries */
  166960. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  166961. p->rc = prepareFreeAndCollectError(
  166962. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  166963. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  166964. );
  166965. }
  166966. /* Create the SELECT statement to read keys in sorted order */
  166967. if( p->rc==SQLITE_OK ){
  166968. char *zSql;
  166969. if( rbuIsVacuum(p) ){
  166970. zSql = sqlite3_mprintf(
  166971. "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
  166972. zCollist,
  166973. pIter->zDataTbl,
  166974. zCollist, zLimit
  166975. );
  166976. }else
  166977. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  166978. zSql = sqlite3_mprintf(
  166979. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  166980. zCollist, p->zStateDb, pIter->zDataTbl,
  166981. zCollist, zLimit
  166982. );
  166983. }else{
  166984. zSql = sqlite3_mprintf(
  166985. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  166986. "UNION ALL "
  166987. "SELECT %s, rbu_control FROM '%q' "
  166988. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  166989. "ORDER BY %s%s",
  166990. zCollist, p->zStateDb, pIter->zDataTbl,
  166991. zCollist, pIter->zDataTbl,
  166992. zCollist, zLimit
  166993. );
  166994. }
  166995. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  166996. }
  166997. sqlite3_free(zImposterCols);
  166998. sqlite3_free(zImposterPK);
  166999. sqlite3_free(zWhere);
  167000. sqlite3_free(zBind);
  167001. }else{
  167002. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  167003. ||(pIter->eType==RBU_PK_NONE)
  167004. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  167005. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  167006. const char *zWrite; /* Imposter table name */
  167007. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  167008. char *zWhere = rbuObjIterGetWhere(p, pIter);
  167009. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  167010. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  167011. zCollist = rbuObjIterGetCollist(p, pIter);
  167012. pIter->nCol = pIter->nTblCol;
  167013. /* Create the imposter table or tables (if required). */
  167014. rbuCreateImposterTable(p, pIter);
  167015. rbuCreateImposterTable2(p, pIter);
  167016. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  167017. /* Create the INSERT statement to write to the target PK b-tree */
  167018. if( p->rc==SQLITE_OK ){
  167019. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  167020. sqlite3_mprintf(
  167021. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  167022. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  167023. )
  167024. );
  167025. }
  167026. /* Create the DELETE statement to write to the target PK b-tree.
  167027. ** Because it only performs INSERT operations, this is not required for
  167028. ** an rbu vacuum handle. */
  167029. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  167030. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  167031. sqlite3_mprintf(
  167032. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  167033. )
  167034. );
  167035. }
  167036. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  167037. const char *zRbuRowid = "";
  167038. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  167039. zRbuRowid = ", rbu_rowid";
  167040. }
  167041. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  167042. rbuMPrintfExec(p, p->dbRbu,
  167043. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  167044. "SELECT *%s FROM '%q' WHERE 0;"
  167045. , p->zStateDb, pIter->zDataTbl
  167046. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  167047. , pIter->zDataTbl
  167048. );
  167049. rbuMPrintfExec(p, p->dbMain,
  167050. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  167051. "BEGIN "
  167052. " SELECT rbu_tmp_insert(3, %s);"
  167053. "END;"
  167054. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  167055. "BEGIN "
  167056. " SELECT rbu_tmp_insert(3, %s);"
  167057. "END;"
  167058. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  167059. "BEGIN "
  167060. " SELECT rbu_tmp_insert(4, %s);"
  167061. "END;",
  167062. zWrite, zTbl, zOldlist,
  167063. zWrite, zTbl, zOldlist,
  167064. zWrite, zTbl, zNewlist
  167065. );
  167066. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  167067. rbuMPrintfExec(p, p->dbMain,
  167068. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  167069. "BEGIN "
  167070. " SELECT rbu_tmp_insert(0, %s);"
  167071. "END;",
  167072. zWrite, zTbl, zNewlist
  167073. );
  167074. }
  167075. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  167076. }
  167077. /* Create the SELECT statement to read keys from data_xxx */
  167078. if( p->rc==SQLITE_OK ){
  167079. const char *zRbuRowid = "";
  167080. if( bRbuRowid ){
  167081. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  167082. }
  167083. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  167084. sqlite3_mprintf(
  167085. "SELECT %s,%s rbu_control%s FROM '%q'%s",
  167086. zCollist,
  167087. (rbuIsVacuum(p) ? "0 AS " : ""),
  167088. zRbuRowid,
  167089. pIter->zDataTbl, zLimit
  167090. )
  167091. );
  167092. }
  167093. sqlite3_free(zWhere);
  167094. sqlite3_free(zOldlist);
  167095. sqlite3_free(zNewlist);
  167096. sqlite3_free(zBindings);
  167097. }
  167098. sqlite3_free(zCollist);
  167099. sqlite3_free(zLimit);
  167100. }
  167101. return p->rc;
  167102. }
  167103. /*
  167104. ** Set output variable *ppStmt to point to an UPDATE statement that may
  167105. ** be used to update the imposter table for the main table b-tree of the
  167106. ** table object that pIter currently points to, assuming that the
  167107. ** rbu_control column of the data_xyz table contains zMask.
  167108. **
  167109. ** If the zMask string does not specify any columns to update, then this
  167110. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  167111. */
  167112. static int rbuGetUpdateStmt(
  167113. sqlite3rbu *p, /* RBU handle */
  167114. RbuObjIter *pIter, /* Object iterator */
  167115. const char *zMask, /* rbu_control value ('x.x.') */
  167116. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  167117. ){
  167118. RbuUpdateStmt **pp;
  167119. RbuUpdateStmt *pUp = 0;
  167120. int nUp = 0;
  167121. /* In case an error occurs */
  167122. *ppStmt = 0;
  167123. /* Search for an existing statement. If one is found, shift it to the front
  167124. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  167125. ** to the number of statements currently in the cache and pUp to the
  167126. ** last object in the list. */
  167127. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  167128. pUp = *pp;
  167129. if( strcmp(pUp->zMask, zMask)==0 ){
  167130. *pp = pUp->pNext;
  167131. pUp->pNext = pIter->pRbuUpdate;
  167132. pIter->pRbuUpdate = pUp;
  167133. *ppStmt = pUp->pUpdate;
  167134. return SQLITE_OK;
  167135. }
  167136. nUp++;
  167137. }
  167138. assert( pUp==0 || pUp->pNext==0 );
  167139. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  167140. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  167141. *pp = 0;
  167142. sqlite3_finalize(pUp->pUpdate);
  167143. pUp->pUpdate = 0;
  167144. }else{
  167145. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  167146. }
  167147. if( pUp ){
  167148. char *zWhere = rbuObjIterGetWhere(p, pIter);
  167149. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  167150. char *zUpdate = 0;
  167151. pUp->zMask = (char*)&pUp[1];
  167152. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  167153. pUp->pNext = pIter->pRbuUpdate;
  167154. pIter->pRbuUpdate = pUp;
  167155. if( zSet ){
  167156. const char *zPrefix = "";
  167157. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  167158. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  167159. zPrefix, pIter->zTbl, zSet, zWhere
  167160. );
  167161. p->rc = prepareFreeAndCollectError(
  167162. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  167163. );
  167164. *ppStmt = pUp->pUpdate;
  167165. }
  167166. sqlite3_free(zWhere);
  167167. sqlite3_free(zSet);
  167168. }
  167169. return p->rc;
  167170. }
  167171. static sqlite3 *rbuOpenDbhandle(
  167172. sqlite3rbu *p,
  167173. const char *zName,
  167174. int bUseVfs
  167175. ){
  167176. sqlite3 *db = 0;
  167177. if( p->rc==SQLITE_OK ){
  167178. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  167179. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  167180. if( p->rc ){
  167181. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  167182. sqlite3_close(db);
  167183. db = 0;
  167184. }
  167185. }
  167186. return db;
  167187. }
  167188. /*
  167189. ** Free an RbuState object allocated by rbuLoadState().
  167190. */
  167191. static void rbuFreeState(RbuState *p){
  167192. if( p ){
  167193. sqlite3_free(p->zTbl);
  167194. sqlite3_free(p->zDataTbl);
  167195. sqlite3_free(p->zIdx);
  167196. sqlite3_free(p);
  167197. }
  167198. }
  167199. /*
  167200. ** Allocate an RbuState object and load the contents of the rbu_state
  167201. ** table into it. Return a pointer to the new object. It is the
  167202. ** responsibility of the caller to eventually free the object using
  167203. ** sqlite3_free().
  167204. **
  167205. ** If an error occurs, leave an error code and message in the rbu handle
  167206. ** and return NULL.
  167207. */
  167208. static RbuState *rbuLoadState(sqlite3rbu *p){
  167209. RbuState *pRet = 0;
  167210. sqlite3_stmt *pStmt = 0;
  167211. int rc;
  167212. int rc2;
  167213. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  167214. if( pRet==0 ) return 0;
  167215. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  167216. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  167217. );
  167218. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  167219. switch( sqlite3_column_int(pStmt, 0) ){
  167220. case RBU_STATE_STAGE:
  167221. pRet->eStage = sqlite3_column_int(pStmt, 1);
  167222. if( pRet->eStage!=RBU_STAGE_OAL
  167223. && pRet->eStage!=RBU_STAGE_MOVE
  167224. && pRet->eStage!=RBU_STAGE_CKPT
  167225. ){
  167226. p->rc = SQLITE_CORRUPT;
  167227. }
  167228. break;
  167229. case RBU_STATE_TBL:
  167230. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  167231. break;
  167232. case RBU_STATE_IDX:
  167233. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  167234. break;
  167235. case RBU_STATE_ROW:
  167236. pRet->nRow = sqlite3_column_int(pStmt, 1);
  167237. break;
  167238. case RBU_STATE_PROGRESS:
  167239. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  167240. break;
  167241. case RBU_STATE_CKPT:
  167242. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  167243. break;
  167244. case RBU_STATE_COOKIE:
  167245. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  167246. break;
  167247. case RBU_STATE_OALSZ:
  167248. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  167249. break;
  167250. case RBU_STATE_PHASEONESTEP:
  167251. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  167252. break;
  167253. case RBU_STATE_DATATBL:
  167254. pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  167255. break;
  167256. default:
  167257. rc = SQLITE_CORRUPT;
  167258. break;
  167259. }
  167260. }
  167261. rc2 = sqlite3_finalize(pStmt);
  167262. if( rc==SQLITE_OK ) rc = rc2;
  167263. p->rc = rc;
  167264. return pRet;
  167265. }
  167266. /*
  167267. ** Open the database handle and attach the RBU database as "rbu". If an
  167268. ** error occurs, leave an error code and message in the RBU handle.
  167269. */
  167270. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  167271. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  167272. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  167273. /* Open the RBU database */
  167274. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  167275. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  167276. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  167277. if( p->zState==0 ){
  167278. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  167279. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  167280. }
  167281. }
  167282. /* If using separate RBU and state databases, attach the state database to
  167283. ** the RBU db handle now. */
  167284. if( p->zState ){
  167285. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  167286. memcpy(p->zStateDb, "stat", 4);
  167287. }else{
  167288. memcpy(p->zStateDb, "main", 4);
  167289. }
  167290. #if 0
  167291. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  167292. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  167293. }
  167294. #endif
  167295. /* If it has not already been created, create the rbu_state table */
  167296. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  167297. #if 0
  167298. if( rbuIsVacuum(p) ){
  167299. if( p->rc==SQLITE_OK ){
  167300. int rc2;
  167301. int bOk = 0;
  167302. sqlite3_stmt *pCnt = 0;
  167303. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  167304. "SELECT count(*) FROM stat.sqlite_master"
  167305. );
  167306. if( p->rc==SQLITE_OK
  167307. && sqlite3_step(pCnt)==SQLITE_ROW
  167308. && 1==sqlite3_column_int(pCnt, 0)
  167309. ){
  167310. bOk = 1;
  167311. }
  167312. rc2 = sqlite3_finalize(pCnt);
  167313. if( p->rc==SQLITE_OK ) p->rc = rc2;
  167314. if( p->rc==SQLITE_OK && bOk==0 ){
  167315. p->rc = SQLITE_ERROR;
  167316. p->zErrmsg = sqlite3_mprintf("invalid state database");
  167317. }
  167318. if( p->rc==SQLITE_OK ){
  167319. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  167320. }
  167321. }
  167322. }
  167323. #endif
  167324. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  167325. int bOpen = 0;
  167326. int rc;
  167327. p->nRbu = 0;
  167328. p->pRbuFd = 0;
  167329. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  167330. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  167331. if( p->eStage>=RBU_STAGE_MOVE ){
  167332. bOpen = 1;
  167333. }else{
  167334. RbuState *pState = rbuLoadState(p);
  167335. if( pState ){
  167336. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  167337. rbuFreeState(pState);
  167338. }
  167339. }
  167340. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  167341. }
  167342. p->eStage = 0;
  167343. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  167344. if( !rbuIsVacuum(p) ){
  167345. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  167346. }else if( p->pRbuFd->pWalFd ){
  167347. if( pbRetry ){
  167348. p->pRbuFd->bNolock = 0;
  167349. sqlite3_close(p->dbRbu);
  167350. sqlite3_close(p->dbMain);
  167351. p->dbMain = 0;
  167352. p->dbRbu = 0;
  167353. *pbRetry = 1;
  167354. return;
  167355. }
  167356. p->rc = SQLITE_ERROR;
  167357. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  167358. }else{
  167359. char *zTarget;
  167360. char *zExtra = 0;
  167361. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  167362. zExtra = &p->zRbu[5];
  167363. while( *zExtra ){
  167364. if( *zExtra++=='?' ) break;
  167365. }
  167366. if( *zExtra=='\0' ) zExtra = 0;
  167367. }
  167368. zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
  167369. sqlite3_db_filename(p->dbRbu, "main"),
  167370. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  167371. );
  167372. if( zTarget==0 ){
  167373. p->rc = SQLITE_NOMEM;
  167374. return;
  167375. }
  167376. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  167377. sqlite3_free(zTarget);
  167378. }
  167379. }
  167380. if( p->rc==SQLITE_OK ){
  167381. p->rc = sqlite3_create_function(p->dbMain,
  167382. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  167383. );
  167384. }
  167385. if( p->rc==SQLITE_OK ){
  167386. p->rc = sqlite3_create_function(p->dbMain,
  167387. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  167388. );
  167389. }
  167390. if( p->rc==SQLITE_OK ){
  167391. p->rc = sqlite3_create_function(p->dbRbu,
  167392. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  167393. );
  167394. }
  167395. if( p->rc==SQLITE_OK ){
  167396. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  167397. }
  167398. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  167399. /* Mark the database file just opened as an RBU target database. If
  167400. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  167401. ** This is an error. */
  167402. if( p->rc==SQLITE_OK ){
  167403. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  167404. }
  167405. if( p->rc==SQLITE_NOTFOUND ){
  167406. p->rc = SQLITE_ERROR;
  167407. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  167408. }
  167409. }
  167410. /*
  167411. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  167412. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  167413. **
  167414. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  167415. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  167416. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  167417. ** three characters, then shorten the suffix on z[] to be the last three
  167418. ** characters of the original suffix.
  167419. **
  167420. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  167421. ** do the suffix shortening regardless of URI parameter.
  167422. **
  167423. ** Examples:
  167424. **
  167425. ** test.db-journal => test.nal
  167426. ** test.db-wal => test.wal
  167427. ** test.db-shm => test.shm
  167428. ** test.db-mj7f3319fa => test.9fa
  167429. */
  167430. static void rbuFileSuffix3(const char *zBase, char *z){
  167431. #ifdef SQLITE_ENABLE_8_3_NAMES
  167432. #if SQLITE_ENABLE_8_3_NAMES<2
  167433. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  167434. #endif
  167435. {
  167436. int i, sz;
  167437. sz = (int)strlen(z)&0xffffff;
  167438. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  167439. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  167440. }
  167441. #endif
  167442. }
  167443. /*
  167444. ** Return the current wal-index header checksum for the target database
  167445. ** as a 64-bit integer.
  167446. **
  167447. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  167448. ** blob starting at byte offset 40.
  167449. */
  167450. static i64 rbuShmChecksum(sqlite3rbu *p){
  167451. i64 iRet = 0;
  167452. if( p->rc==SQLITE_OK ){
  167453. sqlite3_file *pDb = p->pTargetFd->pReal;
  167454. u32 volatile *ptr;
  167455. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  167456. if( p->rc==SQLITE_OK ){
  167457. iRet = ((i64)ptr[10] << 32) + ptr[11];
  167458. }
  167459. }
  167460. return iRet;
  167461. }
  167462. /*
  167463. ** This function is called as part of initializing or reinitializing an
  167464. ** incremental checkpoint.
  167465. **
  167466. ** It populates the sqlite3rbu.aFrame[] array with the set of
  167467. ** (wal frame -> db page) copy operations required to checkpoint the
  167468. ** current wal file, and obtains the set of shm locks required to safely
  167469. ** perform the copy operations directly on the file-system.
  167470. **
  167471. ** If argument pState is not NULL, then the incremental checkpoint is
  167472. ** being resumed. In this case, if the checksum of the wal-index-header
  167473. ** following recovery is not the same as the checksum saved in the RbuState
  167474. ** object, then the rbu handle is set to DONE state. This occurs if some
  167475. ** other client appends a transaction to the wal file in the middle of
  167476. ** an incremental checkpoint.
  167477. */
  167478. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  167479. /* If pState is NULL, then the wal file may not have been opened and
  167480. ** recovered. Running a read-statement here to ensure that doing so
  167481. ** does not interfere with the "capture" process below. */
  167482. if( pState==0 ){
  167483. p->eStage = 0;
  167484. if( p->rc==SQLITE_OK ){
  167485. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  167486. }
  167487. }
  167488. /* Assuming no error has occurred, run a "restart" checkpoint with the
  167489. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  167490. ** special behaviour in the rbu VFS:
  167491. **
  167492. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  167493. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  167494. ** proceed with running a passive checkpoint instead of failing).
  167495. **
  167496. ** * Attempts to read from the *-wal file or write to the database file
  167497. ** do not perform any IO. Instead, the frame/page combinations that
  167498. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  167499. ** array.
  167500. **
  167501. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  167502. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  167503. ** no-ops. These locks will not be released until the connection
  167504. ** is closed.
  167505. **
  167506. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  167507. ** error.
  167508. **
  167509. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  167510. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  167511. ** array populated with a set of (frame -> page) mappings. Because the
  167512. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  167513. ** data from the wal file into the database file according to the
  167514. ** contents of aFrame[].
  167515. */
  167516. if( p->rc==SQLITE_OK ){
  167517. int rc2;
  167518. p->eStage = RBU_STAGE_CAPTURE;
  167519. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  167520. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  167521. }
  167522. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  167523. p->eStage = RBU_STAGE_CKPT;
  167524. p->nStep = (pState ? pState->nRow : 0);
  167525. p->aBuf = rbuMalloc(p, p->pgsz);
  167526. p->iWalCksum = rbuShmChecksum(p);
  167527. }
  167528. if( p->rc==SQLITE_OK ){
  167529. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  167530. p->rc = SQLITE_DONE;
  167531. p->eStage = RBU_STAGE_DONE;
  167532. }else{
  167533. int nSectorSize;
  167534. sqlite3_file *pDb = p->pTargetFd->pReal;
  167535. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  167536. assert( p->nPagePerSector==0 );
  167537. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  167538. if( nSectorSize>p->pgsz ){
  167539. p->nPagePerSector = nSectorSize / p->pgsz;
  167540. }else{
  167541. p->nPagePerSector = 1;
  167542. }
  167543. /* Call xSync() on the wal file. This causes SQLite to sync the
  167544. ** directory in which the target database and the wal file reside, in
  167545. ** case it has not been synced since the rename() call in
  167546. ** rbuMoveOalFile(). */
  167547. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  167548. }
  167549. }
  167550. }
  167551. /*
  167552. ** Called when iAmt bytes are read from offset iOff of the wal file while
  167553. ** the rbu object is in capture mode. Record the frame number of the frame
  167554. ** being read in the aFrame[] array.
  167555. */
  167556. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  167557. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  167558. u32 iFrame;
  167559. if( pRbu->mLock!=mReq ){
  167560. pRbu->rc = SQLITE_BUSY;
  167561. return SQLITE_INTERNAL;
  167562. }
  167563. pRbu->pgsz = iAmt;
  167564. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  167565. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  167566. RbuFrame *aNew;
  167567. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  167568. if( aNew==0 ) return SQLITE_NOMEM;
  167569. pRbu->aFrame = aNew;
  167570. pRbu->nFrameAlloc = nNew;
  167571. }
  167572. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  167573. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  167574. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  167575. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  167576. pRbu->nFrame++;
  167577. return SQLITE_OK;
  167578. }
  167579. /*
  167580. ** Called when a page of data is written to offset iOff of the database
  167581. ** file while the rbu handle is in capture mode. Record the page number
  167582. ** of the page being written in the aFrame[] array.
  167583. */
  167584. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  167585. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  167586. return SQLITE_OK;
  167587. }
  167588. /*
  167589. ** This is called as part of an incremental checkpoint operation. Copy
  167590. ** a single frame of data from the wal file into the database file, as
  167591. ** indicated by the RbuFrame object.
  167592. */
  167593. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  167594. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  167595. sqlite3_file *pDb = p->pTargetFd->pReal;
  167596. i64 iOff;
  167597. assert( p->rc==SQLITE_OK );
  167598. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  167599. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  167600. if( p->rc ) return;
  167601. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  167602. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  167603. }
  167604. /*
  167605. ** Take an EXCLUSIVE lock on the database file.
  167606. */
  167607. static void rbuLockDatabase(sqlite3rbu *p){
  167608. sqlite3_file *pReal = p->pTargetFd->pReal;
  167609. assert( p->rc==SQLITE_OK );
  167610. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  167611. if( p->rc==SQLITE_OK ){
  167612. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  167613. }
  167614. }
  167615. #if defined(_WIN32_WCE)
  167616. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  167617. int nChar;
  167618. LPWSTR zWideFilename;
  167619. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  167620. if( nChar==0 ){
  167621. return 0;
  167622. }
  167623. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  167624. if( zWideFilename==0 ){
  167625. return 0;
  167626. }
  167627. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  167628. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  167629. nChar);
  167630. if( nChar==0 ){
  167631. sqlite3_free(zWideFilename);
  167632. zWideFilename = 0;
  167633. }
  167634. return zWideFilename;
  167635. }
  167636. #endif
  167637. /*
  167638. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  167639. ** on the database file. This proc moves the *-oal file to the *-wal path,
  167640. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  167641. ** If an error occurs, leave an error code and error message in the rbu
  167642. ** handle.
  167643. */
  167644. static void rbuMoveOalFile(sqlite3rbu *p){
  167645. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  167646. const char *zMove = zBase;
  167647. char *zOal;
  167648. char *zWal;
  167649. if( rbuIsVacuum(p) ){
  167650. zMove = sqlite3_db_filename(p->dbRbu, "main");
  167651. }
  167652. zOal = sqlite3_mprintf("%s-oal", zMove);
  167653. zWal = sqlite3_mprintf("%s-wal", zMove);
  167654. assert( p->eStage==RBU_STAGE_MOVE );
  167655. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  167656. if( zWal==0 || zOal==0 ){
  167657. p->rc = SQLITE_NOMEM;
  167658. }else{
  167659. /* Move the *-oal file to *-wal. At this point connection p->db is
  167660. ** holding a SHARED lock on the target database file (because it is
  167661. ** in WAL mode). So no other connection may be writing the db.
  167662. **
  167663. ** In order to ensure that there are no database readers, an EXCLUSIVE
  167664. ** lock is obtained here before the *-oal is moved to *-wal.
  167665. */
  167666. rbuLockDatabase(p);
  167667. if( p->rc==SQLITE_OK ){
  167668. rbuFileSuffix3(zBase, zWal);
  167669. rbuFileSuffix3(zBase, zOal);
  167670. /* Re-open the databases. */
  167671. rbuObjIterFinalize(&p->objiter);
  167672. sqlite3_close(p->dbRbu);
  167673. sqlite3_close(p->dbMain);
  167674. p->dbMain = 0;
  167675. p->dbRbu = 0;
  167676. #if defined(_WIN32_WCE)
  167677. {
  167678. LPWSTR zWideOal;
  167679. LPWSTR zWideWal;
  167680. zWideOal = rbuWinUtf8ToUnicode(zOal);
  167681. if( zWideOal ){
  167682. zWideWal = rbuWinUtf8ToUnicode(zWal);
  167683. if( zWideWal ){
  167684. if( MoveFileW(zWideOal, zWideWal) ){
  167685. p->rc = SQLITE_OK;
  167686. }else{
  167687. p->rc = SQLITE_IOERR;
  167688. }
  167689. sqlite3_free(zWideWal);
  167690. }else{
  167691. p->rc = SQLITE_IOERR_NOMEM;
  167692. }
  167693. sqlite3_free(zWideOal);
  167694. }else{
  167695. p->rc = SQLITE_IOERR_NOMEM;
  167696. }
  167697. }
  167698. #else
  167699. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  167700. #endif
  167701. if( p->rc==SQLITE_OK ){
  167702. rbuOpenDatabase(p, 0);
  167703. rbuSetupCheckpoint(p, 0);
  167704. }
  167705. }
  167706. }
  167707. sqlite3_free(zWal);
  167708. sqlite3_free(zOal);
  167709. }
  167710. /*
  167711. ** The SELECT statement iterating through the keys for the current object
  167712. ** (p->objiter.pSelect) currently points to a valid row. This function
  167713. ** determines the type of operation requested by this row and returns
  167714. ** one of the following values to indicate the result:
  167715. **
  167716. ** * RBU_INSERT
  167717. ** * RBU_DELETE
  167718. ** * RBU_IDX_DELETE
  167719. ** * RBU_UPDATE
  167720. **
  167721. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  167722. ** point to the text value indicating the columns to update.
  167723. **
  167724. ** If the rbu_control field contains an invalid value, an error code and
  167725. ** message are left in the RBU handle and zero returned.
  167726. */
  167727. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  167728. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  167729. int res = 0; /* Return value */
  167730. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  167731. case SQLITE_INTEGER: {
  167732. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  167733. switch( iVal ){
  167734. case 0: res = RBU_INSERT; break;
  167735. case 1: res = RBU_DELETE; break;
  167736. case 2: res = RBU_REPLACE; break;
  167737. case 3: res = RBU_IDX_DELETE; break;
  167738. case 4: res = RBU_IDX_INSERT; break;
  167739. }
  167740. break;
  167741. }
  167742. case SQLITE_TEXT: {
  167743. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  167744. if( z==0 ){
  167745. p->rc = SQLITE_NOMEM;
  167746. }else{
  167747. *pzMask = (const char*)z;
  167748. }
  167749. res = RBU_UPDATE;
  167750. break;
  167751. }
  167752. default:
  167753. break;
  167754. }
  167755. if( res==0 ){
  167756. rbuBadControlError(p);
  167757. }
  167758. return res;
  167759. }
  167760. #ifdef SQLITE_DEBUG
  167761. /*
  167762. ** Assert that column iCol of statement pStmt is named zName.
  167763. */
  167764. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  167765. const char *zCol = sqlite3_column_name(pStmt, iCol);
  167766. assert( 0==sqlite3_stricmp(zName, zCol) );
  167767. }
  167768. #else
  167769. # define assertColumnName(x,y,z)
  167770. #endif
  167771. /*
  167772. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  167773. ** RBU_IDX_DELETE. This function performs the work of a single
  167774. ** sqlite3rbu_step() call for the type of operation specified by eType.
  167775. */
  167776. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  167777. RbuObjIter *pIter = &p->objiter;
  167778. sqlite3_value *pVal;
  167779. sqlite3_stmt *pWriter;
  167780. int i;
  167781. assert( p->rc==SQLITE_OK );
  167782. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  167783. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  167784. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  167785. );
  167786. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  167787. ** statement below does actually delete a row, nPhaseOneStep will be
  167788. ** incremented by the same amount when SQL function rbu_tmp_insert()
  167789. ** is invoked by the trigger. */
  167790. if( eType==RBU_DELETE ){
  167791. p->nPhaseOneStep -= p->objiter.nIndex;
  167792. }
  167793. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  167794. pWriter = pIter->pDelete;
  167795. }else{
  167796. pWriter = pIter->pInsert;
  167797. }
  167798. for(i=0; i<pIter->nCol; i++){
  167799. /* If this is an INSERT into a table b-tree and the table has an
  167800. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  167801. ** to write a NULL into the IPK column. That is not permitted. */
  167802. if( eType==RBU_INSERT
  167803. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  167804. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  167805. ){
  167806. p->rc = SQLITE_MISMATCH;
  167807. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  167808. return;
  167809. }
  167810. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  167811. continue;
  167812. }
  167813. pVal = sqlite3_column_value(pIter->pSelect, i);
  167814. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  167815. if( p->rc ) return;
  167816. }
  167817. if( pIter->zIdx==0 ){
  167818. if( pIter->eType==RBU_PK_VTAB
  167819. || pIter->eType==RBU_PK_NONE
  167820. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  167821. ){
  167822. /* For a virtual table, or a table with no primary key, the
  167823. ** SELECT statement is:
  167824. **
  167825. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  167826. **
  167827. ** Hence column_value(pIter->nCol+1).
  167828. */
  167829. assertColumnName(pIter->pSelect, pIter->nCol+1,
  167830. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  167831. );
  167832. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  167833. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  167834. }
  167835. }
  167836. if( p->rc==SQLITE_OK ){
  167837. sqlite3_step(pWriter);
  167838. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  167839. }
  167840. }
  167841. /*
  167842. ** This function does the work for an sqlite3rbu_step() call.
  167843. **
  167844. ** The object-iterator (p->objiter) currently points to a valid object,
  167845. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  167846. ** input row. Perform whatever processing is required and return.
  167847. **
  167848. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  167849. ** and message is left in the RBU handle and a copy of the error code
  167850. ** returned.
  167851. */
  167852. static int rbuStep(sqlite3rbu *p){
  167853. RbuObjIter *pIter = &p->objiter;
  167854. const char *zMask = 0;
  167855. int eType = rbuStepType(p, &zMask);
  167856. if( eType ){
  167857. assert( eType==RBU_INSERT || eType==RBU_DELETE
  167858. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  167859. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  167860. );
  167861. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  167862. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  167863. rbuBadControlError(p);
  167864. }
  167865. else if( eType==RBU_REPLACE ){
  167866. if( pIter->zIdx==0 ){
  167867. p->nPhaseOneStep += p->objiter.nIndex;
  167868. rbuStepOneOp(p, RBU_DELETE);
  167869. }
  167870. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  167871. }
  167872. else if( eType!=RBU_UPDATE ){
  167873. rbuStepOneOp(p, eType);
  167874. }
  167875. else{
  167876. sqlite3_value *pVal;
  167877. sqlite3_stmt *pUpdate = 0;
  167878. assert( eType==RBU_UPDATE );
  167879. p->nPhaseOneStep -= p->objiter.nIndex;
  167880. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  167881. if( pUpdate ){
  167882. int i;
  167883. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  167884. char c = zMask[pIter->aiSrcOrder[i]];
  167885. pVal = sqlite3_column_value(pIter->pSelect, i);
  167886. if( pIter->abTblPk[i] || c!='.' ){
  167887. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  167888. }
  167889. }
  167890. if( p->rc==SQLITE_OK
  167891. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  167892. ){
  167893. /* Bind the rbu_rowid value to column _rowid_ */
  167894. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  167895. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  167896. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  167897. }
  167898. if( p->rc==SQLITE_OK ){
  167899. sqlite3_step(pUpdate);
  167900. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  167901. }
  167902. }
  167903. }
  167904. }
  167905. return p->rc;
  167906. }
  167907. /*
  167908. ** Increment the schema cookie of the main database opened by p->dbMain.
  167909. **
  167910. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  167911. ** opened by p->dbMain to one more than the schema cookie of the main
  167912. ** db opened by p->dbRbu.
  167913. */
  167914. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  167915. if( p->rc==SQLITE_OK ){
  167916. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  167917. int iCookie = 1000000;
  167918. sqlite3_stmt *pStmt;
  167919. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  167920. "PRAGMA schema_version"
  167921. );
  167922. if( p->rc==SQLITE_OK ){
  167923. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  167924. ** is already a transaction open, so the prepared statement cannot
  167925. ** throw an SQLITE_SCHEMA exception. The only database page the
  167926. ** statement reads is page 1, which is guaranteed to be in the cache.
  167927. ** And no memory allocations are required. */
  167928. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  167929. iCookie = sqlite3_column_int(pStmt, 0);
  167930. }
  167931. rbuFinalize(p, pStmt);
  167932. }
  167933. if( p->rc==SQLITE_OK ){
  167934. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  167935. }
  167936. }
  167937. }
  167938. /*
  167939. ** Update the contents of the rbu_state table within the rbu database. The
  167940. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  167941. ** are determined by inspecting the rbu handle passed as the first argument.
  167942. */
  167943. static void rbuSaveState(sqlite3rbu *p, int eStage){
  167944. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  167945. sqlite3_stmt *pInsert = 0;
  167946. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  167947. int rc;
  167948. assert( p->zErrmsg==0 );
  167949. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  167950. sqlite3_mprintf(
  167951. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  167952. "(%d, %d), "
  167953. "(%d, %Q), "
  167954. "(%d, %Q), "
  167955. "(%d, %d), "
  167956. "(%d, %d), "
  167957. "(%d, %lld), "
  167958. "(%d, %lld), "
  167959. "(%d, %lld), "
  167960. "(%d, %lld), "
  167961. "(%d, %Q) ",
  167962. p->zStateDb,
  167963. RBU_STATE_STAGE, eStage,
  167964. RBU_STATE_TBL, p->objiter.zTbl,
  167965. RBU_STATE_IDX, p->objiter.zIdx,
  167966. RBU_STATE_ROW, p->nStep,
  167967. RBU_STATE_PROGRESS, p->nProgress,
  167968. RBU_STATE_CKPT, p->iWalCksum,
  167969. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  167970. RBU_STATE_OALSZ, p->iOalSz,
  167971. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
  167972. RBU_STATE_DATATBL, p->objiter.zDataTbl
  167973. )
  167974. );
  167975. assert( pInsert==0 || rc==SQLITE_OK );
  167976. if( rc==SQLITE_OK ){
  167977. sqlite3_step(pInsert);
  167978. rc = sqlite3_finalize(pInsert);
  167979. }
  167980. if( rc!=SQLITE_OK ) p->rc = rc;
  167981. }
  167982. }
  167983. /*
  167984. ** The second argument passed to this function is the name of a PRAGMA
  167985. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  167986. ** This function executes the following on sqlite3rbu.dbRbu:
  167987. **
  167988. ** "PRAGMA main.$zPragma"
  167989. **
  167990. ** where $zPragma is the string passed as the second argument, then
  167991. ** on sqlite3rbu.dbMain:
  167992. **
  167993. ** "PRAGMA main.$zPragma = $val"
  167994. **
  167995. ** where $val is the value returned by the first PRAGMA invocation.
  167996. **
  167997. ** In short, it copies the value of the specified PRAGMA setting from
  167998. ** dbRbu to dbMain.
  167999. */
  168000. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  168001. if( p->rc==SQLITE_OK ){
  168002. sqlite3_stmt *pPragma = 0;
  168003. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  168004. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  168005. );
  168006. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  168007. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  168008. zPragma, sqlite3_column_int(pPragma, 0)
  168009. );
  168010. }
  168011. rbuFinalize(p, pPragma);
  168012. }
  168013. }
  168014. /*
  168015. ** The RBU handle passed as the only argument has just been opened and
  168016. ** the state database is empty. If this RBU handle was opened for an
  168017. ** RBU vacuum operation, create the schema in the target db.
  168018. */
  168019. static void rbuCreateTargetSchema(sqlite3rbu *p){
  168020. sqlite3_stmt *pSql = 0;
  168021. sqlite3_stmt *pInsert = 0;
  168022. assert( rbuIsVacuum(p) );
  168023. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  168024. if( p->rc==SQLITE_OK ){
  168025. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  168026. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  168027. " AND name!='sqlite_sequence' "
  168028. " ORDER BY type DESC"
  168029. );
  168030. }
  168031. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  168032. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  168033. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  168034. }
  168035. rbuFinalize(p, pSql);
  168036. if( p->rc!=SQLITE_OK ) return;
  168037. if( p->rc==SQLITE_OK ){
  168038. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  168039. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  168040. );
  168041. }
  168042. if( p->rc==SQLITE_OK ){
  168043. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  168044. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  168045. );
  168046. }
  168047. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  168048. int i;
  168049. for(i=0; i<5; i++){
  168050. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  168051. }
  168052. sqlite3_step(pInsert);
  168053. p->rc = sqlite3_reset(pInsert);
  168054. }
  168055. if( p->rc==SQLITE_OK ){
  168056. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  168057. }
  168058. rbuFinalize(p, pSql);
  168059. rbuFinalize(p, pInsert);
  168060. }
  168061. /*
  168062. ** Step the RBU object.
  168063. */
  168064. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  168065. if( p ){
  168066. switch( p->eStage ){
  168067. case RBU_STAGE_OAL: {
  168068. RbuObjIter *pIter = &p->objiter;
  168069. /* If this is an RBU vacuum operation and the state table was empty
  168070. ** when this handle was opened, create the target database schema. */
  168071. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  168072. rbuCreateTargetSchema(p);
  168073. rbuCopyPragma(p, "user_version");
  168074. rbuCopyPragma(p, "application_id");
  168075. }
  168076. while( p->rc==SQLITE_OK && pIter->zTbl ){
  168077. if( pIter->bCleanup ){
  168078. /* Clean up the rbu_tmp_xxx table for the previous table. It
  168079. ** cannot be dropped as there are currently active SQL statements.
  168080. ** But the contents can be deleted. */
  168081. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  168082. rbuMPrintfExec(p, p->dbRbu,
  168083. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  168084. );
  168085. }
  168086. }else{
  168087. rbuObjIterPrepareAll(p, pIter, 0);
  168088. /* Advance to the next row to process. */
  168089. if( p->rc==SQLITE_OK ){
  168090. int rc = sqlite3_step(pIter->pSelect);
  168091. if( rc==SQLITE_ROW ){
  168092. p->nProgress++;
  168093. p->nStep++;
  168094. return rbuStep(p);
  168095. }
  168096. p->rc = sqlite3_reset(pIter->pSelect);
  168097. p->nStep = 0;
  168098. }
  168099. }
  168100. rbuObjIterNext(p, pIter);
  168101. }
  168102. if( p->rc==SQLITE_OK ){
  168103. assert( pIter->zTbl==0 );
  168104. rbuSaveState(p, RBU_STAGE_MOVE);
  168105. rbuIncrSchemaCookie(p);
  168106. if( p->rc==SQLITE_OK ){
  168107. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  168108. }
  168109. if( p->rc==SQLITE_OK ){
  168110. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  168111. }
  168112. p->eStage = RBU_STAGE_MOVE;
  168113. }
  168114. break;
  168115. }
  168116. case RBU_STAGE_MOVE: {
  168117. if( p->rc==SQLITE_OK ){
  168118. rbuMoveOalFile(p);
  168119. p->nProgress++;
  168120. }
  168121. break;
  168122. }
  168123. case RBU_STAGE_CKPT: {
  168124. if( p->rc==SQLITE_OK ){
  168125. if( p->nStep>=p->nFrame ){
  168126. sqlite3_file *pDb = p->pTargetFd->pReal;
  168127. /* Sync the db file */
  168128. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  168129. /* Update nBackfill */
  168130. if( p->rc==SQLITE_OK ){
  168131. void volatile *ptr;
  168132. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  168133. if( p->rc==SQLITE_OK ){
  168134. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  168135. }
  168136. }
  168137. if( p->rc==SQLITE_OK ){
  168138. p->eStage = RBU_STAGE_DONE;
  168139. p->rc = SQLITE_DONE;
  168140. }
  168141. }else{
  168142. /* At one point the following block copied a single frame from the
  168143. ** wal file to the database file. So that one call to sqlite3rbu_step()
  168144. ** checkpointed a single frame.
  168145. **
  168146. ** However, if the sector-size is larger than the page-size, and the
  168147. ** application calls sqlite3rbu_savestate() or close() immediately
  168148. ** after this step, then rbu_step() again, then a power failure occurs,
  168149. ** then the database page written here may be damaged. Work around
  168150. ** this by checkpointing frames until the next page in the aFrame[]
  168151. ** lies on a different disk sector to the current one. */
  168152. u32 iSector;
  168153. do{
  168154. RbuFrame *pFrame = &p->aFrame[p->nStep];
  168155. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  168156. rbuCheckpointFrame(p, pFrame);
  168157. p->nStep++;
  168158. }while( p->nStep<p->nFrame
  168159. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  168160. && p->rc==SQLITE_OK
  168161. );
  168162. }
  168163. p->nProgress++;
  168164. }
  168165. break;
  168166. }
  168167. default:
  168168. break;
  168169. }
  168170. return p->rc;
  168171. }else{
  168172. return SQLITE_NOMEM;
  168173. }
  168174. }
  168175. /*
  168176. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  168177. ** otherwise. Either or both argument may be NULL. Two NULL values are
  168178. ** considered equal, and NULL is considered distinct from all other values.
  168179. */
  168180. static int rbuStrCompare(const char *z1, const char *z2){
  168181. if( z1==0 && z2==0 ) return 0;
  168182. if( z1==0 || z2==0 ) return 1;
  168183. return (sqlite3_stricmp(z1, z2)!=0);
  168184. }
  168185. /*
  168186. ** This function is called as part of sqlite3rbu_open() when initializing
  168187. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  168188. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  168189. ** things so that the next call to sqlite3rbu_step() continues on from
  168190. ** where the previous rbu handle left off.
  168191. **
  168192. ** If an error occurs, an error code and error message are left in the
  168193. ** rbu handle passed as the first argument.
  168194. */
  168195. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  168196. assert( p->rc==SQLITE_OK );
  168197. if( pState->zTbl ){
  168198. RbuObjIter *pIter = &p->objiter;
  168199. int rc = SQLITE_OK;
  168200. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  168201. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  168202. || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
  168203. || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
  168204. )){
  168205. rc = rbuObjIterNext(p, pIter);
  168206. }
  168207. if( rc==SQLITE_OK && !pIter->zTbl ){
  168208. rc = SQLITE_ERROR;
  168209. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  168210. }
  168211. if( rc==SQLITE_OK ){
  168212. p->nStep = pState->nRow;
  168213. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  168214. }
  168215. p->rc = rc;
  168216. }
  168217. }
  168218. /*
  168219. ** If there is a "*-oal" file in the file-system corresponding to the
  168220. ** target database in the file-system, delete it. If an error occurs,
  168221. ** leave an error code and error message in the rbu handle.
  168222. */
  168223. static void rbuDeleteOalFile(sqlite3rbu *p){
  168224. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  168225. if( zOal ){
  168226. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  168227. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  168228. pVfs->xDelete(pVfs, zOal, 0);
  168229. sqlite3_free(zOal);
  168230. }
  168231. }
  168232. /*
  168233. ** Allocate a private rbu VFS for the rbu handle passed as the only
  168234. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  168235. ** specified a URI with a vfs=? option in place of a target database
  168236. ** file name.
  168237. */
  168238. static void rbuCreateVfs(sqlite3rbu *p){
  168239. int rnd;
  168240. char zRnd[64];
  168241. assert( p->rc==SQLITE_OK );
  168242. sqlite3_randomness(sizeof(int), (void*)&rnd);
  168243. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  168244. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  168245. if( p->rc==SQLITE_OK ){
  168246. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  168247. assert( pVfs );
  168248. p->zVfsName = pVfs->zName;
  168249. ((rbu_vfs*)pVfs)->pRbu = p;
  168250. }
  168251. }
  168252. /*
  168253. ** Destroy the private VFS created for the rbu handle passed as the only
  168254. ** argument by an earlier call to rbuCreateVfs().
  168255. */
  168256. static void rbuDeleteVfs(sqlite3rbu *p){
  168257. if( p->zVfsName ){
  168258. sqlite3rbu_destroy_vfs(p->zVfsName);
  168259. p->zVfsName = 0;
  168260. }
  168261. }
  168262. /*
  168263. ** This user-defined SQL function is invoked with a single argument - the
  168264. ** name of a table expected to appear in the target database. It returns
  168265. ** the number of auxilliary indexes on the table.
  168266. */
  168267. static void rbuIndexCntFunc(
  168268. sqlite3_context *pCtx,
  168269. int nVal,
  168270. sqlite3_value **apVal
  168271. ){
  168272. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  168273. sqlite3_stmt *pStmt = 0;
  168274. char *zErrmsg = 0;
  168275. int rc;
  168276. assert( nVal==1 );
  168277. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  168278. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  168279. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  168280. );
  168281. if( rc!=SQLITE_OK ){
  168282. sqlite3_result_error(pCtx, zErrmsg, -1);
  168283. }else{
  168284. int nIndex = 0;
  168285. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  168286. nIndex = sqlite3_column_int(pStmt, 0);
  168287. }
  168288. rc = sqlite3_finalize(pStmt);
  168289. if( rc==SQLITE_OK ){
  168290. sqlite3_result_int(pCtx, nIndex);
  168291. }else{
  168292. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  168293. }
  168294. }
  168295. sqlite3_free(zErrmsg);
  168296. }
  168297. /*
  168298. ** If the RBU database contains the rbu_count table, use it to initialize
  168299. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  168300. ** is assumed to contain the same columns as:
  168301. **
  168302. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  168303. **
  168304. ** There should be one row in the table for each data_xxx table in the
  168305. ** database. The 'tbl' column should contain the name of a data_xxx table,
  168306. ** and the cnt column the number of rows it contains.
  168307. **
  168308. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  168309. ** for all rows in the rbu_count table, where nIndex is the number of
  168310. ** indexes on the corresponding target database table.
  168311. */
  168312. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  168313. if( p->rc==SQLITE_OK ){
  168314. sqlite3_stmt *pStmt = 0;
  168315. int bExists = 0; /* True if rbu_count exists */
  168316. p->nPhaseOneStep = -1;
  168317. p->rc = sqlite3_create_function(p->dbRbu,
  168318. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  168319. );
  168320. /* Check for the rbu_count table. If it does not exist, or if an error
  168321. ** occurs, nPhaseOneStep will be left set to -1. */
  168322. if( p->rc==SQLITE_OK ){
  168323. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  168324. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  168325. );
  168326. }
  168327. if( p->rc==SQLITE_OK ){
  168328. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  168329. bExists = 1;
  168330. }
  168331. p->rc = sqlite3_finalize(pStmt);
  168332. }
  168333. if( p->rc==SQLITE_OK && bExists ){
  168334. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  168335. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  168336. "FROM rbu_count"
  168337. );
  168338. if( p->rc==SQLITE_OK ){
  168339. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  168340. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  168341. }
  168342. p->rc = sqlite3_finalize(pStmt);
  168343. }
  168344. }
  168345. }
  168346. }
  168347. static sqlite3rbu *openRbuHandle(
  168348. const char *zTarget,
  168349. const char *zRbu,
  168350. const char *zState
  168351. ){
  168352. sqlite3rbu *p;
  168353. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  168354. size_t nRbu = strlen(zRbu);
  168355. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  168356. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  168357. if( p ){
  168358. RbuState *pState = 0;
  168359. /* Create the custom VFS. */
  168360. memset(p, 0, sizeof(sqlite3rbu));
  168361. rbuCreateVfs(p);
  168362. /* Open the target, RBU and state databases */
  168363. if( p->rc==SQLITE_OK ){
  168364. char *pCsr = (char*)&p[1];
  168365. int bRetry = 0;
  168366. if( zTarget ){
  168367. p->zTarget = pCsr;
  168368. memcpy(p->zTarget, zTarget, nTarget+1);
  168369. pCsr += nTarget+1;
  168370. }
  168371. p->zRbu = pCsr;
  168372. memcpy(p->zRbu, zRbu, nRbu+1);
  168373. pCsr += nRbu+1;
  168374. if( zState ){
  168375. p->zState = rbuMPrintf(p, "%s", zState);
  168376. }
  168377. /* If the first attempt to open the database file fails and the bRetry
  168378. ** flag it set, this means that the db was not opened because it seemed
  168379. ** to be a wal-mode db. But, this may have happened due to an earlier
  168380. ** RBU vacuum operation leaving an old wal file in the directory.
  168381. ** If this is the case, it will have been checkpointed and deleted
  168382. ** when the handle was closed and a second attempt to open the
  168383. ** database may succeed. */
  168384. rbuOpenDatabase(p, &bRetry);
  168385. if( bRetry ){
  168386. rbuOpenDatabase(p, 0);
  168387. }
  168388. }
  168389. if( p->rc==SQLITE_OK ){
  168390. pState = rbuLoadState(p);
  168391. assert( pState || p->rc!=SQLITE_OK );
  168392. if( p->rc==SQLITE_OK ){
  168393. if( pState->eStage==0 ){
  168394. rbuDeleteOalFile(p);
  168395. rbuInitPhaseOneSteps(p);
  168396. p->eStage = RBU_STAGE_OAL;
  168397. }else{
  168398. p->eStage = pState->eStage;
  168399. p->nPhaseOneStep = pState->nPhaseOneStep;
  168400. }
  168401. p->nProgress = pState->nProgress;
  168402. p->iOalSz = pState->iOalSz;
  168403. }
  168404. }
  168405. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  168406. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  168407. if( p->eStage==RBU_STAGE_OAL ){
  168408. p->rc = SQLITE_ERROR;
  168409. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  168410. }else if( p->eStage==RBU_STAGE_MOVE ){
  168411. p->eStage = RBU_STAGE_CKPT;
  168412. p->nStep = 0;
  168413. }
  168414. }
  168415. if( p->rc==SQLITE_OK
  168416. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  168417. && pState->eStage!=0
  168418. ){
  168419. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  168420. if( pFd->iCookie!=pState->iCookie ){
  168421. /* At this point (pTargetFd->iCookie) contains the value of the
  168422. ** change-counter cookie (the thing that gets incremented when a
  168423. ** transaction is committed in rollback mode) currently stored on
  168424. ** page 1 of the database file. */
  168425. p->rc = SQLITE_BUSY;
  168426. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  168427. (rbuIsVacuum(p) ? "vacuum" : "update")
  168428. );
  168429. }
  168430. }
  168431. if( p->rc==SQLITE_OK ){
  168432. if( p->eStage==RBU_STAGE_OAL ){
  168433. sqlite3 *db = p->dbMain;
  168434. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  168435. /* Point the object iterator at the first object */
  168436. if( p->rc==SQLITE_OK ){
  168437. p->rc = rbuObjIterFirst(p, &p->objiter);
  168438. }
  168439. /* If the RBU database contains no data_xxx tables, declare the RBU
  168440. ** update finished. */
  168441. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  168442. p->rc = SQLITE_DONE;
  168443. p->eStage = RBU_STAGE_DONE;
  168444. }else{
  168445. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  168446. rbuCopyPragma(p, "page_size");
  168447. rbuCopyPragma(p, "auto_vacuum");
  168448. }
  168449. /* Open transactions both databases. The *-oal file is opened or
  168450. ** created at this point. */
  168451. if( p->rc==SQLITE_OK ){
  168452. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  168453. }
  168454. /* Check if the main database is a zipvfs db. If it is, set the upper
  168455. ** level pager to use "journal_mode=off". This prevents it from
  168456. ** generating a large journal using a temp file. */
  168457. if( p->rc==SQLITE_OK ){
  168458. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  168459. if( frc==SQLITE_OK ){
  168460. p->rc = sqlite3_exec(
  168461. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  168462. }
  168463. }
  168464. if( p->rc==SQLITE_OK ){
  168465. rbuSetupOal(p, pState);
  168466. }
  168467. }
  168468. }else if( p->eStage==RBU_STAGE_MOVE ){
  168469. /* no-op */
  168470. }else if( p->eStage==RBU_STAGE_CKPT ){
  168471. rbuSetupCheckpoint(p, pState);
  168472. }else if( p->eStage==RBU_STAGE_DONE ){
  168473. p->rc = SQLITE_DONE;
  168474. }else{
  168475. p->rc = SQLITE_CORRUPT;
  168476. }
  168477. }
  168478. rbuFreeState(pState);
  168479. }
  168480. return p;
  168481. }
  168482. /*
  168483. ** Allocate and return an RBU handle with all fields zeroed except for the
  168484. ** error code, which is set to SQLITE_MISUSE.
  168485. */
  168486. static sqlite3rbu *rbuMisuseError(void){
  168487. sqlite3rbu *pRet;
  168488. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  168489. if( pRet ){
  168490. memset(pRet, 0, sizeof(sqlite3rbu));
  168491. pRet->rc = SQLITE_MISUSE;
  168492. }
  168493. return pRet;
  168494. }
  168495. /*
  168496. ** Open and return a new RBU handle.
  168497. */
  168498. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  168499. const char *zTarget,
  168500. const char *zRbu,
  168501. const char *zState
  168502. ){
  168503. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  168504. /* TODO: Check that zTarget and zRbu are non-NULL */
  168505. return openRbuHandle(zTarget, zRbu, zState);
  168506. }
  168507. /*
  168508. ** Open a handle to begin or resume an RBU VACUUM operation.
  168509. */
  168510. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  168511. const char *zTarget,
  168512. const char *zState
  168513. ){
  168514. if( zTarget==0 ){ return rbuMisuseError(); }
  168515. /* TODO: Check that both arguments are non-NULL */
  168516. return openRbuHandle(0, zTarget, zState);
  168517. }
  168518. /*
  168519. ** Return the database handle used by pRbu.
  168520. */
  168521. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  168522. sqlite3 *db = 0;
  168523. if( pRbu ){
  168524. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  168525. }
  168526. return db;
  168527. }
  168528. /*
  168529. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  168530. ** then edit any error message string so as to remove all occurrences of
  168531. ** the pattern "rbu_imp_[0-9]*".
  168532. */
  168533. static void rbuEditErrmsg(sqlite3rbu *p){
  168534. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  168535. unsigned int i;
  168536. size_t nErrmsg = strlen(p->zErrmsg);
  168537. for(i=0; i<(nErrmsg-8); i++){
  168538. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  168539. int nDel = 8;
  168540. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  168541. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  168542. nErrmsg -= nDel;
  168543. }
  168544. }
  168545. }
  168546. }
  168547. /*
  168548. ** Close the RBU handle.
  168549. */
  168550. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  168551. int rc;
  168552. if( p ){
  168553. /* Commit the transaction to the *-oal file. */
  168554. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  168555. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  168556. }
  168557. /* Sync the db file if currently doing an incremental checkpoint */
  168558. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  168559. sqlite3_file *pDb = p->pTargetFd->pReal;
  168560. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  168561. }
  168562. rbuSaveState(p, p->eStage);
  168563. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  168564. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  168565. }
  168566. /* Close any open statement handles. */
  168567. rbuObjIterFinalize(&p->objiter);
  168568. /* If this is an RBU vacuum handle and the vacuum has either finished
  168569. ** successfully or encountered an error, delete the contents of the
  168570. ** state table. This causes the next call to sqlite3rbu_vacuum()
  168571. ** specifying the current target and state databases to start a new
  168572. ** vacuum from scratch. */
  168573. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  168574. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  168575. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  168576. }
  168577. /* Close the open database handle and VFS object. */
  168578. sqlite3_close(p->dbRbu);
  168579. sqlite3_close(p->dbMain);
  168580. assert( p->szTemp==0 );
  168581. rbuDeleteVfs(p);
  168582. sqlite3_free(p->aBuf);
  168583. sqlite3_free(p->aFrame);
  168584. rbuEditErrmsg(p);
  168585. rc = p->rc;
  168586. if( pzErrmsg ){
  168587. *pzErrmsg = p->zErrmsg;
  168588. }else{
  168589. sqlite3_free(p->zErrmsg);
  168590. }
  168591. sqlite3_free(p->zState);
  168592. sqlite3_free(p);
  168593. }else{
  168594. rc = SQLITE_NOMEM;
  168595. *pzErrmsg = 0;
  168596. }
  168597. return rc;
  168598. }
  168599. /*
  168600. ** Return the total number of key-value operations (inserts, deletes or
  168601. ** updates) that have been performed on the target database since the
  168602. ** current RBU update was started.
  168603. */
  168604. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  168605. return pRbu->nProgress;
  168606. }
  168607. /*
  168608. ** Return permyriadage progress indications for the two main stages of
  168609. ** an RBU update.
  168610. */
  168611. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  168612. const int MAX_PROGRESS = 10000;
  168613. switch( p->eStage ){
  168614. case RBU_STAGE_OAL:
  168615. if( p->nPhaseOneStep>0 ){
  168616. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  168617. }else{
  168618. *pnOne = -1;
  168619. }
  168620. *pnTwo = 0;
  168621. break;
  168622. case RBU_STAGE_MOVE:
  168623. *pnOne = MAX_PROGRESS;
  168624. *pnTwo = 0;
  168625. break;
  168626. case RBU_STAGE_CKPT:
  168627. *pnOne = MAX_PROGRESS;
  168628. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  168629. break;
  168630. case RBU_STAGE_DONE:
  168631. *pnOne = MAX_PROGRESS;
  168632. *pnTwo = MAX_PROGRESS;
  168633. break;
  168634. default:
  168635. assert( 0 );
  168636. }
  168637. }
  168638. /*
  168639. ** Return the current state of the RBU vacuum or update operation.
  168640. */
  168641. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  168642. int aRes[] = {
  168643. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  168644. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  168645. };
  168646. assert( RBU_STAGE_OAL==1 );
  168647. assert( RBU_STAGE_MOVE==2 );
  168648. assert( RBU_STAGE_CKPT==4 );
  168649. assert( RBU_STAGE_DONE==5 );
  168650. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  168651. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  168652. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  168653. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  168654. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  168655. return SQLITE_RBU_STATE_ERROR;
  168656. }else{
  168657. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  168658. assert( p->eStage==RBU_STAGE_OAL
  168659. || p->eStage==RBU_STAGE_MOVE
  168660. || p->eStage==RBU_STAGE_CKPT
  168661. || p->eStage==RBU_STAGE_DONE
  168662. );
  168663. return aRes[p->eStage];
  168664. }
  168665. }
  168666. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  168667. int rc = p->rc;
  168668. if( rc==SQLITE_DONE ) return SQLITE_OK;
  168669. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  168670. if( p->eStage==RBU_STAGE_OAL ){
  168671. assert( rc!=SQLITE_DONE );
  168672. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  168673. }
  168674. /* Sync the db file */
  168675. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  168676. sqlite3_file *pDb = p->pTargetFd->pReal;
  168677. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  168678. }
  168679. p->rc = rc;
  168680. rbuSaveState(p, p->eStage);
  168681. rc = p->rc;
  168682. if( p->eStage==RBU_STAGE_OAL ){
  168683. assert( rc!=SQLITE_DONE );
  168684. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  168685. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  168686. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  168687. }
  168688. p->rc = rc;
  168689. return rc;
  168690. }
  168691. /**************************************************************************
  168692. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  168693. ** of a standard VFS in the following ways:
  168694. **
  168695. ** 1. Whenever the first page of a main database file is read or
  168696. ** written, the value of the change-counter cookie is stored in
  168697. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  168698. ** database header field is stored in rbu_file.iWriteVer. This ensures
  168699. ** that the values are always trustworthy within an open transaction.
  168700. **
  168701. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  168702. ** member variable of the associated database file descriptor is set
  168703. ** to point to the new file. A mutex protected linked list of all main
  168704. ** db fds opened using a particular RBU VFS is maintained at
  168705. ** rbu_vfs.pMain to facilitate this.
  168706. **
  168707. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  168708. ** object can be marked as the target database of an RBU update. This
  168709. ** turns on the following extra special behaviour:
  168710. **
  168711. ** 3a. If xAccess() is called to check if there exists a *-wal file
  168712. ** associated with an RBU target database currently in RBU_STAGE_OAL
  168713. ** stage (preparing the *-oal file), the following special handling
  168714. ** applies:
  168715. **
  168716. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  168717. ** target database may not be in wal mode already.
  168718. **
  168719. ** * if the *-wal file does not exist, set the output parameter to
  168720. ** non-zero (to tell SQLite that it does exist) anyway.
  168721. **
  168722. ** Then, when xOpen() is called to open the *-wal file associated with
  168723. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  168724. ** file, the rbu vfs opens the corresponding *-oal file instead.
  168725. **
  168726. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  168727. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  168728. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  168729. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  168730. ** because assert() statements in some VFS implementations fail if
  168731. ** xShmLock() is called before xShmMap().
  168732. **
  168733. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  168734. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  168735. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  168736. ** from automatically checkpointing a *-wal (or *-oal) file from within
  168737. ** sqlite3_close().
  168738. **
  168739. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  168740. ** all xWrite() calls on the target database file perform no IO.
  168741. ** Instead the frame and page numbers that would be read and written
  168742. ** are recorded. Additionally, successful attempts to obtain exclusive
  168743. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  168744. ** database file are recorded. xShmLock() calls to unlock the same
  168745. ** locks are no-ops (so that once obtained, these locks are never
  168746. ** relinquished). Finally, calls to xSync() on the target database
  168747. ** file fail with SQLITE_INTERNAL errors.
  168748. */
  168749. static void rbuUnlockShm(rbu_file *p){
  168750. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  168751. if( p->pRbu ){
  168752. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  168753. int i;
  168754. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  168755. if( (1<<i) & p->pRbu->mLock ){
  168756. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  168757. }
  168758. }
  168759. p->pRbu->mLock = 0;
  168760. }
  168761. }
  168762. /*
  168763. */
  168764. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  168765. sqlite3rbu *pRbu = pFd->pRbu;
  168766. i64 nDiff = nNew - pFd->sz;
  168767. pRbu->szTemp += nDiff;
  168768. pFd->sz = nNew;
  168769. assert( pRbu->szTemp>=0 );
  168770. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  168771. return SQLITE_OK;
  168772. }
  168773. /*
  168774. ** Close an rbu file.
  168775. */
  168776. static int rbuVfsClose(sqlite3_file *pFile){
  168777. rbu_file *p = (rbu_file*)pFile;
  168778. int rc;
  168779. int i;
  168780. /* Free the contents of the apShm[] array. And the array itself. */
  168781. for(i=0; i<p->nShm; i++){
  168782. sqlite3_free(p->apShm[i]);
  168783. }
  168784. sqlite3_free(p->apShm);
  168785. p->apShm = 0;
  168786. sqlite3_free(p->zDel);
  168787. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  168788. rbu_file **pp;
  168789. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  168790. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  168791. *pp = p->pMainNext;
  168792. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  168793. rbuUnlockShm(p);
  168794. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  168795. }
  168796. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  168797. rbuUpdateTempSize(p, 0);
  168798. }
  168799. /* Close the underlying file handle */
  168800. rc = p->pReal->pMethods->xClose(p->pReal);
  168801. return rc;
  168802. }
  168803. /*
  168804. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  168805. ** passed as the only argument.
  168806. */
  168807. static u32 rbuGetU32(u8 *aBuf){
  168808. return ((u32)aBuf[0] << 24)
  168809. + ((u32)aBuf[1] << 16)
  168810. + ((u32)aBuf[2] << 8)
  168811. + ((u32)aBuf[3]);
  168812. }
  168813. /*
  168814. ** Write an unsigned 32-bit value in big-endian format to the supplied
  168815. ** buffer.
  168816. */
  168817. static void rbuPutU32(u8 *aBuf, u32 iVal){
  168818. aBuf[0] = (iVal >> 24) & 0xFF;
  168819. aBuf[1] = (iVal >> 16) & 0xFF;
  168820. aBuf[2] = (iVal >> 8) & 0xFF;
  168821. aBuf[3] = (iVal >> 0) & 0xFF;
  168822. }
  168823. static void rbuPutU16(u8 *aBuf, u16 iVal){
  168824. aBuf[0] = (iVal >> 8) & 0xFF;
  168825. aBuf[1] = (iVal >> 0) & 0xFF;
  168826. }
  168827. /*
  168828. ** Read data from an rbuVfs-file.
  168829. */
  168830. static int rbuVfsRead(
  168831. sqlite3_file *pFile,
  168832. void *zBuf,
  168833. int iAmt,
  168834. sqlite_int64 iOfst
  168835. ){
  168836. rbu_file *p = (rbu_file*)pFile;
  168837. sqlite3rbu *pRbu = p->pRbu;
  168838. int rc;
  168839. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  168840. assert( p->openFlags & SQLITE_OPEN_WAL );
  168841. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  168842. }else{
  168843. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  168844. && (p->openFlags & SQLITE_OPEN_WAL)
  168845. && iOfst>=pRbu->iOalSz
  168846. ){
  168847. rc = SQLITE_OK;
  168848. memset(zBuf, 0, iAmt);
  168849. }else{
  168850. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  168851. #if 1
  168852. /* If this is being called to read the first page of the target
  168853. ** database as part of an rbu vacuum operation, synthesize the
  168854. ** contents of the first page if it does not yet exist. Otherwise,
  168855. ** SQLite will not check for a *-wal file. */
  168856. if( pRbu && rbuIsVacuum(pRbu)
  168857. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  168858. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  168859. && pRbu->rc==SQLITE_OK
  168860. ){
  168861. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  168862. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  168863. if( rc==SQLITE_OK ){
  168864. u8 *aBuf = (u8*)zBuf;
  168865. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  168866. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  168867. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  168868. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  168869. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  168870. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  168871. if( iAmt>100 ){
  168872. memset(&aBuf[100], 0, iAmt-100);
  168873. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  168874. aBuf[100] = 0x0D;
  168875. }
  168876. }
  168877. }
  168878. #endif
  168879. }
  168880. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  168881. /* These look like magic numbers. But they are stable, as they are part
  168882. ** of the definition of the SQLite file format, which may not change. */
  168883. u8 *pBuf = (u8*)zBuf;
  168884. p->iCookie = rbuGetU32(&pBuf[24]);
  168885. p->iWriteVer = pBuf[19];
  168886. }
  168887. }
  168888. return rc;
  168889. }
  168890. /*
  168891. ** Write data to an rbuVfs-file.
  168892. */
  168893. static int rbuVfsWrite(
  168894. sqlite3_file *pFile,
  168895. const void *zBuf,
  168896. int iAmt,
  168897. sqlite_int64 iOfst
  168898. ){
  168899. rbu_file *p = (rbu_file*)pFile;
  168900. sqlite3rbu *pRbu = p->pRbu;
  168901. int rc;
  168902. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  168903. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  168904. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  168905. }else{
  168906. if( pRbu ){
  168907. if( pRbu->eStage==RBU_STAGE_OAL
  168908. && (p->openFlags & SQLITE_OPEN_WAL)
  168909. && iOfst>=pRbu->iOalSz
  168910. ){
  168911. pRbu->iOalSz = iAmt + iOfst;
  168912. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  168913. i64 szNew = iAmt+iOfst;
  168914. if( szNew>p->sz ){
  168915. rc = rbuUpdateTempSize(p, szNew);
  168916. if( rc!=SQLITE_OK ) return rc;
  168917. }
  168918. }
  168919. }
  168920. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  168921. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  168922. /* These look like magic numbers. But they are stable, as they are part
  168923. ** of the definition of the SQLite file format, which may not change. */
  168924. u8 *pBuf = (u8*)zBuf;
  168925. p->iCookie = rbuGetU32(&pBuf[24]);
  168926. p->iWriteVer = pBuf[19];
  168927. }
  168928. }
  168929. return rc;
  168930. }
  168931. /*
  168932. ** Truncate an rbuVfs-file.
  168933. */
  168934. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  168935. rbu_file *p = (rbu_file*)pFile;
  168936. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  168937. int rc = rbuUpdateTempSize(p, size);
  168938. if( rc!=SQLITE_OK ) return rc;
  168939. }
  168940. return p->pReal->pMethods->xTruncate(p->pReal, size);
  168941. }
  168942. /*
  168943. ** Sync an rbuVfs-file.
  168944. */
  168945. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  168946. rbu_file *p = (rbu_file *)pFile;
  168947. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  168948. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  168949. return SQLITE_INTERNAL;
  168950. }
  168951. return SQLITE_OK;
  168952. }
  168953. return p->pReal->pMethods->xSync(p->pReal, flags);
  168954. }
  168955. /*
  168956. ** Return the current file-size of an rbuVfs-file.
  168957. */
  168958. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  168959. rbu_file *p = (rbu_file *)pFile;
  168960. int rc;
  168961. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  168962. /* If this is an RBU vacuum operation and this is the target database,
  168963. ** pretend that it has at least one page. Otherwise, SQLite will not
  168964. ** check for the existance of a *-wal file. rbuVfsRead() contains
  168965. ** similar logic. */
  168966. if( rc==SQLITE_OK && *pSize==0
  168967. && p->pRbu && rbuIsVacuum(p->pRbu)
  168968. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  168969. ){
  168970. *pSize = 1024;
  168971. }
  168972. return rc;
  168973. }
  168974. /*
  168975. ** Lock an rbuVfs-file.
  168976. */
  168977. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  168978. rbu_file *p = (rbu_file*)pFile;
  168979. sqlite3rbu *pRbu = p->pRbu;
  168980. int rc = SQLITE_OK;
  168981. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  168982. if( eLock==SQLITE_LOCK_EXCLUSIVE
  168983. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  168984. ){
  168985. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  168986. ** prevents it from checkpointing the database from sqlite3_close(). */
  168987. rc = SQLITE_BUSY;
  168988. }else{
  168989. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  168990. }
  168991. return rc;
  168992. }
  168993. /*
  168994. ** Unlock an rbuVfs-file.
  168995. */
  168996. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  168997. rbu_file *p = (rbu_file *)pFile;
  168998. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  168999. }
  169000. /*
  169001. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  169002. */
  169003. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  169004. rbu_file *p = (rbu_file *)pFile;
  169005. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  169006. }
  169007. /*
  169008. ** File control method. For custom operations on an rbuVfs-file.
  169009. */
  169010. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  169011. rbu_file *p = (rbu_file *)pFile;
  169012. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  169013. int rc;
  169014. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  169015. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  169016. );
  169017. if( op==SQLITE_FCNTL_RBU ){
  169018. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  169019. /* First try to find another RBU vfs lower down in the vfs stack. If
  169020. ** one is found, this vfs will operate in pass-through mode. The lower
  169021. ** level vfs will do the special RBU handling. */
  169022. rc = xControl(p->pReal, op, pArg);
  169023. if( rc==SQLITE_NOTFOUND ){
  169024. /* Now search for a zipvfs instance lower down in the VFS stack. If
  169025. ** one is found, this is an error. */
  169026. void *dummy = 0;
  169027. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  169028. if( rc==SQLITE_OK ){
  169029. rc = SQLITE_ERROR;
  169030. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  169031. }else if( rc==SQLITE_NOTFOUND ){
  169032. pRbu->pTargetFd = p;
  169033. p->pRbu = pRbu;
  169034. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  169035. rc = SQLITE_OK;
  169036. }
  169037. }
  169038. return rc;
  169039. }
  169040. else if( op==SQLITE_FCNTL_RBUCNT ){
  169041. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  169042. pRbu->nRbu++;
  169043. pRbu->pRbuFd = p;
  169044. p->bNolock = 1;
  169045. }
  169046. rc = xControl(p->pReal, op, pArg);
  169047. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  169048. rbu_vfs *pRbuVfs = p->pRbuVfs;
  169049. char *zIn = *(char**)pArg;
  169050. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  169051. *(char**)pArg = zOut;
  169052. if( zOut==0 ) rc = SQLITE_NOMEM;
  169053. }
  169054. return rc;
  169055. }
  169056. /*
  169057. ** Return the sector-size in bytes for an rbuVfs-file.
  169058. */
  169059. static int rbuVfsSectorSize(sqlite3_file *pFile){
  169060. rbu_file *p = (rbu_file *)pFile;
  169061. return p->pReal->pMethods->xSectorSize(p->pReal);
  169062. }
  169063. /*
  169064. ** Return the device characteristic flags supported by an rbuVfs-file.
  169065. */
  169066. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  169067. rbu_file *p = (rbu_file *)pFile;
  169068. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  169069. }
  169070. /*
  169071. ** Take or release a shared-memory lock.
  169072. */
  169073. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  169074. rbu_file *p = (rbu_file*)pFile;
  169075. sqlite3rbu *pRbu = p->pRbu;
  169076. int rc = SQLITE_OK;
  169077. #ifdef SQLITE_AMALGAMATION
  169078. assert( WAL_CKPT_LOCK==1 );
  169079. #endif
  169080. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  169081. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  169082. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  169083. ** taking this lock also prevents any checkpoints from occurring.
  169084. ** todo: really, it's not clear why this might occur, as
  169085. ** wal_autocheckpoint ought to be turned off. */
  169086. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  169087. }else{
  169088. int bCapture = 0;
  169089. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  169090. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  169091. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  169092. ){
  169093. bCapture = 1;
  169094. }
  169095. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  169096. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  169097. if( bCapture && rc==SQLITE_OK ){
  169098. pRbu->mLock |= (1 << ofst);
  169099. }
  169100. }
  169101. }
  169102. return rc;
  169103. }
  169104. /*
  169105. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  169106. */
  169107. static int rbuVfsShmMap(
  169108. sqlite3_file *pFile,
  169109. int iRegion,
  169110. int szRegion,
  169111. int isWrite,
  169112. void volatile **pp
  169113. ){
  169114. rbu_file *p = (rbu_file*)pFile;
  169115. int rc = SQLITE_OK;
  169116. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  169117. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  169118. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  169119. ** instead of a file on disk. */
  169120. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  169121. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  169122. if( iRegion<=p->nShm ){
  169123. int nByte = (iRegion+1) * sizeof(char*);
  169124. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  169125. if( apNew==0 ){
  169126. rc = SQLITE_NOMEM;
  169127. }else{
  169128. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  169129. p->apShm = apNew;
  169130. p->nShm = iRegion+1;
  169131. }
  169132. }
  169133. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  169134. char *pNew = (char*)sqlite3_malloc64(szRegion);
  169135. if( pNew==0 ){
  169136. rc = SQLITE_NOMEM;
  169137. }else{
  169138. memset(pNew, 0, szRegion);
  169139. p->apShm[iRegion] = pNew;
  169140. }
  169141. }
  169142. if( rc==SQLITE_OK ){
  169143. *pp = p->apShm[iRegion];
  169144. }else{
  169145. *pp = 0;
  169146. }
  169147. }else{
  169148. assert( p->apShm==0 );
  169149. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  169150. }
  169151. return rc;
  169152. }
  169153. /*
  169154. ** Memory barrier.
  169155. */
  169156. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  169157. rbu_file *p = (rbu_file *)pFile;
  169158. p->pReal->pMethods->xShmBarrier(p->pReal);
  169159. }
  169160. /*
  169161. ** The xShmUnmap method.
  169162. */
  169163. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  169164. rbu_file *p = (rbu_file*)pFile;
  169165. int rc = SQLITE_OK;
  169166. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  169167. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  169168. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  169169. /* no-op */
  169170. }else{
  169171. /* Release the checkpointer and writer locks */
  169172. rbuUnlockShm(p);
  169173. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  169174. }
  169175. return rc;
  169176. }
  169177. /*
  169178. ** Given that zWal points to a buffer containing a wal file name passed to
  169179. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  169180. ** file-handle opened by the same database connection on the corresponding
  169181. ** database file.
  169182. */
  169183. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  169184. rbu_file *pDb;
  169185. sqlite3_mutex_enter(pRbuVfs->mutex);
  169186. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  169187. sqlite3_mutex_leave(pRbuVfs->mutex);
  169188. return pDb;
  169189. }
  169190. /*
  169191. ** A main database named zName has just been opened. The following
  169192. ** function returns a pointer to a buffer owned by SQLite that contains
  169193. ** the name of the *-wal file this db connection will use. SQLite
  169194. ** happens to pass a pointer to this buffer when using xAccess()
  169195. ** or xOpen() to operate on the *-wal file.
  169196. */
  169197. static const char *rbuMainToWal(const char *zName, int flags){
  169198. int n = (int)strlen(zName);
  169199. const char *z = &zName[n];
  169200. if( flags & SQLITE_OPEN_URI ){
  169201. int odd = 0;
  169202. while( 1 ){
  169203. if( z[0]==0 ){
  169204. odd = 1 - odd;
  169205. if( odd && z[1]==0 ) break;
  169206. }
  169207. z++;
  169208. }
  169209. z += 2;
  169210. }else{
  169211. while( *z==0 ) z++;
  169212. }
  169213. z += (n + 8 + 1);
  169214. return z;
  169215. }
  169216. /*
  169217. ** Open an rbu file handle.
  169218. */
  169219. static int rbuVfsOpen(
  169220. sqlite3_vfs *pVfs,
  169221. const char *zName,
  169222. sqlite3_file *pFile,
  169223. int flags,
  169224. int *pOutFlags
  169225. ){
  169226. static sqlite3_io_methods rbuvfs_io_methods = {
  169227. 2, /* iVersion */
  169228. rbuVfsClose, /* xClose */
  169229. rbuVfsRead, /* xRead */
  169230. rbuVfsWrite, /* xWrite */
  169231. rbuVfsTruncate, /* xTruncate */
  169232. rbuVfsSync, /* xSync */
  169233. rbuVfsFileSize, /* xFileSize */
  169234. rbuVfsLock, /* xLock */
  169235. rbuVfsUnlock, /* xUnlock */
  169236. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  169237. rbuVfsFileControl, /* xFileControl */
  169238. rbuVfsSectorSize, /* xSectorSize */
  169239. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  169240. rbuVfsShmMap, /* xShmMap */
  169241. rbuVfsShmLock, /* xShmLock */
  169242. rbuVfsShmBarrier, /* xShmBarrier */
  169243. rbuVfsShmUnmap, /* xShmUnmap */
  169244. 0, 0 /* xFetch, xUnfetch */
  169245. };
  169246. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  169247. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  169248. rbu_file *pFd = (rbu_file *)pFile;
  169249. int rc = SQLITE_OK;
  169250. const char *zOpen = zName;
  169251. int oflags = flags;
  169252. memset(pFd, 0, sizeof(rbu_file));
  169253. pFd->pReal = (sqlite3_file*)&pFd[1];
  169254. pFd->pRbuVfs = pRbuVfs;
  169255. pFd->openFlags = flags;
  169256. if( zName ){
  169257. if( flags & SQLITE_OPEN_MAIN_DB ){
  169258. /* A main database has just been opened. The following block sets
  169259. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  169260. ** the name of the *-wal file this db connection will use. SQLite
  169261. ** happens to pass a pointer to this buffer when using xAccess()
  169262. ** or xOpen() to operate on the *-wal file. */
  169263. pFd->zWal = rbuMainToWal(zName, flags);
  169264. }
  169265. else if( flags & SQLITE_OPEN_WAL ){
  169266. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  169267. if( pDb ){
  169268. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  169269. /* This call is to open a *-wal file. Intead, open the *-oal. This
  169270. ** code ensures that the string passed to xOpen() is terminated by a
  169271. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  169272. ** parameter from it. */
  169273. const char *zBase = zName;
  169274. size_t nCopy;
  169275. char *zCopy;
  169276. if( rbuIsVacuum(pDb->pRbu) ){
  169277. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  169278. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  169279. }
  169280. nCopy = strlen(zBase);
  169281. zCopy = sqlite3_malloc64(nCopy+2);
  169282. if( zCopy ){
  169283. memcpy(zCopy, zBase, nCopy);
  169284. zCopy[nCopy-3] = 'o';
  169285. zCopy[nCopy] = '\0';
  169286. zCopy[nCopy+1] = '\0';
  169287. zOpen = (const char*)(pFd->zDel = zCopy);
  169288. }else{
  169289. rc = SQLITE_NOMEM;
  169290. }
  169291. pFd->pRbu = pDb->pRbu;
  169292. }
  169293. pDb->pWalFd = pFd;
  169294. }
  169295. }
  169296. }else{
  169297. pFd->pRbu = pRbuVfs->pRbu;
  169298. }
  169299. if( oflags & SQLITE_OPEN_MAIN_DB
  169300. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  169301. ){
  169302. assert( oflags & SQLITE_OPEN_MAIN_DB );
  169303. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  169304. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  169305. zOpen = 0;
  169306. }
  169307. if( rc==SQLITE_OK ){
  169308. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  169309. }
  169310. if( pFd->pReal->pMethods ){
  169311. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  169312. ** pointer and, if the file is a main database file, link it into the
  169313. ** mutex protected linked list of all such files. */
  169314. pFile->pMethods = &rbuvfs_io_methods;
  169315. if( flags & SQLITE_OPEN_MAIN_DB ){
  169316. sqlite3_mutex_enter(pRbuVfs->mutex);
  169317. pFd->pMainNext = pRbuVfs->pMain;
  169318. pRbuVfs->pMain = pFd;
  169319. sqlite3_mutex_leave(pRbuVfs->mutex);
  169320. }
  169321. }else{
  169322. sqlite3_free(pFd->zDel);
  169323. }
  169324. return rc;
  169325. }
  169326. /*
  169327. ** Delete the file located at zPath.
  169328. */
  169329. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  169330. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169331. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  169332. }
  169333. /*
  169334. ** Test for access permissions. Return true if the requested permission
  169335. ** is available, or false otherwise.
  169336. */
  169337. static int rbuVfsAccess(
  169338. sqlite3_vfs *pVfs,
  169339. const char *zPath,
  169340. int flags,
  169341. int *pResOut
  169342. ){
  169343. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  169344. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  169345. int rc;
  169346. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  169347. /* If this call is to check if a *-wal file associated with an RBU target
  169348. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  169349. ** the following special handling is activated:
  169350. **
  169351. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  169352. ** ensures that the RBU extension never tries to update a database
  169353. ** in wal mode, even if the first page of the database file has
  169354. ** been damaged.
  169355. **
  169356. ** b) if the *-wal file does not exist, claim that it does anyway,
  169357. ** causing SQLite to call xOpen() to open it. This call will also
  169358. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  169359. ** file opened instead.
  169360. */
  169361. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  169362. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  169363. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  169364. if( *pResOut ){
  169365. rc = SQLITE_CANTOPEN;
  169366. }else{
  169367. sqlite3_int64 sz = 0;
  169368. rc = rbuVfsFileSize(&pDb->base, &sz);
  169369. *pResOut = (sz>0);
  169370. }
  169371. }
  169372. }
  169373. return rc;
  169374. }
  169375. /*
  169376. ** Populate buffer zOut with the full canonical pathname corresponding
  169377. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  169378. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  169379. */
  169380. static int rbuVfsFullPathname(
  169381. sqlite3_vfs *pVfs,
  169382. const char *zPath,
  169383. int nOut,
  169384. char *zOut
  169385. ){
  169386. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169387. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  169388. }
  169389. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  169390. /*
  169391. ** Open the dynamic library located at zPath and return a handle.
  169392. */
  169393. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  169394. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169395. return pRealVfs->xDlOpen(pRealVfs, zPath);
  169396. }
  169397. /*
  169398. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  169399. ** utf-8 string describing the most recent error encountered associated
  169400. ** with dynamic libraries.
  169401. */
  169402. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  169403. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169404. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  169405. }
  169406. /*
  169407. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  169408. */
  169409. static void (*rbuVfsDlSym(
  169410. sqlite3_vfs *pVfs,
  169411. void *pArg,
  169412. const char *zSym
  169413. ))(void){
  169414. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169415. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  169416. }
  169417. /*
  169418. ** Close the dynamic library handle pHandle.
  169419. */
  169420. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  169421. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169422. pRealVfs->xDlClose(pRealVfs, pHandle);
  169423. }
  169424. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  169425. /*
  169426. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  169427. ** random data.
  169428. */
  169429. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  169430. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169431. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  169432. }
  169433. /*
  169434. ** Sleep for nMicro microseconds. Return the number of microseconds
  169435. ** actually slept.
  169436. */
  169437. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  169438. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169439. return pRealVfs->xSleep(pRealVfs, nMicro);
  169440. }
  169441. /*
  169442. ** Return the current time as a Julian Day number in *pTimeOut.
  169443. */
  169444. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  169445. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  169446. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  169447. }
  169448. /*
  169449. ** No-op.
  169450. */
  169451. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  169452. return 0;
  169453. }
  169454. /*
  169455. ** Deregister and destroy an RBU vfs created by an earlier call to
  169456. ** sqlite3rbu_create_vfs().
  169457. */
  169458. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  169459. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  169460. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  169461. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  169462. sqlite3_vfs_unregister(pVfs);
  169463. sqlite3_free(pVfs);
  169464. }
  169465. }
  169466. /*
  169467. ** Create an RBU VFS named zName that accesses the underlying file-system
  169468. ** via existing VFS zParent. The new object is registered as a non-default
  169469. ** VFS with SQLite before returning.
  169470. */
  169471. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  169472. /* Template for VFS */
  169473. static sqlite3_vfs vfs_template = {
  169474. 1, /* iVersion */
  169475. 0, /* szOsFile */
  169476. 0, /* mxPathname */
  169477. 0, /* pNext */
  169478. 0, /* zName */
  169479. 0, /* pAppData */
  169480. rbuVfsOpen, /* xOpen */
  169481. rbuVfsDelete, /* xDelete */
  169482. rbuVfsAccess, /* xAccess */
  169483. rbuVfsFullPathname, /* xFullPathname */
  169484. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  169485. rbuVfsDlOpen, /* xDlOpen */
  169486. rbuVfsDlError, /* xDlError */
  169487. rbuVfsDlSym, /* xDlSym */
  169488. rbuVfsDlClose, /* xDlClose */
  169489. #else
  169490. 0, 0, 0, 0,
  169491. #endif
  169492. rbuVfsRandomness, /* xRandomness */
  169493. rbuVfsSleep, /* xSleep */
  169494. rbuVfsCurrentTime, /* xCurrentTime */
  169495. rbuVfsGetLastError, /* xGetLastError */
  169496. 0, /* xCurrentTimeInt64 (version 2) */
  169497. 0, 0, 0 /* Unimplemented version 3 methods */
  169498. };
  169499. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  169500. int rc = SQLITE_OK;
  169501. size_t nName;
  169502. size_t nByte;
  169503. nName = strlen(zName);
  169504. nByte = sizeof(rbu_vfs) + nName + 1;
  169505. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  169506. if( pNew==0 ){
  169507. rc = SQLITE_NOMEM;
  169508. }else{
  169509. sqlite3_vfs *pParent; /* Parent VFS */
  169510. memset(pNew, 0, nByte);
  169511. pParent = sqlite3_vfs_find(zParent);
  169512. if( pParent==0 ){
  169513. rc = SQLITE_NOTFOUND;
  169514. }else{
  169515. char *zSpace;
  169516. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  169517. pNew->base.mxPathname = pParent->mxPathname;
  169518. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  169519. pNew->pRealVfs = pParent;
  169520. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  169521. memcpy(zSpace, zName, nName);
  169522. /* Allocate the mutex and register the new VFS (not as the default) */
  169523. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  169524. if( pNew->mutex==0 ){
  169525. rc = SQLITE_NOMEM;
  169526. }else{
  169527. rc = sqlite3_vfs_register(&pNew->base, 0);
  169528. }
  169529. }
  169530. if( rc!=SQLITE_OK ){
  169531. sqlite3_mutex_free(pNew->mutex);
  169532. sqlite3_free(pNew);
  169533. }
  169534. }
  169535. return rc;
  169536. }
  169537. /*
  169538. ** Configure the aggregate temp file size limit for this RBU handle.
  169539. */
  169540. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  169541. if( n>=0 ){
  169542. pRbu->szTempLimit = n;
  169543. }
  169544. return pRbu->szTempLimit;
  169545. }
  169546. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  169547. return pRbu->szTemp;
  169548. }
  169549. /**************************************************************************/
  169550. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  169551. /************** End of sqlite3rbu.c ******************************************/
  169552. /************** Begin file dbstat.c ******************************************/
  169553. /*
  169554. ** 2010 July 12
  169555. **
  169556. ** The author disclaims copyright to this source code. In place of
  169557. ** a legal notice, here is a blessing:
  169558. **
  169559. ** May you do good and not evil.
  169560. ** May you find forgiveness for yourself and forgive others.
  169561. ** May you share freely, never taking more than you give.
  169562. **
  169563. ******************************************************************************
  169564. **
  169565. ** This file contains an implementation of the "dbstat" virtual table.
  169566. **
  169567. ** The dbstat virtual table is used to extract low-level formatting
  169568. ** information from an SQLite database in order to implement the
  169569. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  169570. ** for an example implementation.
  169571. **
  169572. ** Additional information is available on the "dbstat.html" page of the
  169573. ** official SQLite documentation.
  169574. */
  169575. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  169576. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  169577. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  169578. /*
  169579. ** Page paths:
  169580. **
  169581. ** The value of the 'path' column describes the path taken from the
  169582. ** root-node of the b-tree structure to each page. The value of the
  169583. ** root-node path is '/'.
  169584. **
  169585. ** The value of the path for the left-most child page of the root of
  169586. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  169587. ** so the pages to the left have smaller keys than the pages to the right.)
  169588. ** The next to left-most child of the root page is
  169589. ** '/001', and so on, each sibling page identified by a 3-digit hex
  169590. ** value. The children of the 451st left-most sibling have paths such
  169591. ** as '/1c2/000/, '/1c2/001/' etc.
  169592. **
  169593. ** Overflow pages are specified by appending a '+' character and a
  169594. ** six-digit hexadecimal value to the path to the cell they are linked
  169595. ** from. For example, the three overflow pages in a chain linked from
  169596. ** the left-most cell of the 450th child of the root page are identified
  169597. ** by the paths:
  169598. **
  169599. ** '/1c2/000+000000' // First page in overflow chain
  169600. ** '/1c2/000+000001' // Second page in overflow chain
  169601. ** '/1c2/000+000002' // Third page in overflow chain
  169602. **
  169603. ** If the paths are sorted using the BINARY collation sequence, then
  169604. ** the overflow pages associated with a cell will appear earlier in the
  169605. ** sort-order than its child page:
  169606. **
  169607. ** '/1c2/000/' // Left-most child of 451st child of root
  169608. */
  169609. #define VTAB_SCHEMA \
  169610. "CREATE TABLE xx( " \
  169611. " name TEXT, /* Name of table or index */" \
  169612. " path TEXT, /* Path to page from root */" \
  169613. " pageno INTEGER, /* Page number */" \
  169614. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  169615. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  169616. " payload INTEGER, /* Bytes of payload on this page */" \
  169617. " unused INTEGER, /* Bytes of unused space on this page */" \
  169618. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  169619. " pgoffset INTEGER, /* Offset of page in file */" \
  169620. " pgsize INTEGER, /* Size of the page */" \
  169621. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  169622. ");"
  169623. typedef struct StatTable StatTable;
  169624. typedef struct StatCursor StatCursor;
  169625. typedef struct StatPage StatPage;
  169626. typedef struct StatCell StatCell;
  169627. struct StatCell {
  169628. int nLocal; /* Bytes of local payload */
  169629. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  169630. int nOvfl; /* Entries in aOvfl[] */
  169631. u32 *aOvfl; /* Array of overflow page numbers */
  169632. int nLastOvfl; /* Bytes of payload on final overflow page */
  169633. int iOvfl; /* Iterates through aOvfl[] */
  169634. };
  169635. struct StatPage {
  169636. u32 iPgno;
  169637. DbPage *pPg;
  169638. int iCell;
  169639. char *zPath; /* Path to this page */
  169640. /* Variables populated by statDecodePage(): */
  169641. u8 flags; /* Copy of flags byte */
  169642. int nCell; /* Number of cells on page */
  169643. int nUnused; /* Number of unused bytes on page */
  169644. StatCell *aCell; /* Array of parsed cells */
  169645. u32 iRightChildPg; /* Right-child page number (or 0) */
  169646. int nMxPayload; /* Largest payload of any cell on this page */
  169647. };
  169648. struct StatCursor {
  169649. sqlite3_vtab_cursor base;
  169650. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  169651. int isEof; /* After pStmt has returned SQLITE_DONE */
  169652. int iDb; /* Schema used for this query */
  169653. StatPage aPage[32];
  169654. int iPage; /* Current entry in aPage[] */
  169655. /* Values to return. */
  169656. char *zName; /* Value of 'name' column */
  169657. char *zPath; /* Value of 'path' column */
  169658. u32 iPageno; /* Value of 'pageno' column */
  169659. char *zPagetype; /* Value of 'pagetype' column */
  169660. int nCell; /* Value of 'ncell' column */
  169661. int nPayload; /* Value of 'payload' column */
  169662. int nUnused; /* Value of 'unused' column */
  169663. int nMxPayload; /* Value of 'mx_payload' column */
  169664. i64 iOffset; /* Value of 'pgOffset' column */
  169665. int szPage; /* Value of 'pgSize' column */
  169666. };
  169667. struct StatTable {
  169668. sqlite3_vtab base;
  169669. sqlite3 *db;
  169670. int iDb; /* Index of database to analyze */
  169671. };
  169672. #ifndef get2byte
  169673. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  169674. #endif
  169675. /*
  169676. ** Connect to or create a statvfs virtual table.
  169677. */
  169678. static int statConnect(
  169679. sqlite3 *db,
  169680. void *pAux,
  169681. int argc, const char *const*argv,
  169682. sqlite3_vtab **ppVtab,
  169683. char **pzErr
  169684. ){
  169685. StatTable *pTab = 0;
  169686. int rc = SQLITE_OK;
  169687. int iDb;
  169688. if( argc>=4 ){
  169689. Token nm;
  169690. sqlite3TokenInit(&nm, (char*)argv[3]);
  169691. iDb = sqlite3FindDb(db, &nm);
  169692. if( iDb<0 ){
  169693. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  169694. return SQLITE_ERROR;
  169695. }
  169696. }else{
  169697. iDb = 0;
  169698. }
  169699. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  169700. if( rc==SQLITE_OK ){
  169701. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  169702. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  169703. }
  169704. assert( rc==SQLITE_OK || pTab==0 );
  169705. if( rc==SQLITE_OK ){
  169706. memset(pTab, 0, sizeof(StatTable));
  169707. pTab->db = db;
  169708. pTab->iDb = iDb;
  169709. }
  169710. *ppVtab = (sqlite3_vtab*)pTab;
  169711. return rc;
  169712. }
  169713. /*
  169714. ** Disconnect from or destroy a statvfs virtual table.
  169715. */
  169716. static int statDisconnect(sqlite3_vtab *pVtab){
  169717. sqlite3_free(pVtab);
  169718. return SQLITE_OK;
  169719. }
  169720. /*
  169721. ** There is no "best-index". This virtual table always does a linear
  169722. ** scan. However, a schema=? constraint should cause this table to
  169723. ** operate on a different database schema, so check for it.
  169724. **
  169725. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  169726. */
  169727. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  169728. int i;
  169729. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  169730. /* Look for a valid schema=? constraint. If found, change the idxNum to
  169731. ** 1 and request the value of that constraint be sent to xFilter. And
  169732. ** lower the cost estimate to encourage the constrained version to be
  169733. ** used.
  169734. */
  169735. for(i=0; i<pIdxInfo->nConstraint; i++){
  169736. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  169737. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  169738. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  169739. pIdxInfo->idxNum = 1;
  169740. pIdxInfo->estimatedCost = 1.0;
  169741. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  169742. pIdxInfo->aConstraintUsage[i].omit = 1;
  169743. break;
  169744. }
  169745. /* Records are always returned in ascending order of (name, path).
  169746. ** If this will satisfy the client, set the orderByConsumed flag so that
  169747. ** SQLite does not do an external sort.
  169748. */
  169749. if( ( pIdxInfo->nOrderBy==1
  169750. && pIdxInfo->aOrderBy[0].iColumn==0
  169751. && pIdxInfo->aOrderBy[0].desc==0
  169752. ) ||
  169753. ( pIdxInfo->nOrderBy==2
  169754. && pIdxInfo->aOrderBy[0].iColumn==0
  169755. && pIdxInfo->aOrderBy[0].desc==0
  169756. && pIdxInfo->aOrderBy[1].iColumn==1
  169757. && pIdxInfo->aOrderBy[1].desc==0
  169758. )
  169759. ){
  169760. pIdxInfo->orderByConsumed = 1;
  169761. }
  169762. return SQLITE_OK;
  169763. }
  169764. /*
  169765. ** Open a new statvfs cursor.
  169766. */
  169767. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  169768. StatTable *pTab = (StatTable *)pVTab;
  169769. StatCursor *pCsr;
  169770. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  169771. if( pCsr==0 ){
  169772. return SQLITE_NOMEM_BKPT;
  169773. }else{
  169774. memset(pCsr, 0, sizeof(StatCursor));
  169775. pCsr->base.pVtab = pVTab;
  169776. pCsr->iDb = pTab->iDb;
  169777. }
  169778. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  169779. return SQLITE_OK;
  169780. }
  169781. static void statClearPage(StatPage *p){
  169782. int i;
  169783. if( p->aCell ){
  169784. for(i=0; i<p->nCell; i++){
  169785. sqlite3_free(p->aCell[i].aOvfl);
  169786. }
  169787. sqlite3_free(p->aCell);
  169788. }
  169789. sqlite3PagerUnref(p->pPg);
  169790. sqlite3_free(p->zPath);
  169791. memset(p, 0, sizeof(StatPage));
  169792. }
  169793. static void statResetCsr(StatCursor *pCsr){
  169794. int i;
  169795. sqlite3_reset(pCsr->pStmt);
  169796. for(i=0; i<ArraySize(pCsr->aPage); i++){
  169797. statClearPage(&pCsr->aPage[i]);
  169798. }
  169799. pCsr->iPage = 0;
  169800. sqlite3_free(pCsr->zPath);
  169801. pCsr->zPath = 0;
  169802. pCsr->isEof = 0;
  169803. }
  169804. /*
  169805. ** Close a statvfs cursor.
  169806. */
  169807. static int statClose(sqlite3_vtab_cursor *pCursor){
  169808. StatCursor *pCsr = (StatCursor *)pCursor;
  169809. statResetCsr(pCsr);
  169810. sqlite3_finalize(pCsr->pStmt);
  169811. sqlite3_free(pCsr);
  169812. return SQLITE_OK;
  169813. }
  169814. static void getLocalPayload(
  169815. int nUsable, /* Usable bytes per page */
  169816. u8 flags, /* Page flags */
  169817. int nTotal, /* Total record (payload) size */
  169818. int *pnLocal /* OUT: Bytes stored locally */
  169819. ){
  169820. int nLocal;
  169821. int nMinLocal;
  169822. int nMaxLocal;
  169823. if( flags==0x0D ){ /* Table leaf node */
  169824. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  169825. nMaxLocal = nUsable - 35;
  169826. }else{ /* Index interior and leaf nodes */
  169827. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  169828. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  169829. }
  169830. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  169831. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  169832. *pnLocal = nLocal;
  169833. }
  169834. static int statDecodePage(Btree *pBt, StatPage *p){
  169835. int nUnused;
  169836. int iOff;
  169837. int nHdr;
  169838. int isLeaf;
  169839. int szPage;
  169840. u8 *aData = sqlite3PagerGetData(p->pPg);
  169841. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  169842. p->flags = aHdr[0];
  169843. p->nCell = get2byte(&aHdr[3]);
  169844. p->nMxPayload = 0;
  169845. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  169846. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  169847. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  169848. nUnused += (int)aHdr[7];
  169849. iOff = get2byte(&aHdr[1]);
  169850. while( iOff ){
  169851. nUnused += get2byte(&aData[iOff+2]);
  169852. iOff = get2byte(&aData[iOff]);
  169853. }
  169854. p->nUnused = nUnused;
  169855. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  169856. szPage = sqlite3BtreeGetPageSize(pBt);
  169857. if( p->nCell ){
  169858. int i; /* Used to iterate through cells */
  169859. int nUsable; /* Usable bytes per page */
  169860. sqlite3BtreeEnter(pBt);
  169861. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  169862. sqlite3BtreeLeave(pBt);
  169863. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  169864. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  169865. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  169866. for(i=0; i<p->nCell; i++){
  169867. StatCell *pCell = &p->aCell[i];
  169868. iOff = get2byte(&aData[nHdr+i*2]);
  169869. if( !isLeaf ){
  169870. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  169871. iOff += 4;
  169872. }
  169873. if( p->flags==0x05 ){
  169874. /* A table interior node. nPayload==0. */
  169875. }else{
  169876. u32 nPayload; /* Bytes of payload total (local+overflow) */
  169877. int nLocal; /* Bytes of payload stored locally */
  169878. iOff += getVarint32(&aData[iOff], nPayload);
  169879. if( p->flags==0x0D ){
  169880. u64 dummy;
  169881. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  169882. }
  169883. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  169884. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  169885. pCell->nLocal = nLocal;
  169886. assert( nLocal>=0 );
  169887. assert( nPayload>=(u32)nLocal );
  169888. assert( nLocal<=(nUsable-35) );
  169889. if( nPayload>(u32)nLocal ){
  169890. int j;
  169891. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  169892. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  169893. pCell->nOvfl = nOvfl;
  169894. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  169895. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  169896. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  169897. for(j=1; j<nOvfl; j++){
  169898. int rc;
  169899. u32 iPrev = pCell->aOvfl[j-1];
  169900. DbPage *pPg = 0;
  169901. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  169902. if( rc!=SQLITE_OK ){
  169903. assert( pPg==0 );
  169904. return rc;
  169905. }
  169906. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  169907. sqlite3PagerUnref(pPg);
  169908. }
  169909. }
  169910. }
  169911. }
  169912. }
  169913. return SQLITE_OK;
  169914. }
  169915. /*
  169916. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  169917. ** the current value of pCsr->iPageno.
  169918. */
  169919. static void statSizeAndOffset(StatCursor *pCsr){
  169920. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  169921. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  169922. Pager *pPager = sqlite3BtreePager(pBt);
  169923. sqlite3_file *fd;
  169924. sqlite3_int64 x[2];
  169925. /* The default page size and offset */
  169926. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  169927. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  169928. /* If connected to a ZIPVFS backend, override the page size and
  169929. ** offset with actual values obtained from ZIPVFS.
  169930. */
  169931. fd = sqlite3PagerFile(pPager);
  169932. x[0] = pCsr->iPageno;
  169933. if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  169934. pCsr->iOffset = x[0];
  169935. pCsr->szPage = (int)x[1];
  169936. }
  169937. }
  169938. /*
  169939. ** Move a statvfs cursor to the next entry in the file.
  169940. */
  169941. static int statNext(sqlite3_vtab_cursor *pCursor){
  169942. int rc;
  169943. int nPayload;
  169944. char *z;
  169945. StatCursor *pCsr = (StatCursor *)pCursor;
  169946. StatTable *pTab = (StatTable *)pCursor->pVtab;
  169947. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  169948. Pager *pPager = sqlite3BtreePager(pBt);
  169949. sqlite3_free(pCsr->zPath);
  169950. pCsr->zPath = 0;
  169951. statNextRestart:
  169952. if( pCsr->aPage[0].pPg==0 ){
  169953. rc = sqlite3_step(pCsr->pStmt);
  169954. if( rc==SQLITE_ROW ){
  169955. int nPage;
  169956. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  169957. sqlite3PagerPagecount(pPager, &nPage);
  169958. if( nPage==0 ){
  169959. pCsr->isEof = 1;
  169960. return sqlite3_reset(pCsr->pStmt);
  169961. }
  169962. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  169963. pCsr->aPage[0].iPgno = iRoot;
  169964. pCsr->aPage[0].iCell = 0;
  169965. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  169966. pCsr->iPage = 0;
  169967. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  169968. }else{
  169969. pCsr->isEof = 1;
  169970. return sqlite3_reset(pCsr->pStmt);
  169971. }
  169972. }else{
  169973. /* Page p itself has already been visited. */
  169974. StatPage *p = &pCsr->aPage[pCsr->iPage];
  169975. while( p->iCell<p->nCell ){
  169976. StatCell *pCell = &p->aCell[p->iCell];
  169977. if( pCell->iOvfl<pCell->nOvfl ){
  169978. int nUsable;
  169979. sqlite3BtreeEnter(pBt);
  169980. nUsable = sqlite3BtreeGetPageSize(pBt) -
  169981. sqlite3BtreeGetReserveNoMutex(pBt);
  169982. sqlite3BtreeLeave(pBt);
  169983. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  169984. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  169985. pCsr->zPagetype = "overflow";
  169986. pCsr->nCell = 0;
  169987. pCsr->nMxPayload = 0;
  169988. pCsr->zPath = z = sqlite3_mprintf(
  169989. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  169990. );
  169991. if( pCell->iOvfl<pCell->nOvfl-1 ){
  169992. pCsr->nUnused = 0;
  169993. pCsr->nPayload = nUsable - 4;
  169994. }else{
  169995. pCsr->nPayload = pCell->nLastOvfl;
  169996. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  169997. }
  169998. pCell->iOvfl++;
  169999. statSizeAndOffset(pCsr);
  170000. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  170001. }
  170002. if( p->iRightChildPg ) break;
  170003. p->iCell++;
  170004. }
  170005. if( !p->iRightChildPg || p->iCell>p->nCell ){
  170006. statClearPage(p);
  170007. if( pCsr->iPage==0 ) return statNext(pCursor);
  170008. pCsr->iPage--;
  170009. goto statNextRestart; /* Tail recursion */
  170010. }
  170011. pCsr->iPage++;
  170012. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  170013. if( p->iCell==p->nCell ){
  170014. p[1].iPgno = p->iRightChildPg;
  170015. }else{
  170016. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  170017. }
  170018. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  170019. p[1].iCell = 0;
  170020. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  170021. p->iCell++;
  170022. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  170023. }
  170024. /* Populate the StatCursor fields with the values to be returned
  170025. ** by the xColumn() and xRowid() methods.
  170026. */
  170027. if( rc==SQLITE_OK ){
  170028. int i;
  170029. StatPage *p = &pCsr->aPage[pCsr->iPage];
  170030. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  170031. pCsr->iPageno = p->iPgno;
  170032. rc = statDecodePage(pBt, p);
  170033. if( rc==SQLITE_OK ){
  170034. statSizeAndOffset(pCsr);
  170035. switch( p->flags ){
  170036. case 0x05: /* table internal */
  170037. case 0x02: /* index internal */
  170038. pCsr->zPagetype = "internal";
  170039. break;
  170040. case 0x0D: /* table leaf */
  170041. case 0x0A: /* index leaf */
  170042. pCsr->zPagetype = "leaf";
  170043. break;
  170044. default:
  170045. pCsr->zPagetype = "corrupted";
  170046. break;
  170047. }
  170048. pCsr->nCell = p->nCell;
  170049. pCsr->nUnused = p->nUnused;
  170050. pCsr->nMxPayload = p->nMxPayload;
  170051. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  170052. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  170053. nPayload = 0;
  170054. for(i=0; i<p->nCell; i++){
  170055. nPayload += p->aCell[i].nLocal;
  170056. }
  170057. pCsr->nPayload = nPayload;
  170058. }
  170059. }
  170060. return rc;
  170061. }
  170062. static int statEof(sqlite3_vtab_cursor *pCursor){
  170063. StatCursor *pCsr = (StatCursor *)pCursor;
  170064. return pCsr->isEof;
  170065. }
  170066. static int statFilter(
  170067. sqlite3_vtab_cursor *pCursor,
  170068. int idxNum, const char *idxStr,
  170069. int argc, sqlite3_value **argv
  170070. ){
  170071. StatCursor *pCsr = (StatCursor *)pCursor;
  170072. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  170073. char *zSql;
  170074. int rc = SQLITE_OK;
  170075. char *zMaster;
  170076. if( idxNum==1 ){
  170077. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  170078. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  170079. if( pCsr->iDb<0 ){
  170080. sqlite3_free(pCursor->pVtab->zErrMsg);
  170081. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  170082. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  170083. }
  170084. }else{
  170085. pCsr->iDb = pTab->iDb;
  170086. }
  170087. statResetCsr(pCsr);
  170088. sqlite3_finalize(pCsr->pStmt);
  170089. pCsr->pStmt = 0;
  170090. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  170091. zSql = sqlite3_mprintf(
  170092. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  170093. " UNION ALL "
  170094. "SELECT name, rootpage, type"
  170095. " FROM \"%w\".%s WHERE rootpage!=0"
  170096. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
  170097. if( zSql==0 ){
  170098. return SQLITE_NOMEM_BKPT;
  170099. }else{
  170100. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  170101. sqlite3_free(zSql);
  170102. }
  170103. if( rc==SQLITE_OK ){
  170104. rc = statNext(pCursor);
  170105. }
  170106. return rc;
  170107. }
  170108. static int statColumn(
  170109. sqlite3_vtab_cursor *pCursor,
  170110. sqlite3_context *ctx,
  170111. int i
  170112. ){
  170113. StatCursor *pCsr = (StatCursor *)pCursor;
  170114. switch( i ){
  170115. case 0: /* name */
  170116. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  170117. break;
  170118. case 1: /* path */
  170119. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  170120. break;
  170121. case 2: /* pageno */
  170122. sqlite3_result_int64(ctx, pCsr->iPageno);
  170123. break;
  170124. case 3: /* pagetype */
  170125. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  170126. break;
  170127. case 4: /* ncell */
  170128. sqlite3_result_int(ctx, pCsr->nCell);
  170129. break;
  170130. case 5: /* payload */
  170131. sqlite3_result_int(ctx, pCsr->nPayload);
  170132. break;
  170133. case 6: /* unused */
  170134. sqlite3_result_int(ctx, pCsr->nUnused);
  170135. break;
  170136. case 7: /* mx_payload */
  170137. sqlite3_result_int(ctx, pCsr->nMxPayload);
  170138. break;
  170139. case 8: /* pgoffset */
  170140. sqlite3_result_int64(ctx, pCsr->iOffset);
  170141. break;
  170142. case 9: /* pgsize */
  170143. sqlite3_result_int(ctx, pCsr->szPage);
  170144. break;
  170145. default: { /* schema */
  170146. sqlite3 *db = sqlite3_context_db_handle(ctx);
  170147. int iDb = pCsr->iDb;
  170148. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  170149. break;
  170150. }
  170151. }
  170152. return SQLITE_OK;
  170153. }
  170154. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  170155. StatCursor *pCsr = (StatCursor *)pCursor;
  170156. *pRowid = pCsr->iPageno;
  170157. return SQLITE_OK;
  170158. }
  170159. /*
  170160. ** Invoke this routine to register the "dbstat" virtual table module
  170161. */
  170162. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  170163. static sqlite3_module dbstat_module = {
  170164. 0, /* iVersion */
  170165. statConnect, /* xCreate */
  170166. statConnect, /* xConnect */
  170167. statBestIndex, /* xBestIndex */
  170168. statDisconnect, /* xDisconnect */
  170169. statDisconnect, /* xDestroy */
  170170. statOpen, /* xOpen - open a cursor */
  170171. statClose, /* xClose - close a cursor */
  170172. statFilter, /* xFilter - configure scan constraints */
  170173. statNext, /* xNext - advance a cursor */
  170174. statEof, /* xEof - check for end of scan */
  170175. statColumn, /* xColumn - read data */
  170176. statRowid, /* xRowid - read data */
  170177. 0, /* xUpdate */
  170178. 0, /* xBegin */
  170179. 0, /* xSync */
  170180. 0, /* xCommit */
  170181. 0, /* xRollback */
  170182. 0, /* xFindMethod */
  170183. 0, /* xRename */
  170184. 0, /* xSavepoint */
  170185. 0, /* xRelease */
  170186. 0, /* xRollbackTo */
  170187. };
  170188. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  170189. }
  170190. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  170191. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  170192. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  170193. /************** End of dbstat.c **********************************************/
  170194. /************** Begin file dbpage.c ******************************************/
  170195. /*
  170196. ** 2017-10-11
  170197. **
  170198. ** The author disclaims copyright to this source code. In place of
  170199. ** a legal notice, here is a blessing:
  170200. **
  170201. ** May you do good and not evil.
  170202. ** May you find forgiveness for yourself and forgive others.
  170203. ** May you share freely, never taking more than you give.
  170204. **
  170205. ******************************************************************************
  170206. **
  170207. ** This file contains an implementation of the "sqlite_dbpage" virtual table.
  170208. **
  170209. ** The sqlite_dbpage virtual table is used to read or write whole raw
  170210. ** pages of the database file. The pager interface is used so that
  170211. ** uncommitted changes and changes recorded in the WAL file are correctly
  170212. ** retrieved.
  170213. **
  170214. ** Usage example:
  170215. **
  170216. ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
  170217. **
  170218. ** This is an eponymous virtual table so it does not need to be created before
  170219. ** use. The optional argument to the sqlite_dbpage() table name is the
  170220. ** schema for the database file that is to be read. The default schema is
  170221. ** "main".
  170222. **
  170223. ** The data field of sqlite_dbpage table can be updated. The new
  170224. ** value must be a BLOB which is the correct page size, otherwise the
  170225. ** update fails. Rows may not be deleted or inserted.
  170226. */
  170227. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  170228. #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
  170229. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  170230. typedef struct DbpageTable DbpageTable;
  170231. typedef struct DbpageCursor DbpageCursor;
  170232. struct DbpageCursor {
  170233. sqlite3_vtab_cursor base; /* Base class. Must be first */
  170234. int pgno; /* Current page number */
  170235. int mxPgno; /* Last page to visit on this scan */
  170236. Pager *pPager; /* Pager being read/written */
  170237. DbPage *pPage1; /* Page 1 of the database */
  170238. int iDb; /* Index of database to analyze */
  170239. int szPage; /* Size of each page in bytes */
  170240. };
  170241. struct DbpageTable {
  170242. sqlite3_vtab base; /* Base class. Must be first */
  170243. sqlite3 *db; /* The database */
  170244. };
  170245. /* Columns */
  170246. #define DBPAGE_COLUMN_PGNO 0
  170247. #define DBPAGE_COLUMN_DATA 1
  170248. #define DBPAGE_COLUMN_SCHEMA 2
  170249. /*
  170250. ** Connect to or create a dbpagevfs virtual table.
  170251. */
  170252. static int dbpageConnect(
  170253. sqlite3 *db,
  170254. void *pAux,
  170255. int argc, const char *const*argv,
  170256. sqlite3_vtab **ppVtab,
  170257. char **pzErr
  170258. ){
  170259. DbpageTable *pTab = 0;
  170260. int rc = SQLITE_OK;
  170261. rc = sqlite3_declare_vtab(db,
  170262. "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  170263. if( rc==SQLITE_OK ){
  170264. pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
  170265. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  170266. }
  170267. assert( rc==SQLITE_OK || pTab==0 );
  170268. if( rc==SQLITE_OK ){
  170269. memset(pTab, 0, sizeof(DbpageTable));
  170270. pTab->db = db;
  170271. }
  170272. *ppVtab = (sqlite3_vtab*)pTab;
  170273. return rc;
  170274. }
  170275. /*
  170276. ** Disconnect from or destroy a dbpagevfs virtual table.
  170277. */
  170278. static int dbpageDisconnect(sqlite3_vtab *pVtab){
  170279. sqlite3_free(pVtab);
  170280. return SQLITE_OK;
  170281. }
  170282. /*
  170283. ** idxNum:
  170284. **
  170285. ** 0 schema=main, full table scan
  170286. ** 1 schema=main, pgno=?1
  170287. ** 2 schema=?1, full table scan
  170288. ** 3 schema=?1, pgno=?2
  170289. */
  170290. static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  170291. int i;
  170292. int iPlan = 0;
  170293. /* If there is a schema= constraint, it must be honored. Report a
  170294. ** ridiculously large estimated cost if the schema= constraint is
  170295. ** unavailable
  170296. */
  170297. for(i=0; i<pIdxInfo->nConstraint; i++){
  170298. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  170299. if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
  170300. if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  170301. if( !p->usable ){
  170302. /* No solution. Use the default SQLITE_BIG_DBL cost */
  170303. pIdxInfo->estimatedRows = 0x7fffffff;
  170304. return SQLITE_OK;
  170305. }
  170306. iPlan = 2;
  170307. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  170308. pIdxInfo->aConstraintUsage[i].omit = 1;
  170309. break;
  170310. }
  170311. /* If we reach this point, it means that either there is no schema=
  170312. ** constraint (in which case we use the "main" schema) or else the
  170313. ** schema constraint was accepted. Lower the estimated cost accordingly
  170314. */
  170315. pIdxInfo->estimatedCost = 1.0e6;
  170316. /* Check for constraints against pgno */
  170317. for(i=0; i<pIdxInfo->nConstraint; i++){
  170318. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  170319. if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  170320. pIdxInfo->estimatedRows = 1;
  170321. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  170322. pIdxInfo->estimatedCost = 1.0;
  170323. pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
  170324. pIdxInfo->aConstraintUsage[i].omit = 1;
  170325. iPlan |= 1;
  170326. break;
  170327. }
  170328. }
  170329. pIdxInfo->idxNum = iPlan;
  170330. if( pIdxInfo->nOrderBy>=1
  170331. && pIdxInfo->aOrderBy[0].iColumn<=0
  170332. && pIdxInfo->aOrderBy[0].desc==0
  170333. ){
  170334. pIdxInfo->orderByConsumed = 1;
  170335. }
  170336. return SQLITE_OK;
  170337. }
  170338. /*
  170339. ** Open a new dbpagevfs cursor.
  170340. */
  170341. static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  170342. DbpageCursor *pCsr;
  170343. pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
  170344. if( pCsr==0 ){
  170345. return SQLITE_NOMEM_BKPT;
  170346. }else{
  170347. memset(pCsr, 0, sizeof(DbpageCursor));
  170348. pCsr->base.pVtab = pVTab;
  170349. pCsr->pgno = -1;
  170350. }
  170351. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  170352. return SQLITE_OK;
  170353. }
  170354. /*
  170355. ** Close a dbpagevfs cursor.
  170356. */
  170357. static int dbpageClose(sqlite3_vtab_cursor *pCursor){
  170358. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  170359. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  170360. sqlite3_free(pCsr);
  170361. return SQLITE_OK;
  170362. }
  170363. /*
  170364. ** Move a dbpagevfs cursor to the next entry in the file.
  170365. */
  170366. static int dbpageNext(sqlite3_vtab_cursor *pCursor){
  170367. int rc = SQLITE_OK;
  170368. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  170369. pCsr->pgno++;
  170370. return rc;
  170371. }
  170372. static int dbpageEof(sqlite3_vtab_cursor *pCursor){
  170373. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  170374. return pCsr->pgno > pCsr->mxPgno;
  170375. }
  170376. /*
  170377. ** idxNum:
  170378. **
  170379. ** 0 schema=main, full table scan
  170380. ** 1 schema=main, pgno=?1
  170381. ** 2 schema=?1, full table scan
  170382. ** 3 schema=?1, pgno=?2
  170383. **
  170384. ** idxStr is not used
  170385. */
  170386. static int dbpageFilter(
  170387. sqlite3_vtab_cursor *pCursor,
  170388. int idxNum, const char *idxStr,
  170389. int argc, sqlite3_value **argv
  170390. ){
  170391. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  170392. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  170393. int rc;
  170394. sqlite3 *db = pTab->db;
  170395. Btree *pBt;
  170396. /* Default setting is no rows of result */
  170397. pCsr->pgno = 1;
  170398. pCsr->mxPgno = 0;
  170399. if( idxNum & 2 ){
  170400. const char *zSchema;
  170401. assert( argc>=1 );
  170402. zSchema = (const char*)sqlite3_value_text(argv[0]);
  170403. pCsr->iDb = sqlite3FindDbName(db, zSchema);
  170404. if( pCsr->iDb<0 ) return SQLITE_OK;
  170405. }else{
  170406. pCsr->iDb = 0;
  170407. }
  170408. pBt = db->aDb[pCsr->iDb].pBt;
  170409. if( pBt==0 ) return SQLITE_OK;
  170410. pCsr->pPager = sqlite3BtreePager(pBt);
  170411. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  170412. pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
  170413. if( idxNum & 1 ){
  170414. assert( argc>(idxNum>>1) );
  170415. pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
  170416. if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
  170417. pCsr->pgno = 1;
  170418. pCsr->mxPgno = 0;
  170419. }else{
  170420. pCsr->mxPgno = pCsr->pgno;
  170421. }
  170422. }else{
  170423. assert( pCsr->pgno==1 );
  170424. }
  170425. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  170426. rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
  170427. return rc;
  170428. }
  170429. static int dbpageColumn(
  170430. sqlite3_vtab_cursor *pCursor,
  170431. sqlite3_context *ctx,
  170432. int i
  170433. ){
  170434. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  170435. int rc = SQLITE_OK;
  170436. switch( i ){
  170437. case 0: { /* pgno */
  170438. sqlite3_result_int(ctx, pCsr->pgno);
  170439. break;
  170440. }
  170441. case 1: { /* data */
  170442. DbPage *pDbPage = 0;
  170443. rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
  170444. if( rc==SQLITE_OK ){
  170445. sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
  170446. SQLITE_TRANSIENT);
  170447. }
  170448. sqlite3PagerUnref(pDbPage);
  170449. break;
  170450. }
  170451. default: { /* schema */
  170452. sqlite3 *db = sqlite3_context_db_handle(ctx);
  170453. sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
  170454. break;
  170455. }
  170456. }
  170457. return SQLITE_OK;
  170458. }
  170459. static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  170460. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  170461. *pRowid = pCsr->pgno;
  170462. return SQLITE_OK;
  170463. }
  170464. static int dbpageUpdate(
  170465. sqlite3_vtab *pVtab,
  170466. int argc,
  170467. sqlite3_value **argv,
  170468. sqlite_int64 *pRowid
  170469. ){
  170470. DbpageTable *pTab = (DbpageTable *)pVtab;
  170471. Pgno pgno;
  170472. DbPage *pDbPage = 0;
  170473. int rc = SQLITE_OK;
  170474. char *zErr = 0;
  170475. const char *zSchema;
  170476. int iDb;
  170477. Btree *pBt;
  170478. Pager *pPager;
  170479. int szPage;
  170480. if( argc==1 ){
  170481. zErr = "cannot delete";
  170482. goto update_fail;
  170483. }
  170484. pgno = sqlite3_value_int(argv[0]);
  170485. if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
  170486. zErr = "cannot insert";
  170487. goto update_fail;
  170488. }
  170489. zSchema = (const char*)sqlite3_value_text(argv[4]);
  170490. iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
  170491. if( iDb<0 ){
  170492. zErr = "no such schema";
  170493. goto update_fail;
  170494. }
  170495. pBt = pTab->db->aDb[iDb].pBt;
  170496. if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
  170497. zErr = "bad page number";
  170498. goto update_fail;
  170499. }
  170500. szPage = sqlite3BtreeGetPageSize(pBt);
  170501. if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
  170502. || sqlite3_value_bytes(argv[3])!=szPage
  170503. ){
  170504. zErr = "bad page value";
  170505. goto update_fail;
  170506. }
  170507. pPager = sqlite3BtreePager(pBt);
  170508. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  170509. if( rc==SQLITE_OK ){
  170510. rc = sqlite3PagerWrite(pDbPage);
  170511. if( rc==SQLITE_OK ){
  170512. memcpy(sqlite3PagerGetData(pDbPage),
  170513. sqlite3_value_blob(argv[3]),
  170514. szPage);
  170515. }
  170516. }
  170517. sqlite3PagerUnref(pDbPage);
  170518. return rc;
  170519. update_fail:
  170520. sqlite3_free(pVtab->zErrMsg);
  170521. pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
  170522. return SQLITE_ERROR;
  170523. }
  170524. /* Since we do not know in advance which database files will be
  170525. ** written by the sqlite_dbpage virtual table, start a write transaction
  170526. ** on them all.
  170527. */
  170528. static int dbpageBegin(sqlite3_vtab *pVtab){
  170529. DbpageTable *pTab = (DbpageTable *)pVtab;
  170530. sqlite3 *db = pTab->db;
  170531. int i;
  170532. for(i=0; i<db->nDb; i++){
  170533. Btree *pBt = db->aDb[i].pBt;
  170534. if( pBt ) sqlite3BtreeBeginTrans(pBt, 1);
  170535. }
  170536. return SQLITE_OK;
  170537. }
  170538. /*
  170539. ** Invoke this routine to register the "dbpage" virtual table module
  170540. */
  170541. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  170542. static sqlite3_module dbpage_module = {
  170543. 0, /* iVersion */
  170544. dbpageConnect, /* xCreate */
  170545. dbpageConnect, /* xConnect */
  170546. dbpageBestIndex, /* xBestIndex */
  170547. dbpageDisconnect, /* xDisconnect */
  170548. dbpageDisconnect, /* xDestroy */
  170549. dbpageOpen, /* xOpen - open a cursor */
  170550. dbpageClose, /* xClose - close a cursor */
  170551. dbpageFilter, /* xFilter - configure scan constraints */
  170552. dbpageNext, /* xNext - advance a cursor */
  170553. dbpageEof, /* xEof - check for end of scan */
  170554. dbpageColumn, /* xColumn - read data */
  170555. dbpageRowid, /* xRowid - read data */
  170556. dbpageUpdate, /* xUpdate */
  170557. dbpageBegin, /* xBegin */
  170558. 0, /* xSync */
  170559. 0, /* xCommit */
  170560. 0, /* xRollback */
  170561. 0, /* xFindMethod */
  170562. 0, /* xRename */
  170563. 0, /* xSavepoint */
  170564. 0, /* xRelease */
  170565. 0, /* xRollbackTo */
  170566. };
  170567. return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
  170568. }
  170569. #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
  170570. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
  170571. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  170572. /************** End of dbpage.c **********************************************/
  170573. /************** Begin file sqlite3session.c **********************************/
  170574. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  170575. /* #include "sqlite3session.h" */
  170576. /* #include <assert.h> */
  170577. /* #include <string.h> */
  170578. #ifndef SQLITE_AMALGAMATION
  170579. /* # include "sqliteInt.h" */
  170580. /* # include "vdbeInt.h" */
  170581. #endif
  170582. typedef struct SessionTable SessionTable;
  170583. typedef struct SessionChange SessionChange;
  170584. typedef struct SessionBuffer SessionBuffer;
  170585. typedef struct SessionInput SessionInput;
  170586. /*
  170587. ** Minimum chunk size used by streaming versions of functions.
  170588. */
  170589. #ifndef SESSIONS_STRM_CHUNK_SIZE
  170590. # ifdef SQLITE_TEST
  170591. # define SESSIONS_STRM_CHUNK_SIZE 64
  170592. # else
  170593. # define SESSIONS_STRM_CHUNK_SIZE 1024
  170594. # endif
  170595. #endif
  170596. typedef struct SessionHook SessionHook;
  170597. struct SessionHook {
  170598. void *pCtx;
  170599. int (*xOld)(void*,int,sqlite3_value**);
  170600. int (*xNew)(void*,int,sqlite3_value**);
  170601. int (*xCount)(void*);
  170602. int (*xDepth)(void*);
  170603. };
  170604. /*
  170605. ** Session handle structure.
  170606. */
  170607. struct sqlite3_session {
  170608. sqlite3 *db; /* Database handle session is attached to */
  170609. char *zDb; /* Name of database session is attached to */
  170610. int bEnable; /* True if currently recording */
  170611. int bIndirect; /* True if all changes are indirect */
  170612. int bAutoAttach; /* True to auto-attach tables */
  170613. int rc; /* Non-zero if an error has occurred */
  170614. void *pFilterCtx; /* First argument to pass to xTableFilter */
  170615. int (*xTableFilter)(void *pCtx, const char *zTab);
  170616. sqlite3_value *pZeroBlob; /* Value containing X'' */
  170617. sqlite3_session *pNext; /* Next session object on same db. */
  170618. SessionTable *pTable; /* List of attached tables */
  170619. SessionHook hook; /* APIs to grab new and old data with */
  170620. };
  170621. /*
  170622. ** Instances of this structure are used to build strings or binary records.
  170623. */
  170624. struct SessionBuffer {
  170625. u8 *aBuf; /* Pointer to changeset buffer */
  170626. int nBuf; /* Size of buffer aBuf */
  170627. int nAlloc; /* Size of allocation containing aBuf */
  170628. };
  170629. /*
  170630. ** An object of this type is used internally as an abstraction for
  170631. ** input data. Input data may be supplied either as a single large buffer
  170632. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  170633. ** sqlite3changeset_start_strm()).
  170634. */
  170635. struct SessionInput {
  170636. int bNoDiscard; /* If true, do not discard in InputBuffer() */
  170637. int iCurrent; /* Offset in aData[] of current change */
  170638. int iNext; /* Offset in aData[] of next change */
  170639. u8 *aData; /* Pointer to buffer containing changeset */
  170640. int nData; /* Number of bytes in aData */
  170641. SessionBuffer buf; /* Current read buffer */
  170642. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  170643. void *pIn; /* First argument to xInput */
  170644. int bEof; /* Set to true after xInput finished */
  170645. };
  170646. /*
  170647. ** Structure for changeset iterators.
  170648. */
  170649. struct sqlite3_changeset_iter {
  170650. SessionInput in; /* Input buffer or stream */
  170651. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  170652. int bPatchset; /* True if this is a patchset */
  170653. int rc; /* Iterator error code */
  170654. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  170655. char *zTab; /* Current table */
  170656. int nCol; /* Number of columns in zTab */
  170657. int op; /* Current operation */
  170658. int bIndirect; /* True if current change was indirect */
  170659. u8 *abPK; /* Primary key array */
  170660. sqlite3_value **apValue; /* old.* and new.* values */
  170661. };
  170662. /*
  170663. ** Each session object maintains a set of the following structures, one
  170664. ** for each table the session object is monitoring. The structures are
  170665. ** stored in a linked list starting at sqlite3_session.pTable.
  170666. **
  170667. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  170668. ** been modified in any way since the session object was attached to the
  170669. ** table.
  170670. **
  170671. ** The data associated with each hash-table entry is a structure containing
  170672. ** a subset of the initial values that the modified row contained at the
  170673. ** start of the session. Or no initial values if the row was inserted.
  170674. */
  170675. struct SessionTable {
  170676. SessionTable *pNext;
  170677. char *zName; /* Local name of table */
  170678. int nCol; /* Number of columns in table zName */
  170679. int bStat1; /* True if this is sqlite_stat1 */
  170680. const char **azCol; /* Column names */
  170681. u8 *abPK; /* Array of primary key flags */
  170682. int nEntry; /* Total number of entries in hash table */
  170683. int nChange; /* Size of apChange[] array */
  170684. SessionChange **apChange; /* Hash table buckets */
  170685. };
  170686. /*
  170687. ** RECORD FORMAT:
  170688. **
  170689. ** The following record format is similar to (but not compatible with) that
  170690. ** used in SQLite database files. This format is used as part of the
  170691. ** change-set binary format, and so must be architecture independent.
  170692. **
  170693. ** Unlike the SQLite database record format, each field is self-contained -
  170694. ** there is no separation of header and data. Each field begins with a
  170695. ** single byte describing its type, as follows:
  170696. **
  170697. ** 0x00: Undefined value.
  170698. ** 0x01: Integer value.
  170699. ** 0x02: Real value.
  170700. ** 0x03: Text value.
  170701. ** 0x04: Blob value.
  170702. ** 0x05: SQL NULL value.
  170703. **
  170704. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  170705. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  170706. ** only of the single type byte. For other types of values, the type byte
  170707. ** is followed by:
  170708. **
  170709. ** Text values:
  170710. ** A varint containing the number of bytes in the value (encoded using
  170711. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  170712. ** of the text value. There is no nul terminator.
  170713. **
  170714. ** Blob values:
  170715. ** A varint containing the number of bytes in the value, followed by
  170716. ** a buffer containing the value itself.
  170717. **
  170718. ** Integer values:
  170719. ** An 8-byte big-endian integer value.
  170720. **
  170721. ** Real values:
  170722. ** An 8-byte big-endian IEEE 754-2008 real value.
  170723. **
  170724. ** Varint values are encoded in the same way as varints in the SQLite
  170725. ** record format.
  170726. **
  170727. ** CHANGESET FORMAT:
  170728. **
  170729. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  170730. ** one or more tables. Operations on a single table are grouped together,
  170731. ** but may occur in any order (i.e. deletes, updates and inserts are all
  170732. ** mixed together).
  170733. **
  170734. ** Each group of changes begins with a table header:
  170735. **
  170736. ** 1 byte: Constant 0x54 (capital 'T')
  170737. ** Varint: Number of columns in the table.
  170738. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  170739. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  170740. **
  170741. ** Followed by one or more changes to the table.
  170742. **
  170743. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  170744. ** 1 byte: The "indirect-change" flag.
  170745. ** old.* record: (delete and update only)
  170746. ** new.* record: (insert and update only)
  170747. **
  170748. ** The "old.*" and "new.*" records, if present, are N field records in the
  170749. ** format described above under "RECORD FORMAT", where N is the number of
  170750. ** columns in the table. The i'th field of each record is associated with
  170751. ** the i'th column of the table, counting from left to right in the order
  170752. ** in which columns were declared in the CREATE TABLE statement.
  170753. **
  170754. ** The new.* record that is part of each INSERT change contains the values
  170755. ** that make up the new row. Similarly, the old.* record that is part of each
  170756. ** DELETE change contains the values that made up the row that was deleted
  170757. ** from the database. In the changeset format, the records that are part
  170758. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  170759. ** fields.
  170760. **
  170761. ** Within the old.* record associated with an UPDATE change, all fields
  170762. ** associated with table columns that are not PRIMARY KEY columns and are
  170763. ** not modified by the UPDATE change are set to "undefined". Other fields
  170764. ** are set to the values that made up the row before the UPDATE that the
  170765. ** change records took place. Within the new.* record, fields associated
  170766. ** with table columns modified by the UPDATE change contain the new
  170767. ** values. Fields associated with table columns that are not modified
  170768. ** are set to "undefined".
  170769. **
  170770. ** PATCHSET FORMAT:
  170771. **
  170772. ** A patchset is also a collection of changes. It is similar to a changeset,
  170773. ** but leaves undefined those fields that are not useful if no conflict
  170774. ** resolution is required when applying the changeset.
  170775. **
  170776. ** Each group of changes begins with a table header:
  170777. **
  170778. ** 1 byte: Constant 0x50 (capital 'P')
  170779. ** Varint: Number of columns in the table.
  170780. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  170781. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  170782. **
  170783. ** Followed by one or more changes to the table.
  170784. **
  170785. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  170786. ** 1 byte: The "indirect-change" flag.
  170787. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  170788. ** full record for INSERT).
  170789. **
  170790. ** As in the changeset format, each field of the single record that is part
  170791. ** of a patchset change is associated with the correspondingly positioned
  170792. ** table column, counting from left to right within the CREATE TABLE
  170793. ** statement.
  170794. **
  170795. ** For a DELETE change, all fields within the record except those associated
  170796. ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
  170797. ** values identifying the row to delete.
  170798. **
  170799. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  170800. ** columns and columns that are modified by the UPDATE are set to "undefined".
  170801. ** PRIMARY KEY fields contain the values identifying the table row to update,
  170802. ** and fields associated with modified columns contain the new column values.
  170803. **
  170804. ** The records associated with INSERT changes are in the same format as for
  170805. ** changesets. It is not possible for a record associated with an INSERT
  170806. ** change to contain a field set to "undefined".
  170807. */
  170808. /*
  170809. ** For each row modified during a session, there exists a single instance of
  170810. ** this structure stored in a SessionTable.aChange[] hash table.
  170811. */
  170812. struct SessionChange {
  170813. int op; /* One of UPDATE, DELETE, INSERT */
  170814. int bIndirect; /* True if this change is "indirect" */
  170815. int nRecord; /* Number of bytes in buffer aRecord[] */
  170816. u8 *aRecord; /* Buffer containing old.* record */
  170817. SessionChange *pNext; /* For hash-table collisions */
  170818. };
  170819. /*
  170820. ** Write a varint with value iVal into the buffer at aBuf. Return the
  170821. ** number of bytes written.
  170822. */
  170823. static int sessionVarintPut(u8 *aBuf, int iVal){
  170824. return putVarint32(aBuf, iVal);
  170825. }
  170826. /*
  170827. ** Return the number of bytes required to store value iVal as a varint.
  170828. */
  170829. static int sessionVarintLen(int iVal){
  170830. return sqlite3VarintLen(iVal);
  170831. }
  170832. /*
  170833. ** Read a varint value from aBuf[] into *piVal. Return the number of
  170834. ** bytes read.
  170835. */
  170836. static int sessionVarintGet(u8 *aBuf, int *piVal){
  170837. return getVarint32(aBuf, *piVal);
  170838. }
  170839. /* Load an unaligned and unsigned 32-bit integer */
  170840. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  170841. /*
  170842. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  170843. ** the value read.
  170844. */
  170845. static sqlite3_int64 sessionGetI64(u8 *aRec){
  170846. u64 x = SESSION_UINT32(aRec);
  170847. u32 y = SESSION_UINT32(aRec+4);
  170848. x = (x<<32) + y;
  170849. return (sqlite3_int64)x;
  170850. }
  170851. /*
  170852. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  170853. */
  170854. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  170855. aBuf[0] = (i>>56) & 0xFF;
  170856. aBuf[1] = (i>>48) & 0xFF;
  170857. aBuf[2] = (i>>40) & 0xFF;
  170858. aBuf[3] = (i>>32) & 0xFF;
  170859. aBuf[4] = (i>>24) & 0xFF;
  170860. aBuf[5] = (i>>16) & 0xFF;
  170861. aBuf[6] = (i>> 8) & 0xFF;
  170862. aBuf[7] = (i>> 0) & 0xFF;
  170863. }
  170864. /*
  170865. ** This function is used to serialize the contents of value pValue (see
  170866. ** comment titled "RECORD FORMAT" above).
  170867. **
  170868. ** If it is non-NULL, the serialized form of the value is written to
  170869. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  170870. ** returning. Or, if aBuf is NULL, the only thing this function does is
  170871. ** set *pnWrite.
  170872. **
  170873. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  170874. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  170875. ** SQLITE_NOMEM is returned.
  170876. */
  170877. static int sessionSerializeValue(
  170878. u8 *aBuf, /* If non-NULL, write serialized value here */
  170879. sqlite3_value *pValue, /* Value to serialize */
  170880. int *pnWrite /* IN/OUT: Increment by bytes written */
  170881. ){
  170882. int nByte; /* Size of serialized value in bytes */
  170883. if( pValue ){
  170884. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  170885. eType = sqlite3_value_type(pValue);
  170886. if( aBuf ) aBuf[0] = eType;
  170887. switch( eType ){
  170888. case SQLITE_NULL:
  170889. nByte = 1;
  170890. break;
  170891. case SQLITE_INTEGER:
  170892. case SQLITE_FLOAT:
  170893. if( aBuf ){
  170894. /* TODO: SQLite does something special to deal with mixed-endian
  170895. ** floating point values (e.g. ARM7). This code probably should
  170896. ** too. */
  170897. u64 i;
  170898. if( eType==SQLITE_INTEGER ){
  170899. i = (u64)sqlite3_value_int64(pValue);
  170900. }else{
  170901. double r;
  170902. assert( sizeof(double)==8 && sizeof(u64)==8 );
  170903. r = sqlite3_value_double(pValue);
  170904. memcpy(&i, &r, 8);
  170905. }
  170906. sessionPutI64(&aBuf[1], i);
  170907. }
  170908. nByte = 9;
  170909. break;
  170910. default: {
  170911. u8 *z;
  170912. int n;
  170913. int nVarint;
  170914. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  170915. if( eType==SQLITE_TEXT ){
  170916. z = (u8 *)sqlite3_value_text(pValue);
  170917. }else{
  170918. z = (u8 *)sqlite3_value_blob(pValue);
  170919. }
  170920. n = sqlite3_value_bytes(pValue);
  170921. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  170922. nVarint = sessionVarintLen(n);
  170923. if( aBuf ){
  170924. sessionVarintPut(&aBuf[1], n);
  170925. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  170926. }
  170927. nByte = 1 + nVarint + n;
  170928. break;
  170929. }
  170930. }
  170931. }else{
  170932. nByte = 1;
  170933. if( aBuf ) aBuf[0] = '\0';
  170934. }
  170935. if( pnWrite ) *pnWrite += nByte;
  170936. return SQLITE_OK;
  170937. }
  170938. /*
  170939. ** This macro is used to calculate hash key values for data structures. In
  170940. ** order to use this macro, the entire data structure must be represented
  170941. ** as a series of unsigned integers. In order to calculate a hash-key value
  170942. ** for a data structure represented as three such integers, the macro may
  170943. ** then be used as follows:
  170944. **
  170945. ** int hash_key_value;
  170946. ** hash_key_value = HASH_APPEND(0, <value 1>);
  170947. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  170948. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  170949. **
  170950. ** In practice, the data structures this macro is used for are the primary
  170951. ** key values of modified rows.
  170952. */
  170953. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  170954. /*
  170955. ** Append the hash of the 64-bit integer passed as the second argument to the
  170956. ** hash-key value passed as the first. Return the new hash-key value.
  170957. */
  170958. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  170959. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  170960. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  170961. }
  170962. /*
  170963. ** Append the hash of the blob passed via the second and third arguments to
  170964. ** the hash-key value passed as the first. Return the new hash-key value.
  170965. */
  170966. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  170967. int i;
  170968. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  170969. return h;
  170970. }
  170971. /*
  170972. ** Append the hash of the data type passed as the second argument to the
  170973. ** hash-key value passed as the first. Return the new hash-key value.
  170974. */
  170975. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  170976. return HASH_APPEND(h, eType);
  170977. }
  170978. /*
  170979. ** This function may only be called from within a pre-update callback.
  170980. ** It calculates a hash based on the primary key values of the old.* or
  170981. ** new.* row currently available and, assuming no error occurs, writes it to
  170982. ** *piHash before returning. If the primary key contains one or more NULL
  170983. ** values, *pbNullPK is set to true before returning.
  170984. **
  170985. ** If an error occurs, an SQLite error code is returned and the final values
  170986. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  170987. ** and the output variables are set as described above.
  170988. */
  170989. static int sessionPreupdateHash(
  170990. sqlite3_session *pSession, /* Session object that owns pTab */
  170991. SessionTable *pTab, /* Session table handle */
  170992. int bNew, /* True to hash the new.* PK */
  170993. int *piHash, /* OUT: Hash value */
  170994. int *pbNullPK /* OUT: True if there are NULL values in PK */
  170995. ){
  170996. unsigned int h = 0; /* Hash value to return */
  170997. int i; /* Used to iterate through columns */
  170998. assert( *pbNullPK==0 );
  170999. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  171000. for(i=0; i<pTab->nCol; i++){
  171001. if( pTab->abPK[i] ){
  171002. int rc;
  171003. int eType;
  171004. sqlite3_value *pVal;
  171005. if( bNew ){
  171006. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  171007. }else{
  171008. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  171009. }
  171010. if( rc!=SQLITE_OK ) return rc;
  171011. eType = sqlite3_value_type(pVal);
  171012. h = sessionHashAppendType(h, eType);
  171013. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  171014. i64 iVal;
  171015. if( eType==SQLITE_INTEGER ){
  171016. iVal = sqlite3_value_int64(pVal);
  171017. }else{
  171018. double rVal = sqlite3_value_double(pVal);
  171019. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  171020. memcpy(&iVal, &rVal, 8);
  171021. }
  171022. h = sessionHashAppendI64(h, iVal);
  171023. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  171024. const u8 *z;
  171025. int n;
  171026. if( eType==SQLITE_TEXT ){
  171027. z = (const u8 *)sqlite3_value_text(pVal);
  171028. }else{
  171029. z = (const u8 *)sqlite3_value_blob(pVal);
  171030. }
  171031. n = sqlite3_value_bytes(pVal);
  171032. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  171033. h = sessionHashAppendBlob(h, n, z);
  171034. }else{
  171035. assert( eType==SQLITE_NULL );
  171036. assert( pTab->bStat1==0 || i!=1 );
  171037. *pbNullPK = 1;
  171038. }
  171039. }
  171040. }
  171041. *piHash = (h % pTab->nChange);
  171042. return SQLITE_OK;
  171043. }
  171044. /*
  171045. ** The buffer that the argument points to contains a serialized SQL value.
  171046. ** Return the number of bytes of space occupied by the value (including
  171047. ** the type byte).
  171048. */
  171049. static int sessionSerialLen(u8 *a){
  171050. int e = *a;
  171051. int n;
  171052. if( e==0 || e==0xFF ) return 1;
  171053. if( e==SQLITE_NULL ) return 1;
  171054. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  171055. return sessionVarintGet(&a[1], &n) + 1 + n;
  171056. }
  171057. /*
  171058. ** Based on the primary key values stored in change aRecord, calculate a
  171059. ** hash key. Assume the has table has nBucket buckets. The hash keys
  171060. ** calculated by this function are compatible with those calculated by
  171061. ** sessionPreupdateHash().
  171062. **
  171063. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  171064. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  171065. */
  171066. static unsigned int sessionChangeHash(
  171067. SessionTable *pTab, /* Table handle */
  171068. int bPkOnly, /* Record consists of PK fields only */
  171069. u8 *aRecord, /* Change record */
  171070. int nBucket /* Assume this many buckets in hash table */
  171071. ){
  171072. unsigned int h = 0; /* Value to return */
  171073. int i; /* Used to iterate through columns */
  171074. u8 *a = aRecord; /* Used to iterate through change record */
  171075. for(i=0; i<pTab->nCol; i++){
  171076. int eType = *a;
  171077. int isPK = pTab->abPK[i];
  171078. if( bPkOnly && isPK==0 ) continue;
  171079. /* It is not possible for eType to be SQLITE_NULL here. The session
  171080. ** module does not record changes for rows with NULL values stored in
  171081. ** primary key columns. */
  171082. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  171083. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  171084. || eType==SQLITE_NULL || eType==0
  171085. );
  171086. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  171087. if( isPK ){
  171088. a++;
  171089. h = sessionHashAppendType(h, eType);
  171090. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  171091. h = sessionHashAppendI64(h, sessionGetI64(a));
  171092. a += 8;
  171093. }else{
  171094. int n;
  171095. a += sessionVarintGet(a, &n);
  171096. h = sessionHashAppendBlob(h, n, a);
  171097. a += n;
  171098. }
  171099. }else{
  171100. a += sessionSerialLen(a);
  171101. }
  171102. }
  171103. return (h % nBucket);
  171104. }
  171105. /*
  171106. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  171107. ** This function returns true if the two records apply to the same row (i.e.
  171108. ** have the same values stored in the primary key columns), or false
  171109. ** otherwise.
  171110. */
  171111. static int sessionChangeEqual(
  171112. SessionTable *pTab, /* Table used for PK definition */
  171113. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  171114. u8 *aLeft, /* Change record */
  171115. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  171116. u8 *aRight /* Change record */
  171117. ){
  171118. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  171119. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  171120. int iCol; /* Used to iterate through table columns */
  171121. for(iCol=0; iCol<pTab->nCol; iCol++){
  171122. if( pTab->abPK[iCol] ){
  171123. int n1 = sessionSerialLen(a1);
  171124. int n2 = sessionSerialLen(a2);
  171125. if( n1!=n2 || memcmp(a1, a2, n1) ){
  171126. return 0;
  171127. }
  171128. a1 += n1;
  171129. a2 += n2;
  171130. }else{
  171131. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  171132. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  171133. }
  171134. }
  171135. return 1;
  171136. }
  171137. /*
  171138. ** Arguments aLeft and aRight both point to buffers containing change
  171139. ** records with nCol columns. This function "merges" the two records into
  171140. ** a single records which is written to the buffer at *paOut. *paOut is
  171141. ** then set to point to one byte after the last byte written before
  171142. ** returning.
  171143. **
  171144. ** The merging of records is done as follows: For each column, if the
  171145. ** aRight record contains a value for the column, copy the value from
  171146. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  171147. ** record contains a value for a given column, then neither does the
  171148. ** output record.
  171149. */
  171150. static void sessionMergeRecord(
  171151. u8 **paOut,
  171152. int nCol,
  171153. u8 *aLeft,
  171154. u8 *aRight
  171155. ){
  171156. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  171157. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  171158. u8 *aOut = *paOut; /* Output cursor */
  171159. int iCol; /* Used to iterate from 0 to nCol */
  171160. for(iCol=0; iCol<nCol; iCol++){
  171161. int n1 = sessionSerialLen(a1);
  171162. int n2 = sessionSerialLen(a2);
  171163. if( *a2 ){
  171164. memcpy(aOut, a2, n2);
  171165. aOut += n2;
  171166. }else{
  171167. memcpy(aOut, a1, n1);
  171168. aOut += n1;
  171169. }
  171170. a1 += n1;
  171171. a2 += n2;
  171172. }
  171173. *paOut = aOut;
  171174. }
  171175. /*
  171176. ** This is a helper function used by sessionMergeUpdate().
  171177. **
  171178. ** When this function is called, both *paOne and *paTwo point to a value
  171179. ** within a change record. Before it returns, both have been advanced so
  171180. ** as to point to the next value in the record.
  171181. **
  171182. ** If, when this function is called, *paTwo points to a valid value (i.e.
  171183. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  171184. ** pointer is returned and *pnVal is set to the number of bytes in the
  171185. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  171186. ** set to the number of bytes in the value at *paOne. If *paOne points
  171187. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  171188. **
  171189. ** if( *paTwo is valid ) return *paTwo;
  171190. ** return *paOne;
  171191. **
  171192. */
  171193. static u8 *sessionMergeValue(
  171194. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  171195. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  171196. int *pnVal /* OUT: Bytes in returned value */
  171197. ){
  171198. u8 *a1 = *paOne;
  171199. u8 *a2 = *paTwo;
  171200. u8 *pRet = 0;
  171201. int n1;
  171202. assert( a1 );
  171203. if( a2 ){
  171204. int n2 = sessionSerialLen(a2);
  171205. if( *a2 ){
  171206. *pnVal = n2;
  171207. pRet = a2;
  171208. }
  171209. *paTwo = &a2[n2];
  171210. }
  171211. n1 = sessionSerialLen(a1);
  171212. if( pRet==0 ){
  171213. *pnVal = n1;
  171214. pRet = a1;
  171215. }
  171216. *paOne = &a1[n1];
  171217. return pRet;
  171218. }
  171219. /*
  171220. ** This function is used by changeset_concat() to merge two UPDATE changes
  171221. ** on the same row.
  171222. */
  171223. static int sessionMergeUpdate(
  171224. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  171225. SessionTable *pTab, /* Table change pertains to */
  171226. int bPatchset, /* True if records are patchset records */
  171227. u8 *aOldRecord1, /* old.* record for first change */
  171228. u8 *aOldRecord2, /* old.* record for second change */
  171229. u8 *aNewRecord1, /* new.* record for first change */
  171230. u8 *aNewRecord2 /* new.* record for second change */
  171231. ){
  171232. u8 *aOld1 = aOldRecord1;
  171233. u8 *aOld2 = aOldRecord2;
  171234. u8 *aNew1 = aNewRecord1;
  171235. u8 *aNew2 = aNewRecord2;
  171236. u8 *aOut = *paOut;
  171237. int i;
  171238. if( bPatchset==0 ){
  171239. int bRequired = 0;
  171240. assert( aOldRecord1 && aNewRecord1 );
  171241. /* Write the old.* vector first. */
  171242. for(i=0; i<pTab->nCol; i++){
  171243. int nOld;
  171244. u8 *aOld;
  171245. int nNew;
  171246. u8 *aNew;
  171247. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  171248. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  171249. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  171250. if( pTab->abPK[i]==0 ) bRequired = 1;
  171251. memcpy(aOut, aOld, nOld);
  171252. aOut += nOld;
  171253. }else{
  171254. *(aOut++) = '\0';
  171255. }
  171256. }
  171257. if( !bRequired ) return 0;
  171258. }
  171259. /* Write the new.* vector */
  171260. aOld1 = aOldRecord1;
  171261. aOld2 = aOldRecord2;
  171262. aNew1 = aNewRecord1;
  171263. aNew2 = aNewRecord2;
  171264. for(i=0; i<pTab->nCol; i++){
  171265. int nOld;
  171266. u8 *aOld;
  171267. int nNew;
  171268. u8 *aNew;
  171269. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  171270. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  171271. if( bPatchset==0
  171272. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  171273. ){
  171274. *(aOut++) = '\0';
  171275. }else{
  171276. memcpy(aOut, aNew, nNew);
  171277. aOut += nNew;
  171278. }
  171279. }
  171280. *paOut = aOut;
  171281. return 1;
  171282. }
  171283. /*
  171284. ** This function is only called from within a pre-update-hook callback.
  171285. ** It determines if the current pre-update-hook change affects the same row
  171286. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  171287. ** if the pre-update-hook does not affect the same row as pChange, it returns
  171288. ** false.
  171289. */
  171290. static int sessionPreupdateEqual(
  171291. sqlite3_session *pSession, /* Session object that owns SessionTable */
  171292. SessionTable *pTab, /* Table associated with change */
  171293. SessionChange *pChange, /* Change to compare to */
  171294. int op /* Current pre-update operation */
  171295. ){
  171296. int iCol; /* Used to iterate through columns */
  171297. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  171298. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  171299. for(iCol=0; iCol<pTab->nCol; iCol++){
  171300. if( !pTab->abPK[iCol] ){
  171301. a += sessionSerialLen(a);
  171302. }else{
  171303. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  171304. int rc; /* Error code from preupdate_new/old */
  171305. int eType = *a++; /* Type of value from change record */
  171306. /* The following calls to preupdate_new() and preupdate_old() can not
  171307. ** fail. This is because they cache their return values, and by the
  171308. ** time control flows to here they have already been called once from
  171309. ** within sessionPreupdateHash(). The first two asserts below verify
  171310. ** this (that the method has already been called). */
  171311. if( op==SQLITE_INSERT ){
  171312. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  171313. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  171314. }else{
  171315. /* assert( db->pPreUpdate->pUnpacked ); */
  171316. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  171317. }
  171318. assert( rc==SQLITE_OK );
  171319. if( sqlite3_value_type(pVal)!=eType ) return 0;
  171320. /* A SessionChange object never has a NULL value in a PK column */
  171321. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  171322. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  171323. );
  171324. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  171325. i64 iVal = sessionGetI64(a);
  171326. a += 8;
  171327. if( eType==SQLITE_INTEGER ){
  171328. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  171329. }else{
  171330. double rVal;
  171331. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  171332. memcpy(&rVal, &iVal, 8);
  171333. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  171334. }
  171335. }else{
  171336. int n;
  171337. const u8 *z;
  171338. a += sessionVarintGet(a, &n);
  171339. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  171340. if( eType==SQLITE_TEXT ){
  171341. z = sqlite3_value_text(pVal);
  171342. }else{
  171343. z = sqlite3_value_blob(pVal);
  171344. }
  171345. if( n>0 && memcmp(a, z, n) ) return 0;
  171346. a += n;
  171347. }
  171348. }
  171349. }
  171350. return 1;
  171351. }
  171352. /*
  171353. ** If required, grow the hash table used to store changes on table pTab
  171354. ** (part of the session pSession). If a fatal OOM error occurs, set the
  171355. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  171356. ** SQLITE_OK.
  171357. **
  171358. ** It is possible that a non-fatal OOM error occurs in this function. In
  171359. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  171360. ** Growing the hash table in this case is a performance optimization only,
  171361. ** it is not required for correct operation.
  171362. */
  171363. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  171364. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  171365. int i;
  171366. SessionChange **apNew;
  171367. int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
  171368. apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
  171369. if( apNew==0 ){
  171370. if( pTab->nChange==0 ){
  171371. return SQLITE_ERROR;
  171372. }
  171373. return SQLITE_OK;
  171374. }
  171375. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  171376. for(i=0; i<pTab->nChange; i++){
  171377. SessionChange *p;
  171378. SessionChange *pNext;
  171379. for(p=pTab->apChange[i]; p; p=pNext){
  171380. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  171381. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  171382. pNext = p->pNext;
  171383. p->pNext = apNew[iHash];
  171384. apNew[iHash] = p;
  171385. }
  171386. }
  171387. sqlite3_free(pTab->apChange);
  171388. pTab->nChange = nNew;
  171389. pTab->apChange = apNew;
  171390. }
  171391. return SQLITE_OK;
  171392. }
  171393. /*
  171394. ** This function queries the database for the names of the columns of table
  171395. ** zThis, in schema zDb.
  171396. **
  171397. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  171398. ** of columns in the database table and variable *pzTab is set to point to a
  171399. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  171400. ** point to an array of pointers to column names. And *pabPK (again, if not
  171401. ** NULL) is set to point to an array of booleans - true if the corresponding
  171402. ** column is part of the primary key.
  171403. **
  171404. ** For example, if the table is declared as:
  171405. **
  171406. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  171407. **
  171408. ** Then the four output variables are populated as follows:
  171409. **
  171410. ** *pnCol = 4
  171411. ** *pzTab = "tbl1"
  171412. ** *pazCol = {"w", "x", "y", "z"}
  171413. ** *pabPK = {1, 0, 0, 1}
  171414. **
  171415. ** All returned buffers are part of the same single allocation, which must
  171416. ** be freed using sqlite3_free() by the caller
  171417. */
  171418. static int sessionTableInfo(
  171419. sqlite3 *db, /* Database connection */
  171420. const char *zDb, /* Name of attached database (e.g. "main") */
  171421. const char *zThis, /* Table name */
  171422. int *pnCol, /* OUT: number of columns */
  171423. const char **pzTab, /* OUT: Copy of zThis */
  171424. const char ***pazCol, /* OUT: Array of column names for table */
  171425. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  171426. ){
  171427. char *zPragma;
  171428. sqlite3_stmt *pStmt;
  171429. int rc;
  171430. int nByte;
  171431. int nDbCol = 0;
  171432. int nThis;
  171433. int i;
  171434. u8 *pAlloc = 0;
  171435. char **azCol = 0;
  171436. u8 *abPK = 0;
  171437. assert( pazCol && pabPK );
  171438. nThis = sqlite3Strlen30(zThis);
  171439. if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
  171440. rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
  171441. if( rc==SQLITE_OK ){
  171442. /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
  171443. zPragma = sqlite3_mprintf(
  171444. "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
  171445. "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
  171446. "SELECT 2, 'stat', '', 0, '', 0"
  171447. );
  171448. }else if( rc==SQLITE_ERROR ){
  171449. zPragma = sqlite3_mprintf("");
  171450. }else{
  171451. return rc;
  171452. }
  171453. }else{
  171454. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  171455. }
  171456. if( !zPragma ) return SQLITE_NOMEM;
  171457. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  171458. sqlite3_free(zPragma);
  171459. if( rc!=SQLITE_OK ) return rc;
  171460. nByte = nThis + 1;
  171461. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  171462. nByte += sqlite3_column_bytes(pStmt, 1);
  171463. nDbCol++;
  171464. }
  171465. rc = sqlite3_reset(pStmt);
  171466. if( rc==SQLITE_OK ){
  171467. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  171468. pAlloc = sqlite3_malloc(nByte);
  171469. if( pAlloc==0 ){
  171470. rc = SQLITE_NOMEM;
  171471. }
  171472. }
  171473. if( rc==SQLITE_OK ){
  171474. azCol = (char **)pAlloc;
  171475. pAlloc = (u8 *)&azCol[nDbCol];
  171476. abPK = (u8 *)pAlloc;
  171477. pAlloc = &abPK[nDbCol];
  171478. if( pzTab ){
  171479. memcpy(pAlloc, zThis, nThis+1);
  171480. *pzTab = (char *)pAlloc;
  171481. pAlloc += nThis+1;
  171482. }
  171483. i = 0;
  171484. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  171485. int nName = sqlite3_column_bytes(pStmt, 1);
  171486. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  171487. if( zName==0 ) break;
  171488. memcpy(pAlloc, zName, nName+1);
  171489. azCol[i] = (char *)pAlloc;
  171490. pAlloc += nName+1;
  171491. abPK[i] = sqlite3_column_int(pStmt, 5);
  171492. i++;
  171493. }
  171494. rc = sqlite3_reset(pStmt);
  171495. }
  171496. /* If successful, populate the output variables. Otherwise, zero them and
  171497. ** free any allocation made. An error code will be returned in this case.
  171498. */
  171499. if( rc==SQLITE_OK ){
  171500. *pazCol = (const char **)azCol;
  171501. *pabPK = abPK;
  171502. *pnCol = nDbCol;
  171503. }else{
  171504. *pazCol = 0;
  171505. *pabPK = 0;
  171506. *pnCol = 0;
  171507. if( pzTab ) *pzTab = 0;
  171508. sqlite3_free(azCol);
  171509. }
  171510. sqlite3_finalize(pStmt);
  171511. return rc;
  171512. }
  171513. /*
  171514. ** This function is only called from within a pre-update handler for a
  171515. ** write to table pTab, part of session pSession. If this is the first
  171516. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  171517. ** abPK[] arrays accordingly.
  171518. **
  171519. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  171520. ** non-zero returned. Or, if no error occurs but the table has no primary
  171521. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  171522. ** indicate that updates on this table should be ignored. SessionTable.abPK
  171523. ** is set to NULL in this case.
  171524. */
  171525. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  171526. if( pTab->nCol==0 ){
  171527. u8 *abPK;
  171528. assert( pTab->azCol==0 || pTab->abPK==0 );
  171529. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  171530. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  171531. );
  171532. if( pSession->rc==SQLITE_OK ){
  171533. int i;
  171534. for(i=0; i<pTab->nCol; i++){
  171535. if( abPK[i] ){
  171536. pTab->abPK = abPK;
  171537. break;
  171538. }
  171539. }
  171540. if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
  171541. pTab->bStat1 = 1;
  171542. }
  171543. }
  171544. }
  171545. return (pSession->rc || pTab->abPK==0);
  171546. }
  171547. /*
  171548. ** Versions of the four methods in object SessionHook for use with the
  171549. ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
  171550. ** blob each time a NULL value is read from the "idx" column of the
  171551. ** sqlite_stat1 table.
  171552. */
  171553. typedef struct SessionStat1Ctx SessionStat1Ctx;
  171554. struct SessionStat1Ctx {
  171555. SessionHook hook;
  171556. sqlite3_session *pSession;
  171557. };
  171558. static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
  171559. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  171560. sqlite3_value *pVal = 0;
  171561. int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
  171562. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  171563. pVal = p->pSession->pZeroBlob;
  171564. }
  171565. *ppVal = pVal;
  171566. return rc;
  171567. }
  171568. static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
  171569. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  171570. sqlite3_value *pVal = 0;
  171571. int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
  171572. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  171573. pVal = p->pSession->pZeroBlob;
  171574. }
  171575. *ppVal = pVal;
  171576. return rc;
  171577. }
  171578. static int sessionStat1Count(void *pCtx){
  171579. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  171580. return p->hook.xCount(p->hook.pCtx);
  171581. }
  171582. static int sessionStat1Depth(void *pCtx){
  171583. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  171584. return p->hook.xDepth(p->hook.pCtx);
  171585. }
  171586. /*
  171587. ** This function is only called from with a pre-update-hook reporting a
  171588. ** change on table pTab (attached to session pSession). The type of change
  171589. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  171590. **
  171591. ** Unless one is already present or an error occurs, an entry is added
  171592. ** to the changed-rows hash table associated with table pTab.
  171593. */
  171594. static void sessionPreupdateOneChange(
  171595. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  171596. sqlite3_session *pSession, /* Session object pTab is attached to */
  171597. SessionTable *pTab /* Table that change applies to */
  171598. ){
  171599. int iHash;
  171600. int bNull = 0;
  171601. int rc = SQLITE_OK;
  171602. SessionStat1Ctx stat1 = {0};
  171603. if( pSession->rc ) return;
  171604. /* Load table details if required */
  171605. if( sessionInitTable(pSession, pTab) ) return;
  171606. /* Check the number of columns in this xPreUpdate call matches the
  171607. ** number of columns in the table. */
  171608. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  171609. pSession->rc = SQLITE_SCHEMA;
  171610. return;
  171611. }
  171612. /* Grow the hash table if required */
  171613. if( sessionGrowHash(0, pTab) ){
  171614. pSession->rc = SQLITE_NOMEM;
  171615. return;
  171616. }
  171617. if( pTab->bStat1 ){
  171618. stat1.hook = pSession->hook;
  171619. stat1.pSession = pSession;
  171620. pSession->hook.pCtx = (void*)&stat1;
  171621. pSession->hook.xNew = sessionStat1New;
  171622. pSession->hook.xOld = sessionStat1Old;
  171623. pSession->hook.xCount = sessionStat1Count;
  171624. pSession->hook.xDepth = sessionStat1Depth;
  171625. if( pSession->pZeroBlob==0 ){
  171626. sqlite3_value *p = sqlite3ValueNew(0);
  171627. if( p==0 ){
  171628. rc = SQLITE_NOMEM;
  171629. goto error_out;
  171630. }
  171631. sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
  171632. pSession->pZeroBlob = p;
  171633. }
  171634. }
  171635. /* Calculate the hash-key for this change. If the primary key of the row
  171636. ** includes a NULL value, exit early. Such changes are ignored by the
  171637. ** session module. */
  171638. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  171639. if( rc!=SQLITE_OK ) goto error_out;
  171640. if( bNull==0 ){
  171641. /* Search the hash table for an existing record for this row. */
  171642. SessionChange *pC;
  171643. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  171644. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  171645. }
  171646. if( pC==0 ){
  171647. /* Create a new change object containing all the old values (if
  171648. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  171649. ** values (if this is an INSERT). */
  171650. SessionChange *pChange; /* New change object */
  171651. int nByte; /* Number of bytes to allocate */
  171652. int i; /* Used to iterate through columns */
  171653. assert( rc==SQLITE_OK );
  171654. pTab->nEntry++;
  171655. /* Figure out how large an allocation is required */
  171656. nByte = sizeof(SessionChange);
  171657. for(i=0; i<pTab->nCol; i++){
  171658. sqlite3_value *p = 0;
  171659. if( op!=SQLITE_INSERT ){
  171660. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  171661. assert( trc==SQLITE_OK );
  171662. }else if( pTab->abPK[i] ){
  171663. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  171664. assert( trc==SQLITE_OK );
  171665. }
  171666. /* This may fail if SQLite value p contains a utf-16 string that must
  171667. ** be converted to utf-8 and an OOM error occurs while doing so. */
  171668. rc = sessionSerializeValue(0, p, &nByte);
  171669. if( rc!=SQLITE_OK ) goto error_out;
  171670. }
  171671. /* Allocate the change object */
  171672. pChange = (SessionChange *)sqlite3_malloc(nByte);
  171673. if( !pChange ){
  171674. rc = SQLITE_NOMEM;
  171675. goto error_out;
  171676. }else{
  171677. memset(pChange, 0, sizeof(SessionChange));
  171678. pChange->aRecord = (u8 *)&pChange[1];
  171679. }
  171680. /* Populate the change object. None of the preupdate_old(),
  171681. ** preupdate_new() or SerializeValue() calls below may fail as all
  171682. ** required values and encodings have already been cached in memory.
  171683. ** It is not possible for an OOM to occur in this block. */
  171684. nByte = 0;
  171685. for(i=0; i<pTab->nCol; i++){
  171686. sqlite3_value *p = 0;
  171687. if( op!=SQLITE_INSERT ){
  171688. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  171689. }else if( pTab->abPK[i] ){
  171690. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  171691. }
  171692. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  171693. }
  171694. /* Add the change to the hash-table */
  171695. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  171696. pChange->bIndirect = 1;
  171697. }
  171698. pChange->nRecord = nByte;
  171699. pChange->op = op;
  171700. pChange->pNext = pTab->apChange[iHash];
  171701. pTab->apChange[iHash] = pChange;
  171702. }else if( pC->bIndirect ){
  171703. /* If the existing change is considered "indirect", but this current
  171704. ** change is "direct", mark the change object as direct. */
  171705. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  171706. && pSession->bIndirect==0
  171707. ){
  171708. pC->bIndirect = 0;
  171709. }
  171710. }
  171711. }
  171712. /* If an error has occurred, mark the session object as failed. */
  171713. error_out:
  171714. if( pTab->bStat1 ){
  171715. pSession->hook = stat1.hook;
  171716. }
  171717. if( rc!=SQLITE_OK ){
  171718. pSession->rc = rc;
  171719. }
  171720. }
  171721. static int sessionFindTable(
  171722. sqlite3_session *pSession,
  171723. const char *zName,
  171724. SessionTable **ppTab
  171725. ){
  171726. int rc = SQLITE_OK;
  171727. int nName = sqlite3Strlen30(zName);
  171728. SessionTable *pRet;
  171729. /* Search for an existing table */
  171730. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  171731. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  171732. }
  171733. if( pRet==0 && pSession->bAutoAttach ){
  171734. /* If there is a table-filter configured, invoke it. If it returns 0,
  171735. ** do not automatically add the new table. */
  171736. if( pSession->xTableFilter==0
  171737. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  171738. ){
  171739. rc = sqlite3session_attach(pSession, zName);
  171740. if( rc==SQLITE_OK ){
  171741. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  171742. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  171743. }
  171744. }
  171745. }
  171746. assert( rc==SQLITE_OK || pRet==0 );
  171747. *ppTab = pRet;
  171748. return rc;
  171749. }
  171750. /*
  171751. ** The 'pre-update' hook registered by this module with SQLite databases.
  171752. */
  171753. static void xPreUpdate(
  171754. void *pCtx, /* Copy of third arg to preupdate_hook() */
  171755. sqlite3 *db, /* Database handle */
  171756. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  171757. char const *zDb, /* Database name */
  171758. char const *zName, /* Table name */
  171759. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  171760. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  171761. ){
  171762. sqlite3_session *pSession;
  171763. int nDb = sqlite3Strlen30(zDb);
  171764. assert( sqlite3_mutex_held(db->mutex) );
  171765. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  171766. SessionTable *pTab;
  171767. /* If this session is attached to a different database ("main", "temp"
  171768. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  171769. ** to the next session object attached to this database. */
  171770. if( pSession->bEnable==0 ) continue;
  171771. if( pSession->rc ) continue;
  171772. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  171773. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  171774. if( pTab ){
  171775. assert( pSession->rc==SQLITE_OK );
  171776. sessionPreupdateOneChange(op, pSession, pTab);
  171777. if( op==SQLITE_UPDATE ){
  171778. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  171779. }
  171780. }
  171781. }
  171782. }
  171783. /*
  171784. ** The pre-update hook implementations.
  171785. */
  171786. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  171787. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  171788. }
  171789. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  171790. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  171791. }
  171792. static int sessionPreupdateCount(void *pCtx){
  171793. return sqlite3_preupdate_count((sqlite3*)pCtx);
  171794. }
  171795. static int sessionPreupdateDepth(void *pCtx){
  171796. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  171797. }
  171798. /*
  171799. ** Install the pre-update hooks on the session object passed as the only
  171800. ** argument.
  171801. */
  171802. static void sessionPreupdateHooks(
  171803. sqlite3_session *pSession
  171804. ){
  171805. pSession->hook.pCtx = (void*)pSession->db;
  171806. pSession->hook.xOld = sessionPreupdateOld;
  171807. pSession->hook.xNew = sessionPreupdateNew;
  171808. pSession->hook.xCount = sessionPreupdateCount;
  171809. pSession->hook.xDepth = sessionPreupdateDepth;
  171810. }
  171811. typedef struct SessionDiffCtx SessionDiffCtx;
  171812. struct SessionDiffCtx {
  171813. sqlite3_stmt *pStmt;
  171814. int nOldOff;
  171815. };
  171816. /*
  171817. ** The diff hook implementations.
  171818. */
  171819. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  171820. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  171821. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  171822. return SQLITE_OK;
  171823. }
  171824. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  171825. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  171826. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  171827. return SQLITE_OK;
  171828. }
  171829. static int sessionDiffCount(void *pCtx){
  171830. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  171831. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  171832. }
  171833. static int sessionDiffDepth(void *pCtx){
  171834. return 0;
  171835. }
  171836. /*
  171837. ** Install the diff hooks on the session object passed as the only
  171838. ** argument.
  171839. */
  171840. static void sessionDiffHooks(
  171841. sqlite3_session *pSession,
  171842. SessionDiffCtx *pDiffCtx
  171843. ){
  171844. pSession->hook.pCtx = (void*)pDiffCtx;
  171845. pSession->hook.xOld = sessionDiffOld;
  171846. pSession->hook.xNew = sessionDiffNew;
  171847. pSession->hook.xCount = sessionDiffCount;
  171848. pSession->hook.xDepth = sessionDiffDepth;
  171849. }
  171850. static char *sessionExprComparePK(
  171851. int nCol,
  171852. const char *zDb1, const char *zDb2,
  171853. const char *zTab,
  171854. const char **azCol, u8 *abPK
  171855. ){
  171856. int i;
  171857. const char *zSep = "";
  171858. char *zRet = 0;
  171859. for(i=0; i<nCol; i++){
  171860. if( abPK[i] ){
  171861. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  171862. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  171863. );
  171864. zSep = " AND ";
  171865. if( zRet==0 ) break;
  171866. }
  171867. }
  171868. return zRet;
  171869. }
  171870. static char *sessionExprCompareOther(
  171871. int nCol,
  171872. const char *zDb1, const char *zDb2,
  171873. const char *zTab,
  171874. const char **azCol, u8 *abPK
  171875. ){
  171876. int i;
  171877. const char *zSep = "";
  171878. char *zRet = 0;
  171879. int bHave = 0;
  171880. for(i=0; i<nCol; i++){
  171881. if( abPK[i]==0 ){
  171882. bHave = 1;
  171883. zRet = sqlite3_mprintf(
  171884. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  171885. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  171886. );
  171887. zSep = " OR ";
  171888. if( zRet==0 ) break;
  171889. }
  171890. }
  171891. if( bHave==0 ){
  171892. assert( zRet==0 );
  171893. zRet = sqlite3_mprintf("0");
  171894. }
  171895. return zRet;
  171896. }
  171897. static char *sessionSelectFindNew(
  171898. int nCol,
  171899. const char *zDb1, /* Pick rows in this db only */
  171900. const char *zDb2, /* But not in this one */
  171901. const char *zTbl, /* Table name */
  171902. const char *zExpr
  171903. ){
  171904. char *zRet = sqlite3_mprintf(
  171905. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  171906. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  171907. ")",
  171908. zDb1, zTbl, zDb2, zTbl, zExpr
  171909. );
  171910. return zRet;
  171911. }
  171912. static int sessionDiffFindNew(
  171913. int op,
  171914. sqlite3_session *pSession,
  171915. SessionTable *pTab,
  171916. const char *zDb1,
  171917. const char *zDb2,
  171918. char *zExpr
  171919. ){
  171920. int rc = SQLITE_OK;
  171921. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  171922. if( zStmt==0 ){
  171923. rc = SQLITE_NOMEM;
  171924. }else{
  171925. sqlite3_stmt *pStmt;
  171926. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  171927. if( rc==SQLITE_OK ){
  171928. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  171929. pDiffCtx->pStmt = pStmt;
  171930. pDiffCtx->nOldOff = 0;
  171931. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  171932. sessionPreupdateOneChange(op, pSession, pTab);
  171933. }
  171934. rc = sqlite3_finalize(pStmt);
  171935. }
  171936. sqlite3_free(zStmt);
  171937. }
  171938. return rc;
  171939. }
  171940. static int sessionDiffFindModified(
  171941. sqlite3_session *pSession,
  171942. SessionTable *pTab,
  171943. const char *zFrom,
  171944. const char *zExpr
  171945. ){
  171946. int rc = SQLITE_OK;
  171947. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  171948. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  171949. );
  171950. if( zExpr2==0 ){
  171951. rc = SQLITE_NOMEM;
  171952. }else{
  171953. char *zStmt = sqlite3_mprintf(
  171954. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  171955. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  171956. );
  171957. if( zStmt==0 ){
  171958. rc = SQLITE_NOMEM;
  171959. }else{
  171960. sqlite3_stmt *pStmt;
  171961. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  171962. if( rc==SQLITE_OK ){
  171963. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  171964. pDiffCtx->pStmt = pStmt;
  171965. pDiffCtx->nOldOff = pTab->nCol;
  171966. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  171967. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  171968. }
  171969. rc = sqlite3_finalize(pStmt);
  171970. }
  171971. sqlite3_free(zStmt);
  171972. }
  171973. }
  171974. return rc;
  171975. }
  171976. SQLITE_API int sqlite3session_diff(
  171977. sqlite3_session *pSession,
  171978. const char *zFrom,
  171979. const char *zTbl,
  171980. char **pzErrMsg
  171981. ){
  171982. const char *zDb = pSession->zDb;
  171983. int rc = pSession->rc;
  171984. SessionDiffCtx d;
  171985. memset(&d, 0, sizeof(d));
  171986. sessionDiffHooks(pSession, &d);
  171987. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  171988. if( pzErrMsg ) *pzErrMsg = 0;
  171989. if( rc==SQLITE_OK ){
  171990. char *zExpr = 0;
  171991. sqlite3 *db = pSession->db;
  171992. SessionTable *pTo; /* Table zTbl */
  171993. /* Locate and if necessary initialize the target table object */
  171994. rc = sessionFindTable(pSession, zTbl, &pTo);
  171995. if( pTo==0 ) goto diff_out;
  171996. if( sessionInitTable(pSession, pTo) ){
  171997. rc = pSession->rc;
  171998. goto diff_out;
  171999. }
  172000. /* Check the table schemas match */
  172001. if( rc==SQLITE_OK ){
  172002. int bHasPk = 0;
  172003. int bMismatch = 0;
  172004. int nCol; /* Columns in zFrom.zTbl */
  172005. u8 *abPK;
  172006. const char **azCol = 0;
  172007. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  172008. if( rc==SQLITE_OK ){
  172009. if( pTo->nCol!=nCol ){
  172010. bMismatch = 1;
  172011. }else{
  172012. int i;
  172013. for(i=0; i<nCol; i++){
  172014. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  172015. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  172016. if( abPK[i] ) bHasPk = 1;
  172017. }
  172018. }
  172019. }
  172020. sqlite3_free((char*)azCol);
  172021. if( bMismatch ){
  172022. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  172023. rc = SQLITE_SCHEMA;
  172024. }
  172025. if( bHasPk==0 ){
  172026. /* Ignore tables with no primary keys */
  172027. goto diff_out;
  172028. }
  172029. }
  172030. if( rc==SQLITE_OK ){
  172031. zExpr = sessionExprComparePK(pTo->nCol,
  172032. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  172033. );
  172034. }
  172035. /* Find new rows */
  172036. if( rc==SQLITE_OK ){
  172037. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  172038. }
  172039. /* Find old rows */
  172040. if( rc==SQLITE_OK ){
  172041. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  172042. }
  172043. /* Find modified rows */
  172044. if( rc==SQLITE_OK ){
  172045. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  172046. }
  172047. sqlite3_free(zExpr);
  172048. }
  172049. diff_out:
  172050. sessionPreupdateHooks(pSession);
  172051. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  172052. return rc;
  172053. }
  172054. /*
  172055. ** Create a session object. This session object will record changes to
  172056. ** database zDb attached to connection db.
  172057. */
  172058. SQLITE_API int sqlite3session_create(
  172059. sqlite3 *db, /* Database handle */
  172060. const char *zDb, /* Name of db (e.g. "main") */
  172061. sqlite3_session **ppSession /* OUT: New session object */
  172062. ){
  172063. sqlite3_session *pNew; /* Newly allocated session object */
  172064. sqlite3_session *pOld; /* Session object already attached to db */
  172065. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  172066. /* Zero the output value in case an error occurs. */
  172067. *ppSession = 0;
  172068. /* Allocate and populate the new session object. */
  172069. pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
  172070. if( !pNew ) return SQLITE_NOMEM;
  172071. memset(pNew, 0, sizeof(sqlite3_session));
  172072. pNew->db = db;
  172073. pNew->zDb = (char *)&pNew[1];
  172074. pNew->bEnable = 1;
  172075. memcpy(pNew->zDb, zDb, nDb+1);
  172076. sessionPreupdateHooks(pNew);
  172077. /* Add the new session object to the linked list of session objects
  172078. ** attached to database handle $db. Do this under the cover of the db
  172079. ** handle mutex. */
  172080. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  172081. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  172082. pNew->pNext = pOld;
  172083. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  172084. *ppSession = pNew;
  172085. return SQLITE_OK;
  172086. }
  172087. /*
  172088. ** Free the list of table objects passed as the first argument. The contents
  172089. ** of the changed-rows hash tables are also deleted.
  172090. */
  172091. static void sessionDeleteTable(SessionTable *pList){
  172092. SessionTable *pNext;
  172093. SessionTable *pTab;
  172094. for(pTab=pList; pTab; pTab=pNext){
  172095. int i;
  172096. pNext = pTab->pNext;
  172097. for(i=0; i<pTab->nChange; i++){
  172098. SessionChange *p;
  172099. SessionChange *pNextChange;
  172100. for(p=pTab->apChange[i]; p; p=pNextChange){
  172101. pNextChange = p->pNext;
  172102. sqlite3_free(p);
  172103. }
  172104. }
  172105. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  172106. sqlite3_free(pTab->apChange);
  172107. sqlite3_free(pTab);
  172108. }
  172109. }
  172110. /*
  172111. ** Delete a session object previously allocated using sqlite3session_create().
  172112. */
  172113. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  172114. sqlite3 *db = pSession->db;
  172115. sqlite3_session *pHead;
  172116. sqlite3_session **pp;
  172117. /* Unlink the session from the linked list of sessions attached to the
  172118. ** database handle. Hold the db mutex while doing so. */
  172119. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  172120. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  172121. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  172122. if( (*pp)==pSession ){
  172123. *pp = (*pp)->pNext;
  172124. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  172125. break;
  172126. }
  172127. }
  172128. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  172129. sqlite3ValueFree(pSession->pZeroBlob);
  172130. /* Delete all attached table objects. And the contents of their
  172131. ** associated hash-tables. */
  172132. sessionDeleteTable(pSession->pTable);
  172133. /* Free the session object itself. */
  172134. sqlite3_free(pSession);
  172135. }
  172136. /*
  172137. ** Set a table filter on a Session Object.
  172138. */
  172139. SQLITE_API void sqlite3session_table_filter(
  172140. sqlite3_session *pSession,
  172141. int(*xFilter)(void*, const char*),
  172142. void *pCtx /* First argument passed to xFilter */
  172143. ){
  172144. pSession->bAutoAttach = 1;
  172145. pSession->pFilterCtx = pCtx;
  172146. pSession->xTableFilter = xFilter;
  172147. }
  172148. /*
  172149. ** Attach a table to a session. All subsequent changes made to the table
  172150. ** while the session object is enabled will be recorded.
  172151. **
  172152. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  172153. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  172154. ** or not.
  172155. */
  172156. SQLITE_API int sqlite3session_attach(
  172157. sqlite3_session *pSession, /* Session object */
  172158. const char *zName /* Table name */
  172159. ){
  172160. int rc = SQLITE_OK;
  172161. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  172162. if( !zName ){
  172163. pSession->bAutoAttach = 1;
  172164. }else{
  172165. SessionTable *pTab; /* New table object (if required) */
  172166. int nName; /* Number of bytes in string zName */
  172167. /* First search for an existing entry. If one is found, this call is
  172168. ** a no-op. Return early. */
  172169. nName = sqlite3Strlen30(zName);
  172170. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  172171. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  172172. }
  172173. if( !pTab ){
  172174. /* Allocate new SessionTable object. */
  172175. pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
  172176. if( !pTab ){
  172177. rc = SQLITE_NOMEM;
  172178. }else{
  172179. /* Populate the new SessionTable object and link it into the list.
  172180. ** The new object must be linked onto the end of the list, not
  172181. ** simply added to the start of it in order to ensure that tables
  172182. ** appear in the correct order when a changeset or patchset is
  172183. ** eventually generated. */
  172184. SessionTable **ppTab;
  172185. memset(pTab, 0, sizeof(SessionTable));
  172186. pTab->zName = (char *)&pTab[1];
  172187. memcpy(pTab->zName, zName, nName+1);
  172188. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  172189. *ppTab = pTab;
  172190. }
  172191. }
  172192. }
  172193. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  172194. return rc;
  172195. }
  172196. /*
  172197. ** Ensure that there is room in the buffer to append nByte bytes of data.
  172198. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  172199. **
  172200. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  172201. ** set *pRc to SQLITE_NOMEM and return non-zero.
  172202. */
  172203. static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
  172204. if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
  172205. u8 *aNew;
  172206. int nNew = p->nAlloc ? p->nAlloc : 128;
  172207. do {
  172208. nNew = nNew*2;
  172209. }while( nNew<(p->nBuf+nByte) );
  172210. aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
  172211. if( 0==aNew ){
  172212. *pRc = SQLITE_NOMEM;
  172213. }else{
  172214. p->aBuf = aNew;
  172215. p->nAlloc = nNew;
  172216. }
  172217. }
  172218. return (*pRc!=SQLITE_OK);
  172219. }
  172220. /*
  172221. ** Append the value passed as the second argument to the buffer passed
  172222. ** as the first.
  172223. **
  172224. ** This function is a no-op if *pRc is non-zero when it is called.
  172225. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  172226. ** before returning.
  172227. */
  172228. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  172229. int rc = *pRc;
  172230. if( rc==SQLITE_OK ){
  172231. int nByte = 0;
  172232. rc = sessionSerializeValue(0, pVal, &nByte);
  172233. sessionBufferGrow(p, nByte, &rc);
  172234. if( rc==SQLITE_OK ){
  172235. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  172236. p->nBuf += nByte;
  172237. }else{
  172238. *pRc = rc;
  172239. }
  172240. }
  172241. }
  172242. /*
  172243. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  172244. ** called. Otherwise, append a single byte to the buffer.
  172245. **
  172246. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  172247. ** returning.
  172248. */
  172249. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  172250. if( 0==sessionBufferGrow(p, 1, pRc) ){
  172251. p->aBuf[p->nBuf++] = v;
  172252. }
  172253. }
  172254. /*
  172255. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  172256. ** called. Otherwise, append a single varint to the buffer.
  172257. **
  172258. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  172259. ** returning.
  172260. */
  172261. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  172262. if( 0==sessionBufferGrow(p, 9, pRc) ){
  172263. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  172264. }
  172265. }
  172266. /*
  172267. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  172268. ** called. Otherwise, append a blob of data to the buffer.
  172269. **
  172270. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  172271. ** returning.
  172272. */
  172273. static void sessionAppendBlob(
  172274. SessionBuffer *p,
  172275. const u8 *aBlob,
  172276. int nBlob,
  172277. int *pRc
  172278. ){
  172279. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  172280. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  172281. p->nBuf += nBlob;
  172282. }
  172283. }
  172284. /*
  172285. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  172286. ** called. Otherwise, append a string to the buffer. All bytes in the string
  172287. ** up to (but not including) the nul-terminator are written to the buffer.
  172288. **
  172289. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  172290. ** returning.
  172291. */
  172292. static void sessionAppendStr(
  172293. SessionBuffer *p,
  172294. const char *zStr,
  172295. int *pRc
  172296. ){
  172297. int nStr = sqlite3Strlen30(zStr);
  172298. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  172299. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  172300. p->nBuf += nStr;
  172301. }
  172302. }
  172303. /*
  172304. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  172305. ** called. Otherwise, append the string representation of integer iVal
  172306. ** to the buffer. No nul-terminator is written.
  172307. **
  172308. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  172309. ** returning.
  172310. */
  172311. static void sessionAppendInteger(
  172312. SessionBuffer *p, /* Buffer to append to */
  172313. int iVal, /* Value to write the string rep. of */
  172314. int *pRc /* IN/OUT: Error code */
  172315. ){
  172316. char aBuf[24];
  172317. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  172318. sessionAppendStr(p, aBuf, pRc);
  172319. }
  172320. /*
  172321. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  172322. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  172323. ** with any embedded quote characters escaped to the buffer. No
  172324. ** nul-terminator byte is written.
  172325. **
  172326. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  172327. ** returning.
  172328. */
  172329. static void sessionAppendIdent(
  172330. SessionBuffer *p, /* Buffer to a append to */
  172331. const char *zStr, /* String to quote, escape and append */
  172332. int *pRc /* IN/OUT: Error code */
  172333. ){
  172334. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  172335. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  172336. char *zOut = (char *)&p->aBuf[p->nBuf];
  172337. const char *zIn = zStr;
  172338. *zOut++ = '"';
  172339. while( *zIn ){
  172340. if( *zIn=='"' ) *zOut++ = '"';
  172341. *zOut++ = *(zIn++);
  172342. }
  172343. *zOut++ = '"';
  172344. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  172345. }
  172346. }
  172347. /*
  172348. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  172349. ** called. Otherwse, it appends the serialized version of the value stored
  172350. ** in column iCol of the row that SQL statement pStmt currently points
  172351. ** to to the buffer.
  172352. */
  172353. static void sessionAppendCol(
  172354. SessionBuffer *p, /* Buffer to append to */
  172355. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  172356. int iCol, /* Column to read value from */
  172357. int *pRc /* IN/OUT: Error code */
  172358. ){
  172359. if( *pRc==SQLITE_OK ){
  172360. int eType = sqlite3_column_type(pStmt, iCol);
  172361. sessionAppendByte(p, (u8)eType, pRc);
  172362. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  172363. sqlite3_int64 i;
  172364. u8 aBuf[8];
  172365. if( eType==SQLITE_INTEGER ){
  172366. i = sqlite3_column_int64(pStmt, iCol);
  172367. }else{
  172368. double r = sqlite3_column_double(pStmt, iCol);
  172369. memcpy(&i, &r, 8);
  172370. }
  172371. sessionPutI64(aBuf, i);
  172372. sessionAppendBlob(p, aBuf, 8, pRc);
  172373. }
  172374. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  172375. u8 *z;
  172376. int nByte;
  172377. if( eType==SQLITE_BLOB ){
  172378. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  172379. }else{
  172380. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  172381. }
  172382. nByte = sqlite3_column_bytes(pStmt, iCol);
  172383. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  172384. sessionAppendVarint(p, nByte, pRc);
  172385. sessionAppendBlob(p, z, nByte, pRc);
  172386. }else{
  172387. *pRc = SQLITE_NOMEM;
  172388. }
  172389. }
  172390. }
  172391. }
  172392. /*
  172393. **
  172394. ** This function appends an update change to the buffer (see the comments
  172395. ** under "CHANGESET FORMAT" at the top of the file). An update change
  172396. ** consists of:
  172397. **
  172398. ** 1 byte: SQLITE_UPDATE (0x17)
  172399. ** n bytes: old.* record (see RECORD FORMAT)
  172400. ** m bytes: new.* record (see RECORD FORMAT)
  172401. **
  172402. ** The SessionChange object passed as the third argument contains the
  172403. ** values that were stored in the row when the session began (the old.*
  172404. ** values). The statement handle passed as the second argument points
  172405. ** at the current version of the row (the new.* values).
  172406. **
  172407. ** If all of the old.* values are equal to their corresponding new.* value
  172408. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  172409. **
  172410. ** Otherwise, the old.* record contains all primary key values and the
  172411. ** original values of any fields that have been modified. The new.* record
  172412. ** contains the new values of only those fields that have been modified.
  172413. */
  172414. static int sessionAppendUpdate(
  172415. SessionBuffer *pBuf, /* Buffer to append to */
  172416. int bPatchset, /* True for "patchset", 0 for "changeset" */
  172417. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  172418. SessionChange *p, /* Object containing old values */
  172419. u8 *abPK /* Boolean array - true for PK columns */
  172420. ){
  172421. int rc = SQLITE_OK;
  172422. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  172423. int bNoop = 1; /* Set to zero if any values are modified */
  172424. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  172425. int i; /* Used to iterate through columns */
  172426. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  172427. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  172428. sessionAppendByte(pBuf, p->bIndirect, &rc);
  172429. for(i=0; i<sqlite3_column_count(pStmt); i++){
  172430. int bChanged = 0;
  172431. int nAdvance;
  172432. int eType = *pCsr;
  172433. switch( eType ){
  172434. case SQLITE_NULL:
  172435. nAdvance = 1;
  172436. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  172437. bChanged = 1;
  172438. }
  172439. break;
  172440. case SQLITE_FLOAT:
  172441. case SQLITE_INTEGER: {
  172442. nAdvance = 9;
  172443. if( eType==sqlite3_column_type(pStmt, i) ){
  172444. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  172445. if( eType==SQLITE_INTEGER ){
  172446. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  172447. }else{
  172448. double dVal;
  172449. memcpy(&dVal, &iVal, 8);
  172450. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  172451. }
  172452. }
  172453. bChanged = 1;
  172454. break;
  172455. }
  172456. default: {
  172457. int n;
  172458. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  172459. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  172460. nAdvance = nHdr + n;
  172461. if( eType==sqlite3_column_type(pStmt, i)
  172462. && n==sqlite3_column_bytes(pStmt, i)
  172463. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  172464. ){
  172465. break;
  172466. }
  172467. bChanged = 1;
  172468. }
  172469. }
  172470. /* If at least one field has been modified, this is not a no-op. */
  172471. if( bChanged ) bNoop = 0;
  172472. /* Add a field to the old.* record. This is omitted if this modules is
  172473. ** currently generating a patchset. */
  172474. if( bPatchset==0 ){
  172475. if( bChanged || abPK[i] ){
  172476. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  172477. }else{
  172478. sessionAppendByte(pBuf, 0, &rc);
  172479. }
  172480. }
  172481. /* Add a field to the new.* record. Or the only record if currently
  172482. ** generating a patchset. */
  172483. if( bChanged || (bPatchset && abPK[i]) ){
  172484. sessionAppendCol(&buf2, pStmt, i, &rc);
  172485. }else{
  172486. sessionAppendByte(&buf2, 0, &rc);
  172487. }
  172488. pCsr += nAdvance;
  172489. }
  172490. if( bNoop ){
  172491. pBuf->nBuf = nRewind;
  172492. }else{
  172493. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  172494. }
  172495. sqlite3_free(buf2.aBuf);
  172496. return rc;
  172497. }
  172498. /*
  172499. ** Append a DELETE change to the buffer passed as the first argument. Use
  172500. ** the changeset format if argument bPatchset is zero, or the patchset
  172501. ** format otherwise.
  172502. */
  172503. static int sessionAppendDelete(
  172504. SessionBuffer *pBuf, /* Buffer to append to */
  172505. int bPatchset, /* True for "patchset", 0 for "changeset" */
  172506. SessionChange *p, /* Object containing old values */
  172507. int nCol, /* Number of columns in table */
  172508. u8 *abPK /* Boolean array - true for PK columns */
  172509. ){
  172510. int rc = SQLITE_OK;
  172511. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  172512. sessionAppendByte(pBuf, p->bIndirect, &rc);
  172513. if( bPatchset==0 ){
  172514. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  172515. }else{
  172516. int i;
  172517. u8 *a = p->aRecord;
  172518. for(i=0; i<nCol; i++){
  172519. u8 *pStart = a;
  172520. int eType = *a++;
  172521. switch( eType ){
  172522. case 0:
  172523. case SQLITE_NULL:
  172524. assert( abPK[i]==0 );
  172525. break;
  172526. case SQLITE_FLOAT:
  172527. case SQLITE_INTEGER:
  172528. a += 8;
  172529. break;
  172530. default: {
  172531. int n;
  172532. a += sessionVarintGet(a, &n);
  172533. a += n;
  172534. break;
  172535. }
  172536. }
  172537. if( abPK[i] ){
  172538. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  172539. }
  172540. }
  172541. assert( (a - p->aRecord)==p->nRecord );
  172542. }
  172543. return rc;
  172544. }
  172545. /*
  172546. ** Formulate and prepare a SELECT statement to retrieve a row from table
  172547. ** zTab in database zDb based on its primary key. i.e.
  172548. **
  172549. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  172550. */
  172551. static int sessionSelectStmt(
  172552. sqlite3 *db, /* Database handle */
  172553. const char *zDb, /* Database name */
  172554. const char *zTab, /* Table name */
  172555. int nCol, /* Number of columns in table */
  172556. const char **azCol, /* Names of table columns */
  172557. u8 *abPK, /* PRIMARY KEY array */
  172558. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  172559. ){
  172560. int rc = SQLITE_OK;
  172561. char *zSql = 0;
  172562. int nSql = -1;
  172563. if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
  172564. zSql = sqlite3_mprintf(
  172565. "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
  172566. "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
  172567. );
  172568. if( zSql==0 ) rc = SQLITE_NOMEM;
  172569. }else{
  172570. int i;
  172571. const char *zSep = "";
  172572. SessionBuffer buf = {0, 0, 0};
  172573. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  172574. sessionAppendIdent(&buf, zDb, &rc);
  172575. sessionAppendStr(&buf, ".", &rc);
  172576. sessionAppendIdent(&buf, zTab, &rc);
  172577. sessionAppendStr(&buf, " WHERE ", &rc);
  172578. for(i=0; i<nCol; i++){
  172579. if( abPK[i] ){
  172580. sessionAppendStr(&buf, zSep, &rc);
  172581. sessionAppendIdent(&buf, azCol[i], &rc);
  172582. sessionAppendStr(&buf, " IS ?", &rc);
  172583. sessionAppendInteger(&buf, i+1, &rc);
  172584. zSep = " AND ";
  172585. }
  172586. }
  172587. zSql = (char*)buf.aBuf;
  172588. nSql = buf.nBuf;
  172589. }
  172590. if( rc==SQLITE_OK ){
  172591. rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  172592. }
  172593. sqlite3_free(zSql);
  172594. return rc;
  172595. }
  172596. /*
  172597. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  172598. ** to the SELECT statement passed as the first argument. The SELECT statement
  172599. ** is as prepared by function sessionSelectStmt().
  172600. **
  172601. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  172602. ** error code (e.g. SQLITE_NOMEM) otherwise.
  172603. */
  172604. static int sessionSelectBind(
  172605. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  172606. int nCol, /* Number of columns in table */
  172607. u8 *abPK, /* PRIMARY KEY array */
  172608. SessionChange *pChange /* Change structure */
  172609. ){
  172610. int i;
  172611. int rc = SQLITE_OK;
  172612. u8 *a = pChange->aRecord;
  172613. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  172614. int eType = *a++;
  172615. switch( eType ){
  172616. case 0:
  172617. case SQLITE_NULL:
  172618. assert( abPK[i]==0 );
  172619. break;
  172620. case SQLITE_INTEGER: {
  172621. if( abPK[i] ){
  172622. i64 iVal = sessionGetI64(a);
  172623. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  172624. }
  172625. a += 8;
  172626. break;
  172627. }
  172628. case SQLITE_FLOAT: {
  172629. if( abPK[i] ){
  172630. double rVal;
  172631. i64 iVal = sessionGetI64(a);
  172632. memcpy(&rVal, &iVal, 8);
  172633. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  172634. }
  172635. a += 8;
  172636. break;
  172637. }
  172638. case SQLITE_TEXT: {
  172639. int n;
  172640. a += sessionVarintGet(a, &n);
  172641. if( abPK[i] ){
  172642. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  172643. }
  172644. a += n;
  172645. break;
  172646. }
  172647. default: {
  172648. int n;
  172649. assert( eType==SQLITE_BLOB );
  172650. a += sessionVarintGet(a, &n);
  172651. if( abPK[i] ){
  172652. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  172653. }
  172654. a += n;
  172655. break;
  172656. }
  172657. }
  172658. }
  172659. return rc;
  172660. }
  172661. /*
  172662. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  172663. ** is called. Otherwise, append a serialized table header (part of the binary
  172664. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  172665. ** SQLite error code before returning.
  172666. */
  172667. static void sessionAppendTableHdr(
  172668. SessionBuffer *pBuf, /* Append header to this buffer */
  172669. int bPatchset, /* Use the patchset format if true */
  172670. SessionTable *pTab, /* Table object to append header for */
  172671. int *pRc /* IN/OUT: Error code */
  172672. ){
  172673. /* Write a table header */
  172674. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  172675. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  172676. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  172677. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  172678. }
  172679. /*
  172680. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  172681. ** (if it is non-zero) based on the current contents of the session object
  172682. ** passed as the first argument.
  172683. **
  172684. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  172685. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  172686. ** occurs, an SQLite error code is returned and both output variables set
  172687. ** to 0.
  172688. */
  172689. static int sessionGenerateChangeset(
  172690. sqlite3_session *pSession, /* Session object */
  172691. int bPatchset, /* True for patchset, false for changeset */
  172692. int (*xOutput)(void *pOut, const void *pData, int nData),
  172693. void *pOut, /* First argument for xOutput */
  172694. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  172695. void **ppChangeset /* OUT: Buffer containing changeset */
  172696. ){
  172697. sqlite3 *db = pSession->db; /* Source database handle */
  172698. SessionTable *pTab; /* Used to iterate through attached tables */
  172699. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  172700. int rc; /* Return code */
  172701. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  172702. /* Zero the output variables in case an error occurs. If this session
  172703. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  172704. ** this call will be a no-op. */
  172705. if( xOutput==0 ){
  172706. *pnChangeset = 0;
  172707. *ppChangeset = 0;
  172708. }
  172709. if( pSession->rc ) return pSession->rc;
  172710. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  172711. if( rc!=SQLITE_OK ) return rc;
  172712. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  172713. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  172714. if( pTab->nEntry ){
  172715. const char *zName = pTab->zName;
  172716. int nCol; /* Number of columns in table */
  172717. u8 *abPK; /* Primary key array */
  172718. const char **azCol = 0; /* Table columns */
  172719. int i; /* Used to iterate through hash buckets */
  172720. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  172721. int nRewind = buf.nBuf; /* Initial size of write buffer */
  172722. int nNoop; /* Size of buffer after writing tbl header */
  172723. /* Check the table schema is still Ok. */
  172724. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  172725. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  172726. rc = SQLITE_SCHEMA;
  172727. }
  172728. /* Write a table header */
  172729. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  172730. /* Build and compile a statement to execute: */
  172731. if( rc==SQLITE_OK ){
  172732. rc = sessionSelectStmt(
  172733. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  172734. }
  172735. nNoop = buf.nBuf;
  172736. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  172737. SessionChange *p; /* Used to iterate through changes */
  172738. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  172739. rc = sessionSelectBind(pSel, nCol, abPK, p);
  172740. if( rc!=SQLITE_OK ) continue;
  172741. if( sqlite3_step(pSel)==SQLITE_ROW ){
  172742. if( p->op==SQLITE_INSERT ){
  172743. int iCol;
  172744. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  172745. sessionAppendByte(&buf, p->bIndirect, &rc);
  172746. for(iCol=0; iCol<nCol; iCol++){
  172747. sessionAppendCol(&buf, pSel, iCol, &rc);
  172748. }
  172749. }else{
  172750. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  172751. }
  172752. }else if( p->op!=SQLITE_INSERT ){
  172753. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  172754. }
  172755. if( rc==SQLITE_OK ){
  172756. rc = sqlite3_reset(pSel);
  172757. }
  172758. /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
  172759. ** its contents to the xOutput() callback. */
  172760. if( xOutput
  172761. && rc==SQLITE_OK
  172762. && buf.nBuf>nNoop
  172763. && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
  172764. ){
  172765. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  172766. nNoop = -1;
  172767. buf.nBuf = 0;
  172768. }
  172769. }
  172770. }
  172771. sqlite3_finalize(pSel);
  172772. if( buf.nBuf==nNoop ){
  172773. buf.nBuf = nRewind;
  172774. }
  172775. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  172776. }
  172777. }
  172778. if( rc==SQLITE_OK ){
  172779. if( xOutput==0 ){
  172780. *pnChangeset = buf.nBuf;
  172781. *ppChangeset = buf.aBuf;
  172782. buf.aBuf = 0;
  172783. }else if( buf.nBuf>0 ){
  172784. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  172785. }
  172786. }
  172787. sqlite3_free(buf.aBuf);
  172788. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  172789. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  172790. return rc;
  172791. }
  172792. /*
  172793. ** Obtain a changeset object containing all changes recorded by the
  172794. ** session object passed as the first argument.
  172795. **
  172796. ** It is the responsibility of the caller to eventually free the buffer
  172797. ** using sqlite3_free().
  172798. */
  172799. SQLITE_API int sqlite3session_changeset(
  172800. sqlite3_session *pSession, /* Session object */
  172801. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  172802. void **ppChangeset /* OUT: Buffer containing changeset */
  172803. ){
  172804. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  172805. }
  172806. /*
  172807. ** Streaming version of sqlite3session_changeset().
  172808. */
  172809. SQLITE_API int sqlite3session_changeset_strm(
  172810. sqlite3_session *pSession,
  172811. int (*xOutput)(void *pOut, const void *pData, int nData),
  172812. void *pOut
  172813. ){
  172814. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  172815. }
  172816. /*
  172817. ** Streaming version of sqlite3session_patchset().
  172818. */
  172819. SQLITE_API int sqlite3session_patchset_strm(
  172820. sqlite3_session *pSession,
  172821. int (*xOutput)(void *pOut, const void *pData, int nData),
  172822. void *pOut
  172823. ){
  172824. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  172825. }
  172826. /*
  172827. ** Obtain a patchset object containing all changes recorded by the
  172828. ** session object passed as the first argument.
  172829. **
  172830. ** It is the responsibility of the caller to eventually free the buffer
  172831. ** using sqlite3_free().
  172832. */
  172833. SQLITE_API int sqlite3session_patchset(
  172834. sqlite3_session *pSession, /* Session object */
  172835. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  172836. void **ppPatchset /* OUT: Buffer containing changeset */
  172837. ){
  172838. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  172839. }
  172840. /*
  172841. ** Enable or disable the session object passed as the first argument.
  172842. */
  172843. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  172844. int ret;
  172845. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  172846. if( bEnable>=0 ){
  172847. pSession->bEnable = bEnable;
  172848. }
  172849. ret = pSession->bEnable;
  172850. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  172851. return ret;
  172852. }
  172853. /*
  172854. ** Enable or disable the session object passed as the first argument.
  172855. */
  172856. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  172857. int ret;
  172858. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  172859. if( bIndirect>=0 ){
  172860. pSession->bIndirect = bIndirect;
  172861. }
  172862. ret = pSession->bIndirect;
  172863. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  172864. return ret;
  172865. }
  172866. /*
  172867. ** Return true if there have been no changes to monitored tables recorded
  172868. ** by the session object passed as the only argument.
  172869. */
  172870. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  172871. int ret = 0;
  172872. SessionTable *pTab;
  172873. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  172874. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  172875. ret = (pTab->nEntry>0);
  172876. }
  172877. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  172878. return (ret==0);
  172879. }
  172880. /*
  172881. ** Do the work for either sqlite3changeset_start() or start_strm().
  172882. */
  172883. static int sessionChangesetStart(
  172884. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  172885. int (*xInput)(void *pIn, void *pData, int *pnData),
  172886. void *pIn,
  172887. int nChangeset, /* Size of buffer pChangeset in bytes */
  172888. void *pChangeset /* Pointer to buffer containing changeset */
  172889. ){
  172890. sqlite3_changeset_iter *pRet; /* Iterator to return */
  172891. int nByte; /* Number of bytes to allocate for iterator */
  172892. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  172893. /* Zero the output variable in case an error occurs. */
  172894. *pp = 0;
  172895. /* Allocate and initialize the iterator structure. */
  172896. nByte = sizeof(sqlite3_changeset_iter);
  172897. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  172898. if( !pRet ) return SQLITE_NOMEM;
  172899. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  172900. pRet->in.aData = (u8 *)pChangeset;
  172901. pRet->in.nData = nChangeset;
  172902. pRet->in.xInput = xInput;
  172903. pRet->in.pIn = pIn;
  172904. pRet->in.bEof = (xInput ? 0 : 1);
  172905. /* Populate the output variable and return success. */
  172906. *pp = pRet;
  172907. return SQLITE_OK;
  172908. }
  172909. /*
  172910. ** Create an iterator used to iterate through the contents of a changeset.
  172911. */
  172912. SQLITE_API int sqlite3changeset_start(
  172913. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  172914. int nChangeset, /* Size of buffer pChangeset in bytes */
  172915. void *pChangeset /* Pointer to buffer containing changeset */
  172916. ){
  172917. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
  172918. }
  172919. /*
  172920. ** Streaming version of sqlite3changeset_start().
  172921. */
  172922. SQLITE_API int sqlite3changeset_start_strm(
  172923. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  172924. int (*xInput)(void *pIn, void *pData, int *pnData),
  172925. void *pIn
  172926. ){
  172927. return sessionChangesetStart(pp, xInput, pIn, 0, 0);
  172928. }
  172929. /*
  172930. ** If the SessionInput object passed as the only argument is a streaming
  172931. ** object and the buffer is full, discard some data to free up space.
  172932. */
  172933. static void sessionDiscardData(SessionInput *pIn){
  172934. if( pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
  172935. int nMove = pIn->buf.nBuf - pIn->iNext;
  172936. assert( nMove>=0 );
  172937. if( nMove>0 ){
  172938. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  172939. }
  172940. pIn->buf.nBuf -= pIn->iNext;
  172941. pIn->iNext = 0;
  172942. pIn->nData = pIn->buf.nBuf;
  172943. }
  172944. }
  172945. /*
  172946. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  172947. ** if there are not nByte bytes remaining in the input, that all available
  172948. ** data is in the buffer.
  172949. **
  172950. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  172951. */
  172952. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  172953. int rc = SQLITE_OK;
  172954. if( pIn->xInput ){
  172955. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  172956. int nNew = SESSIONS_STRM_CHUNK_SIZE;
  172957. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  172958. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  172959. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  172960. if( nNew==0 ){
  172961. pIn->bEof = 1;
  172962. }else{
  172963. pIn->buf.nBuf += nNew;
  172964. }
  172965. }
  172966. pIn->aData = pIn->buf.aBuf;
  172967. pIn->nData = pIn->buf.nBuf;
  172968. }
  172969. }
  172970. return rc;
  172971. }
  172972. /*
  172973. ** When this function is called, *ppRec points to the start of a record
  172974. ** that contains nCol values. This function advances the pointer *ppRec
  172975. ** until it points to the byte immediately following that record.
  172976. */
  172977. static void sessionSkipRecord(
  172978. u8 **ppRec, /* IN/OUT: Record pointer */
  172979. int nCol /* Number of values in record */
  172980. ){
  172981. u8 *aRec = *ppRec;
  172982. int i;
  172983. for(i=0; i<nCol; i++){
  172984. int eType = *aRec++;
  172985. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  172986. int nByte;
  172987. aRec += sessionVarintGet((u8*)aRec, &nByte);
  172988. aRec += nByte;
  172989. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  172990. aRec += 8;
  172991. }
  172992. }
  172993. *ppRec = aRec;
  172994. }
  172995. /*
  172996. ** This function sets the value of the sqlite3_value object passed as the
  172997. ** first argument to a copy of the string or blob held in the aData[]
  172998. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  172999. ** error occurs.
  173000. */
  173001. static int sessionValueSetStr(
  173002. sqlite3_value *pVal, /* Set the value of this object */
  173003. u8 *aData, /* Buffer containing string or blob data */
  173004. int nData, /* Size of buffer aData[] in bytes */
  173005. u8 enc /* String encoding (0 for blobs) */
  173006. ){
  173007. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  173008. ** argument to sqlite3ValueSetStr() and have the copy created
  173009. ** automatically. But doing so makes it difficult to detect any OOM
  173010. ** error. Hence the code to create the copy externally. */
  173011. u8 *aCopy = sqlite3_malloc(nData+1);
  173012. if( aCopy==0 ) return SQLITE_NOMEM;
  173013. memcpy(aCopy, aData, nData);
  173014. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  173015. return SQLITE_OK;
  173016. }
  173017. /*
  173018. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  173019. ** for details.
  173020. **
  173021. ** When this function is called, *paChange points to the start of the record
  173022. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  173023. ** one byte after the end of the same record before this function returns.
  173024. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  173025. ** if abPK is other than NULL, then the record contains only the PK fields
  173026. ** (in other words, it is a patchset DELETE record).
  173027. **
  173028. ** If successful, each element of the apOut[] array (allocated by the caller)
  173029. ** is set to point to an sqlite3_value object containing the value read
  173030. ** from the corresponding position in the record. If that value is not
  173031. ** included in the record (i.e. because the record is part of an UPDATE change
  173032. ** and the field was not modified), the corresponding element of apOut[] is
  173033. ** set to NULL.
  173034. **
  173035. ** It is the responsibility of the caller to free all sqlite_value structures
  173036. ** using sqlite3_free().
  173037. **
  173038. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  173039. ** The apOut[] array may have been partially populated in this case.
  173040. */
  173041. static int sessionReadRecord(
  173042. SessionInput *pIn, /* Input data */
  173043. int nCol, /* Number of values in record */
  173044. u8 *abPK, /* Array of primary key flags, or NULL */
  173045. sqlite3_value **apOut /* Write values to this array */
  173046. ){
  173047. int i; /* Used to iterate through columns */
  173048. int rc = SQLITE_OK;
  173049. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  173050. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  173051. if( abPK && abPK[i]==0 ) continue;
  173052. rc = sessionInputBuffer(pIn, 9);
  173053. if( rc==SQLITE_OK ){
  173054. if( pIn->iNext>=pIn->nData ){
  173055. rc = SQLITE_CORRUPT_BKPT;
  173056. }else{
  173057. eType = pIn->aData[pIn->iNext++];
  173058. assert( apOut[i]==0 );
  173059. if( eType ){
  173060. apOut[i] = sqlite3ValueNew(0);
  173061. if( !apOut[i] ) rc = SQLITE_NOMEM;
  173062. }
  173063. }
  173064. }
  173065. if( rc==SQLITE_OK ){
  173066. u8 *aVal = &pIn->aData[pIn->iNext];
  173067. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  173068. int nByte;
  173069. pIn->iNext += sessionVarintGet(aVal, &nByte);
  173070. rc = sessionInputBuffer(pIn, nByte);
  173071. if( rc==SQLITE_OK ){
  173072. if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
  173073. rc = SQLITE_CORRUPT_BKPT;
  173074. }else{
  173075. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  173076. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  173077. pIn->iNext += nByte;
  173078. }
  173079. }
  173080. }
  173081. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  173082. sqlite3_int64 v = sessionGetI64(aVal);
  173083. if( eType==SQLITE_INTEGER ){
  173084. sqlite3VdbeMemSetInt64(apOut[i], v);
  173085. }else{
  173086. double d;
  173087. memcpy(&d, &v, 8);
  173088. sqlite3VdbeMemSetDouble(apOut[i], d);
  173089. }
  173090. pIn->iNext += 8;
  173091. }
  173092. }
  173093. }
  173094. return rc;
  173095. }
  173096. /*
  173097. ** The input pointer currently points to the second byte of a table-header.
  173098. ** Specifically, to the following:
  173099. **
  173100. ** + number of columns in table (varint)
  173101. ** + array of PK flags (1 byte per column),
  173102. ** + table name (nul terminated).
  173103. **
  173104. ** This function ensures that all of the above is present in the input
  173105. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  173106. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  173107. ** The input pointer is not moved.
  173108. */
  173109. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  173110. int rc = SQLITE_OK;
  173111. int nCol = 0;
  173112. int nRead = 0;
  173113. rc = sessionInputBuffer(pIn, 9);
  173114. if( rc==SQLITE_OK ){
  173115. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  173116. /* The hard upper limit for the number of columns in an SQLite
  173117. ** database table is, according to sqliteLimit.h, 32676. So
  173118. ** consider any table-header that purports to have more than 65536
  173119. ** columns to be corrupt. This is convenient because otherwise,
  173120. ** if the (nCol>65536) condition below were omitted, a sufficiently
  173121. ** large value for nCol may cause nRead to wrap around and become
  173122. ** negative. Leading to a crash. */
  173123. if( nCol<0 || nCol>65536 ){
  173124. rc = SQLITE_CORRUPT_BKPT;
  173125. }else{
  173126. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  173127. nRead += nCol;
  173128. }
  173129. }
  173130. while( rc==SQLITE_OK ){
  173131. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  173132. nRead++;
  173133. }
  173134. if( (pIn->iNext + nRead)<pIn->nData ) break;
  173135. rc = sessionInputBuffer(pIn, nRead + 100);
  173136. }
  173137. *pnByte = nRead+1;
  173138. return rc;
  173139. }
  173140. /*
  173141. ** The input pointer currently points to the first byte of the first field
  173142. ** of a record consisting of nCol columns. This function ensures the entire
  173143. ** record is buffered. It does not move the input pointer.
  173144. **
  173145. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  173146. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  173147. ** final value of *pnByte is undefined in this case.
  173148. */
  173149. static int sessionChangesetBufferRecord(
  173150. SessionInput *pIn, /* Input data */
  173151. int nCol, /* Number of columns in record */
  173152. int *pnByte /* OUT: Size of record in bytes */
  173153. ){
  173154. int rc = SQLITE_OK;
  173155. int nByte = 0;
  173156. int i;
  173157. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  173158. int eType;
  173159. rc = sessionInputBuffer(pIn, nByte + 10);
  173160. if( rc==SQLITE_OK ){
  173161. eType = pIn->aData[pIn->iNext + nByte++];
  173162. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  173163. int n;
  173164. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  173165. nByte += n;
  173166. rc = sessionInputBuffer(pIn, nByte);
  173167. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  173168. nByte += 8;
  173169. }
  173170. }
  173171. }
  173172. *pnByte = nByte;
  173173. return rc;
  173174. }
  173175. /*
  173176. ** The input pointer currently points to the second byte of a table-header.
  173177. ** Specifically, to the following:
  173178. **
  173179. ** + number of columns in table (varint)
  173180. ** + array of PK flags (1 byte per column),
  173181. ** + table name (nul terminated).
  173182. **
  173183. ** This function decodes the table-header and populates the p->nCol,
  173184. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  173185. ** also allocated or resized according to the new value of p->nCol. The
  173186. ** input pointer is left pointing to the byte following the table header.
  173187. **
  173188. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  173189. ** is returned and the final values of the various fields enumerated above
  173190. ** are undefined.
  173191. */
  173192. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  173193. int rc;
  173194. int nCopy;
  173195. assert( p->rc==SQLITE_OK );
  173196. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  173197. if( rc==SQLITE_OK ){
  173198. int nByte;
  173199. int nVarint;
  173200. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  173201. if( p->nCol>0 ){
  173202. nCopy -= nVarint;
  173203. p->in.iNext += nVarint;
  173204. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  173205. p->tblhdr.nBuf = 0;
  173206. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  173207. }else{
  173208. rc = SQLITE_CORRUPT_BKPT;
  173209. }
  173210. }
  173211. if( rc==SQLITE_OK ){
  173212. int iPK = sizeof(sqlite3_value*)*p->nCol*2;
  173213. memset(p->tblhdr.aBuf, 0, iPK);
  173214. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  173215. p->in.iNext += nCopy;
  173216. }
  173217. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  173218. p->abPK = (u8*)&p->apValue[p->nCol*2];
  173219. p->zTab = (char*)&p->abPK[p->nCol];
  173220. return (p->rc = rc);
  173221. }
  173222. /*
  173223. ** Advance the changeset iterator to the next change.
  173224. **
  173225. ** If both paRec and pnRec are NULL, then this function works like the public
  173226. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  173227. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  173228. **
  173229. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  173230. ** record is written to *paRec before returning and the number of bytes in
  173231. ** the record to *pnRec.
  173232. **
  173233. ** Either way, this function returns SQLITE_ROW if the iterator is
  173234. ** successfully advanced to the next change in the changeset, an SQLite
  173235. ** error code if an error occurs, or SQLITE_DONE if there are no further
  173236. ** changes in the changeset.
  173237. */
  173238. static int sessionChangesetNext(
  173239. sqlite3_changeset_iter *p, /* Changeset iterator */
  173240. u8 **paRec, /* If non-NULL, store record pointer here */
  173241. int *pnRec, /* If non-NULL, store size of record here */
  173242. int *pbNew /* If non-NULL, true if new table */
  173243. ){
  173244. int i;
  173245. u8 op;
  173246. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  173247. /* If the iterator is in the error-state, return immediately. */
  173248. if( p->rc!=SQLITE_OK ) return p->rc;
  173249. /* Free the current contents of p->apValue[], if any. */
  173250. if( p->apValue ){
  173251. for(i=0; i<p->nCol*2; i++){
  173252. sqlite3ValueFree(p->apValue[i]);
  173253. }
  173254. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  173255. }
  173256. /* Make sure the buffer contains at least 10 bytes of input data, or all
  173257. ** remaining data if there are less than 10 bytes available. This is
  173258. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  173259. ** it, or for the two single byte values otherwise. */
  173260. p->rc = sessionInputBuffer(&p->in, 2);
  173261. if( p->rc!=SQLITE_OK ) return p->rc;
  173262. /* If the iterator is already at the end of the changeset, return DONE. */
  173263. if( p->in.iNext>=p->in.nData ){
  173264. return SQLITE_DONE;
  173265. }
  173266. sessionDiscardData(&p->in);
  173267. p->in.iCurrent = p->in.iNext;
  173268. op = p->in.aData[p->in.iNext++];
  173269. while( op=='T' || op=='P' ){
  173270. if( pbNew ) *pbNew = 1;
  173271. p->bPatchset = (op=='P');
  173272. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  173273. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  173274. p->in.iCurrent = p->in.iNext;
  173275. if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
  173276. op = p->in.aData[p->in.iNext++];
  173277. }
  173278. if( p->zTab==0 ){
  173279. /* The first record in the changeset is not a table header. Must be a
  173280. ** corrupt changeset. */
  173281. assert( p->in.iNext==1 );
  173282. return (p->rc = SQLITE_CORRUPT_BKPT);
  173283. }
  173284. p->op = op;
  173285. p->bIndirect = p->in.aData[p->in.iNext++];
  173286. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  173287. return (p->rc = SQLITE_CORRUPT_BKPT);
  173288. }
  173289. if( paRec ){
  173290. int nVal; /* Number of values to buffer */
  173291. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  173292. nVal = p->nCol * 2;
  173293. }else if( p->bPatchset && op==SQLITE_DELETE ){
  173294. nVal = 0;
  173295. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  173296. }else{
  173297. nVal = p->nCol;
  173298. }
  173299. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  173300. if( p->rc!=SQLITE_OK ) return p->rc;
  173301. *paRec = &p->in.aData[p->in.iNext];
  173302. p->in.iNext += *pnRec;
  173303. }else{
  173304. /* If this is an UPDATE or DELETE, read the old.* record. */
  173305. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  173306. u8 *abPK = p->bPatchset ? p->abPK : 0;
  173307. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
  173308. if( p->rc!=SQLITE_OK ) return p->rc;
  173309. }
  173310. /* If this is an INSERT or UPDATE, read the new.* record. */
  173311. if( p->op!=SQLITE_DELETE ){
  173312. p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
  173313. if( p->rc!=SQLITE_OK ) return p->rc;
  173314. }
  173315. if( p->bPatchset && p->op==SQLITE_UPDATE ){
  173316. /* If this is an UPDATE that is part of a patchset, then all PK and
  173317. ** modified fields are present in the new.* record. The old.* record
  173318. ** is currently completely empty. This block shifts the PK fields from
  173319. ** new.* to old.*, to accommodate the code that reads these arrays. */
  173320. for(i=0; i<p->nCol; i++){
  173321. assert( p->apValue[i]==0 );
  173322. if( p->abPK[i] ){
  173323. p->apValue[i] = p->apValue[i+p->nCol];
  173324. if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
  173325. p->apValue[i+p->nCol] = 0;
  173326. }
  173327. }
  173328. }
  173329. }
  173330. return SQLITE_ROW;
  173331. }
  173332. /*
  173333. ** Advance an iterator created by sqlite3changeset_start() to the next
  173334. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  173335. ** or SQLITE_CORRUPT.
  173336. **
  173337. ** This function may not be called on iterators passed to a conflict handler
  173338. ** callback by changeset_apply().
  173339. */
  173340. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  173341. return sessionChangesetNext(p, 0, 0, 0);
  173342. }
  173343. /*
  173344. ** The following function extracts information on the current change
  173345. ** from a changeset iterator. It may only be called after changeset_next()
  173346. ** has returned SQLITE_ROW.
  173347. */
  173348. SQLITE_API int sqlite3changeset_op(
  173349. sqlite3_changeset_iter *pIter, /* Iterator handle */
  173350. const char **pzTab, /* OUT: Pointer to table name */
  173351. int *pnCol, /* OUT: Number of columns in table */
  173352. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  173353. int *pbIndirect /* OUT: True if change is indirect */
  173354. ){
  173355. *pOp = pIter->op;
  173356. *pnCol = pIter->nCol;
  173357. *pzTab = pIter->zTab;
  173358. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  173359. return SQLITE_OK;
  173360. }
  173361. /*
  173362. ** Return information regarding the PRIMARY KEY and number of columns in
  173363. ** the database table affected by the change that pIter currently points
  173364. ** to. This function may only be called after changeset_next() returns
  173365. ** SQLITE_ROW.
  173366. */
  173367. SQLITE_API int sqlite3changeset_pk(
  173368. sqlite3_changeset_iter *pIter, /* Iterator object */
  173369. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  173370. int *pnCol /* OUT: Number of entries in output array */
  173371. ){
  173372. *pabPK = pIter->abPK;
  173373. if( pnCol ) *pnCol = pIter->nCol;
  173374. return SQLITE_OK;
  173375. }
  173376. /*
  173377. ** This function may only be called while the iterator is pointing to an
  173378. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  173379. ** Otherwise, SQLITE_MISUSE is returned.
  173380. **
  173381. ** It sets *ppValue to point to an sqlite3_value structure containing the
  173382. ** iVal'th value in the old.* record. Or, if that particular value is not
  173383. ** included in the record (because the change is an UPDATE and the field
  173384. ** was not modified and is not a PK column), set *ppValue to NULL.
  173385. **
  173386. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  173387. ** not modified. Otherwise, SQLITE_OK.
  173388. */
  173389. SQLITE_API int sqlite3changeset_old(
  173390. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  173391. int iVal, /* Index of old.* value to retrieve */
  173392. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  173393. ){
  173394. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  173395. return SQLITE_MISUSE;
  173396. }
  173397. if( iVal<0 || iVal>=pIter->nCol ){
  173398. return SQLITE_RANGE;
  173399. }
  173400. *ppValue = pIter->apValue[iVal];
  173401. return SQLITE_OK;
  173402. }
  173403. /*
  173404. ** This function may only be called while the iterator is pointing to an
  173405. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  173406. ** Otherwise, SQLITE_MISUSE is returned.
  173407. **
  173408. ** It sets *ppValue to point to an sqlite3_value structure containing the
  173409. ** iVal'th value in the new.* record. Or, if that particular value is not
  173410. ** included in the record (because the change is an UPDATE and the field
  173411. ** was not modified), set *ppValue to NULL.
  173412. **
  173413. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  173414. ** not modified. Otherwise, SQLITE_OK.
  173415. */
  173416. SQLITE_API int sqlite3changeset_new(
  173417. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  173418. int iVal, /* Index of new.* value to retrieve */
  173419. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  173420. ){
  173421. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  173422. return SQLITE_MISUSE;
  173423. }
  173424. if( iVal<0 || iVal>=pIter->nCol ){
  173425. return SQLITE_RANGE;
  173426. }
  173427. *ppValue = pIter->apValue[pIter->nCol+iVal];
  173428. return SQLITE_OK;
  173429. }
  173430. /*
  173431. ** The following two macros are used internally. They are similar to the
  173432. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  173433. ** they omit all error checking and return a pointer to the requested value.
  173434. */
  173435. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  173436. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  173437. /*
  173438. ** This function may only be called with a changeset iterator that has been
  173439. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  173440. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  173441. **
  173442. ** If successful, *ppValue is set to point to an sqlite3_value structure
  173443. ** containing the iVal'th value of the conflicting record.
  173444. **
  173445. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  173446. ** code is returned. Otherwise, SQLITE_OK.
  173447. */
  173448. SQLITE_API int sqlite3changeset_conflict(
  173449. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  173450. int iVal, /* Index of conflict record value to fetch */
  173451. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  173452. ){
  173453. if( !pIter->pConflict ){
  173454. return SQLITE_MISUSE;
  173455. }
  173456. if( iVal<0 || iVal>=pIter->nCol ){
  173457. return SQLITE_RANGE;
  173458. }
  173459. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  173460. return SQLITE_OK;
  173461. }
  173462. /*
  173463. ** This function may only be called with an iterator passed to an
  173464. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  173465. ** it sets the output variable to the total number of known foreign key
  173466. ** violations in the destination database and returns SQLITE_OK.
  173467. **
  173468. ** In all other cases this function returns SQLITE_MISUSE.
  173469. */
  173470. SQLITE_API int sqlite3changeset_fk_conflicts(
  173471. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  173472. int *pnOut /* OUT: Number of FK violations */
  173473. ){
  173474. if( pIter->pConflict || pIter->apValue ){
  173475. return SQLITE_MISUSE;
  173476. }
  173477. *pnOut = pIter->nCol;
  173478. return SQLITE_OK;
  173479. }
  173480. /*
  173481. ** Finalize an iterator allocated with sqlite3changeset_start().
  173482. **
  173483. ** This function may not be called on iterators passed to a conflict handler
  173484. ** callback by changeset_apply().
  173485. */
  173486. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  173487. int rc = SQLITE_OK;
  173488. if( p ){
  173489. int i; /* Used to iterate through p->apValue[] */
  173490. rc = p->rc;
  173491. if( p->apValue ){
  173492. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  173493. }
  173494. sqlite3_free(p->tblhdr.aBuf);
  173495. sqlite3_free(p->in.buf.aBuf);
  173496. sqlite3_free(p);
  173497. }
  173498. return rc;
  173499. }
  173500. static int sessionChangesetInvert(
  173501. SessionInput *pInput, /* Input changeset */
  173502. int (*xOutput)(void *pOut, const void *pData, int nData),
  173503. void *pOut,
  173504. int *pnInverted, /* OUT: Number of bytes in output changeset */
  173505. void **ppInverted /* OUT: Inverse of pChangeset */
  173506. ){
  173507. int rc = SQLITE_OK; /* Return value */
  173508. SessionBuffer sOut; /* Output buffer */
  173509. int nCol = 0; /* Number of cols in current table */
  173510. u8 *abPK = 0; /* PK array for current table */
  173511. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  173512. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  173513. /* Initialize the output buffer */
  173514. memset(&sOut, 0, sizeof(SessionBuffer));
  173515. /* Zero the output variables in case an error occurs. */
  173516. if( ppInverted ){
  173517. *ppInverted = 0;
  173518. *pnInverted = 0;
  173519. }
  173520. while( 1 ){
  173521. u8 eType;
  173522. /* Test for EOF. */
  173523. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  173524. if( pInput->iNext>=pInput->nData ) break;
  173525. eType = pInput->aData[pInput->iNext];
  173526. switch( eType ){
  173527. case 'T': {
  173528. /* A 'table' record consists of:
  173529. **
  173530. ** * A constant 'T' character,
  173531. ** * Number of columns in said table (a varint),
  173532. ** * An array of nCol bytes (sPK),
  173533. ** * A nul-terminated table name.
  173534. */
  173535. int nByte;
  173536. int nVar;
  173537. pInput->iNext++;
  173538. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  173539. goto finished_invert;
  173540. }
  173541. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  173542. sPK.nBuf = 0;
  173543. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  173544. sessionAppendByte(&sOut, eType, &rc);
  173545. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  173546. if( rc ) goto finished_invert;
  173547. pInput->iNext += nByte;
  173548. sqlite3_free(apVal);
  173549. apVal = 0;
  173550. abPK = sPK.aBuf;
  173551. break;
  173552. }
  173553. case SQLITE_INSERT:
  173554. case SQLITE_DELETE: {
  173555. int nByte;
  173556. int bIndirect = pInput->aData[pInput->iNext+1];
  173557. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  173558. pInput->iNext += 2;
  173559. assert( rc==SQLITE_OK );
  173560. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  173561. sessionAppendByte(&sOut, eType2, &rc);
  173562. sessionAppendByte(&sOut, bIndirect, &rc);
  173563. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  173564. pInput->iNext += nByte;
  173565. if( rc ) goto finished_invert;
  173566. break;
  173567. }
  173568. case SQLITE_UPDATE: {
  173569. int iCol;
  173570. if( 0==apVal ){
  173571. apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
  173572. if( 0==apVal ){
  173573. rc = SQLITE_NOMEM;
  173574. goto finished_invert;
  173575. }
  173576. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  173577. }
  173578. /* Write the header for the new UPDATE change. Same as the original. */
  173579. sessionAppendByte(&sOut, eType, &rc);
  173580. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  173581. /* Read the old.* and new.* records for the update change. */
  173582. pInput->iNext += 2;
  173583. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  173584. if( rc==SQLITE_OK ){
  173585. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  173586. }
  173587. /* Write the new old.* record. Consists of the PK columns from the
  173588. ** original old.* record, and the other values from the original
  173589. ** new.* record. */
  173590. for(iCol=0; iCol<nCol; iCol++){
  173591. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  173592. sessionAppendValue(&sOut, pVal, &rc);
  173593. }
  173594. /* Write the new new.* record. Consists of a copy of all values
  173595. ** from the original old.* record, except for the PK columns, which
  173596. ** are set to "undefined". */
  173597. for(iCol=0; iCol<nCol; iCol++){
  173598. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  173599. sessionAppendValue(&sOut, pVal, &rc);
  173600. }
  173601. for(iCol=0; iCol<nCol*2; iCol++){
  173602. sqlite3ValueFree(apVal[iCol]);
  173603. }
  173604. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  173605. if( rc!=SQLITE_OK ){
  173606. goto finished_invert;
  173607. }
  173608. break;
  173609. }
  173610. default:
  173611. rc = SQLITE_CORRUPT_BKPT;
  173612. goto finished_invert;
  173613. }
  173614. assert( rc==SQLITE_OK );
  173615. if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  173616. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  173617. sOut.nBuf = 0;
  173618. if( rc!=SQLITE_OK ) goto finished_invert;
  173619. }
  173620. }
  173621. assert( rc==SQLITE_OK );
  173622. if( pnInverted ){
  173623. *pnInverted = sOut.nBuf;
  173624. *ppInverted = sOut.aBuf;
  173625. sOut.aBuf = 0;
  173626. }else if( sOut.nBuf>0 ){
  173627. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  173628. }
  173629. finished_invert:
  173630. sqlite3_free(sOut.aBuf);
  173631. sqlite3_free(apVal);
  173632. sqlite3_free(sPK.aBuf);
  173633. return rc;
  173634. }
  173635. /*
  173636. ** Invert a changeset object.
  173637. */
  173638. SQLITE_API int sqlite3changeset_invert(
  173639. int nChangeset, /* Number of bytes in input */
  173640. const void *pChangeset, /* Input changeset */
  173641. int *pnInverted, /* OUT: Number of bytes in output changeset */
  173642. void **ppInverted /* OUT: Inverse of pChangeset */
  173643. ){
  173644. SessionInput sInput;
  173645. /* Set up the input stream */
  173646. memset(&sInput, 0, sizeof(SessionInput));
  173647. sInput.nData = nChangeset;
  173648. sInput.aData = (u8*)pChangeset;
  173649. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  173650. }
  173651. /*
  173652. ** Streaming version of sqlite3changeset_invert().
  173653. */
  173654. SQLITE_API int sqlite3changeset_invert_strm(
  173655. int (*xInput)(void *pIn, void *pData, int *pnData),
  173656. void *pIn,
  173657. int (*xOutput)(void *pOut, const void *pData, int nData),
  173658. void *pOut
  173659. ){
  173660. SessionInput sInput;
  173661. int rc;
  173662. /* Set up the input stream */
  173663. memset(&sInput, 0, sizeof(SessionInput));
  173664. sInput.xInput = xInput;
  173665. sInput.pIn = pIn;
  173666. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  173667. sqlite3_free(sInput.buf.aBuf);
  173668. return rc;
  173669. }
  173670. typedef struct SessionApplyCtx SessionApplyCtx;
  173671. struct SessionApplyCtx {
  173672. sqlite3 *db;
  173673. sqlite3_stmt *pDelete; /* DELETE statement */
  173674. sqlite3_stmt *pUpdate; /* UPDATE statement */
  173675. sqlite3_stmt *pInsert; /* INSERT statement */
  173676. sqlite3_stmt *pSelect; /* SELECT statement */
  173677. int nCol; /* Size of azCol[] and abPK[] arrays */
  173678. const char **azCol; /* Array of column names */
  173679. u8 *abPK; /* Boolean array - true if column is in PK */
  173680. int bStat1; /* True if table is sqlite_stat1 */
  173681. int bDeferConstraints; /* True to defer constraints */
  173682. SessionBuffer constraints; /* Deferred constraints are stored here */
  173683. SessionBuffer rebase; /* Rebase information (if any) here */
  173684. int bRebaseStarted; /* If table header is already in rebase */
  173685. };
  173686. /*
  173687. ** Formulate a statement to DELETE a row from database db. Assuming a table
  173688. ** structure like this:
  173689. **
  173690. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  173691. **
  173692. ** The DELETE statement looks like this:
  173693. **
  173694. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  173695. **
  173696. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  173697. ** matching b and d values, or 1 otherwise. The second case comes up if the
  173698. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  173699. **
  173700. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  173701. ** pointing to the prepared version of the SQL statement.
  173702. */
  173703. static int sessionDeleteRow(
  173704. sqlite3 *db, /* Database handle */
  173705. const char *zTab, /* Table name */
  173706. SessionApplyCtx *p /* Session changeset-apply context */
  173707. ){
  173708. int i;
  173709. const char *zSep = "";
  173710. int rc = SQLITE_OK;
  173711. SessionBuffer buf = {0, 0, 0};
  173712. int nPk = 0;
  173713. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  173714. sessionAppendIdent(&buf, zTab, &rc);
  173715. sessionAppendStr(&buf, " WHERE ", &rc);
  173716. for(i=0; i<p->nCol; i++){
  173717. if( p->abPK[i] ){
  173718. nPk++;
  173719. sessionAppendStr(&buf, zSep, &rc);
  173720. sessionAppendIdent(&buf, p->azCol[i], &rc);
  173721. sessionAppendStr(&buf, " = ?", &rc);
  173722. sessionAppendInteger(&buf, i+1, &rc);
  173723. zSep = " AND ";
  173724. }
  173725. }
  173726. if( nPk<p->nCol ){
  173727. sessionAppendStr(&buf, " AND (?", &rc);
  173728. sessionAppendInteger(&buf, p->nCol+1, &rc);
  173729. sessionAppendStr(&buf, " OR ", &rc);
  173730. zSep = "";
  173731. for(i=0; i<p->nCol; i++){
  173732. if( !p->abPK[i] ){
  173733. sessionAppendStr(&buf, zSep, &rc);
  173734. sessionAppendIdent(&buf, p->azCol[i], &rc);
  173735. sessionAppendStr(&buf, " IS ?", &rc);
  173736. sessionAppendInteger(&buf, i+1, &rc);
  173737. zSep = "AND ";
  173738. }
  173739. }
  173740. sessionAppendStr(&buf, ")", &rc);
  173741. }
  173742. if( rc==SQLITE_OK ){
  173743. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  173744. }
  173745. sqlite3_free(buf.aBuf);
  173746. return rc;
  173747. }
  173748. /*
  173749. ** Formulate and prepare a statement to UPDATE a row from database db.
  173750. ** Assuming a table structure like this:
  173751. **
  173752. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  173753. **
  173754. ** The UPDATE statement looks like this:
  173755. **
  173756. ** UPDATE x SET
  173757. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  173758. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  173759. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  173760. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  173761. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  173762. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  173763. ** )
  173764. **
  173765. ** For each column in the table, there are three variables to bind:
  173766. **
  173767. ** ?(i*3+1) The old.* value of the column, if any.
  173768. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  173769. ** ?(i*3+3) The new.* value of the column, if any.
  173770. **
  173771. ** Also, a boolean flag that, if set to true, causes the statement to update
  173772. ** a row even if the non-PK values do not match. This is required if the
  173773. ** conflict-handler is invoked with CHANGESET_DATA and returns
  173774. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  173775. **
  173776. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  173777. ** pointing to the prepared version of the SQL statement.
  173778. */
  173779. static int sessionUpdateRow(
  173780. sqlite3 *db, /* Database handle */
  173781. const char *zTab, /* Table name */
  173782. SessionApplyCtx *p /* Session changeset-apply context */
  173783. ){
  173784. int rc = SQLITE_OK;
  173785. int i;
  173786. const char *zSep = "";
  173787. SessionBuffer buf = {0, 0, 0};
  173788. /* Append "UPDATE tbl SET " */
  173789. sessionAppendStr(&buf, "UPDATE ", &rc);
  173790. sessionAppendIdent(&buf, zTab, &rc);
  173791. sessionAppendStr(&buf, " SET ", &rc);
  173792. /* Append the assignments */
  173793. for(i=0; i<p->nCol; i++){
  173794. sessionAppendStr(&buf, zSep, &rc);
  173795. sessionAppendIdent(&buf, p->azCol[i], &rc);
  173796. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  173797. sessionAppendInteger(&buf, i*3+2, &rc);
  173798. sessionAppendStr(&buf, " THEN ?", &rc);
  173799. sessionAppendInteger(&buf, i*3+3, &rc);
  173800. sessionAppendStr(&buf, " ELSE ", &rc);
  173801. sessionAppendIdent(&buf, p->azCol[i], &rc);
  173802. sessionAppendStr(&buf, " END", &rc);
  173803. zSep = ", ";
  173804. }
  173805. /* Append the PK part of the WHERE clause */
  173806. sessionAppendStr(&buf, " WHERE ", &rc);
  173807. for(i=0; i<p->nCol; i++){
  173808. if( p->abPK[i] ){
  173809. sessionAppendIdent(&buf, p->azCol[i], &rc);
  173810. sessionAppendStr(&buf, " = ?", &rc);
  173811. sessionAppendInteger(&buf, i*3+1, &rc);
  173812. sessionAppendStr(&buf, " AND ", &rc);
  173813. }
  173814. }
  173815. /* Append the non-PK part of the WHERE clause */
  173816. sessionAppendStr(&buf, " (?", &rc);
  173817. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  173818. sessionAppendStr(&buf, " OR 1", &rc);
  173819. for(i=0; i<p->nCol; i++){
  173820. if( !p->abPK[i] ){
  173821. sessionAppendStr(&buf, " AND (?", &rc);
  173822. sessionAppendInteger(&buf, i*3+2, &rc);
  173823. sessionAppendStr(&buf, "=0 OR ", &rc);
  173824. sessionAppendIdent(&buf, p->azCol[i], &rc);
  173825. sessionAppendStr(&buf, " IS ?", &rc);
  173826. sessionAppendInteger(&buf, i*3+1, &rc);
  173827. sessionAppendStr(&buf, ")", &rc);
  173828. }
  173829. }
  173830. sessionAppendStr(&buf, ")", &rc);
  173831. if( rc==SQLITE_OK ){
  173832. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  173833. }
  173834. sqlite3_free(buf.aBuf);
  173835. return rc;
  173836. }
  173837. /*
  173838. ** Formulate and prepare an SQL statement to query table zTab by primary
  173839. ** key. Assuming the following table structure:
  173840. **
  173841. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  173842. **
  173843. ** The SELECT statement looks like this:
  173844. **
  173845. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  173846. **
  173847. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  173848. ** pointing to the prepared version of the SQL statement.
  173849. */
  173850. static int sessionSelectRow(
  173851. sqlite3 *db, /* Database handle */
  173852. const char *zTab, /* Table name */
  173853. SessionApplyCtx *p /* Session changeset-apply context */
  173854. ){
  173855. return sessionSelectStmt(
  173856. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  173857. }
  173858. /*
  173859. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  173860. ** For example:
  173861. **
  173862. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  173863. **
  173864. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  173865. ** pointing to the prepared version of the SQL statement.
  173866. */
  173867. static int sessionInsertRow(
  173868. sqlite3 *db, /* Database handle */
  173869. const char *zTab, /* Table name */
  173870. SessionApplyCtx *p /* Session changeset-apply context */
  173871. ){
  173872. int rc = SQLITE_OK;
  173873. int i;
  173874. SessionBuffer buf = {0, 0, 0};
  173875. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  173876. sessionAppendIdent(&buf, zTab, &rc);
  173877. sessionAppendStr(&buf, "(", &rc);
  173878. for(i=0; i<p->nCol; i++){
  173879. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  173880. sessionAppendIdent(&buf, p->azCol[i], &rc);
  173881. }
  173882. sessionAppendStr(&buf, ") VALUES(?", &rc);
  173883. for(i=1; i<p->nCol; i++){
  173884. sessionAppendStr(&buf, ", ?", &rc);
  173885. }
  173886. sessionAppendStr(&buf, ")", &rc);
  173887. if( rc==SQLITE_OK ){
  173888. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  173889. }
  173890. sqlite3_free(buf.aBuf);
  173891. return rc;
  173892. }
  173893. static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
  173894. return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
  173895. }
  173896. /*
  173897. ** Prepare statements for applying changes to the sqlite_stat1 table.
  173898. ** These are similar to those created by sessionSelectRow(),
  173899. ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
  173900. ** other tables.
  173901. */
  173902. static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
  173903. int rc = sessionSelectRow(db, "sqlite_stat1", p);
  173904. if( rc==SQLITE_OK ){
  173905. rc = sessionPrepare(db, &p->pInsert,
  173906. "INSERT INTO main.sqlite_stat1 VALUES(?1, "
  173907. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
  173908. "?3)"
  173909. );
  173910. }
  173911. if( rc==SQLITE_OK ){
  173912. rc = sessionPrepare(db, &p->pUpdate,
  173913. "UPDATE main.sqlite_stat1 SET "
  173914. "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
  173915. "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
  173916. "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
  173917. "WHERE tbl=?1 AND idx IS "
  173918. "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
  173919. "AND (?10 OR ?8=0 OR stat IS ?7)"
  173920. );
  173921. }
  173922. if( rc==SQLITE_OK ){
  173923. rc = sessionPrepare(db, &p->pDelete,
  173924. "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
  173925. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
  173926. "AND (?4 OR stat IS ?3)"
  173927. );
  173928. }
  173929. return rc;
  173930. }
  173931. /*
  173932. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  173933. ** See comments in the body of this function for details.
  173934. */
  173935. static int sessionBindValue(
  173936. sqlite3_stmt *pStmt, /* Statement to bind value to */
  173937. int i, /* Parameter number to bind to */
  173938. sqlite3_value *pVal /* Value to bind */
  173939. ){
  173940. int eType = sqlite3_value_type(pVal);
  173941. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  173942. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  173943. ** the (pVal->z) variable remains as it was or the type of the value is
  173944. ** set to SQLITE_NULL. */
  173945. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  173946. /* This condition occurs when an earlier OOM in a call to
  173947. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  173948. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  173949. return SQLITE_NOMEM;
  173950. }
  173951. return sqlite3_bind_value(pStmt, i, pVal);
  173952. }
  173953. /*
  173954. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  173955. ** transfers new.* values from the current iterator entry to statement
  173956. ** pStmt. The table being inserted into has nCol columns.
  173957. **
  173958. ** New.* value $i from the iterator is bound to variable ($i+1) of
  173959. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  173960. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  173961. ** to an array nCol elements in size. In this case only those values for
  173962. ** which abPK[$i] is true are read from the iterator and bound to the
  173963. ** statement.
  173964. **
  173965. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  173966. */
  173967. static int sessionBindRow(
  173968. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  173969. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  173970. int nCol, /* Number of columns */
  173971. u8 *abPK, /* If not NULL, bind only if true */
  173972. sqlite3_stmt *pStmt /* Bind values to this statement */
  173973. ){
  173974. int i;
  173975. int rc = SQLITE_OK;
  173976. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  173977. ** argument iterator points to a suitable entry. Make sure that xValue
  173978. ** is one of these to guarantee that it is safe to ignore the return
  173979. ** in the code below. */
  173980. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  173981. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  173982. if( !abPK || abPK[i] ){
  173983. sqlite3_value *pVal;
  173984. (void)xValue(pIter, i, &pVal);
  173985. if( pVal==0 ){
  173986. /* The value in the changeset was "undefined". This indicates a
  173987. ** corrupt changeset blob. */
  173988. rc = SQLITE_CORRUPT_BKPT;
  173989. }else{
  173990. rc = sessionBindValue(pStmt, i+1, pVal);
  173991. }
  173992. }
  173993. }
  173994. return rc;
  173995. }
  173996. /*
  173997. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  173998. ** This function binds the primary key values from the change that changeset
  173999. ** iterator pIter points to to the SELECT and attempts to seek to the table
  174000. ** entry. If a row is found, the SELECT statement left pointing at the row
  174001. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  174002. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  174003. ** error occurs, the statement is reset and an SQLite error code is returned.
  174004. **
  174005. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  174006. ** statement pSelect. If any other value is returned, the statement does
  174007. ** not require a reset().
  174008. **
  174009. ** If the iterator currently points to an INSERT record, bind values from the
  174010. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  174011. ** UPDATE, bind values from the old.* record.
  174012. */
  174013. static int sessionSeekToRow(
  174014. sqlite3 *db, /* Database handle */
  174015. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  174016. u8 *abPK, /* Primary key flags array */
  174017. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  174018. ){
  174019. int rc; /* Return code */
  174020. int nCol; /* Number of columns in table */
  174021. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  174022. const char *zDummy; /* Unused */
  174023. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  174024. rc = sessionBindRow(pIter,
  174025. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  174026. nCol, abPK, pSelect
  174027. );
  174028. if( rc==SQLITE_OK ){
  174029. rc = sqlite3_step(pSelect);
  174030. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  174031. }
  174032. return rc;
  174033. }
  174034. /*
  174035. ** This function is called from within sqlite3changset_apply_v2() when
  174036. ** a conflict is encountered and resolved using conflict resolution
  174037. ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
  174038. ** It adds a conflict resolution record to the buffer in
  174039. ** SessionApplyCtx.rebase, which will eventually be returned to the caller
  174040. ** of apply_v2() as the "rebase" buffer.
  174041. **
  174042. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  174043. */
  174044. static int sessionRebaseAdd(
  174045. SessionApplyCtx *p, /* Apply context */
  174046. int eType, /* Conflict resolution (OMIT or REPLACE) */
  174047. sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
  174048. ){
  174049. int rc = SQLITE_OK;
  174050. int i;
  174051. int eOp = pIter->op;
  174052. if( p->bRebaseStarted==0 ){
  174053. /* Append a table-header to the rebase buffer */
  174054. const char *zTab = pIter->zTab;
  174055. sessionAppendByte(&p->rebase, 'T', &rc);
  174056. sessionAppendVarint(&p->rebase, p->nCol, &rc);
  174057. sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
  174058. sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
  174059. p->bRebaseStarted = 1;
  174060. }
  174061. assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
  174062. assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
  174063. sessionAppendByte(&p->rebase,
  174064. (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
  174065. );
  174066. sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
  174067. for(i=0; i<p->nCol; i++){
  174068. sqlite3_value *pVal = 0;
  174069. if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
  174070. sqlite3changeset_old(pIter, i, &pVal);
  174071. }else{
  174072. sqlite3changeset_new(pIter, i, &pVal);
  174073. }
  174074. sessionAppendValue(&p->rebase, pVal, &rc);
  174075. }
  174076. return rc;
  174077. }
  174078. /*
  174079. ** Invoke the conflict handler for the change that the changeset iterator
  174080. ** currently points to.
  174081. **
  174082. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  174083. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  174084. ** depends solely on eType, as follows:
  174085. **
  174086. ** eType value Value passed to xConflict
  174087. ** -------------------------------------------------
  174088. ** CHANGESET_DATA CHANGESET_NOTFOUND
  174089. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  174090. **
  174091. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  174092. ** record with the same primary key as the record about to be deleted, updated
  174093. ** or inserted. If such a record can be found, it is available to the conflict
  174094. ** handler as the "conflicting" record. In this case the type of conflict
  174095. ** handler invoked is as follows:
  174096. **
  174097. ** eType value PK Record found? Value passed to xConflict
  174098. ** ----------------------------------------------------------------
  174099. ** CHANGESET_DATA Yes CHANGESET_DATA
  174100. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  174101. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  174102. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  174103. **
  174104. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  174105. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  174106. ** is set to non-zero before returning SQLITE_OK.
  174107. **
  174108. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  174109. ** returned. Or, if the conflict handler returns an invalid value,
  174110. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  174111. ** this function returns SQLITE_OK.
  174112. */
  174113. static int sessionConflictHandler(
  174114. int eType, /* Either CHANGESET_DATA or CONFLICT */
  174115. SessionApplyCtx *p, /* changeset_apply() context */
  174116. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  174117. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  174118. void *pCtx, /* First argument for conflict handler */
  174119. int *pbReplace /* OUT: Set to true if PK row is found */
  174120. ){
  174121. int res = 0; /* Value returned by conflict handler */
  174122. int rc;
  174123. int nCol;
  174124. int op;
  174125. const char *zDummy;
  174126. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  174127. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  174128. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  174129. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  174130. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  174131. if( pbReplace ){
  174132. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  174133. }else{
  174134. rc = SQLITE_OK;
  174135. }
  174136. if( rc==SQLITE_ROW ){
  174137. /* There exists another row with the new.* primary key. */
  174138. pIter->pConflict = p->pSelect;
  174139. res = xConflict(pCtx, eType, pIter);
  174140. pIter->pConflict = 0;
  174141. rc = sqlite3_reset(p->pSelect);
  174142. }else if( rc==SQLITE_OK ){
  174143. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  174144. /* Instead of invoking the conflict handler, append the change blob
  174145. ** to the SessionApplyCtx.constraints buffer. */
  174146. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  174147. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  174148. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  174149. return SQLITE_OK;
  174150. }else{
  174151. /* No other row with the new.* primary key. */
  174152. res = xConflict(pCtx, eType+1, pIter);
  174153. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  174154. }
  174155. }
  174156. if( rc==SQLITE_OK ){
  174157. switch( res ){
  174158. case SQLITE_CHANGESET_REPLACE:
  174159. assert( pbReplace );
  174160. *pbReplace = 1;
  174161. break;
  174162. case SQLITE_CHANGESET_OMIT:
  174163. break;
  174164. case SQLITE_CHANGESET_ABORT:
  174165. rc = SQLITE_ABORT;
  174166. break;
  174167. default:
  174168. rc = SQLITE_MISUSE;
  174169. break;
  174170. }
  174171. if( rc==SQLITE_OK ){
  174172. rc = sessionRebaseAdd(p, res, pIter);
  174173. }
  174174. }
  174175. return rc;
  174176. }
  174177. /*
  174178. ** Attempt to apply the change that the iterator passed as the first argument
  174179. ** currently points to to the database. If a conflict is encountered, invoke
  174180. ** the conflict handler callback.
  174181. **
  174182. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  174183. ** one is encountered, update or delete the row with the matching primary key
  174184. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  174185. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  174186. ** to true before returning. In this case the caller will invoke this function
  174187. ** again, this time with pbRetry set to NULL.
  174188. **
  174189. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  174190. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  174191. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  174192. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  174193. ** before retrying. In this case the caller attempts to remove the conflicting
  174194. ** row before invoking this function again, this time with pbReplace set
  174195. ** to NULL.
  174196. **
  174197. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  174198. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  174199. ** returned.
  174200. */
  174201. static int sessionApplyOneOp(
  174202. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  174203. SessionApplyCtx *p, /* changeset_apply() context */
  174204. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  174205. void *pCtx, /* First argument for the conflict handler */
  174206. int *pbReplace, /* OUT: True to remove PK row and retry */
  174207. int *pbRetry /* OUT: True to retry. */
  174208. ){
  174209. const char *zDummy;
  174210. int op;
  174211. int nCol;
  174212. int rc = SQLITE_OK;
  174213. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  174214. assert( p->azCol && p->abPK );
  174215. assert( !pbReplace || *pbReplace==0 );
  174216. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  174217. if( op==SQLITE_DELETE ){
  174218. /* Bind values to the DELETE statement. If conflict handling is required,
  174219. ** bind values for all columns and set bound variable (nCol+1) to true.
  174220. ** Or, if conflict handling is not required, bind just the PK column
  174221. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  174222. ** is not required if:
  174223. **
  174224. ** * this is a patchset, or
  174225. ** * (pbRetry==0), or
  174226. ** * all columns of the table are PK columns (in this case there is
  174227. ** no (nCol+1) variable to bind to).
  174228. */
  174229. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  174230. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  174231. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  174232. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  174233. }
  174234. if( rc!=SQLITE_OK ) return rc;
  174235. sqlite3_step(p->pDelete);
  174236. rc = sqlite3_reset(p->pDelete);
  174237. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  174238. rc = sessionConflictHandler(
  174239. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  174240. );
  174241. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  174242. rc = sessionConflictHandler(
  174243. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  174244. );
  174245. }
  174246. }else if( op==SQLITE_UPDATE ){
  174247. int i;
  174248. /* Bind values to the UPDATE statement. */
  174249. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  174250. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  174251. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  174252. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  174253. if( pOld ){
  174254. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  174255. }
  174256. if( rc==SQLITE_OK && pNew ){
  174257. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  174258. }
  174259. }
  174260. if( rc==SQLITE_OK ){
  174261. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  174262. }
  174263. if( rc!=SQLITE_OK ) return rc;
  174264. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  174265. ** the result will be SQLITE_OK with 0 rows modified. */
  174266. sqlite3_step(p->pUpdate);
  174267. rc = sqlite3_reset(p->pUpdate);
  174268. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  174269. /* A NOTFOUND or DATA error. Search the table to see if it contains
  174270. ** a row with a matching primary key. If so, this is a DATA conflict.
  174271. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  174272. rc = sessionConflictHandler(
  174273. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  174274. );
  174275. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  174276. /* This is always a CONSTRAINT conflict. */
  174277. rc = sessionConflictHandler(
  174278. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  174279. );
  174280. }
  174281. }else{
  174282. assert( op==SQLITE_INSERT );
  174283. if( p->bStat1 ){
  174284. /* Check if there is a conflicting row. For sqlite_stat1, this needs
  174285. ** to be done using a SELECT, as there is no PRIMARY KEY in the
  174286. ** database schema to throw an exception if a duplicate is inserted. */
  174287. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  174288. if( rc==SQLITE_ROW ){
  174289. rc = SQLITE_CONSTRAINT;
  174290. sqlite3_reset(p->pSelect);
  174291. }
  174292. }
  174293. if( rc==SQLITE_OK ){
  174294. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  174295. if( rc!=SQLITE_OK ) return rc;
  174296. sqlite3_step(p->pInsert);
  174297. rc = sqlite3_reset(p->pInsert);
  174298. }
  174299. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  174300. rc = sessionConflictHandler(
  174301. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  174302. );
  174303. }
  174304. }
  174305. return rc;
  174306. }
  174307. /*
  174308. ** Attempt to apply the change that the iterator passed as the first argument
  174309. ** currently points to to the database. If a conflict is encountered, invoke
  174310. ** the conflict handler callback.
  174311. **
  174312. ** The difference between this function and sessionApplyOne() is that this
  174313. ** function handles the case where the conflict-handler is invoked and
  174314. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  174315. ** retried in some manner.
  174316. */
  174317. static int sessionApplyOneWithRetry(
  174318. sqlite3 *db, /* Apply change to "main" db of this handle */
  174319. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  174320. SessionApplyCtx *pApply, /* Apply context */
  174321. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  174322. void *pCtx /* First argument passed to xConflict */
  174323. ){
  174324. int bReplace = 0;
  174325. int bRetry = 0;
  174326. int rc;
  174327. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  174328. if( rc==SQLITE_OK ){
  174329. /* If the bRetry flag is set, the change has not been applied due to an
  174330. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  174331. ** a row with the correct PK is present in the db, but one or more other
  174332. ** fields do not contain the expected values) and the conflict handler
  174333. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  174334. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  174335. ** the SQLITE_CHANGESET_DATA problem. */
  174336. if( bRetry ){
  174337. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  174338. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  174339. }
  174340. /* If the bReplace flag is set, the change is an INSERT that has not
  174341. ** been performed because the database already contains a row with the
  174342. ** specified primary key and the conflict handler returned
  174343. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  174344. ** before reattempting the INSERT. */
  174345. else if( bReplace ){
  174346. assert( pIter->op==SQLITE_INSERT );
  174347. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  174348. if( rc==SQLITE_OK ){
  174349. rc = sessionBindRow(pIter,
  174350. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  174351. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  174352. }
  174353. if( rc==SQLITE_OK ){
  174354. sqlite3_step(pApply->pDelete);
  174355. rc = sqlite3_reset(pApply->pDelete);
  174356. }
  174357. if( rc==SQLITE_OK ){
  174358. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  174359. }
  174360. if( rc==SQLITE_OK ){
  174361. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  174362. }
  174363. }
  174364. }
  174365. return rc;
  174366. }
  174367. /*
  174368. ** Retry the changes accumulated in the pApply->constraints buffer.
  174369. */
  174370. static int sessionRetryConstraints(
  174371. sqlite3 *db,
  174372. int bPatchset,
  174373. const char *zTab,
  174374. SessionApplyCtx *pApply,
  174375. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  174376. void *pCtx /* First argument passed to xConflict */
  174377. ){
  174378. int rc = SQLITE_OK;
  174379. while( pApply->constraints.nBuf ){
  174380. sqlite3_changeset_iter *pIter2 = 0;
  174381. SessionBuffer cons = pApply->constraints;
  174382. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  174383. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
  174384. if( rc==SQLITE_OK ){
  174385. int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  174386. int rc2;
  174387. pIter2->bPatchset = bPatchset;
  174388. pIter2->zTab = (char*)zTab;
  174389. pIter2->nCol = pApply->nCol;
  174390. pIter2->abPK = pApply->abPK;
  174391. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  174392. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  174393. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  174394. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  174395. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  174396. }
  174397. rc2 = sqlite3changeset_finalize(pIter2);
  174398. if( rc==SQLITE_OK ) rc = rc2;
  174399. }
  174400. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  174401. sqlite3_free(cons.aBuf);
  174402. if( rc!=SQLITE_OK ) break;
  174403. if( pApply->constraints.nBuf>=cons.nBuf ){
  174404. /* No progress was made on the last round. */
  174405. pApply->bDeferConstraints = 0;
  174406. }
  174407. }
  174408. return rc;
  174409. }
  174410. /*
  174411. ** Argument pIter is a changeset iterator that has been initialized, but
  174412. ** not yet passed to sqlite3changeset_next(). This function applies the
  174413. ** changeset to the main database attached to handle "db". The supplied
  174414. ** conflict handler callback is invoked to resolve any conflicts encountered
  174415. ** while applying the change.
  174416. */
  174417. static int sessionChangesetApply(
  174418. sqlite3 *db, /* Apply change to "main" db of this handle */
  174419. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  174420. int(*xFilter)(
  174421. void *pCtx, /* Copy of sixth arg to _apply() */
  174422. const char *zTab /* Table name */
  174423. ),
  174424. int(*xConflict)(
  174425. void *pCtx, /* Copy of fifth arg to _apply() */
  174426. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  174427. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  174428. ),
  174429. void *pCtx, /* First argument passed to xConflict */
  174430. void **ppRebase, int *pnRebase, /* OUT: Rebase information */
  174431. int flags /* SESSION_APPLY_XXX flags */
  174432. ){
  174433. int schemaMismatch = 0;
  174434. int rc = SQLITE_OK; /* Return code */
  174435. const char *zTab = 0; /* Name of current table */
  174436. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  174437. SessionApplyCtx sApply; /* changeset_apply() context object */
  174438. int bPatchset;
  174439. assert( xConflict!=0 );
  174440. pIter->in.bNoDiscard = 1;
  174441. memset(&sApply, 0, sizeof(sApply));
  174442. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  174443. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  174444. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  174445. }
  174446. if( rc==SQLITE_OK ){
  174447. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  174448. }
  174449. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  174450. int nCol;
  174451. int op;
  174452. const char *zNew;
  174453. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  174454. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  174455. u8 *abPK;
  174456. rc = sessionRetryConstraints(
  174457. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  174458. );
  174459. if( rc!=SQLITE_OK ) break;
  174460. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  174461. sqlite3_finalize(sApply.pDelete);
  174462. sqlite3_finalize(sApply.pUpdate);
  174463. sqlite3_finalize(sApply.pInsert);
  174464. sqlite3_finalize(sApply.pSelect);
  174465. sApply.db = db;
  174466. sApply.pDelete = 0;
  174467. sApply.pUpdate = 0;
  174468. sApply.pInsert = 0;
  174469. sApply.pSelect = 0;
  174470. sApply.nCol = 0;
  174471. sApply.azCol = 0;
  174472. sApply.abPK = 0;
  174473. sApply.bStat1 = 0;
  174474. sApply.bDeferConstraints = 1;
  174475. sApply.bRebaseStarted = 0;
  174476. memset(&sApply.constraints, 0, sizeof(SessionBuffer));
  174477. /* If an xFilter() callback was specified, invoke it now. If the
  174478. ** xFilter callback returns zero, skip this table. If it returns
  174479. ** non-zero, proceed. */
  174480. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  174481. if( schemaMismatch ){
  174482. zTab = sqlite3_mprintf("%s", zNew);
  174483. if( zTab==0 ){
  174484. rc = SQLITE_NOMEM;
  174485. break;
  174486. }
  174487. nTab = (int)strlen(zTab);
  174488. sApply.azCol = (const char **)zTab;
  174489. }else{
  174490. int nMinCol = 0;
  174491. int i;
  174492. sqlite3changeset_pk(pIter, &abPK, 0);
  174493. rc = sessionTableInfo(
  174494. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  174495. );
  174496. if( rc!=SQLITE_OK ) break;
  174497. for(i=0; i<sApply.nCol; i++){
  174498. if( sApply.abPK[i] ) nMinCol = i+1;
  174499. }
  174500. if( sApply.nCol==0 ){
  174501. schemaMismatch = 1;
  174502. sqlite3_log(SQLITE_SCHEMA,
  174503. "sqlite3changeset_apply(): no such table: %s", zTab
  174504. );
  174505. }
  174506. else if( sApply.nCol<nCol ){
  174507. schemaMismatch = 1;
  174508. sqlite3_log(SQLITE_SCHEMA,
  174509. "sqlite3changeset_apply(): table %s has %d columns, "
  174510. "expected %d or more",
  174511. zTab, sApply.nCol, nCol
  174512. );
  174513. }
  174514. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  174515. schemaMismatch = 1;
  174516. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  174517. "primary key mismatch for table %s", zTab
  174518. );
  174519. }
  174520. else{
  174521. sApply.nCol = nCol;
  174522. if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
  174523. if( (rc = sessionStat1Sql(db, &sApply) ) ){
  174524. break;
  174525. }
  174526. sApply.bStat1 = 1;
  174527. }else{
  174528. if((rc = sessionSelectRow(db, zTab, &sApply))
  174529. || (rc = sessionUpdateRow(db, zTab, &sApply))
  174530. || (rc = sessionDeleteRow(db, zTab, &sApply))
  174531. || (rc = sessionInsertRow(db, zTab, &sApply))
  174532. ){
  174533. break;
  174534. }
  174535. sApply.bStat1 = 0;
  174536. }
  174537. }
  174538. nTab = sqlite3Strlen30(zTab);
  174539. }
  174540. }
  174541. /* If there is a schema mismatch on the current table, proceed to the
  174542. ** next change. A log message has already been issued. */
  174543. if( schemaMismatch ) continue;
  174544. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  174545. }
  174546. bPatchset = pIter->bPatchset;
  174547. if( rc==SQLITE_OK ){
  174548. rc = sqlite3changeset_finalize(pIter);
  174549. }else{
  174550. sqlite3changeset_finalize(pIter);
  174551. }
  174552. if( rc==SQLITE_OK ){
  174553. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  174554. }
  174555. if( rc==SQLITE_OK ){
  174556. int nFk, notUsed;
  174557. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  174558. if( nFk!=0 ){
  174559. int res = SQLITE_CHANGESET_ABORT;
  174560. sqlite3_changeset_iter sIter;
  174561. memset(&sIter, 0, sizeof(sIter));
  174562. sIter.nCol = nFk;
  174563. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  174564. if( res!=SQLITE_CHANGESET_OMIT ){
  174565. rc = SQLITE_CONSTRAINT;
  174566. }
  174567. }
  174568. }
  174569. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  174570. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  174571. if( rc==SQLITE_OK ){
  174572. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  174573. }else{
  174574. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  174575. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  174576. }
  174577. }
  174578. if( rc==SQLITE_OK && bPatchset==0 && ppRebase && pnRebase ){
  174579. *ppRebase = (void*)sApply.rebase.aBuf;
  174580. *pnRebase = sApply.rebase.nBuf;
  174581. sApply.rebase.aBuf = 0;
  174582. }
  174583. sqlite3_finalize(sApply.pInsert);
  174584. sqlite3_finalize(sApply.pDelete);
  174585. sqlite3_finalize(sApply.pUpdate);
  174586. sqlite3_finalize(sApply.pSelect);
  174587. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  174588. sqlite3_free((char*)sApply.constraints.aBuf);
  174589. sqlite3_free((char*)sApply.rebase.aBuf);
  174590. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  174591. return rc;
  174592. }
  174593. /*
  174594. ** Apply the changeset passed via pChangeset/nChangeset to the main
  174595. ** database attached to handle "db".
  174596. */
  174597. SQLITE_API int sqlite3changeset_apply_v2(
  174598. sqlite3 *db, /* Apply change to "main" db of this handle */
  174599. int nChangeset, /* Size of changeset in bytes */
  174600. void *pChangeset, /* Changeset blob */
  174601. int(*xFilter)(
  174602. void *pCtx, /* Copy of sixth arg to _apply() */
  174603. const char *zTab /* Table name */
  174604. ),
  174605. int(*xConflict)(
  174606. void *pCtx, /* Copy of sixth arg to _apply() */
  174607. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  174608. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  174609. ),
  174610. void *pCtx, /* First argument passed to xConflict */
  174611. void **ppRebase, int *pnRebase,
  174612. int flags
  174613. ){
  174614. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  174615. int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
  174616. if( rc==SQLITE_OK ){
  174617. rc = sessionChangesetApply(
  174618. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  174619. );
  174620. }
  174621. return rc;
  174622. }
  174623. /*
  174624. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  174625. ** attached to handle "db". Invoke the supplied conflict handler callback
  174626. ** to resolve any conflicts encountered while applying the change.
  174627. */
  174628. SQLITE_API int sqlite3changeset_apply(
  174629. sqlite3 *db, /* Apply change to "main" db of this handle */
  174630. int nChangeset, /* Size of changeset in bytes */
  174631. void *pChangeset, /* Changeset blob */
  174632. int(*xFilter)(
  174633. void *pCtx, /* Copy of sixth arg to _apply() */
  174634. const char *zTab /* Table name */
  174635. ),
  174636. int(*xConflict)(
  174637. void *pCtx, /* Copy of fifth arg to _apply() */
  174638. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  174639. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  174640. ),
  174641. void *pCtx /* First argument passed to xConflict */
  174642. ){
  174643. return sqlite3changeset_apply_v2(
  174644. db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
  174645. );
  174646. }
  174647. /*
  174648. ** Apply the changeset passed via xInput/pIn to the main database
  174649. ** attached to handle "db". Invoke the supplied conflict handler callback
  174650. ** to resolve any conflicts encountered while applying the change.
  174651. */
  174652. SQLITE_API int sqlite3changeset_apply_v2_strm(
  174653. sqlite3 *db, /* Apply change to "main" db of this handle */
  174654. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  174655. void *pIn, /* First arg for xInput */
  174656. int(*xFilter)(
  174657. void *pCtx, /* Copy of sixth arg to _apply() */
  174658. const char *zTab /* Table name */
  174659. ),
  174660. int(*xConflict)(
  174661. void *pCtx, /* Copy of sixth arg to _apply() */
  174662. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  174663. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  174664. ),
  174665. void *pCtx, /* First argument passed to xConflict */
  174666. void **ppRebase, int *pnRebase,
  174667. int flags
  174668. ){
  174669. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  174670. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  174671. if( rc==SQLITE_OK ){
  174672. rc = sessionChangesetApply(
  174673. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  174674. );
  174675. }
  174676. return rc;
  174677. }
  174678. SQLITE_API int sqlite3changeset_apply_strm(
  174679. sqlite3 *db, /* Apply change to "main" db of this handle */
  174680. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  174681. void *pIn, /* First arg for xInput */
  174682. int(*xFilter)(
  174683. void *pCtx, /* Copy of sixth arg to _apply() */
  174684. const char *zTab /* Table name */
  174685. ),
  174686. int(*xConflict)(
  174687. void *pCtx, /* Copy of sixth arg to _apply() */
  174688. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  174689. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  174690. ),
  174691. void *pCtx /* First argument passed to xConflict */
  174692. ){
  174693. return sqlite3changeset_apply_v2_strm(
  174694. db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
  174695. );
  174696. }
  174697. /*
  174698. ** sqlite3_changegroup handle.
  174699. */
  174700. struct sqlite3_changegroup {
  174701. int rc; /* Error code */
  174702. int bPatch; /* True to accumulate patchsets */
  174703. SessionTable *pList; /* List of tables in current patch */
  174704. };
  174705. /*
  174706. ** This function is called to merge two changes to the same row together as
  174707. ** part of an sqlite3changeset_concat() operation. A new change object is
  174708. ** allocated and a pointer to it stored in *ppNew.
  174709. */
  174710. static int sessionChangeMerge(
  174711. SessionTable *pTab, /* Table structure */
  174712. int bRebase, /* True for a rebase hash-table */
  174713. int bPatchset, /* True for patchsets */
  174714. SessionChange *pExist, /* Existing change */
  174715. int op2, /* Second change operation */
  174716. int bIndirect, /* True if second change is indirect */
  174717. u8 *aRec, /* Second change record */
  174718. int nRec, /* Number of bytes in aRec */
  174719. SessionChange **ppNew /* OUT: Merged change */
  174720. ){
  174721. SessionChange *pNew = 0;
  174722. int rc = SQLITE_OK;
  174723. if( !pExist ){
  174724. pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
  174725. if( !pNew ){
  174726. return SQLITE_NOMEM;
  174727. }
  174728. memset(pNew, 0, sizeof(SessionChange));
  174729. pNew->op = op2;
  174730. pNew->bIndirect = bIndirect;
  174731. pNew->aRecord = (u8*)&pNew[1];
  174732. if( bIndirect==0 || bRebase==0 ){
  174733. pNew->nRecord = nRec;
  174734. memcpy(pNew->aRecord, aRec, nRec);
  174735. }else{
  174736. int i;
  174737. u8 *pIn = aRec;
  174738. u8 *pOut = pNew->aRecord;
  174739. for(i=0; i<pTab->nCol; i++){
  174740. int nIn = sessionSerialLen(pIn);
  174741. if( *pIn==0 ){
  174742. *pOut++ = 0;
  174743. }else if( pTab->abPK[i]==0 ){
  174744. *pOut++ = 0xFF;
  174745. }else{
  174746. memcpy(pOut, pIn, nIn);
  174747. pOut += nIn;
  174748. }
  174749. pIn += nIn;
  174750. }
  174751. pNew->nRecord = pOut - pNew->aRecord;
  174752. }
  174753. }else if( bRebase ){
  174754. if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
  174755. *ppNew = pExist;
  174756. }else{
  174757. int nByte = nRec + pExist->nRecord + sizeof(SessionChange);
  174758. pNew = (SessionChange*)sqlite3_malloc(nByte);
  174759. if( pNew==0 ){
  174760. rc = SQLITE_NOMEM;
  174761. }else{
  174762. int i;
  174763. u8 *a1 = pExist->aRecord;
  174764. u8 *a2 = aRec;
  174765. u8 *pOut;
  174766. memset(pNew, 0, nByte);
  174767. pNew->bIndirect = bIndirect || pExist->bIndirect;
  174768. pNew->op = op2;
  174769. pOut = pNew->aRecord = (u8*)&pNew[1];
  174770. for(i=0; i<pTab->nCol; i++){
  174771. int n1 = sessionSerialLen(a1);
  174772. int n2 = sessionSerialLen(a2);
  174773. if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
  174774. *pOut++ = 0xFF;
  174775. }else if( *a2==0 ){
  174776. memcpy(pOut, a1, n1);
  174777. pOut += n1;
  174778. }else{
  174779. memcpy(pOut, a2, n2);
  174780. pOut += n2;
  174781. }
  174782. a1 += n1;
  174783. a2 += n2;
  174784. }
  174785. pNew->nRecord = pOut - pNew->aRecord;
  174786. }
  174787. sqlite3_free(pExist);
  174788. }
  174789. }else{
  174790. int op1 = pExist->op;
  174791. /*
  174792. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  174793. ** op1=INSERT, op2=UPDATE -> INSERT.
  174794. ** op1=INSERT, op2=DELETE -> (none)
  174795. **
  174796. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  174797. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  174798. ** op1=UPDATE, op2=DELETE -> DELETE.
  174799. **
  174800. ** op1=DELETE, op2=INSERT -> UPDATE.
  174801. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  174802. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  174803. */
  174804. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  174805. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  174806. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  174807. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  174808. ){
  174809. pNew = pExist;
  174810. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  174811. sqlite3_free(pExist);
  174812. assert( pNew==0 );
  174813. }else{
  174814. u8 *aExist = pExist->aRecord;
  174815. int nByte;
  174816. u8 *aCsr;
  174817. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  174818. ** buffer of the new object is large enough to hold any record that
  174819. ** may be generated by combining the input records. */
  174820. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  174821. pNew = (SessionChange *)sqlite3_malloc(nByte);
  174822. if( !pNew ){
  174823. sqlite3_free(pExist);
  174824. return SQLITE_NOMEM;
  174825. }
  174826. memset(pNew, 0, sizeof(SessionChange));
  174827. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  174828. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  174829. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  174830. u8 *a1 = aRec;
  174831. assert( op2==SQLITE_UPDATE );
  174832. pNew->op = SQLITE_INSERT;
  174833. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  174834. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  174835. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  174836. assert( op2==SQLITE_INSERT );
  174837. pNew->op = SQLITE_UPDATE;
  174838. if( bPatchset ){
  174839. memcpy(aCsr, aRec, nRec);
  174840. aCsr += nRec;
  174841. }else{
  174842. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  174843. sqlite3_free(pNew);
  174844. pNew = 0;
  174845. }
  174846. }
  174847. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  174848. u8 *a1 = aExist;
  174849. u8 *a2 = aRec;
  174850. assert( op1==SQLITE_UPDATE );
  174851. if( bPatchset==0 ){
  174852. sessionSkipRecord(&a1, pTab->nCol);
  174853. sessionSkipRecord(&a2, pTab->nCol);
  174854. }
  174855. pNew->op = SQLITE_UPDATE;
  174856. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  174857. sqlite3_free(pNew);
  174858. pNew = 0;
  174859. }
  174860. }else{ /* UPDATE + DELETE */
  174861. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  174862. pNew->op = SQLITE_DELETE;
  174863. if( bPatchset ){
  174864. memcpy(aCsr, aRec, nRec);
  174865. aCsr += nRec;
  174866. }else{
  174867. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  174868. }
  174869. }
  174870. if( pNew ){
  174871. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  174872. }
  174873. sqlite3_free(pExist);
  174874. }
  174875. }
  174876. *ppNew = pNew;
  174877. return rc;
  174878. }
  174879. /*
  174880. ** Add all changes in the changeset traversed by the iterator passed as
  174881. ** the first argument to the changegroup hash tables.
  174882. */
  174883. static int sessionChangesetToHash(
  174884. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  174885. sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
  174886. int bRebase /* True if hash table is for rebasing */
  174887. ){
  174888. u8 *aRec;
  174889. int nRec;
  174890. int rc = SQLITE_OK;
  174891. SessionTable *pTab = 0;
  174892. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
  174893. const char *zNew;
  174894. int nCol;
  174895. int op;
  174896. int iHash;
  174897. int bIndirect;
  174898. SessionChange *pChange;
  174899. SessionChange *pExist = 0;
  174900. SessionChange **pp;
  174901. if( pGrp->pList==0 ){
  174902. pGrp->bPatch = pIter->bPatchset;
  174903. }else if( pIter->bPatchset!=pGrp->bPatch ){
  174904. rc = SQLITE_ERROR;
  174905. break;
  174906. }
  174907. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  174908. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  174909. /* Search the list for a matching table */
  174910. int nNew = (int)strlen(zNew);
  174911. u8 *abPK;
  174912. sqlite3changeset_pk(pIter, &abPK, 0);
  174913. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  174914. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  174915. }
  174916. if( !pTab ){
  174917. SessionTable **ppTab;
  174918. pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
  174919. if( !pTab ){
  174920. rc = SQLITE_NOMEM;
  174921. break;
  174922. }
  174923. memset(pTab, 0, sizeof(SessionTable));
  174924. pTab->nCol = nCol;
  174925. pTab->abPK = (u8*)&pTab[1];
  174926. memcpy(pTab->abPK, abPK, nCol);
  174927. pTab->zName = (char*)&pTab->abPK[nCol];
  174928. memcpy(pTab->zName, zNew, nNew+1);
  174929. /* The new object must be linked on to the end of the list, not
  174930. ** simply added to the start of it. This is to ensure that the
  174931. ** tables within the output of sqlite3changegroup_output() are in
  174932. ** the right order. */
  174933. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  174934. *ppTab = pTab;
  174935. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  174936. rc = SQLITE_SCHEMA;
  174937. break;
  174938. }
  174939. }
  174940. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  174941. rc = SQLITE_NOMEM;
  174942. break;
  174943. }
  174944. iHash = sessionChangeHash(
  174945. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  174946. );
  174947. /* Search for existing entry. If found, remove it from the hash table.
  174948. ** Code below may link it back in.
  174949. */
  174950. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  174951. int bPkOnly1 = 0;
  174952. int bPkOnly2 = 0;
  174953. if( pIter->bPatchset ){
  174954. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  174955. bPkOnly2 = op==SQLITE_DELETE;
  174956. }
  174957. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  174958. pExist = *pp;
  174959. *pp = (*pp)->pNext;
  174960. pTab->nEntry--;
  174961. break;
  174962. }
  174963. }
  174964. rc = sessionChangeMerge(pTab, bRebase,
  174965. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  174966. );
  174967. if( rc ) break;
  174968. if( pChange ){
  174969. pChange->pNext = pTab->apChange[iHash];
  174970. pTab->apChange[iHash] = pChange;
  174971. pTab->nEntry++;
  174972. }
  174973. }
  174974. if( rc==SQLITE_OK ) rc = pIter->rc;
  174975. return rc;
  174976. }
  174977. /*
  174978. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  174979. ** added to the changegroup object passed as the first argument.
  174980. **
  174981. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  174982. ** user via one or more calls to xOutput, as with the other streaming
  174983. ** interfaces.
  174984. **
  174985. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  174986. ** buffer containing the output changeset before this function returns. In
  174987. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  174988. ** is the responsibility of the caller to free the output buffer using
  174989. ** sqlite3_free() when it is no longer required.
  174990. **
  174991. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  174992. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  174993. ** are both set to 0 before returning.
  174994. */
  174995. static int sessionChangegroupOutput(
  174996. sqlite3_changegroup *pGrp,
  174997. int (*xOutput)(void *pOut, const void *pData, int nData),
  174998. void *pOut,
  174999. int *pnOut,
  175000. void **ppOut
  175001. ){
  175002. int rc = SQLITE_OK;
  175003. SessionBuffer buf = {0, 0, 0};
  175004. SessionTable *pTab;
  175005. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  175006. /* Create the serialized output changeset based on the contents of the
  175007. ** hash tables attached to the SessionTable objects in list p->pList.
  175008. */
  175009. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  175010. int i;
  175011. if( pTab->nEntry==0 ) continue;
  175012. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  175013. for(i=0; i<pTab->nChange; i++){
  175014. SessionChange *p;
  175015. for(p=pTab->apChange[i]; p; p=p->pNext){
  175016. sessionAppendByte(&buf, p->op, &rc);
  175017. sessionAppendByte(&buf, p->bIndirect, &rc);
  175018. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  175019. }
  175020. }
  175021. if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  175022. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  175023. buf.nBuf = 0;
  175024. }
  175025. }
  175026. if( rc==SQLITE_OK ){
  175027. if( xOutput ){
  175028. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  175029. }else{
  175030. *ppOut = buf.aBuf;
  175031. *pnOut = buf.nBuf;
  175032. buf.aBuf = 0;
  175033. }
  175034. }
  175035. sqlite3_free(buf.aBuf);
  175036. return rc;
  175037. }
  175038. /*
  175039. ** Allocate a new, empty, sqlite3_changegroup.
  175040. */
  175041. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  175042. int rc = SQLITE_OK; /* Return code */
  175043. sqlite3_changegroup *p; /* New object */
  175044. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  175045. if( p==0 ){
  175046. rc = SQLITE_NOMEM;
  175047. }else{
  175048. memset(p, 0, sizeof(sqlite3_changegroup));
  175049. }
  175050. *pp = p;
  175051. return rc;
  175052. }
  175053. /*
  175054. ** Add the changeset currently stored in buffer pData, size nData bytes,
  175055. ** to changeset-group p.
  175056. */
  175057. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  175058. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  175059. int rc; /* Return code */
  175060. rc = sqlite3changeset_start(&pIter, nData, pData);
  175061. if( rc==SQLITE_OK ){
  175062. rc = sessionChangesetToHash(pIter, pGrp, 0);
  175063. }
  175064. sqlite3changeset_finalize(pIter);
  175065. return rc;
  175066. }
  175067. /*
  175068. ** Obtain a buffer containing a changeset representing the concatenation
  175069. ** of all changesets added to the group so far.
  175070. */
  175071. SQLITE_API int sqlite3changegroup_output(
  175072. sqlite3_changegroup *pGrp,
  175073. int *pnData,
  175074. void **ppData
  175075. ){
  175076. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  175077. }
  175078. /*
  175079. ** Streaming versions of changegroup_add().
  175080. */
  175081. SQLITE_API int sqlite3changegroup_add_strm(
  175082. sqlite3_changegroup *pGrp,
  175083. int (*xInput)(void *pIn, void *pData, int *pnData),
  175084. void *pIn
  175085. ){
  175086. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  175087. int rc; /* Return code */
  175088. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  175089. if( rc==SQLITE_OK ){
  175090. rc = sessionChangesetToHash(pIter, pGrp, 0);
  175091. }
  175092. sqlite3changeset_finalize(pIter);
  175093. return rc;
  175094. }
  175095. /*
  175096. ** Streaming versions of changegroup_output().
  175097. */
  175098. SQLITE_API int sqlite3changegroup_output_strm(
  175099. sqlite3_changegroup *pGrp,
  175100. int (*xOutput)(void *pOut, const void *pData, int nData),
  175101. void *pOut
  175102. ){
  175103. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  175104. }
  175105. /*
  175106. ** Delete a changegroup object.
  175107. */
  175108. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  175109. if( pGrp ){
  175110. sessionDeleteTable(pGrp->pList);
  175111. sqlite3_free(pGrp);
  175112. }
  175113. }
  175114. /*
  175115. ** Combine two changesets together.
  175116. */
  175117. SQLITE_API int sqlite3changeset_concat(
  175118. int nLeft, /* Number of bytes in lhs input */
  175119. void *pLeft, /* Lhs input changeset */
  175120. int nRight /* Number of bytes in rhs input */,
  175121. void *pRight, /* Rhs input changeset */
  175122. int *pnOut, /* OUT: Number of bytes in output changeset */
  175123. void **ppOut /* OUT: changeset (left <concat> right) */
  175124. ){
  175125. sqlite3_changegroup *pGrp;
  175126. int rc;
  175127. rc = sqlite3changegroup_new(&pGrp);
  175128. if( rc==SQLITE_OK ){
  175129. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  175130. }
  175131. if( rc==SQLITE_OK ){
  175132. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  175133. }
  175134. if( rc==SQLITE_OK ){
  175135. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  175136. }
  175137. sqlite3changegroup_delete(pGrp);
  175138. return rc;
  175139. }
  175140. /*
  175141. ** Streaming version of sqlite3changeset_concat().
  175142. */
  175143. SQLITE_API int sqlite3changeset_concat_strm(
  175144. int (*xInputA)(void *pIn, void *pData, int *pnData),
  175145. void *pInA,
  175146. int (*xInputB)(void *pIn, void *pData, int *pnData),
  175147. void *pInB,
  175148. int (*xOutput)(void *pOut, const void *pData, int nData),
  175149. void *pOut
  175150. ){
  175151. sqlite3_changegroup *pGrp;
  175152. int rc;
  175153. rc = sqlite3changegroup_new(&pGrp);
  175154. if( rc==SQLITE_OK ){
  175155. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  175156. }
  175157. if( rc==SQLITE_OK ){
  175158. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  175159. }
  175160. if( rc==SQLITE_OK ){
  175161. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  175162. }
  175163. sqlite3changegroup_delete(pGrp);
  175164. return rc;
  175165. }
  175166. /*
  175167. ** Changeset rebaser handle.
  175168. */
  175169. struct sqlite3_rebaser {
  175170. sqlite3_changegroup grp; /* Hash table */
  175171. };
  175172. /*
  175173. ** Buffers a1 and a2 must both contain a sessions module record nCol
  175174. ** fields in size. This function appends an nCol sessions module
  175175. ** record to buffer pBuf that is a copy of a1, except that for
  175176. ** each field that is undefined in a1[], swap in the field from a2[].
  175177. */
  175178. static void sessionAppendRecordMerge(
  175179. SessionBuffer *pBuf, /* Buffer to append to */
  175180. int nCol, /* Number of columns in each record */
  175181. u8 *a1, int n1, /* Record 1 */
  175182. u8 *a2, int n2, /* Record 2 */
  175183. int *pRc /* IN/OUT: error code */
  175184. ){
  175185. sessionBufferGrow(pBuf, n1+n2, pRc);
  175186. if( *pRc==SQLITE_OK ){
  175187. int i;
  175188. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  175189. for(i=0; i<nCol; i++){
  175190. int nn1 = sessionSerialLen(a1);
  175191. int nn2 = sessionSerialLen(a2);
  175192. if( *a1==0 || *a1==0xFF ){
  175193. memcpy(pOut, a2, nn2);
  175194. pOut += nn2;
  175195. }else{
  175196. memcpy(pOut, a1, nn1);
  175197. pOut += nn1;
  175198. }
  175199. a1 += nn1;
  175200. a2 += nn2;
  175201. }
  175202. pBuf->nBuf = pOut-pBuf->aBuf;
  175203. assert( pBuf->nBuf<=pBuf->nAlloc );
  175204. }
  175205. }
  175206. /*
  175207. ** This function is called when rebasing a local UPDATE change against one
  175208. ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
  175209. ** old.* and new.* records for the change. The rebase buffer (a single
  175210. ** record) is in aChange/nChange. The rebased change is appended to buffer
  175211. ** pBuf.
  175212. **
  175213. ** Rebasing the UPDATE involves:
  175214. **
  175215. ** * Removing any changes to fields for which the corresponding field
  175216. ** in the rebase buffer is set to "replaced" (type 0xFF). If this
  175217. ** means the UPDATE change updates no fields, nothing is appended
  175218. ** to the output buffer.
  175219. **
  175220. ** * For each field modified by the local change for which the
  175221. ** corresponding field in the rebase buffer is not "undefined" (0x00)
  175222. ** or "replaced" (0xFF), the old.* value is replaced by the value
  175223. ** in the rebase buffer.
  175224. */
  175225. static void sessionAppendPartialUpdate(
  175226. SessionBuffer *pBuf, /* Append record here */
  175227. sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
  175228. u8 *aRec, int nRec, /* Local change */
  175229. u8 *aChange, int nChange, /* Record to rebase against */
  175230. int *pRc /* IN/OUT: Return Code */
  175231. ){
  175232. sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
  175233. if( *pRc==SQLITE_OK ){
  175234. int bData = 0;
  175235. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  175236. int i;
  175237. u8 *a1 = aRec;
  175238. u8 *a2 = aChange;
  175239. *pOut++ = SQLITE_UPDATE;
  175240. *pOut++ = pIter->bIndirect;
  175241. for(i=0; i<pIter->nCol; i++){
  175242. int n1 = sessionSerialLen(a1);
  175243. int n2 = sessionSerialLen(a2);
  175244. if( pIter->abPK[i] || a2[0]==0 ){
  175245. if( !pIter->abPK[i] ) bData = 1;
  175246. memcpy(pOut, a1, n1);
  175247. pOut += n1;
  175248. }else if( a2[0]!=0xFF ){
  175249. bData = 1;
  175250. memcpy(pOut, a2, n2);
  175251. pOut += n2;
  175252. }else{
  175253. *pOut++ = '\0';
  175254. }
  175255. a1 += n1;
  175256. a2 += n2;
  175257. }
  175258. if( bData ){
  175259. a2 = aChange;
  175260. for(i=0; i<pIter->nCol; i++){
  175261. int n1 = sessionSerialLen(a1);
  175262. int n2 = sessionSerialLen(a2);
  175263. if( pIter->abPK[i] || a2[0]!=0xFF ){
  175264. memcpy(pOut, a1, n1);
  175265. pOut += n1;
  175266. }else{
  175267. *pOut++ = '\0';
  175268. }
  175269. a1 += n1;
  175270. a2 += n2;
  175271. }
  175272. pBuf->nBuf = (pOut - pBuf->aBuf);
  175273. }
  175274. }
  175275. }
  175276. /*
  175277. ** pIter is configured to iterate through a changeset. This function rebases
  175278. ** that changeset according to the current configuration of the rebaser
  175279. ** object passed as the first argument. If no error occurs and argument xOutput
  175280. ** is not NULL, then the changeset is returned to the caller by invoking
  175281. ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
  175282. ** then (*ppOut) is set to point to a buffer containing the rebased changeset
  175283. ** before this function returns. In this case (*pnOut) is set to the size of
  175284. ** the buffer in bytes. It is the responsibility of the caller to eventually
  175285. ** free the (*ppOut) buffer using sqlite3_free().
  175286. **
  175287. ** If an error occurs, an SQLite error code is returned. If ppOut and
  175288. ** pnOut are not NULL, then the two output parameters are set to 0 before
  175289. ** returning.
  175290. */
  175291. static int sessionRebase(
  175292. sqlite3_rebaser *p, /* Rebaser hash table */
  175293. sqlite3_changeset_iter *pIter, /* Input data */
  175294. int (*xOutput)(void *pOut, const void *pData, int nData),
  175295. void *pOut, /* Context for xOutput callback */
  175296. int *pnOut, /* OUT: Number of bytes in output changeset */
  175297. void **ppOut /* OUT: Inverse of pChangeset */
  175298. ){
  175299. int rc = SQLITE_OK;
  175300. u8 *aRec = 0;
  175301. int nRec = 0;
  175302. int bNew = 0;
  175303. SessionTable *pTab = 0;
  175304. SessionBuffer sOut = {0,0,0};
  175305. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
  175306. SessionChange *pChange = 0;
  175307. int bDone = 0;
  175308. if( bNew ){
  175309. const char *zTab = pIter->zTab;
  175310. for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
  175311. if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
  175312. }
  175313. bNew = 0;
  175314. /* A patchset may not be rebased */
  175315. if( pIter->bPatchset ){
  175316. rc = SQLITE_ERROR;
  175317. }
  175318. /* Append a table header to the output for this new table */
  175319. sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
  175320. sessionAppendVarint(&sOut, pIter->nCol, &rc);
  175321. sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
  175322. sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
  175323. }
  175324. if( pTab && rc==SQLITE_OK ){
  175325. int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
  175326. for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
  175327. if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
  175328. break;
  175329. }
  175330. }
  175331. }
  175332. if( pChange ){
  175333. assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
  175334. switch( pIter->op ){
  175335. case SQLITE_INSERT:
  175336. if( pChange->op==SQLITE_INSERT ){
  175337. bDone = 1;
  175338. if( pChange->bIndirect==0 ){
  175339. sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
  175340. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  175341. sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
  175342. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  175343. }
  175344. }
  175345. break;
  175346. case SQLITE_UPDATE:
  175347. bDone = 1;
  175348. if( pChange->op==SQLITE_DELETE ){
  175349. if( pChange->bIndirect==0 ){
  175350. u8 *pCsr = aRec;
  175351. sessionSkipRecord(&pCsr, pIter->nCol);
  175352. sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
  175353. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  175354. sessionAppendRecordMerge(&sOut, pIter->nCol,
  175355. pCsr, nRec-(pCsr-aRec),
  175356. pChange->aRecord, pChange->nRecord, &rc
  175357. );
  175358. }
  175359. }else{
  175360. sessionAppendPartialUpdate(&sOut, pIter,
  175361. aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
  175362. );
  175363. }
  175364. break;
  175365. default:
  175366. assert( pIter->op==SQLITE_DELETE );
  175367. bDone = 1;
  175368. if( pChange->op==SQLITE_INSERT ){
  175369. sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
  175370. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  175371. sessionAppendRecordMerge(&sOut, pIter->nCol,
  175372. pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
  175373. );
  175374. }
  175375. break;
  175376. }
  175377. }
  175378. if( bDone==0 ){
  175379. sessionAppendByte(&sOut, pIter->op, &rc);
  175380. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  175381. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  175382. }
  175383. if( rc==SQLITE_OK && xOutput && sOut.nBuf>SESSIONS_STRM_CHUNK_SIZE ){
  175384. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  175385. sOut.nBuf = 0;
  175386. }
  175387. if( rc ) break;
  175388. }
  175389. if( rc!=SQLITE_OK ){
  175390. sqlite3_free(sOut.aBuf);
  175391. memset(&sOut, 0, sizeof(sOut));
  175392. }
  175393. if( rc==SQLITE_OK ){
  175394. if( xOutput ){
  175395. if( sOut.nBuf>0 ){
  175396. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  175397. }
  175398. }else{
  175399. *ppOut = (void*)sOut.aBuf;
  175400. *pnOut = sOut.nBuf;
  175401. sOut.aBuf = 0;
  175402. }
  175403. }
  175404. sqlite3_free(sOut.aBuf);
  175405. return rc;
  175406. }
  175407. /*
  175408. ** Create a new rebaser object.
  175409. */
  175410. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
  175411. int rc = SQLITE_OK;
  175412. sqlite3_rebaser *pNew;
  175413. pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
  175414. if( pNew==0 ){
  175415. rc = SQLITE_NOMEM;
  175416. }else{
  175417. memset(pNew, 0, sizeof(sqlite3_rebaser));
  175418. }
  175419. *ppNew = pNew;
  175420. return rc;
  175421. }
  175422. /*
  175423. ** Call this one or more times to configure a rebaser.
  175424. */
  175425. SQLITE_API int sqlite3rebaser_configure(
  175426. sqlite3_rebaser *p,
  175427. int nRebase, const void *pRebase
  175428. ){
  175429. sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
  175430. int rc; /* Return code */
  175431. rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
  175432. if( rc==SQLITE_OK ){
  175433. rc = sessionChangesetToHash(pIter, &p->grp, 1);
  175434. }
  175435. sqlite3changeset_finalize(pIter);
  175436. return rc;
  175437. }
  175438. /*
  175439. ** Rebase a changeset according to current rebaser configuration
  175440. */
  175441. SQLITE_API int sqlite3rebaser_rebase(
  175442. sqlite3_rebaser *p,
  175443. int nIn, const void *pIn,
  175444. int *pnOut, void **ppOut
  175445. ){
  175446. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  175447. int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
  175448. if( rc==SQLITE_OK ){
  175449. rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
  175450. sqlite3changeset_finalize(pIter);
  175451. }
  175452. return rc;
  175453. }
  175454. /*
  175455. ** Rebase a changeset according to current rebaser configuration
  175456. */
  175457. SQLITE_API int sqlite3rebaser_rebase_strm(
  175458. sqlite3_rebaser *p,
  175459. int (*xInput)(void *pIn, void *pData, int *pnData),
  175460. void *pIn,
  175461. int (*xOutput)(void *pOut, const void *pData, int nData),
  175462. void *pOut
  175463. ){
  175464. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  175465. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  175466. if( rc==SQLITE_OK ){
  175467. rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
  175468. sqlite3changeset_finalize(pIter);
  175469. }
  175470. return rc;
  175471. }
  175472. /*
  175473. ** Destroy a rebaser object
  175474. */
  175475. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
  175476. if( p ){
  175477. sessionDeleteTable(p->grp.pList);
  175478. sqlite3_free(p);
  175479. }
  175480. }
  175481. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  175482. /************** End of sqlite3session.c **************************************/
  175483. /************** Begin file json1.c *******************************************/
  175484. /*
  175485. ** 2015-08-12
  175486. **
  175487. ** The author disclaims copyright to this source code. In place of
  175488. ** a legal notice, here is a blessing:
  175489. **
  175490. ** May you do good and not evil.
  175491. ** May you find forgiveness for yourself and forgive others.
  175492. ** May you share freely, never taking more than you give.
  175493. **
  175494. ******************************************************************************
  175495. **
  175496. ** This SQLite extension implements JSON functions. The interface is
  175497. ** modeled after MySQL JSON functions:
  175498. **
  175499. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  175500. **
  175501. ** For the time being, all JSON is stored as pure text. (We might add
  175502. ** a JSONB type in the future which stores a binary encoding of JSON in
  175503. ** a BLOB, but there is no support for JSONB in the current implementation.
  175504. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  175505. ** how JSONB might improve on that.)
  175506. */
  175507. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  175508. #if !defined(SQLITEINT_H)
  175509. /* #include "sqlite3ext.h" */
  175510. #endif
  175511. SQLITE_EXTENSION_INIT1
  175512. /* #include <assert.h> */
  175513. /* #include <string.h> */
  175514. /* #include <stdlib.h> */
  175515. /* #include <stdarg.h> */
  175516. /* Mark a function parameter as unused, to suppress nuisance compiler
  175517. ** warnings. */
  175518. #ifndef UNUSED_PARAM
  175519. # define UNUSED_PARAM(X) (void)(X)
  175520. #endif
  175521. #ifndef LARGEST_INT64
  175522. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  175523. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  175524. #endif
  175525. /*
  175526. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  175527. ** to pass signed char values.
  175528. */
  175529. #ifdef sqlite3Isdigit
  175530. /* Use the SQLite core versions if this routine is part of the
  175531. ** SQLite amalgamation */
  175532. # define safe_isdigit(x) sqlite3Isdigit(x)
  175533. # define safe_isalnum(x) sqlite3Isalnum(x)
  175534. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  175535. #else
  175536. /* Use the standard library for separate compilation */
  175537. #include <ctype.h> /* amalgamator: keep */
  175538. # define safe_isdigit(x) isdigit((unsigned char)(x))
  175539. # define safe_isalnum(x) isalnum((unsigned char)(x))
  175540. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  175541. #endif
  175542. /*
  175543. ** Growing our own isspace() routine this way is twice as fast as
  175544. ** the library isspace() function, resulting in a 7% overall performance
  175545. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  175546. */
  175547. static const char jsonIsSpace[] = {
  175548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  175549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175550. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  175564. };
  175565. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  175566. #ifndef SQLITE_AMALGAMATION
  175567. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  175568. ** but the definitions need to be repeated for separate compilation. */
  175569. typedef sqlite3_uint64 u64;
  175570. typedef unsigned int u32;
  175571. typedef unsigned short int u16;
  175572. typedef unsigned char u8;
  175573. #endif
  175574. /* Objects */
  175575. typedef struct JsonString JsonString;
  175576. typedef struct JsonNode JsonNode;
  175577. typedef struct JsonParse JsonParse;
  175578. /* An instance of this object represents a JSON string
  175579. ** under construction. Really, this is a generic string accumulator
  175580. ** that can be and is used to create strings other than JSON.
  175581. */
  175582. struct JsonString {
  175583. sqlite3_context *pCtx; /* Function context - put error messages here */
  175584. char *zBuf; /* Append JSON content here */
  175585. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  175586. u64 nUsed; /* Bytes of zBuf[] currently used */
  175587. u8 bStatic; /* True if zBuf is static space */
  175588. u8 bErr; /* True if an error has been encountered */
  175589. char zSpace[100]; /* Initial static space */
  175590. };
  175591. /* JSON type values
  175592. */
  175593. #define JSON_NULL 0
  175594. #define JSON_TRUE 1
  175595. #define JSON_FALSE 2
  175596. #define JSON_INT 3
  175597. #define JSON_REAL 4
  175598. #define JSON_STRING 5
  175599. #define JSON_ARRAY 6
  175600. #define JSON_OBJECT 7
  175601. /* The "subtype" set for JSON values */
  175602. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  175603. /*
  175604. ** Names of the various JSON types:
  175605. */
  175606. static const char * const jsonType[] = {
  175607. "null", "true", "false", "integer", "real", "text", "array", "object"
  175608. };
  175609. /* Bit values for the JsonNode.jnFlag field
  175610. */
  175611. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  175612. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  175613. #define JNODE_REMOVE 0x04 /* Do not output */
  175614. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  175615. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  175616. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  175617. #define JNODE_LABEL 0x40 /* Is a label of an object */
  175618. /* A single node of parsed JSON
  175619. */
  175620. struct JsonNode {
  175621. u8 eType; /* One of the JSON_ type values */
  175622. u8 jnFlags; /* JNODE flags */
  175623. u32 n; /* Bytes of content, or number of sub-nodes */
  175624. union {
  175625. const char *zJContent; /* Content for INT, REAL, and STRING */
  175626. u32 iAppend; /* More terms for ARRAY and OBJECT */
  175627. u32 iKey; /* Key for ARRAY objects in json_tree() */
  175628. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  175629. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  175630. } u;
  175631. };
  175632. /* A completely parsed JSON string
  175633. */
  175634. struct JsonParse {
  175635. u32 nNode; /* Number of slots of aNode[] used */
  175636. u32 nAlloc; /* Number of slots of aNode[] allocated */
  175637. JsonNode *aNode; /* Array of nodes containing the parse */
  175638. const char *zJson; /* Original JSON string */
  175639. u32 *aUp; /* Index of parent of each node */
  175640. u8 oom; /* Set to true if out of memory */
  175641. u8 nErr; /* Number of errors seen */
  175642. u16 iDepth; /* Nesting depth */
  175643. int nJson; /* Length of the zJson string in bytes */
  175644. };
  175645. /*
  175646. ** Maximum nesting depth of JSON for this implementation.
  175647. **
  175648. ** This limit is needed to avoid a stack overflow in the recursive
  175649. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  175650. ** should go.
  175651. */
  175652. #define JSON_MAX_DEPTH 2000
  175653. /**************************************************************************
  175654. ** Utility routines for dealing with JsonString objects
  175655. **************************************************************************/
  175656. /* Set the JsonString object to an empty string
  175657. */
  175658. static void jsonZero(JsonString *p){
  175659. p->zBuf = p->zSpace;
  175660. p->nAlloc = sizeof(p->zSpace);
  175661. p->nUsed = 0;
  175662. p->bStatic = 1;
  175663. }
  175664. /* Initialize the JsonString object
  175665. */
  175666. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  175667. p->pCtx = pCtx;
  175668. p->bErr = 0;
  175669. jsonZero(p);
  175670. }
  175671. /* Free all allocated memory and reset the JsonString object back to its
  175672. ** initial state.
  175673. */
  175674. static void jsonReset(JsonString *p){
  175675. if( !p->bStatic ) sqlite3_free(p->zBuf);
  175676. jsonZero(p);
  175677. }
  175678. /* Report an out-of-memory (OOM) condition
  175679. */
  175680. static void jsonOom(JsonString *p){
  175681. p->bErr = 1;
  175682. sqlite3_result_error_nomem(p->pCtx);
  175683. jsonReset(p);
  175684. }
  175685. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  175686. ** Return zero on success. Return non-zero on an OOM error
  175687. */
  175688. static int jsonGrow(JsonString *p, u32 N){
  175689. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  175690. char *zNew;
  175691. if( p->bStatic ){
  175692. if( p->bErr ) return 1;
  175693. zNew = sqlite3_malloc64(nTotal);
  175694. if( zNew==0 ){
  175695. jsonOom(p);
  175696. return SQLITE_NOMEM;
  175697. }
  175698. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  175699. p->zBuf = zNew;
  175700. p->bStatic = 0;
  175701. }else{
  175702. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  175703. if( zNew==0 ){
  175704. jsonOom(p);
  175705. return SQLITE_NOMEM;
  175706. }
  175707. p->zBuf = zNew;
  175708. }
  175709. p->nAlloc = nTotal;
  175710. return SQLITE_OK;
  175711. }
  175712. /* Append N bytes from zIn onto the end of the JsonString string.
  175713. */
  175714. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  175715. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  175716. memcpy(p->zBuf+p->nUsed, zIn, N);
  175717. p->nUsed += N;
  175718. }
  175719. /* Append formatted text (not to exceed N bytes) to the JsonString.
  175720. */
  175721. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  175722. va_list ap;
  175723. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  175724. va_start(ap, zFormat);
  175725. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  175726. va_end(ap);
  175727. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  175728. }
  175729. /* Append a single character
  175730. */
  175731. static void jsonAppendChar(JsonString *p, char c){
  175732. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  175733. p->zBuf[p->nUsed++] = c;
  175734. }
  175735. /* Append a comma separator to the output buffer, if the previous
  175736. ** character is not '[' or '{'.
  175737. */
  175738. static void jsonAppendSeparator(JsonString *p){
  175739. char c;
  175740. if( p->nUsed==0 ) return;
  175741. c = p->zBuf[p->nUsed-1];
  175742. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  175743. }
  175744. /* Append the N-byte string in zIn to the end of the JsonString string
  175745. ** under construction. Enclose the string in "..." and escape
  175746. ** any double-quotes or backslash characters contained within the
  175747. ** string.
  175748. */
  175749. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  175750. u32 i;
  175751. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  175752. p->zBuf[p->nUsed++] = '"';
  175753. for(i=0; i<N; i++){
  175754. unsigned char c = ((unsigned const char*)zIn)[i];
  175755. if( c=='"' || c=='\\' ){
  175756. json_simple_escape:
  175757. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  175758. p->zBuf[p->nUsed++] = '\\';
  175759. }else if( c<=0x1f ){
  175760. static const char aSpecial[] = {
  175761. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  175762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  175763. };
  175764. assert( sizeof(aSpecial)==32 );
  175765. assert( aSpecial['\b']=='b' );
  175766. assert( aSpecial['\f']=='f' );
  175767. assert( aSpecial['\n']=='n' );
  175768. assert( aSpecial['\r']=='r' );
  175769. assert( aSpecial['\t']=='t' );
  175770. if( aSpecial[c] ){
  175771. c = aSpecial[c];
  175772. goto json_simple_escape;
  175773. }
  175774. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  175775. p->zBuf[p->nUsed++] = '\\';
  175776. p->zBuf[p->nUsed++] = 'u';
  175777. p->zBuf[p->nUsed++] = '0';
  175778. p->zBuf[p->nUsed++] = '0';
  175779. p->zBuf[p->nUsed++] = '0' + (c>>4);
  175780. c = "0123456789abcdef"[c&0xf];
  175781. }
  175782. p->zBuf[p->nUsed++] = c;
  175783. }
  175784. p->zBuf[p->nUsed++] = '"';
  175785. assert( p->nUsed<p->nAlloc );
  175786. }
  175787. /*
  175788. ** Append a function parameter value to the JSON string under
  175789. ** construction.
  175790. */
  175791. static void jsonAppendValue(
  175792. JsonString *p, /* Append to this JSON string */
  175793. sqlite3_value *pValue /* Value to append */
  175794. ){
  175795. switch( sqlite3_value_type(pValue) ){
  175796. case SQLITE_NULL: {
  175797. jsonAppendRaw(p, "null", 4);
  175798. break;
  175799. }
  175800. case SQLITE_INTEGER:
  175801. case SQLITE_FLOAT: {
  175802. const char *z = (const char*)sqlite3_value_text(pValue);
  175803. u32 n = (u32)sqlite3_value_bytes(pValue);
  175804. jsonAppendRaw(p, z, n);
  175805. break;
  175806. }
  175807. case SQLITE_TEXT: {
  175808. const char *z = (const char*)sqlite3_value_text(pValue);
  175809. u32 n = (u32)sqlite3_value_bytes(pValue);
  175810. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  175811. jsonAppendRaw(p, z, n);
  175812. }else{
  175813. jsonAppendString(p, z, n);
  175814. }
  175815. break;
  175816. }
  175817. default: {
  175818. if( p->bErr==0 ){
  175819. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  175820. p->bErr = 2;
  175821. jsonReset(p);
  175822. }
  175823. break;
  175824. }
  175825. }
  175826. }
  175827. /* Make the JSON in p the result of the SQL function.
  175828. */
  175829. static void jsonResult(JsonString *p){
  175830. if( p->bErr==0 ){
  175831. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  175832. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  175833. SQLITE_UTF8);
  175834. jsonZero(p);
  175835. }
  175836. assert( p->bStatic );
  175837. }
  175838. /**************************************************************************
  175839. ** Utility routines for dealing with JsonNode and JsonParse objects
  175840. **************************************************************************/
  175841. /*
  175842. ** Return the number of consecutive JsonNode slots need to represent
  175843. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  175844. ** OBJECT types, the number might be larger.
  175845. **
  175846. ** Appended elements are not counted. The value returned is the number
  175847. ** by which the JsonNode counter should increment in order to go to the
  175848. ** next peer value.
  175849. */
  175850. static u32 jsonNodeSize(JsonNode *pNode){
  175851. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  175852. }
  175853. /*
  175854. ** Reclaim all memory allocated by a JsonParse object. But do not
  175855. ** delete the JsonParse object itself.
  175856. */
  175857. static void jsonParseReset(JsonParse *pParse){
  175858. sqlite3_free(pParse->aNode);
  175859. pParse->aNode = 0;
  175860. pParse->nNode = 0;
  175861. pParse->nAlloc = 0;
  175862. sqlite3_free(pParse->aUp);
  175863. pParse->aUp = 0;
  175864. }
  175865. /*
  175866. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  175867. */
  175868. static void jsonParseFree(JsonParse *pParse){
  175869. jsonParseReset(pParse);
  175870. sqlite3_free(pParse);
  175871. }
  175872. /*
  175873. ** Convert the JsonNode pNode into a pure JSON string and
  175874. ** append to pOut. Subsubstructure is also included. Return
  175875. ** the number of JsonNode objects that are encoded.
  175876. */
  175877. static void jsonRenderNode(
  175878. JsonNode *pNode, /* The node to render */
  175879. JsonString *pOut, /* Write JSON here */
  175880. sqlite3_value **aReplace /* Replacement values */
  175881. ){
  175882. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  175883. if( pNode->jnFlags & JNODE_REPLACE ){
  175884. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  175885. return;
  175886. }
  175887. pNode = pNode->u.pPatch;
  175888. }
  175889. switch( pNode->eType ){
  175890. default: {
  175891. assert( pNode->eType==JSON_NULL );
  175892. jsonAppendRaw(pOut, "null", 4);
  175893. break;
  175894. }
  175895. case JSON_TRUE: {
  175896. jsonAppendRaw(pOut, "true", 4);
  175897. break;
  175898. }
  175899. case JSON_FALSE: {
  175900. jsonAppendRaw(pOut, "false", 5);
  175901. break;
  175902. }
  175903. case JSON_STRING: {
  175904. if( pNode->jnFlags & JNODE_RAW ){
  175905. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  175906. break;
  175907. }
  175908. /* Fall through into the next case */
  175909. }
  175910. case JSON_REAL:
  175911. case JSON_INT: {
  175912. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  175913. break;
  175914. }
  175915. case JSON_ARRAY: {
  175916. u32 j = 1;
  175917. jsonAppendChar(pOut, '[');
  175918. for(;;){
  175919. while( j<=pNode->n ){
  175920. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  175921. jsonAppendSeparator(pOut);
  175922. jsonRenderNode(&pNode[j], pOut, aReplace);
  175923. }
  175924. j += jsonNodeSize(&pNode[j]);
  175925. }
  175926. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  175927. pNode = &pNode[pNode->u.iAppend];
  175928. j = 1;
  175929. }
  175930. jsonAppendChar(pOut, ']');
  175931. break;
  175932. }
  175933. case JSON_OBJECT: {
  175934. u32 j = 1;
  175935. jsonAppendChar(pOut, '{');
  175936. for(;;){
  175937. while( j<=pNode->n ){
  175938. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  175939. jsonAppendSeparator(pOut);
  175940. jsonRenderNode(&pNode[j], pOut, aReplace);
  175941. jsonAppendChar(pOut, ':');
  175942. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  175943. }
  175944. j += 1 + jsonNodeSize(&pNode[j+1]);
  175945. }
  175946. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  175947. pNode = &pNode[pNode->u.iAppend];
  175948. j = 1;
  175949. }
  175950. jsonAppendChar(pOut, '}');
  175951. break;
  175952. }
  175953. }
  175954. }
  175955. /*
  175956. ** Return a JsonNode and all its descendents as a JSON string.
  175957. */
  175958. static void jsonReturnJson(
  175959. JsonNode *pNode, /* Node to return */
  175960. sqlite3_context *pCtx, /* Return value for this function */
  175961. sqlite3_value **aReplace /* Array of replacement values */
  175962. ){
  175963. JsonString s;
  175964. jsonInit(&s, pCtx);
  175965. jsonRenderNode(pNode, &s, aReplace);
  175966. jsonResult(&s);
  175967. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  175968. }
  175969. /*
  175970. ** Make the JsonNode the return value of the function.
  175971. */
  175972. static void jsonReturn(
  175973. JsonNode *pNode, /* Node to return */
  175974. sqlite3_context *pCtx, /* Return value for this function */
  175975. sqlite3_value **aReplace /* Array of replacement values */
  175976. ){
  175977. switch( pNode->eType ){
  175978. default: {
  175979. assert( pNode->eType==JSON_NULL );
  175980. sqlite3_result_null(pCtx);
  175981. break;
  175982. }
  175983. case JSON_TRUE: {
  175984. sqlite3_result_int(pCtx, 1);
  175985. break;
  175986. }
  175987. case JSON_FALSE: {
  175988. sqlite3_result_int(pCtx, 0);
  175989. break;
  175990. }
  175991. case JSON_INT: {
  175992. sqlite3_int64 i = 0;
  175993. const char *z = pNode->u.zJContent;
  175994. if( z[0]=='-' ){ z++; }
  175995. while( z[0]>='0' && z[0]<='9' ){
  175996. unsigned v = *(z++) - '0';
  175997. if( i>=LARGEST_INT64/10 ){
  175998. if( i>LARGEST_INT64/10 ) goto int_as_real;
  175999. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  176000. if( v==9 ) goto int_as_real;
  176001. if( v==8 ){
  176002. if( pNode->u.zJContent[0]=='-' ){
  176003. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  176004. goto int_done;
  176005. }else{
  176006. goto int_as_real;
  176007. }
  176008. }
  176009. }
  176010. i = i*10 + v;
  176011. }
  176012. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  176013. sqlite3_result_int64(pCtx, i);
  176014. int_done:
  176015. break;
  176016. int_as_real: /* fall through to real */;
  176017. }
  176018. case JSON_REAL: {
  176019. double r;
  176020. #ifdef SQLITE_AMALGAMATION
  176021. const char *z = pNode->u.zJContent;
  176022. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  176023. #else
  176024. r = strtod(pNode->u.zJContent, 0);
  176025. #endif
  176026. sqlite3_result_double(pCtx, r);
  176027. break;
  176028. }
  176029. case JSON_STRING: {
  176030. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  176031. ** json_insert() and json_replace() and those routines do not
  176032. ** call jsonReturn() */
  176033. if( pNode->jnFlags & JNODE_RAW ){
  176034. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  176035. SQLITE_TRANSIENT);
  176036. }else
  176037. #endif
  176038. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  176039. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  176040. /* JSON formatted without any backslash-escapes */
  176041. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  176042. SQLITE_TRANSIENT);
  176043. }else{
  176044. /* Translate JSON formatted string into raw text */
  176045. u32 i;
  176046. u32 n = pNode->n;
  176047. const char *z = pNode->u.zJContent;
  176048. char *zOut;
  176049. u32 j;
  176050. zOut = sqlite3_malloc( n+1 );
  176051. if( zOut==0 ){
  176052. sqlite3_result_error_nomem(pCtx);
  176053. break;
  176054. }
  176055. for(i=1, j=0; i<n-1; i++){
  176056. char c = z[i];
  176057. if( c!='\\' ){
  176058. zOut[j++] = c;
  176059. }else{
  176060. c = z[++i];
  176061. if( c=='u' ){
  176062. u32 v = 0, k;
  176063. for(k=0; k<4; i++, k++){
  176064. assert( i<n-2 );
  176065. c = z[i+1];
  176066. assert( safe_isxdigit(c) );
  176067. if( c<='9' ) v = v*16 + c - '0';
  176068. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  176069. else v = v*16 + c - 'a' + 10;
  176070. }
  176071. if( v==0 ) break;
  176072. if( v<=0x7f ){
  176073. zOut[j++] = (char)v;
  176074. }else if( v<=0x7ff ){
  176075. zOut[j++] = (char)(0xc0 | (v>>6));
  176076. zOut[j++] = 0x80 | (v&0x3f);
  176077. }else{
  176078. zOut[j++] = (char)(0xe0 | (v>>12));
  176079. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  176080. zOut[j++] = 0x80 | (v&0x3f);
  176081. }
  176082. }else{
  176083. if( c=='b' ){
  176084. c = '\b';
  176085. }else if( c=='f' ){
  176086. c = '\f';
  176087. }else if( c=='n' ){
  176088. c = '\n';
  176089. }else if( c=='r' ){
  176090. c = '\r';
  176091. }else if( c=='t' ){
  176092. c = '\t';
  176093. }
  176094. zOut[j++] = c;
  176095. }
  176096. }
  176097. }
  176098. zOut[j] = 0;
  176099. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  176100. }
  176101. break;
  176102. }
  176103. case JSON_ARRAY:
  176104. case JSON_OBJECT: {
  176105. jsonReturnJson(pNode, pCtx, aReplace);
  176106. break;
  176107. }
  176108. }
  176109. }
  176110. /* Forward reference */
  176111. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  176112. /*
  176113. ** A macro to hint to the compiler that a function should not be
  176114. ** inlined.
  176115. */
  176116. #if defined(__GNUC__)
  176117. # define JSON_NOINLINE __attribute__((noinline))
  176118. #elif defined(_MSC_VER) && _MSC_VER>=1310
  176119. # define JSON_NOINLINE __declspec(noinline)
  176120. #else
  176121. # define JSON_NOINLINE
  176122. #endif
  176123. static JSON_NOINLINE int jsonParseAddNodeExpand(
  176124. JsonParse *pParse, /* Append the node to this object */
  176125. u32 eType, /* Node type */
  176126. u32 n, /* Content size or sub-node count */
  176127. const char *zContent /* Content */
  176128. ){
  176129. u32 nNew;
  176130. JsonNode *pNew;
  176131. assert( pParse->nNode>=pParse->nAlloc );
  176132. if( pParse->oom ) return -1;
  176133. nNew = pParse->nAlloc*2 + 10;
  176134. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  176135. if( pNew==0 ){
  176136. pParse->oom = 1;
  176137. return -1;
  176138. }
  176139. pParse->nAlloc = nNew;
  176140. pParse->aNode = pNew;
  176141. assert( pParse->nNode<pParse->nAlloc );
  176142. return jsonParseAddNode(pParse, eType, n, zContent);
  176143. }
  176144. /*
  176145. ** Create a new JsonNode instance based on the arguments and append that
  176146. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  176147. ** new node, or -1 if a memory allocation fails.
  176148. */
  176149. static int jsonParseAddNode(
  176150. JsonParse *pParse, /* Append the node to this object */
  176151. u32 eType, /* Node type */
  176152. u32 n, /* Content size or sub-node count */
  176153. const char *zContent /* Content */
  176154. ){
  176155. JsonNode *p;
  176156. if( pParse->nNode>=pParse->nAlloc ){
  176157. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  176158. }
  176159. p = &pParse->aNode[pParse->nNode];
  176160. p->eType = (u8)eType;
  176161. p->jnFlags = 0;
  176162. p->n = n;
  176163. p->u.zJContent = zContent;
  176164. return pParse->nNode++;
  176165. }
  176166. /*
  176167. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  176168. */
  176169. static int jsonIs4Hex(const char *z){
  176170. int i;
  176171. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  176172. return 1;
  176173. }
  176174. /*
  176175. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  176176. ** index of the first character past the end of the value parsed.
  176177. **
  176178. ** Return negative for a syntax error. Special cases: return -2 if the
  176179. ** first non-whitespace character is '}' and return -3 if the first
  176180. ** non-whitespace character is ']'.
  176181. */
  176182. static int jsonParseValue(JsonParse *pParse, u32 i){
  176183. char c;
  176184. u32 j;
  176185. int iThis;
  176186. int x;
  176187. JsonNode *pNode;
  176188. const char *z = pParse->zJson;
  176189. while( safe_isspace(z[i]) ){ i++; }
  176190. if( (c = z[i])=='{' ){
  176191. /* Parse object */
  176192. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  176193. if( iThis<0 ) return -1;
  176194. for(j=i+1;;j++){
  176195. while( safe_isspace(z[j]) ){ j++; }
  176196. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  176197. x = jsonParseValue(pParse, j);
  176198. if( x<0 ){
  176199. pParse->iDepth--;
  176200. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  176201. return -1;
  176202. }
  176203. if( pParse->oom ) return -1;
  176204. pNode = &pParse->aNode[pParse->nNode-1];
  176205. if( pNode->eType!=JSON_STRING ) return -1;
  176206. pNode->jnFlags |= JNODE_LABEL;
  176207. j = x;
  176208. while( safe_isspace(z[j]) ){ j++; }
  176209. if( z[j]!=':' ) return -1;
  176210. j++;
  176211. x = jsonParseValue(pParse, j);
  176212. pParse->iDepth--;
  176213. if( x<0 ) return -1;
  176214. j = x;
  176215. while( safe_isspace(z[j]) ){ j++; }
  176216. c = z[j];
  176217. if( c==',' ) continue;
  176218. if( c!='}' ) return -1;
  176219. break;
  176220. }
  176221. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  176222. return j+1;
  176223. }else if( c=='[' ){
  176224. /* Parse array */
  176225. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  176226. if( iThis<0 ) return -1;
  176227. for(j=i+1;;j++){
  176228. while( safe_isspace(z[j]) ){ j++; }
  176229. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  176230. x = jsonParseValue(pParse, j);
  176231. pParse->iDepth--;
  176232. if( x<0 ){
  176233. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  176234. return -1;
  176235. }
  176236. j = x;
  176237. while( safe_isspace(z[j]) ){ j++; }
  176238. c = z[j];
  176239. if( c==',' ) continue;
  176240. if( c!=']' ) return -1;
  176241. break;
  176242. }
  176243. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  176244. return j+1;
  176245. }else if( c=='"' ){
  176246. /* Parse string */
  176247. u8 jnFlags = 0;
  176248. j = i+1;
  176249. for(;;){
  176250. c = z[j];
  176251. if( (c & ~0x1f)==0 ){
  176252. /* Control characters are not allowed in strings */
  176253. return -1;
  176254. }
  176255. if( c=='\\' ){
  176256. c = z[++j];
  176257. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  176258. || c=='n' || c=='r' || c=='t'
  176259. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  176260. jnFlags = JNODE_ESCAPE;
  176261. }else{
  176262. return -1;
  176263. }
  176264. }else if( c=='"' ){
  176265. break;
  176266. }
  176267. j++;
  176268. }
  176269. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  176270. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  176271. return j+1;
  176272. }else if( c=='n'
  176273. && strncmp(z+i,"null",4)==0
  176274. && !safe_isalnum(z[i+4]) ){
  176275. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  176276. return i+4;
  176277. }else if( c=='t'
  176278. && strncmp(z+i,"true",4)==0
  176279. && !safe_isalnum(z[i+4]) ){
  176280. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  176281. return i+4;
  176282. }else if( c=='f'
  176283. && strncmp(z+i,"false",5)==0
  176284. && !safe_isalnum(z[i+5]) ){
  176285. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  176286. return i+5;
  176287. }else if( c=='-' || (c>='0' && c<='9') ){
  176288. /* Parse number */
  176289. u8 seenDP = 0;
  176290. u8 seenE = 0;
  176291. assert( '-' < '0' );
  176292. if( c<='0' ){
  176293. j = c=='-' ? i+1 : i;
  176294. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  176295. }
  176296. j = i+1;
  176297. for(;; j++){
  176298. c = z[j];
  176299. if( c>='0' && c<='9' ) continue;
  176300. if( c=='.' ){
  176301. if( z[j-1]=='-' ) return -1;
  176302. if( seenDP ) return -1;
  176303. seenDP = 1;
  176304. continue;
  176305. }
  176306. if( c=='e' || c=='E' ){
  176307. if( z[j-1]<'0' ) return -1;
  176308. if( seenE ) return -1;
  176309. seenDP = seenE = 1;
  176310. c = z[j+1];
  176311. if( c=='+' || c=='-' ){
  176312. j++;
  176313. c = z[j+1];
  176314. }
  176315. if( c<'0' || c>'9' ) return -1;
  176316. continue;
  176317. }
  176318. break;
  176319. }
  176320. if( z[j-1]<'0' ) return -1;
  176321. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  176322. j - i, &z[i]);
  176323. return j;
  176324. }else if( c=='}' ){
  176325. return -2; /* End of {...} */
  176326. }else if( c==']' ){
  176327. return -3; /* End of [...] */
  176328. }else if( c==0 ){
  176329. return 0; /* End of file */
  176330. }else{
  176331. return -1; /* Syntax error */
  176332. }
  176333. }
  176334. /*
  176335. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  176336. ** are any errors. If an error occurs, free all memory associated with
  176337. ** pParse.
  176338. **
  176339. ** pParse is uninitialized when this routine is called.
  176340. */
  176341. static int jsonParse(
  176342. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  176343. sqlite3_context *pCtx, /* Report errors here */
  176344. const char *zJson /* Input JSON text to be parsed */
  176345. ){
  176346. int i;
  176347. memset(pParse, 0, sizeof(*pParse));
  176348. if( zJson==0 ) return 1;
  176349. pParse->zJson = zJson;
  176350. i = jsonParseValue(pParse, 0);
  176351. if( pParse->oom ) i = -1;
  176352. if( i>0 ){
  176353. assert( pParse->iDepth==0 );
  176354. while( safe_isspace(zJson[i]) ) i++;
  176355. if( zJson[i] ) i = -1;
  176356. }
  176357. if( i<=0 ){
  176358. if( pCtx!=0 ){
  176359. if( pParse->oom ){
  176360. sqlite3_result_error_nomem(pCtx);
  176361. }else{
  176362. sqlite3_result_error(pCtx, "malformed JSON", -1);
  176363. }
  176364. }
  176365. jsonParseReset(pParse);
  176366. return 1;
  176367. }
  176368. return 0;
  176369. }
  176370. /* Mark node i of pParse as being a child of iParent. Call recursively
  176371. ** to fill in all the descendants of node i.
  176372. */
  176373. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  176374. JsonNode *pNode = &pParse->aNode[i];
  176375. u32 j;
  176376. pParse->aUp[i] = iParent;
  176377. switch( pNode->eType ){
  176378. case JSON_ARRAY: {
  176379. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  176380. jsonParseFillInParentage(pParse, i+j, i);
  176381. }
  176382. break;
  176383. }
  176384. case JSON_OBJECT: {
  176385. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  176386. pParse->aUp[i+j] = i;
  176387. jsonParseFillInParentage(pParse, i+j+1, i);
  176388. }
  176389. break;
  176390. }
  176391. default: {
  176392. break;
  176393. }
  176394. }
  176395. }
  176396. /*
  176397. ** Compute the parentage of all nodes in a completed parse.
  176398. */
  176399. static int jsonParseFindParents(JsonParse *pParse){
  176400. u32 *aUp;
  176401. assert( pParse->aUp==0 );
  176402. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  176403. if( aUp==0 ){
  176404. pParse->oom = 1;
  176405. return SQLITE_NOMEM;
  176406. }
  176407. jsonParseFillInParentage(pParse, 0, 0);
  176408. return SQLITE_OK;
  176409. }
  176410. /*
  176411. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  176412. */
  176413. #define JSON_CACHE_ID (-429938)
  176414. /*
  176415. ** Obtain a complete parse of the JSON found in the first argument
  176416. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  176417. ** parse if it is available. If the cache is not available or if it
  176418. ** is no longer valid, parse the JSON again and return the new parse,
  176419. ** and also register the new parse so that it will be available for
  176420. ** future sqlite3_get_auxdata() calls.
  176421. */
  176422. static JsonParse *jsonParseCached(
  176423. sqlite3_context *pCtx,
  176424. sqlite3_value **argv
  176425. ){
  176426. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  176427. int nJson = sqlite3_value_bytes(argv[0]);
  176428. JsonParse *p;
  176429. if( zJson==0 ) return 0;
  176430. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  176431. if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
  176432. p->nErr = 0;
  176433. return p; /* The cached entry matches, so return it */
  176434. }
  176435. p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
  176436. if( p==0 ){
  176437. sqlite3_result_error_nomem(pCtx);
  176438. return 0;
  176439. }
  176440. memset(p, 0, sizeof(*p));
  176441. p->zJson = (char*)&p[1];
  176442. memcpy((char*)p->zJson, zJson, nJson+1);
  176443. if( jsonParse(p, pCtx, p->zJson) ){
  176444. sqlite3_free(p);
  176445. return 0;
  176446. }
  176447. p->nJson = nJson;
  176448. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
  176449. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  176450. }
  176451. /*
  176452. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  176453. ** a match.
  176454. */
  176455. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  176456. if( pNode->jnFlags & JNODE_RAW ){
  176457. if( pNode->n!=nKey ) return 0;
  176458. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  176459. }else{
  176460. if( pNode->n!=nKey+2 ) return 0;
  176461. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  176462. }
  176463. }
  176464. /* forward declaration */
  176465. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  176466. /*
  176467. ** Search along zPath to find the node specified. Return a pointer
  176468. ** to that node, or NULL if zPath is malformed or if there is no such
  176469. ** node.
  176470. **
  176471. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  176472. ** possible to do so and if no existing node corresponds to zPath. If
  176473. ** new nodes are appended *pApnd is set to 1.
  176474. */
  176475. static JsonNode *jsonLookupStep(
  176476. JsonParse *pParse, /* The JSON to search */
  176477. u32 iRoot, /* Begin the search at this node */
  176478. const char *zPath, /* The path to search */
  176479. int *pApnd, /* Append nodes to complete path if not NULL */
  176480. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  176481. ){
  176482. u32 i, j, nKey;
  176483. const char *zKey;
  176484. JsonNode *pRoot = &pParse->aNode[iRoot];
  176485. if( zPath[0]==0 ) return pRoot;
  176486. if( zPath[0]=='.' ){
  176487. if( pRoot->eType!=JSON_OBJECT ) return 0;
  176488. zPath++;
  176489. if( zPath[0]=='"' ){
  176490. zKey = zPath + 1;
  176491. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  176492. nKey = i-1;
  176493. if( zPath[i] ){
  176494. i++;
  176495. }else{
  176496. *pzErr = zPath;
  176497. return 0;
  176498. }
  176499. }else{
  176500. zKey = zPath;
  176501. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  176502. nKey = i;
  176503. }
  176504. if( nKey==0 ){
  176505. *pzErr = zPath;
  176506. return 0;
  176507. }
  176508. j = 1;
  176509. for(;;){
  176510. while( j<=pRoot->n ){
  176511. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  176512. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  176513. }
  176514. j++;
  176515. j += jsonNodeSize(&pRoot[j]);
  176516. }
  176517. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  176518. iRoot += pRoot->u.iAppend;
  176519. pRoot = &pParse->aNode[iRoot];
  176520. j = 1;
  176521. }
  176522. if( pApnd ){
  176523. u32 iStart, iLabel;
  176524. JsonNode *pNode;
  176525. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  176526. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  176527. zPath += i;
  176528. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  176529. if( pParse->oom ) return 0;
  176530. if( pNode ){
  176531. pRoot = &pParse->aNode[iRoot];
  176532. pRoot->u.iAppend = iStart - iRoot;
  176533. pRoot->jnFlags |= JNODE_APPEND;
  176534. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  176535. }
  176536. return pNode;
  176537. }
  176538. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  176539. if( pRoot->eType!=JSON_ARRAY ) return 0;
  176540. i = 0;
  176541. j = 1;
  176542. while( safe_isdigit(zPath[j]) ){
  176543. i = i*10 + zPath[j] - '0';
  176544. j++;
  176545. }
  176546. if( zPath[j]!=']' ){
  176547. *pzErr = zPath;
  176548. return 0;
  176549. }
  176550. zPath += j + 1;
  176551. j = 1;
  176552. for(;;){
  176553. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  176554. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  176555. j += jsonNodeSize(&pRoot[j]);
  176556. }
  176557. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  176558. iRoot += pRoot->u.iAppend;
  176559. pRoot = &pParse->aNode[iRoot];
  176560. j = 1;
  176561. }
  176562. if( j<=pRoot->n ){
  176563. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  176564. }
  176565. if( i==0 && pApnd ){
  176566. u32 iStart;
  176567. JsonNode *pNode;
  176568. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  176569. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  176570. if( pParse->oom ) return 0;
  176571. if( pNode ){
  176572. pRoot = &pParse->aNode[iRoot];
  176573. pRoot->u.iAppend = iStart - iRoot;
  176574. pRoot->jnFlags |= JNODE_APPEND;
  176575. }
  176576. return pNode;
  176577. }
  176578. }else{
  176579. *pzErr = zPath;
  176580. }
  176581. return 0;
  176582. }
  176583. /*
  176584. ** Append content to pParse that will complete zPath. Return a pointer
  176585. ** to the inserted node, or return NULL if the append fails.
  176586. */
  176587. static JsonNode *jsonLookupAppend(
  176588. JsonParse *pParse, /* Append content to the JSON parse */
  176589. const char *zPath, /* Description of content to append */
  176590. int *pApnd, /* Set this flag to 1 */
  176591. const char **pzErr /* Make this point to any syntax error */
  176592. ){
  176593. *pApnd = 1;
  176594. if( zPath[0]==0 ){
  176595. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  176596. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  176597. }
  176598. if( zPath[0]=='.' ){
  176599. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  176600. }else if( strncmp(zPath,"[0]",3)==0 ){
  176601. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  176602. }else{
  176603. return 0;
  176604. }
  176605. if( pParse->oom ) return 0;
  176606. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  176607. }
  176608. /*
  176609. ** Return the text of a syntax error message on a JSON path. Space is
  176610. ** obtained from sqlite3_malloc().
  176611. */
  176612. static char *jsonPathSyntaxError(const char *zErr){
  176613. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  176614. }
  176615. /*
  176616. ** Do a node lookup using zPath. Return a pointer to the node on success.
  176617. ** Return NULL if not found or if there is an error.
  176618. **
  176619. ** On an error, write an error message into pCtx and increment the
  176620. ** pParse->nErr counter.
  176621. **
  176622. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  176623. ** nodes are appended.
  176624. */
  176625. static JsonNode *jsonLookup(
  176626. JsonParse *pParse, /* The JSON to search */
  176627. const char *zPath, /* The path to search */
  176628. int *pApnd, /* Append nodes to complete path if not NULL */
  176629. sqlite3_context *pCtx /* Report errors here, if not NULL */
  176630. ){
  176631. const char *zErr = 0;
  176632. JsonNode *pNode = 0;
  176633. char *zMsg;
  176634. if( zPath==0 ) return 0;
  176635. if( zPath[0]!='$' ){
  176636. zErr = zPath;
  176637. goto lookup_err;
  176638. }
  176639. zPath++;
  176640. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  176641. if( zErr==0 ) return pNode;
  176642. lookup_err:
  176643. pParse->nErr++;
  176644. assert( zErr!=0 && pCtx!=0 );
  176645. zMsg = jsonPathSyntaxError(zErr);
  176646. if( zMsg ){
  176647. sqlite3_result_error(pCtx, zMsg, -1);
  176648. sqlite3_free(zMsg);
  176649. }else{
  176650. sqlite3_result_error_nomem(pCtx);
  176651. }
  176652. return 0;
  176653. }
  176654. /*
  176655. ** Report the wrong number of arguments for json_insert(), json_replace()
  176656. ** or json_set().
  176657. */
  176658. static void jsonWrongNumArgs(
  176659. sqlite3_context *pCtx,
  176660. const char *zFuncName
  176661. ){
  176662. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  176663. zFuncName);
  176664. sqlite3_result_error(pCtx, zMsg, -1);
  176665. sqlite3_free(zMsg);
  176666. }
  176667. /*
  176668. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  176669. */
  176670. static void jsonRemoveAllNulls(JsonNode *pNode){
  176671. int i, n;
  176672. assert( pNode->eType==JSON_OBJECT );
  176673. n = pNode->n;
  176674. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  176675. switch( pNode[i].eType ){
  176676. case JSON_NULL:
  176677. pNode[i].jnFlags |= JNODE_REMOVE;
  176678. break;
  176679. case JSON_OBJECT:
  176680. jsonRemoveAllNulls(&pNode[i]);
  176681. break;
  176682. }
  176683. }
  176684. }
  176685. /****************************************************************************
  176686. ** SQL functions used for testing and debugging
  176687. ****************************************************************************/
  176688. #ifdef SQLITE_DEBUG
  176689. /*
  176690. ** The json_parse(JSON) function returns a string which describes
  176691. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  176692. ** well-formed.
  176693. */
  176694. static void jsonParseFunc(
  176695. sqlite3_context *ctx,
  176696. int argc,
  176697. sqlite3_value **argv
  176698. ){
  176699. JsonString s; /* Output string - not real JSON */
  176700. JsonParse x; /* The parse */
  176701. u32 i;
  176702. assert( argc==1 );
  176703. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  176704. jsonParseFindParents(&x);
  176705. jsonInit(&s, ctx);
  176706. for(i=0; i<x.nNode; i++){
  176707. const char *zType;
  176708. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  176709. assert( x.aNode[i].eType==JSON_STRING );
  176710. zType = "label";
  176711. }else{
  176712. zType = jsonType[x.aNode[i].eType];
  176713. }
  176714. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  176715. i, zType, x.aNode[i].n, x.aUp[i]);
  176716. if( x.aNode[i].u.zJContent!=0 ){
  176717. jsonAppendRaw(&s, " ", 1);
  176718. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  176719. }
  176720. jsonAppendRaw(&s, "\n", 1);
  176721. }
  176722. jsonParseReset(&x);
  176723. jsonResult(&s);
  176724. }
  176725. /*
  176726. ** The json_test1(JSON) function return true (1) if the input is JSON
  176727. ** text generated by another json function. It returns (0) if the input
  176728. ** is not known to be JSON.
  176729. */
  176730. static void jsonTest1Func(
  176731. sqlite3_context *ctx,
  176732. int argc,
  176733. sqlite3_value **argv
  176734. ){
  176735. UNUSED_PARAM(argc);
  176736. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  176737. }
  176738. #endif /* SQLITE_DEBUG */
  176739. /****************************************************************************
  176740. ** Scalar SQL function implementations
  176741. ****************************************************************************/
  176742. /*
  176743. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  176744. ** corresponding to the SQL value input. Mostly this means putting
  176745. ** double-quotes around strings and returning the unquoted string "null"
  176746. ** when given a NULL input.
  176747. */
  176748. static void jsonQuoteFunc(
  176749. sqlite3_context *ctx,
  176750. int argc,
  176751. sqlite3_value **argv
  176752. ){
  176753. JsonString jx;
  176754. UNUSED_PARAM(argc);
  176755. jsonInit(&jx, ctx);
  176756. jsonAppendValue(&jx, argv[0]);
  176757. jsonResult(&jx);
  176758. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  176759. }
  176760. /*
  176761. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  176762. ** array that contains all values given in arguments. Or if any argument
  176763. ** is a BLOB, throw an error.
  176764. */
  176765. static void jsonArrayFunc(
  176766. sqlite3_context *ctx,
  176767. int argc,
  176768. sqlite3_value **argv
  176769. ){
  176770. int i;
  176771. JsonString jx;
  176772. jsonInit(&jx, ctx);
  176773. jsonAppendChar(&jx, '[');
  176774. for(i=0; i<argc; i++){
  176775. jsonAppendSeparator(&jx);
  176776. jsonAppendValue(&jx, argv[i]);
  176777. }
  176778. jsonAppendChar(&jx, ']');
  176779. jsonResult(&jx);
  176780. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  176781. }
  176782. /*
  176783. ** json_array_length(JSON)
  176784. ** json_array_length(JSON, PATH)
  176785. **
  176786. ** Return the number of elements in the top-level JSON array.
  176787. ** Return 0 if the input is not a well-formed JSON array.
  176788. */
  176789. static void jsonArrayLengthFunc(
  176790. sqlite3_context *ctx,
  176791. int argc,
  176792. sqlite3_value **argv
  176793. ){
  176794. JsonParse *p; /* The parse */
  176795. sqlite3_int64 n = 0;
  176796. u32 i;
  176797. JsonNode *pNode;
  176798. p = jsonParseCached(ctx, argv);
  176799. if( p==0 ) return;
  176800. assert( p->nNode );
  176801. if( argc==2 ){
  176802. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  176803. pNode = jsonLookup(p, zPath, 0, ctx);
  176804. }else{
  176805. pNode = p->aNode;
  176806. }
  176807. if( pNode==0 ){
  176808. return;
  176809. }
  176810. if( pNode->eType==JSON_ARRAY ){
  176811. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  176812. for(i=1; i<=pNode->n; n++){
  176813. i += jsonNodeSize(&pNode[i]);
  176814. }
  176815. }
  176816. sqlite3_result_int64(ctx, n);
  176817. }
  176818. /*
  176819. ** json_extract(JSON, PATH, ...)
  176820. **
  176821. ** Return the element described by PATH. Return NULL if there is no
  176822. ** PATH element. If there are multiple PATHs, then return a JSON array
  176823. ** with the result from each path. Throw an error if the JSON or any PATH
  176824. ** is malformed.
  176825. */
  176826. static void jsonExtractFunc(
  176827. sqlite3_context *ctx,
  176828. int argc,
  176829. sqlite3_value **argv
  176830. ){
  176831. JsonParse *p; /* The parse */
  176832. JsonNode *pNode;
  176833. const char *zPath;
  176834. JsonString jx;
  176835. int i;
  176836. if( argc<2 ) return;
  176837. p = jsonParseCached(ctx, argv);
  176838. if( p==0 ) return;
  176839. jsonInit(&jx, ctx);
  176840. jsonAppendChar(&jx, '[');
  176841. for(i=1; i<argc; i++){
  176842. zPath = (const char*)sqlite3_value_text(argv[i]);
  176843. pNode = jsonLookup(p, zPath, 0, ctx);
  176844. if( p->nErr ) break;
  176845. if( argc>2 ){
  176846. jsonAppendSeparator(&jx);
  176847. if( pNode ){
  176848. jsonRenderNode(pNode, &jx, 0);
  176849. }else{
  176850. jsonAppendRaw(&jx, "null", 4);
  176851. }
  176852. }else if( pNode ){
  176853. jsonReturn(pNode, ctx, 0);
  176854. }
  176855. }
  176856. if( argc>2 && i==argc ){
  176857. jsonAppendChar(&jx, ']');
  176858. jsonResult(&jx);
  176859. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  176860. }
  176861. jsonReset(&jx);
  176862. }
  176863. /* This is the RFC 7396 MergePatch algorithm.
  176864. */
  176865. static JsonNode *jsonMergePatch(
  176866. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  176867. u32 iTarget, /* Node of the TARGET in pParse */
  176868. JsonNode *pPatch /* The PATCH */
  176869. ){
  176870. u32 i, j;
  176871. u32 iRoot;
  176872. JsonNode *pTarget;
  176873. if( pPatch->eType!=JSON_OBJECT ){
  176874. return pPatch;
  176875. }
  176876. assert( iTarget>=0 && iTarget<pParse->nNode );
  176877. pTarget = &pParse->aNode[iTarget];
  176878. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  176879. if( pTarget->eType!=JSON_OBJECT ){
  176880. jsonRemoveAllNulls(pPatch);
  176881. return pPatch;
  176882. }
  176883. iRoot = iTarget;
  176884. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  176885. u32 nKey;
  176886. const char *zKey;
  176887. assert( pPatch[i].eType==JSON_STRING );
  176888. assert( pPatch[i].jnFlags & JNODE_LABEL );
  176889. nKey = pPatch[i].n;
  176890. zKey = pPatch[i].u.zJContent;
  176891. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  176892. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  176893. assert( pTarget[j].eType==JSON_STRING );
  176894. assert( pTarget[j].jnFlags & JNODE_LABEL );
  176895. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  176896. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  176897. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  176898. if( pPatch[i+1].eType==JSON_NULL ){
  176899. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  176900. }else{
  176901. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  176902. if( pNew==0 ) return 0;
  176903. pTarget = &pParse->aNode[iTarget];
  176904. if( pNew!=&pTarget[j+1] ){
  176905. pTarget[j+1].u.pPatch = pNew;
  176906. pTarget[j+1].jnFlags |= JNODE_PATCH;
  176907. }
  176908. }
  176909. break;
  176910. }
  176911. }
  176912. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  176913. int iStart, iPatch;
  176914. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  176915. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  176916. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  176917. if( pParse->oom ) return 0;
  176918. jsonRemoveAllNulls(pPatch);
  176919. pTarget = &pParse->aNode[iTarget];
  176920. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  176921. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  176922. iRoot = iStart;
  176923. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  176924. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  176925. }
  176926. }
  176927. return pTarget;
  176928. }
  176929. /*
  176930. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  176931. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  176932. ** on the two arguments.
  176933. */
  176934. static void jsonPatchFunc(
  176935. sqlite3_context *ctx,
  176936. int argc,
  176937. sqlite3_value **argv
  176938. ){
  176939. JsonParse x; /* The JSON that is being patched */
  176940. JsonParse y; /* The patch */
  176941. JsonNode *pResult; /* The result of the merge */
  176942. UNUSED_PARAM(argc);
  176943. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  176944. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  176945. jsonParseReset(&x);
  176946. return;
  176947. }
  176948. pResult = jsonMergePatch(&x, 0, y.aNode);
  176949. assert( pResult!=0 || x.oom );
  176950. if( pResult ){
  176951. jsonReturnJson(pResult, ctx, 0);
  176952. }else{
  176953. sqlite3_result_error_nomem(ctx);
  176954. }
  176955. jsonParseReset(&x);
  176956. jsonParseReset(&y);
  176957. }
  176958. /*
  176959. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  176960. ** object that contains all name/value given in arguments. Or if any name
  176961. ** is not a string or if any value is a BLOB, throw an error.
  176962. */
  176963. static void jsonObjectFunc(
  176964. sqlite3_context *ctx,
  176965. int argc,
  176966. sqlite3_value **argv
  176967. ){
  176968. int i;
  176969. JsonString jx;
  176970. const char *z;
  176971. u32 n;
  176972. if( argc&1 ){
  176973. sqlite3_result_error(ctx, "json_object() requires an even number "
  176974. "of arguments", -1);
  176975. return;
  176976. }
  176977. jsonInit(&jx, ctx);
  176978. jsonAppendChar(&jx, '{');
  176979. for(i=0; i<argc; i+=2){
  176980. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  176981. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  176982. jsonReset(&jx);
  176983. return;
  176984. }
  176985. jsonAppendSeparator(&jx);
  176986. z = (const char*)sqlite3_value_text(argv[i]);
  176987. n = (u32)sqlite3_value_bytes(argv[i]);
  176988. jsonAppendString(&jx, z, n);
  176989. jsonAppendChar(&jx, ':');
  176990. jsonAppendValue(&jx, argv[i+1]);
  176991. }
  176992. jsonAppendChar(&jx, '}');
  176993. jsonResult(&jx);
  176994. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  176995. }
  176996. /*
  176997. ** json_remove(JSON, PATH, ...)
  176998. **
  176999. ** Remove the named elements from JSON and return the result. malformed
  177000. ** JSON or PATH arguments result in an error.
  177001. */
  177002. static void jsonRemoveFunc(
  177003. sqlite3_context *ctx,
  177004. int argc,
  177005. sqlite3_value **argv
  177006. ){
  177007. JsonParse x; /* The parse */
  177008. JsonNode *pNode;
  177009. const char *zPath;
  177010. u32 i;
  177011. if( argc<1 ) return;
  177012. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  177013. assert( x.nNode );
  177014. for(i=1; i<(u32)argc; i++){
  177015. zPath = (const char*)sqlite3_value_text(argv[i]);
  177016. if( zPath==0 ) goto remove_done;
  177017. pNode = jsonLookup(&x, zPath, 0, ctx);
  177018. if( x.nErr ) goto remove_done;
  177019. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  177020. }
  177021. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  177022. jsonReturnJson(x.aNode, ctx, 0);
  177023. }
  177024. remove_done:
  177025. jsonParseReset(&x);
  177026. }
  177027. /*
  177028. ** json_replace(JSON, PATH, VALUE, ...)
  177029. **
  177030. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  177031. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  177032. */
  177033. static void jsonReplaceFunc(
  177034. sqlite3_context *ctx,
  177035. int argc,
  177036. sqlite3_value **argv
  177037. ){
  177038. JsonParse x; /* The parse */
  177039. JsonNode *pNode;
  177040. const char *zPath;
  177041. u32 i;
  177042. if( argc<1 ) return;
  177043. if( (argc&1)==0 ) {
  177044. jsonWrongNumArgs(ctx, "replace");
  177045. return;
  177046. }
  177047. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  177048. assert( x.nNode );
  177049. for(i=1; i<(u32)argc; i+=2){
  177050. zPath = (const char*)sqlite3_value_text(argv[i]);
  177051. pNode = jsonLookup(&x, zPath, 0, ctx);
  177052. if( x.nErr ) goto replace_err;
  177053. if( pNode ){
  177054. pNode->jnFlags |= (u8)JNODE_REPLACE;
  177055. pNode->u.iReplace = i + 1;
  177056. }
  177057. }
  177058. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  177059. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  177060. }else{
  177061. jsonReturnJson(x.aNode, ctx, argv);
  177062. }
  177063. replace_err:
  177064. jsonParseReset(&x);
  177065. }
  177066. /*
  177067. ** json_set(JSON, PATH, VALUE, ...)
  177068. **
  177069. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  177070. ** exist. Overwrite existing values that do exist.
  177071. ** If JSON or PATH is malformed, throw an error.
  177072. **
  177073. ** json_insert(JSON, PATH, VALUE, ...)
  177074. **
  177075. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  177076. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  177077. */
  177078. static void jsonSetFunc(
  177079. sqlite3_context *ctx,
  177080. int argc,
  177081. sqlite3_value **argv
  177082. ){
  177083. JsonParse x; /* The parse */
  177084. JsonNode *pNode;
  177085. const char *zPath;
  177086. u32 i;
  177087. int bApnd;
  177088. int bIsSet = *(int*)sqlite3_user_data(ctx);
  177089. if( argc<1 ) return;
  177090. if( (argc&1)==0 ) {
  177091. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  177092. return;
  177093. }
  177094. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  177095. assert( x.nNode );
  177096. for(i=1; i<(u32)argc; i+=2){
  177097. zPath = (const char*)sqlite3_value_text(argv[i]);
  177098. bApnd = 0;
  177099. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  177100. if( x.oom ){
  177101. sqlite3_result_error_nomem(ctx);
  177102. goto jsonSetDone;
  177103. }else if( x.nErr ){
  177104. goto jsonSetDone;
  177105. }else if( pNode && (bApnd || bIsSet) ){
  177106. pNode->jnFlags |= (u8)JNODE_REPLACE;
  177107. pNode->u.iReplace = i + 1;
  177108. }
  177109. }
  177110. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  177111. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  177112. }else{
  177113. jsonReturnJson(x.aNode, ctx, argv);
  177114. }
  177115. jsonSetDone:
  177116. jsonParseReset(&x);
  177117. }
  177118. /*
  177119. ** json_type(JSON)
  177120. ** json_type(JSON, PATH)
  177121. **
  177122. ** Return the top-level "type" of a JSON string. Throw an error if
  177123. ** either the JSON or PATH inputs are not well-formed.
  177124. */
  177125. static void jsonTypeFunc(
  177126. sqlite3_context *ctx,
  177127. int argc,
  177128. sqlite3_value **argv
  177129. ){
  177130. JsonParse x; /* The parse */
  177131. const char *zPath;
  177132. JsonNode *pNode;
  177133. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  177134. assert( x.nNode );
  177135. if( argc==2 ){
  177136. zPath = (const char*)sqlite3_value_text(argv[1]);
  177137. pNode = jsonLookup(&x, zPath, 0, ctx);
  177138. }else{
  177139. pNode = x.aNode;
  177140. }
  177141. if( pNode ){
  177142. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  177143. }
  177144. jsonParseReset(&x);
  177145. }
  177146. /*
  177147. ** json_valid(JSON)
  177148. **
  177149. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  177150. ** Return 0 otherwise.
  177151. */
  177152. static void jsonValidFunc(
  177153. sqlite3_context *ctx,
  177154. int argc,
  177155. sqlite3_value **argv
  177156. ){
  177157. JsonParse x; /* The parse */
  177158. int rc = 0;
  177159. UNUSED_PARAM(argc);
  177160. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  177161. rc = 1;
  177162. }
  177163. jsonParseReset(&x);
  177164. sqlite3_result_int(ctx, rc);
  177165. }
  177166. /****************************************************************************
  177167. ** Aggregate SQL function implementations
  177168. ****************************************************************************/
  177169. /*
  177170. ** json_group_array(VALUE)
  177171. **
  177172. ** Return a JSON array composed of all values in the aggregate.
  177173. */
  177174. static void jsonArrayStep(
  177175. sqlite3_context *ctx,
  177176. int argc,
  177177. sqlite3_value **argv
  177178. ){
  177179. JsonString *pStr;
  177180. UNUSED_PARAM(argc);
  177181. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  177182. if( pStr ){
  177183. if( pStr->zBuf==0 ){
  177184. jsonInit(pStr, ctx);
  177185. jsonAppendChar(pStr, '[');
  177186. }else{
  177187. jsonAppendChar(pStr, ',');
  177188. pStr->pCtx = ctx;
  177189. }
  177190. jsonAppendValue(pStr, argv[0]);
  177191. }
  177192. }
  177193. static void jsonArrayFinal(sqlite3_context *ctx){
  177194. JsonString *pStr;
  177195. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  177196. if( pStr ){
  177197. pStr->pCtx = ctx;
  177198. jsonAppendChar(pStr, ']');
  177199. if( pStr->bErr ){
  177200. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  177201. assert( pStr->bStatic );
  177202. }else{
  177203. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  177204. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  177205. pStr->bStatic = 1;
  177206. }
  177207. }else{
  177208. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  177209. }
  177210. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  177211. }
  177212. /*
  177213. ** json_group_obj(NAME,VALUE)
  177214. **
  177215. ** Return a JSON object composed of all names and values in the aggregate.
  177216. */
  177217. static void jsonObjectStep(
  177218. sqlite3_context *ctx,
  177219. int argc,
  177220. sqlite3_value **argv
  177221. ){
  177222. JsonString *pStr;
  177223. const char *z;
  177224. u32 n;
  177225. UNUSED_PARAM(argc);
  177226. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  177227. if( pStr ){
  177228. if( pStr->zBuf==0 ){
  177229. jsonInit(pStr, ctx);
  177230. jsonAppendChar(pStr, '{');
  177231. }else{
  177232. jsonAppendChar(pStr, ',');
  177233. pStr->pCtx = ctx;
  177234. }
  177235. z = (const char*)sqlite3_value_text(argv[0]);
  177236. n = (u32)sqlite3_value_bytes(argv[0]);
  177237. jsonAppendString(pStr, z, n);
  177238. jsonAppendChar(pStr, ':');
  177239. jsonAppendValue(pStr, argv[1]);
  177240. }
  177241. }
  177242. static void jsonObjectFinal(sqlite3_context *ctx){
  177243. JsonString *pStr;
  177244. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  177245. if( pStr ){
  177246. jsonAppendChar(pStr, '}');
  177247. if( pStr->bErr ){
  177248. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  177249. assert( pStr->bStatic );
  177250. }else{
  177251. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  177252. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  177253. pStr->bStatic = 1;
  177254. }
  177255. }else{
  177256. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  177257. }
  177258. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  177259. }
  177260. #ifndef SQLITE_OMIT_VIRTUALTABLE
  177261. /****************************************************************************
  177262. ** The json_each virtual table
  177263. ****************************************************************************/
  177264. typedef struct JsonEachCursor JsonEachCursor;
  177265. struct JsonEachCursor {
  177266. sqlite3_vtab_cursor base; /* Base class - must be first */
  177267. u32 iRowid; /* The rowid */
  177268. u32 iBegin; /* The first node of the scan */
  177269. u32 i; /* Index in sParse.aNode[] of current row */
  177270. u32 iEnd; /* EOF when i equals or exceeds this value */
  177271. u8 eType; /* Type of top-level element */
  177272. u8 bRecursive; /* True for json_tree(). False for json_each() */
  177273. char *zJson; /* Input JSON */
  177274. char *zRoot; /* Path by which to filter zJson */
  177275. JsonParse sParse; /* Parse of the input JSON */
  177276. };
  177277. /* Constructor for the json_each virtual table */
  177278. static int jsonEachConnect(
  177279. sqlite3 *db,
  177280. void *pAux,
  177281. int argc, const char *const*argv,
  177282. sqlite3_vtab **ppVtab,
  177283. char **pzErr
  177284. ){
  177285. sqlite3_vtab *pNew;
  177286. int rc;
  177287. /* Column numbers */
  177288. #define JEACH_KEY 0
  177289. #define JEACH_VALUE 1
  177290. #define JEACH_TYPE 2
  177291. #define JEACH_ATOM 3
  177292. #define JEACH_ID 4
  177293. #define JEACH_PARENT 5
  177294. #define JEACH_FULLKEY 6
  177295. #define JEACH_PATH 7
  177296. #define JEACH_JSON 8
  177297. #define JEACH_ROOT 9
  177298. UNUSED_PARAM(pzErr);
  177299. UNUSED_PARAM(argv);
  177300. UNUSED_PARAM(argc);
  177301. UNUSED_PARAM(pAux);
  177302. rc = sqlite3_declare_vtab(db,
  177303. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  177304. "json HIDDEN,root HIDDEN)");
  177305. if( rc==SQLITE_OK ){
  177306. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  177307. if( pNew==0 ) return SQLITE_NOMEM;
  177308. memset(pNew, 0, sizeof(*pNew));
  177309. }
  177310. return rc;
  177311. }
  177312. /* destructor for json_each virtual table */
  177313. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  177314. sqlite3_free(pVtab);
  177315. return SQLITE_OK;
  177316. }
  177317. /* constructor for a JsonEachCursor object for json_each(). */
  177318. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  177319. JsonEachCursor *pCur;
  177320. UNUSED_PARAM(p);
  177321. pCur = sqlite3_malloc( sizeof(*pCur) );
  177322. if( pCur==0 ) return SQLITE_NOMEM;
  177323. memset(pCur, 0, sizeof(*pCur));
  177324. *ppCursor = &pCur->base;
  177325. return SQLITE_OK;
  177326. }
  177327. /* constructor for a JsonEachCursor object for json_tree(). */
  177328. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  177329. int rc = jsonEachOpenEach(p, ppCursor);
  177330. if( rc==SQLITE_OK ){
  177331. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  177332. pCur->bRecursive = 1;
  177333. }
  177334. return rc;
  177335. }
  177336. /* Reset a JsonEachCursor back to its original state. Free any memory
  177337. ** held. */
  177338. static void jsonEachCursorReset(JsonEachCursor *p){
  177339. sqlite3_free(p->zJson);
  177340. sqlite3_free(p->zRoot);
  177341. jsonParseReset(&p->sParse);
  177342. p->iRowid = 0;
  177343. p->i = 0;
  177344. p->iEnd = 0;
  177345. p->eType = 0;
  177346. p->zJson = 0;
  177347. p->zRoot = 0;
  177348. }
  177349. /* Destructor for a jsonEachCursor object */
  177350. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  177351. JsonEachCursor *p = (JsonEachCursor*)cur;
  177352. jsonEachCursorReset(p);
  177353. sqlite3_free(cur);
  177354. return SQLITE_OK;
  177355. }
  177356. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  177357. ** of the JSON object */
  177358. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  177359. JsonEachCursor *p = (JsonEachCursor*)cur;
  177360. return p->i >= p->iEnd;
  177361. }
  177362. /* Advance the cursor to the next element for json_tree() */
  177363. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  177364. JsonEachCursor *p = (JsonEachCursor*)cur;
  177365. if( p->bRecursive ){
  177366. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  177367. p->i++;
  177368. p->iRowid++;
  177369. if( p->i<p->iEnd ){
  177370. u32 iUp = p->sParse.aUp[p->i];
  177371. JsonNode *pUp = &p->sParse.aNode[iUp];
  177372. p->eType = pUp->eType;
  177373. if( pUp->eType==JSON_ARRAY ){
  177374. if( iUp==p->i-1 ){
  177375. pUp->u.iKey = 0;
  177376. }else{
  177377. pUp->u.iKey++;
  177378. }
  177379. }
  177380. }
  177381. }else{
  177382. switch( p->eType ){
  177383. case JSON_ARRAY: {
  177384. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  177385. p->iRowid++;
  177386. break;
  177387. }
  177388. case JSON_OBJECT: {
  177389. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  177390. p->iRowid++;
  177391. break;
  177392. }
  177393. default: {
  177394. p->i = p->iEnd;
  177395. break;
  177396. }
  177397. }
  177398. }
  177399. return SQLITE_OK;
  177400. }
  177401. /* Append the name of the path for element i to pStr
  177402. */
  177403. static void jsonEachComputePath(
  177404. JsonEachCursor *p, /* The cursor */
  177405. JsonString *pStr, /* Write the path here */
  177406. u32 i /* Path to this element */
  177407. ){
  177408. JsonNode *pNode, *pUp;
  177409. u32 iUp;
  177410. if( i==0 ){
  177411. jsonAppendChar(pStr, '$');
  177412. return;
  177413. }
  177414. iUp = p->sParse.aUp[i];
  177415. jsonEachComputePath(p, pStr, iUp);
  177416. pNode = &p->sParse.aNode[i];
  177417. pUp = &p->sParse.aNode[iUp];
  177418. if( pUp->eType==JSON_ARRAY ){
  177419. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  177420. }else{
  177421. assert( pUp->eType==JSON_OBJECT );
  177422. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  177423. assert( pNode->eType==JSON_STRING );
  177424. assert( pNode->jnFlags & JNODE_LABEL );
  177425. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  177426. }
  177427. }
  177428. /* Return the value of a column */
  177429. static int jsonEachColumn(
  177430. sqlite3_vtab_cursor *cur, /* The cursor */
  177431. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  177432. int i /* Which column to return */
  177433. ){
  177434. JsonEachCursor *p = (JsonEachCursor*)cur;
  177435. JsonNode *pThis = &p->sParse.aNode[p->i];
  177436. switch( i ){
  177437. case JEACH_KEY: {
  177438. if( p->i==0 ) break;
  177439. if( p->eType==JSON_OBJECT ){
  177440. jsonReturn(pThis, ctx, 0);
  177441. }else if( p->eType==JSON_ARRAY ){
  177442. u32 iKey;
  177443. if( p->bRecursive ){
  177444. if( p->iRowid==0 ) break;
  177445. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  177446. }else{
  177447. iKey = p->iRowid;
  177448. }
  177449. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  177450. }
  177451. break;
  177452. }
  177453. case JEACH_VALUE: {
  177454. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  177455. jsonReturn(pThis, ctx, 0);
  177456. break;
  177457. }
  177458. case JEACH_TYPE: {
  177459. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  177460. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  177461. break;
  177462. }
  177463. case JEACH_ATOM: {
  177464. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  177465. if( pThis->eType>=JSON_ARRAY ) break;
  177466. jsonReturn(pThis, ctx, 0);
  177467. break;
  177468. }
  177469. case JEACH_ID: {
  177470. sqlite3_result_int64(ctx,
  177471. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  177472. break;
  177473. }
  177474. case JEACH_PARENT: {
  177475. if( p->i>p->iBegin && p->bRecursive ){
  177476. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  177477. }
  177478. break;
  177479. }
  177480. case JEACH_FULLKEY: {
  177481. JsonString x;
  177482. jsonInit(&x, ctx);
  177483. if( p->bRecursive ){
  177484. jsonEachComputePath(p, &x, p->i);
  177485. }else{
  177486. if( p->zRoot ){
  177487. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  177488. }else{
  177489. jsonAppendChar(&x, '$');
  177490. }
  177491. if( p->eType==JSON_ARRAY ){
  177492. jsonPrintf(30, &x, "[%d]", p->iRowid);
  177493. }else if( p->eType==JSON_OBJECT ){
  177494. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  177495. }
  177496. }
  177497. jsonResult(&x);
  177498. break;
  177499. }
  177500. case JEACH_PATH: {
  177501. if( p->bRecursive ){
  177502. JsonString x;
  177503. jsonInit(&x, ctx);
  177504. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  177505. jsonResult(&x);
  177506. break;
  177507. }
  177508. /* For json_each() path and root are the same so fall through
  177509. ** into the root case */
  177510. }
  177511. default: {
  177512. const char *zRoot = p->zRoot;
  177513. if( zRoot==0 ) zRoot = "$";
  177514. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  177515. break;
  177516. }
  177517. case JEACH_JSON: {
  177518. assert( i==JEACH_JSON );
  177519. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  177520. break;
  177521. }
  177522. }
  177523. return SQLITE_OK;
  177524. }
  177525. /* Return the current rowid value */
  177526. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  177527. JsonEachCursor *p = (JsonEachCursor*)cur;
  177528. *pRowid = p->iRowid;
  177529. return SQLITE_OK;
  177530. }
  177531. /* The query strategy is to look for an equality constraint on the json
  177532. ** column. Without such a constraint, the table cannot operate. idxNum is
  177533. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  177534. ** and 0 otherwise.
  177535. */
  177536. static int jsonEachBestIndex(
  177537. sqlite3_vtab *tab,
  177538. sqlite3_index_info *pIdxInfo
  177539. ){
  177540. int i;
  177541. int jsonIdx = -1;
  177542. int rootIdx = -1;
  177543. const struct sqlite3_index_constraint *pConstraint;
  177544. UNUSED_PARAM(tab);
  177545. pConstraint = pIdxInfo->aConstraint;
  177546. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  177547. if( pConstraint->usable==0 ) continue;
  177548. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  177549. switch( pConstraint->iColumn ){
  177550. case JEACH_JSON: jsonIdx = i; break;
  177551. case JEACH_ROOT: rootIdx = i; break;
  177552. default: /* no-op */ break;
  177553. }
  177554. }
  177555. if( jsonIdx<0 ){
  177556. pIdxInfo->idxNum = 0;
  177557. pIdxInfo->estimatedCost = 1e99;
  177558. }else{
  177559. pIdxInfo->estimatedCost = 1.0;
  177560. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  177561. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  177562. if( rootIdx<0 ){
  177563. pIdxInfo->idxNum = 1;
  177564. }else{
  177565. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  177566. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  177567. pIdxInfo->idxNum = 3;
  177568. }
  177569. }
  177570. return SQLITE_OK;
  177571. }
  177572. /* Start a search on a new JSON string */
  177573. static int jsonEachFilter(
  177574. sqlite3_vtab_cursor *cur,
  177575. int idxNum, const char *idxStr,
  177576. int argc, sqlite3_value **argv
  177577. ){
  177578. JsonEachCursor *p = (JsonEachCursor*)cur;
  177579. const char *z;
  177580. const char *zRoot = 0;
  177581. sqlite3_int64 n;
  177582. UNUSED_PARAM(idxStr);
  177583. UNUSED_PARAM(argc);
  177584. jsonEachCursorReset(p);
  177585. if( idxNum==0 ) return SQLITE_OK;
  177586. z = (const char*)sqlite3_value_text(argv[0]);
  177587. if( z==0 ) return SQLITE_OK;
  177588. n = sqlite3_value_bytes(argv[0]);
  177589. p->zJson = sqlite3_malloc64( n+1 );
  177590. if( p->zJson==0 ) return SQLITE_NOMEM;
  177591. memcpy(p->zJson, z, (size_t)n+1);
  177592. if( jsonParse(&p->sParse, 0, p->zJson) ){
  177593. int rc = SQLITE_NOMEM;
  177594. if( p->sParse.oom==0 ){
  177595. sqlite3_free(cur->pVtab->zErrMsg);
  177596. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  177597. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  177598. }
  177599. jsonEachCursorReset(p);
  177600. return rc;
  177601. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  177602. jsonEachCursorReset(p);
  177603. return SQLITE_NOMEM;
  177604. }else{
  177605. JsonNode *pNode = 0;
  177606. if( idxNum==3 ){
  177607. const char *zErr = 0;
  177608. zRoot = (const char*)sqlite3_value_text(argv[1]);
  177609. if( zRoot==0 ) return SQLITE_OK;
  177610. n = sqlite3_value_bytes(argv[1]);
  177611. p->zRoot = sqlite3_malloc64( n+1 );
  177612. if( p->zRoot==0 ) return SQLITE_NOMEM;
  177613. memcpy(p->zRoot, zRoot, (size_t)n+1);
  177614. if( zRoot[0]!='$' ){
  177615. zErr = zRoot;
  177616. }else{
  177617. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  177618. }
  177619. if( zErr ){
  177620. sqlite3_free(cur->pVtab->zErrMsg);
  177621. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  177622. jsonEachCursorReset(p);
  177623. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  177624. }else if( pNode==0 ){
  177625. return SQLITE_OK;
  177626. }
  177627. }else{
  177628. pNode = p->sParse.aNode;
  177629. }
  177630. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  177631. p->eType = pNode->eType;
  177632. if( p->eType>=JSON_ARRAY ){
  177633. pNode->u.iKey = 0;
  177634. p->iEnd = p->i + pNode->n + 1;
  177635. if( p->bRecursive ){
  177636. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  177637. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  177638. p->i--;
  177639. }
  177640. }else{
  177641. p->i++;
  177642. }
  177643. }else{
  177644. p->iEnd = p->i+1;
  177645. }
  177646. }
  177647. return SQLITE_OK;
  177648. }
  177649. /* The methods of the json_each virtual table */
  177650. static sqlite3_module jsonEachModule = {
  177651. 0, /* iVersion */
  177652. 0, /* xCreate */
  177653. jsonEachConnect, /* xConnect */
  177654. jsonEachBestIndex, /* xBestIndex */
  177655. jsonEachDisconnect, /* xDisconnect */
  177656. 0, /* xDestroy */
  177657. jsonEachOpenEach, /* xOpen - open a cursor */
  177658. jsonEachClose, /* xClose - close a cursor */
  177659. jsonEachFilter, /* xFilter - configure scan constraints */
  177660. jsonEachNext, /* xNext - advance a cursor */
  177661. jsonEachEof, /* xEof - check for end of scan */
  177662. jsonEachColumn, /* xColumn - read data */
  177663. jsonEachRowid, /* xRowid - read data */
  177664. 0, /* xUpdate */
  177665. 0, /* xBegin */
  177666. 0, /* xSync */
  177667. 0, /* xCommit */
  177668. 0, /* xRollback */
  177669. 0, /* xFindMethod */
  177670. 0, /* xRename */
  177671. 0, /* xSavepoint */
  177672. 0, /* xRelease */
  177673. 0 /* xRollbackTo */
  177674. };
  177675. /* The methods of the json_tree virtual table. */
  177676. static sqlite3_module jsonTreeModule = {
  177677. 0, /* iVersion */
  177678. 0, /* xCreate */
  177679. jsonEachConnect, /* xConnect */
  177680. jsonEachBestIndex, /* xBestIndex */
  177681. jsonEachDisconnect, /* xDisconnect */
  177682. 0, /* xDestroy */
  177683. jsonEachOpenTree, /* xOpen - open a cursor */
  177684. jsonEachClose, /* xClose - close a cursor */
  177685. jsonEachFilter, /* xFilter - configure scan constraints */
  177686. jsonEachNext, /* xNext - advance a cursor */
  177687. jsonEachEof, /* xEof - check for end of scan */
  177688. jsonEachColumn, /* xColumn - read data */
  177689. jsonEachRowid, /* xRowid - read data */
  177690. 0, /* xUpdate */
  177691. 0, /* xBegin */
  177692. 0, /* xSync */
  177693. 0, /* xCommit */
  177694. 0, /* xRollback */
  177695. 0, /* xFindMethod */
  177696. 0, /* xRename */
  177697. 0, /* xSavepoint */
  177698. 0, /* xRelease */
  177699. 0 /* xRollbackTo */
  177700. };
  177701. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  177702. /****************************************************************************
  177703. ** The following routines are the only publically visible identifiers in this
  177704. ** file. Call the following routines in order to register the various SQL
  177705. ** functions and the virtual table implemented by this file.
  177706. ****************************************************************************/
  177707. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  177708. int rc = SQLITE_OK;
  177709. unsigned int i;
  177710. static const struct {
  177711. const char *zName;
  177712. int nArg;
  177713. int flag;
  177714. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  177715. } aFunc[] = {
  177716. { "json", 1, 0, jsonRemoveFunc },
  177717. { "json_array", -1, 0, jsonArrayFunc },
  177718. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  177719. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  177720. { "json_extract", -1, 0, jsonExtractFunc },
  177721. { "json_insert", -1, 0, jsonSetFunc },
  177722. { "json_object", -1, 0, jsonObjectFunc },
  177723. { "json_patch", 2, 0, jsonPatchFunc },
  177724. { "json_quote", 1, 0, jsonQuoteFunc },
  177725. { "json_remove", -1, 0, jsonRemoveFunc },
  177726. { "json_replace", -1, 0, jsonReplaceFunc },
  177727. { "json_set", -1, 1, jsonSetFunc },
  177728. { "json_type", 1, 0, jsonTypeFunc },
  177729. { "json_type", 2, 0, jsonTypeFunc },
  177730. { "json_valid", 1, 0, jsonValidFunc },
  177731. #if SQLITE_DEBUG
  177732. /* DEBUG and TESTING functions */
  177733. { "json_parse", 1, 0, jsonParseFunc },
  177734. { "json_test1", 1, 0, jsonTest1Func },
  177735. #endif
  177736. };
  177737. static const struct {
  177738. const char *zName;
  177739. int nArg;
  177740. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  177741. void (*xFinal)(sqlite3_context*);
  177742. } aAgg[] = {
  177743. { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
  177744. { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
  177745. };
  177746. #ifndef SQLITE_OMIT_VIRTUALTABLE
  177747. static const struct {
  177748. const char *zName;
  177749. sqlite3_module *pModule;
  177750. } aMod[] = {
  177751. { "json_each", &jsonEachModule },
  177752. { "json_tree", &jsonTreeModule },
  177753. };
  177754. #endif
  177755. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  177756. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  177757. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  177758. (void*)&aFunc[i].flag,
  177759. aFunc[i].xFunc, 0, 0);
  177760. }
  177761. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  177762. rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  177763. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  177764. 0, aAgg[i].xStep, aAgg[i].xFinal);
  177765. }
  177766. #ifndef SQLITE_OMIT_VIRTUALTABLE
  177767. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  177768. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  177769. }
  177770. #endif
  177771. return rc;
  177772. }
  177773. #ifndef SQLITE_CORE
  177774. #ifdef _WIN32
  177775. __declspec(dllexport)
  177776. #endif
  177777. SQLITE_API int sqlite3_json_init(
  177778. sqlite3 *db,
  177779. char **pzErrMsg,
  177780. const sqlite3_api_routines *pApi
  177781. ){
  177782. SQLITE_EXTENSION_INIT2(pApi);
  177783. (void)pzErrMsg; /* Unused parameter */
  177784. return sqlite3Json1Init(db);
  177785. }
  177786. #endif
  177787. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  177788. /************** End of json1.c ***********************************************/
  177789. /************** Begin file fts5.c ********************************************/
  177790. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  177791. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  177792. # define NDEBUG 1
  177793. #endif
  177794. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  177795. # undef NDEBUG
  177796. #endif
  177797. /*
  177798. ** 2014 May 31
  177799. **
  177800. ** The author disclaims copyright to this source code. In place of
  177801. ** a legal notice, here is a blessing:
  177802. **
  177803. ** May you do good and not evil.
  177804. ** May you find forgiveness for yourself and forgive others.
  177805. ** May you share freely, never taking more than you give.
  177806. **
  177807. ******************************************************************************
  177808. **
  177809. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  177810. ** FTS5 may be extended with:
  177811. **
  177812. ** * custom tokenizers, and
  177813. ** * custom auxiliary functions.
  177814. */
  177815. #ifndef _FTS5_H
  177816. #define _FTS5_H
  177817. /* #include "sqlite3.h" */
  177818. #if 0
  177819. extern "C" {
  177820. #endif
  177821. /*************************************************************************
  177822. ** CUSTOM AUXILIARY FUNCTIONS
  177823. **
  177824. ** Virtual table implementations may overload SQL functions by implementing
  177825. ** the sqlite3_module.xFindFunction() method.
  177826. */
  177827. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  177828. typedef struct Fts5Context Fts5Context;
  177829. typedef struct Fts5PhraseIter Fts5PhraseIter;
  177830. typedef void (*fts5_extension_function)(
  177831. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  177832. Fts5Context *pFts, /* First arg to pass to pApi functions */
  177833. sqlite3_context *pCtx, /* Context for returning result/error */
  177834. int nVal, /* Number of values in apVal[] array */
  177835. sqlite3_value **apVal /* Array of trailing arguments */
  177836. );
  177837. struct Fts5PhraseIter {
  177838. const unsigned char *a;
  177839. const unsigned char *b;
  177840. };
  177841. /*
  177842. ** EXTENSION API FUNCTIONS
  177843. **
  177844. ** xUserData(pFts):
  177845. ** Return a copy of the context pointer the extension function was
  177846. ** registered with.
  177847. **
  177848. ** xColumnTotalSize(pFts, iCol, pnToken):
  177849. ** If parameter iCol is less than zero, set output variable *pnToken
  177850. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  177851. ** non-negative but less than the number of columns in the table, return
  177852. ** the total number of tokens in column iCol, considering all rows in
  177853. ** the FTS5 table.
  177854. **
  177855. ** If parameter iCol is greater than or equal to the number of columns
  177856. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  177857. ** an OOM condition or IO error), an appropriate SQLite error code is
  177858. ** returned.
  177859. **
  177860. ** xColumnCount(pFts):
  177861. ** Return the number of columns in the table.
  177862. **
  177863. ** xColumnSize(pFts, iCol, pnToken):
  177864. ** If parameter iCol is less than zero, set output variable *pnToken
  177865. ** to the total number of tokens in the current row. Or, if iCol is
  177866. ** non-negative but less than the number of columns in the table, set
  177867. ** *pnToken to the number of tokens in column iCol of the current row.
  177868. **
  177869. ** If parameter iCol is greater than or equal to the number of columns
  177870. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  177871. ** an OOM condition or IO error), an appropriate SQLite error code is
  177872. ** returned.
  177873. **
  177874. ** This function may be quite inefficient if used with an FTS5 table
  177875. ** created with the "columnsize=0" option.
  177876. **
  177877. ** xColumnText:
  177878. ** This function attempts to retrieve the text of column iCol of the
  177879. ** current document. If successful, (*pz) is set to point to a buffer
  177880. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  177881. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  177882. ** if an error occurs, an SQLite error code is returned and the final values
  177883. ** of (*pz) and (*pn) are undefined.
  177884. **
  177885. ** xPhraseCount:
  177886. ** Returns the number of phrases in the current query expression.
  177887. **
  177888. ** xPhraseSize:
  177889. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  177890. ** are numbered starting from zero.
  177891. **
  177892. ** xInstCount:
  177893. ** Set *pnInst to the total number of occurrences of all phrases within
  177894. ** the query within the current row. Return SQLITE_OK if successful, or
  177895. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  177896. **
  177897. ** This API can be quite slow if used with an FTS5 table created with the
  177898. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  177899. ** with either "detail=none" or "detail=column" and "content=" option
  177900. ** (i.e. if it is a contentless table), then this API always returns 0.
  177901. **
  177902. ** xInst:
  177903. ** Query for the details of phrase match iIdx within the current row.
  177904. ** Phrase matches are numbered starting from zero, so the iIdx argument
  177905. ** should be greater than or equal to zero and smaller than the value
  177906. ** output by xInstCount().
  177907. **
  177908. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  177909. ** to the column in which it occurs and *piOff the token offset of the
  177910. ** first token of the phrase. The exception is if the table was created
  177911. ** with the offsets=0 option specified. In this case *piOff is always
  177912. ** set to -1.
  177913. **
  177914. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  177915. ** if an error occurs.
  177916. **
  177917. ** This API can be quite slow if used with an FTS5 table created with the
  177918. ** "detail=none" or "detail=column" option.
  177919. **
  177920. ** xRowid:
  177921. ** Returns the rowid of the current row.
  177922. **
  177923. ** xTokenize:
  177924. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  177925. **
  177926. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  177927. ** This API function is used to query the FTS table for phrase iPhrase
  177928. ** of the current query. Specifically, a query equivalent to:
  177929. **
  177930. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  177931. **
  177932. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  177933. ** current query is executed. Any column filter that applies to
  177934. ** phrase iPhrase of the current query is included in $p. For each
  177935. ** row visited, the callback function passed as the fourth argument
  177936. ** is invoked. The context and API objects passed to the callback
  177937. ** function may be used to access the properties of each matched row.
  177938. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  177939. ** the third argument to pUserData.
  177940. **
  177941. ** If the callback function returns any value other than SQLITE_OK, the
  177942. ** query is abandoned and the xQueryPhrase function returns immediately.
  177943. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  177944. ** Otherwise, the error code is propagated upwards.
  177945. **
  177946. ** If the query runs to completion without incident, SQLITE_OK is returned.
  177947. ** Or, if some error occurs before the query completes or is aborted by
  177948. ** the callback, an SQLite error code is returned.
  177949. **
  177950. **
  177951. ** xSetAuxdata(pFts5, pAux, xDelete)
  177952. **
  177953. ** Save the pointer passed as the second argument as the extension functions
  177954. ** "auxiliary data". The pointer may then be retrieved by the current or any
  177955. ** future invocation of the same fts5 extension function made as part of
  177956. ** of the same MATCH query using the xGetAuxdata() API.
  177957. **
  177958. ** Each extension function is allocated a single auxiliary data slot for
  177959. ** each FTS query (MATCH expression). If the extension function is invoked
  177960. ** more than once for a single FTS query, then all invocations share a
  177961. ** single auxiliary data context.
  177962. **
  177963. ** If there is already an auxiliary data pointer when this function is
  177964. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  177965. ** was specified along with the original pointer, it is invoked at this
  177966. ** point.
  177967. **
  177968. ** The xDelete callback, if one is specified, is also invoked on the
  177969. ** auxiliary data pointer after the FTS5 query has finished.
  177970. **
  177971. ** If an error (e.g. an OOM condition) occurs within this function, an
  177972. ** the auxiliary data is set to NULL and an error code returned. If the
  177973. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  177974. ** pointer before returning.
  177975. **
  177976. **
  177977. ** xGetAuxdata(pFts5, bClear)
  177978. **
  177979. ** Returns the current auxiliary data pointer for the fts5 extension
  177980. ** function. See the xSetAuxdata() method for details.
  177981. **
  177982. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  177983. ** (set to NULL) before this function returns. In this case the xDelete,
  177984. ** if any, is not invoked.
  177985. **
  177986. **
  177987. ** xRowCount(pFts5, pnRow)
  177988. **
  177989. ** This function is used to retrieve the total number of rows in the table.
  177990. ** In other words, the same value that would be returned by:
  177991. **
  177992. ** SELECT count(*) FROM ftstable;
  177993. **
  177994. ** xPhraseFirst()
  177995. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  177996. ** method, to iterate through all instances of a single query phrase within
  177997. ** the current row. This is the same information as is accessible via the
  177998. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  177999. ** to use, this API may be faster under some circumstances. To iterate
  178000. ** through instances of phrase iPhrase, use the following code:
  178001. **
  178002. ** Fts5PhraseIter iter;
  178003. ** int iCol, iOff;
  178004. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  178005. ** iCol>=0;
  178006. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  178007. ** ){
  178008. ** // An instance of phrase iPhrase at offset iOff of column iCol
  178009. ** }
  178010. **
  178011. ** The Fts5PhraseIter structure is defined above. Applications should not
  178012. ** modify this structure directly - it should only be used as shown above
  178013. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  178014. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  178015. **
  178016. ** This API can be quite slow if used with an FTS5 table created with the
  178017. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  178018. ** with either "detail=none" or "detail=column" and "content=" option
  178019. ** (i.e. if it is a contentless table), then this API always iterates
  178020. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  178021. **
  178022. ** xPhraseNext()
  178023. ** See xPhraseFirst above.
  178024. **
  178025. ** xPhraseFirstColumn()
  178026. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  178027. ** and xPhraseNext() APIs described above. The difference is that instead
  178028. ** of iterating through all instances of a phrase in the current row, these
  178029. ** APIs are used to iterate through the set of columns in the current row
  178030. ** that contain one or more instances of a specified phrase. For example:
  178031. **
  178032. ** Fts5PhraseIter iter;
  178033. ** int iCol;
  178034. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  178035. ** iCol>=0;
  178036. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  178037. ** ){
  178038. ** // Column iCol contains at least one instance of phrase iPhrase
  178039. ** }
  178040. **
  178041. ** This API can be quite slow if used with an FTS5 table created with the
  178042. ** "detail=none" option. If the FTS5 table is created with either
  178043. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  178044. ** then this API always iterates through an empty set (all calls to
  178045. ** xPhraseFirstColumn() set iCol to -1).
  178046. **
  178047. ** The information accessed using this API and its companion
  178048. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  178049. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  178050. ** significantly more efficient than those alternatives when used with
  178051. ** "detail=column" tables.
  178052. **
  178053. ** xPhraseNextColumn()
  178054. ** See xPhraseFirstColumn above.
  178055. */
  178056. struct Fts5ExtensionApi {
  178057. int iVersion; /* Currently always set to 3 */
  178058. void *(*xUserData)(Fts5Context*);
  178059. int (*xColumnCount)(Fts5Context*);
  178060. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  178061. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  178062. int (*xTokenize)(Fts5Context*,
  178063. const char *pText, int nText, /* Text to tokenize */
  178064. void *pCtx, /* Context passed to xToken() */
  178065. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  178066. );
  178067. int (*xPhraseCount)(Fts5Context*);
  178068. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  178069. int (*xInstCount)(Fts5Context*, int *pnInst);
  178070. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  178071. sqlite3_int64 (*xRowid)(Fts5Context*);
  178072. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  178073. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  178074. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  178075. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  178076. );
  178077. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  178078. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  178079. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  178080. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  178081. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  178082. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  178083. };
  178084. /*
  178085. ** CUSTOM AUXILIARY FUNCTIONS
  178086. *************************************************************************/
  178087. /*************************************************************************
  178088. ** CUSTOM TOKENIZERS
  178089. **
  178090. ** Applications may also register custom tokenizer types. A tokenizer
  178091. ** is registered by providing fts5 with a populated instance of the
  178092. ** following structure. All structure methods must be defined, setting
  178093. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  178094. ** behaviour. The structure methods are expected to function as follows:
  178095. **
  178096. ** xCreate:
  178097. ** This function is used to allocate and initialize a tokenizer instance.
  178098. ** A tokenizer instance is required to actually tokenize text.
  178099. **
  178100. ** The first argument passed to this function is a copy of the (void*)
  178101. ** pointer provided by the application when the fts5_tokenizer object
  178102. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  178103. ** The second and third arguments are an array of nul-terminated strings
  178104. ** containing the tokenizer arguments, if any, specified following the
  178105. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  178106. ** to create the FTS5 table.
  178107. **
  178108. ** The final argument is an output variable. If successful, (*ppOut)
  178109. ** should be set to point to the new tokenizer handle and SQLITE_OK
  178110. ** returned. If an error occurs, some value other than SQLITE_OK should
  178111. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  178112. ** is undefined.
  178113. **
  178114. ** xDelete:
  178115. ** This function is invoked to delete a tokenizer handle previously
  178116. ** allocated using xCreate(). Fts5 guarantees that this function will
  178117. ** be invoked exactly once for each successful call to xCreate().
  178118. **
  178119. ** xTokenize:
  178120. ** This function is expected to tokenize the nText byte string indicated
  178121. ** by argument pText. pText may or may not be nul-terminated. The first
  178122. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  178123. ** returned by an earlier call to xCreate().
  178124. **
  178125. ** The second argument indicates the reason that FTS5 is requesting
  178126. ** tokenization of the supplied text. This is always one of the following
  178127. ** four values:
  178128. **
  178129. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  178130. ** or removed from the FTS table. The tokenizer is being invoked to
  178131. ** determine the set of tokens to add to (or delete from) the
  178132. ** FTS index.
  178133. **
  178134. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  178135. ** against the FTS index. The tokenizer is being called to tokenize
  178136. ** a bareword or quoted string specified as part of the query.
  178137. **
  178138. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  178139. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  178140. ** followed by a "*" character, indicating that the last token
  178141. ** returned by the tokenizer will be treated as a token prefix.
  178142. **
  178143. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  178144. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  178145. ** function. Or an fts5_api.xColumnSize() request made by the same
  178146. ** on a columnsize=0 database.
  178147. ** </ul>
  178148. **
  178149. ** For each token in the input string, the supplied callback xToken() must
  178150. ** be invoked. The first argument to it should be a copy of the pointer
  178151. ** passed as the second argument to xTokenize(). The third and fourth
  178152. ** arguments are a pointer to a buffer containing the token text, and the
  178153. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  178154. ** of the first byte of and first byte immediately following the text from
  178155. ** which the token is derived within the input.
  178156. **
  178157. ** The second argument passed to the xToken() callback ("tflags") should
  178158. ** normally be set to 0. The exception is if the tokenizer supports
  178159. ** synonyms. In this case see the discussion below for details.
  178160. **
  178161. ** FTS5 assumes the xToken() callback is invoked for each token in the
  178162. ** order that they occur within the input text.
  178163. **
  178164. ** If an xToken() callback returns any value other than SQLITE_OK, then
  178165. ** the tokenization should be abandoned and the xTokenize() method should
  178166. ** immediately return a copy of the xToken() return value. Or, if the
  178167. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  178168. ** if an error occurs with the xTokenize() implementation itself, it
  178169. ** may abandon the tokenization and return any error code other than
  178170. ** SQLITE_OK or SQLITE_DONE.
  178171. **
  178172. ** SYNONYM SUPPORT
  178173. **
  178174. ** Custom tokenizers may also support synonyms. Consider a case in which a
  178175. ** user wishes to query for a phrase such as "first place". Using the
  178176. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  178177. ** of "first place" within the document set, but not alternative forms
  178178. ** such as "1st place". In some applications, it would be better to match
  178179. ** all instances of "first place" or "1st place" regardless of which form
  178180. ** the user specified in the MATCH query text.
  178181. **
  178182. ** There are several ways to approach this in FTS5:
  178183. **
  178184. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  178185. ** In the above example, this means that the tokenizer returns the
  178186. ** same token for inputs "first" and "1st". Say that token is in
  178187. ** fact "first", so that when the user inserts the document "I won
  178188. ** 1st place" entries are added to the index for tokens "i", "won",
  178189. ** "first" and "place". If the user then queries for '1st + place',
  178190. ** the tokenizer substitutes "first" for "1st" and the query works
  178191. ** as expected.
  178192. **
  178193. ** <li> By adding multiple synonyms for a single term to the FTS index.
  178194. ** In this case, when tokenizing query text, the tokenizer may
  178195. ** provide multiple synonyms for a single term within the document.
  178196. ** FTS5 then queries the index for each synonym individually. For
  178197. ** example, faced with the query:
  178198. **
  178199. ** <codeblock>
  178200. ** ... MATCH 'first place'</codeblock>
  178201. **
  178202. ** the tokenizer offers both "1st" and "first" as synonyms for the
  178203. ** first token in the MATCH query and FTS5 effectively runs a query
  178204. ** similar to:
  178205. **
  178206. ** <codeblock>
  178207. ** ... MATCH '(first OR 1st) place'</codeblock>
  178208. **
  178209. ** except that, for the purposes of auxiliary functions, the query
  178210. ** still appears to contain just two phrases - "(first OR 1st)"
  178211. ** being treated as a single phrase.
  178212. **
  178213. ** <li> By adding multiple synonyms for a single term to the FTS index.
  178214. ** Using this method, when tokenizing document text, the tokenizer
  178215. ** provides multiple synonyms for each token. So that when a
  178216. ** document such as "I won first place" is tokenized, entries are
  178217. ** added to the FTS index for "i", "won", "first", "1st" and
  178218. ** "place".
  178219. **
  178220. ** This way, even if the tokenizer does not provide synonyms
  178221. ** when tokenizing query text (it should not - to do would be
  178222. ** inefficient), it doesn't matter if the user queries for
  178223. ** 'first + place' or '1st + place', as there are entires in the
  178224. ** FTS index corresponding to both forms of the first token.
  178225. ** </ol>
  178226. **
  178227. ** Whether it is parsing document or query text, any call to xToken that
  178228. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  178229. ** is considered to supply a synonym for the previous token. For example,
  178230. ** when parsing the document "I won first place", a tokenizer that supports
  178231. ** synonyms would call xToken() 5 times, as follows:
  178232. **
  178233. ** <codeblock>
  178234. ** xToken(pCtx, 0, "i", 1, 0, 1);
  178235. ** xToken(pCtx, 0, "won", 3, 2, 5);
  178236. ** xToken(pCtx, 0, "first", 5, 6, 11);
  178237. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  178238. ** xToken(pCtx, 0, "place", 5, 12, 17);
  178239. **</codeblock>
  178240. **
  178241. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  178242. ** xToken() is called. Multiple synonyms may be specified for a single token
  178243. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  178244. ** There is no limit to the number of synonyms that may be provided for a
  178245. ** single token.
  178246. **
  178247. ** In many cases, method (1) above is the best approach. It does not add
  178248. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  178249. ** so it is efficient in terms of disk space and query speed. However, it
  178250. ** does not support prefix queries very well. If, as suggested above, the
  178251. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  178252. **
  178253. ** <codeblock>
  178254. ** ... MATCH '1s*'</codeblock>
  178255. **
  178256. ** will not match documents that contain the token "1st" (as the tokenizer
  178257. ** will probably not map "1s" to any prefix of "first").
  178258. **
  178259. ** For full prefix support, method (3) may be preferred. In this case,
  178260. ** because the index contains entries for both "first" and "1st", prefix
  178261. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  178262. ** extra entries are added to the FTS index, this method uses more space
  178263. ** within the database.
  178264. **
  178265. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  178266. ** a query such as '1s*' will match documents that contain the literal
  178267. ** token "1st", but not "first" (assuming the tokenizer is not able to
  178268. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  178269. ** will match against "1st" and "first". This method does not require
  178270. ** extra disk space, as no extra entries are added to the FTS index.
  178271. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  178272. ** as separate queries of the FTS index are required for each synonym.
  178273. **
  178274. ** When using methods (2) or (3), it is important that the tokenizer only
  178275. ** provide synonyms when tokenizing document text (method (2)) or query
  178276. ** text (method (3)), not both. Doing so will not cause any errors, but is
  178277. ** inefficient.
  178278. */
  178279. typedef struct Fts5Tokenizer Fts5Tokenizer;
  178280. typedef struct fts5_tokenizer fts5_tokenizer;
  178281. struct fts5_tokenizer {
  178282. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  178283. void (*xDelete)(Fts5Tokenizer*);
  178284. int (*xTokenize)(Fts5Tokenizer*,
  178285. void *pCtx,
  178286. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  178287. const char *pText, int nText,
  178288. int (*xToken)(
  178289. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  178290. int tflags, /* Mask of FTS5_TOKEN_* flags */
  178291. const char *pToken, /* Pointer to buffer containing token */
  178292. int nToken, /* Size of token in bytes */
  178293. int iStart, /* Byte offset of token within input text */
  178294. int iEnd /* Byte offset of end of token within input text */
  178295. )
  178296. );
  178297. };
  178298. /* Flags that may be passed as the third argument to xTokenize() */
  178299. #define FTS5_TOKENIZE_QUERY 0x0001
  178300. #define FTS5_TOKENIZE_PREFIX 0x0002
  178301. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  178302. #define FTS5_TOKENIZE_AUX 0x0008
  178303. /* Flags that may be passed by the tokenizer implementation back to FTS5
  178304. ** as the third argument to the supplied xToken callback. */
  178305. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  178306. /*
  178307. ** END OF CUSTOM TOKENIZERS
  178308. *************************************************************************/
  178309. /*************************************************************************
  178310. ** FTS5 EXTENSION REGISTRATION API
  178311. */
  178312. typedef struct fts5_api fts5_api;
  178313. struct fts5_api {
  178314. int iVersion; /* Currently always set to 2 */
  178315. /* Create a new tokenizer */
  178316. int (*xCreateTokenizer)(
  178317. fts5_api *pApi,
  178318. const char *zName,
  178319. void *pContext,
  178320. fts5_tokenizer *pTokenizer,
  178321. void (*xDestroy)(void*)
  178322. );
  178323. /* Find an existing tokenizer */
  178324. int (*xFindTokenizer)(
  178325. fts5_api *pApi,
  178326. const char *zName,
  178327. void **ppContext,
  178328. fts5_tokenizer *pTokenizer
  178329. );
  178330. /* Create a new auxiliary function */
  178331. int (*xCreateFunction)(
  178332. fts5_api *pApi,
  178333. const char *zName,
  178334. void *pContext,
  178335. fts5_extension_function xFunction,
  178336. void (*xDestroy)(void*)
  178337. );
  178338. };
  178339. /*
  178340. ** END OF REGISTRATION API
  178341. *************************************************************************/
  178342. #if 0
  178343. } /* end of the 'extern "C"' block */
  178344. #endif
  178345. #endif /* _FTS5_H */
  178346. /*
  178347. ** 2014 May 31
  178348. **
  178349. ** The author disclaims copyright to this source code. In place of
  178350. ** a legal notice, here is a blessing:
  178351. **
  178352. ** May you do good and not evil.
  178353. ** May you find forgiveness for yourself and forgive others.
  178354. ** May you share freely, never taking more than you give.
  178355. **
  178356. ******************************************************************************
  178357. **
  178358. */
  178359. #ifndef _FTS5INT_H
  178360. #define _FTS5INT_H
  178361. /* #include "fts5.h" */
  178362. /* #include "sqlite3ext.h" */
  178363. SQLITE_EXTENSION_INIT1
  178364. /* #include <string.h> */
  178365. /* #include <assert.h> */
  178366. #ifndef SQLITE_AMALGAMATION
  178367. typedef unsigned char u8;
  178368. typedef unsigned int u32;
  178369. typedef unsigned short u16;
  178370. typedef short i16;
  178371. typedef sqlite3_int64 i64;
  178372. typedef sqlite3_uint64 u64;
  178373. #ifndef ArraySize
  178374. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  178375. #endif
  178376. #define testcase(x)
  178377. #define ALWAYS(x) 1
  178378. #define NEVER(x) 0
  178379. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  178380. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  178381. /*
  178382. ** Constants for the largest and smallest possible 64-bit signed integers.
  178383. */
  178384. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  178385. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  178386. #endif
  178387. /* Truncate very long tokens to this many bytes. Hard limit is
  178388. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  178389. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  178390. #define FTS5_MAX_TOKEN_SIZE 32768
  178391. /*
  178392. ** Maximum number of prefix indexes on single FTS5 table. This must be
  178393. ** less than 32. If it is set to anything large than that, an #error
  178394. ** directive in fts5_index.c will cause the build to fail.
  178395. */
  178396. #define FTS5_MAX_PREFIX_INDEXES 31
  178397. #define FTS5_DEFAULT_NEARDIST 10
  178398. #define FTS5_DEFAULT_RANK "bm25"
  178399. /* Name of rank and rowid columns */
  178400. #define FTS5_RANK_NAME "rank"
  178401. #define FTS5_ROWID_NAME "rowid"
  178402. #ifdef SQLITE_DEBUG
  178403. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  178404. static int sqlite3Fts5Corrupt(void);
  178405. #else
  178406. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  178407. #endif
  178408. /*
  178409. ** The assert_nc() macro is similar to the assert() macro, except that it
  178410. ** is used for assert() conditions that are true only if it can be
  178411. ** guranteed that the database is not corrupt.
  178412. */
  178413. #ifdef SQLITE_DEBUG
  178414. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  178415. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  178416. #else
  178417. # define assert_nc(x) assert(x)
  178418. #endif
  178419. /* Mark a function parameter as unused, to suppress nuisance compiler
  178420. ** warnings. */
  178421. #ifndef UNUSED_PARAM
  178422. # define UNUSED_PARAM(X) (void)(X)
  178423. #endif
  178424. #ifndef UNUSED_PARAM2
  178425. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  178426. #endif
  178427. typedef struct Fts5Global Fts5Global;
  178428. typedef struct Fts5Colset Fts5Colset;
  178429. /* If a NEAR() clump or phrase may only match a specific set of columns,
  178430. ** then an object of the following type is used to record the set of columns.
  178431. ** Each entry in the aiCol[] array is a column that may be matched.
  178432. **
  178433. ** This object is used by fts5_expr.c and fts5_index.c.
  178434. */
  178435. struct Fts5Colset {
  178436. int nCol;
  178437. int aiCol[1];
  178438. };
  178439. /**************************************************************************
  178440. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  178441. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  178442. */
  178443. typedef struct Fts5Config Fts5Config;
  178444. /*
  178445. ** An instance of the following structure encodes all information that can
  178446. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  178447. **
  178448. ** And all information loaded from the %_config table.
  178449. **
  178450. ** nAutomerge:
  178451. ** The minimum number of segments that an auto-merge operation should
  178452. ** attempt to merge together. A value of 1 sets the object to use the
  178453. ** compile time default. Zero disables auto-merge altogether.
  178454. **
  178455. ** zContent:
  178456. **
  178457. ** zContentRowid:
  178458. ** The value of the content_rowid= option, if one was specified. Or
  178459. ** the string "rowid" otherwise. This text is not quoted - if it is
  178460. ** used as part of an SQL statement it needs to be quoted appropriately.
  178461. **
  178462. ** zContentExprlist:
  178463. **
  178464. ** pzErrmsg:
  178465. ** This exists in order to allow the fts5_index.c module to return a
  178466. ** decent error message if it encounters a file-format version it does
  178467. ** not understand.
  178468. **
  178469. ** bColumnsize:
  178470. ** True if the %_docsize table is created.
  178471. **
  178472. ** bPrefixIndex:
  178473. ** This is only used for debugging. If set to false, any prefix indexes
  178474. ** are ignored. This value is configured using:
  178475. **
  178476. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  178477. **
  178478. */
  178479. struct Fts5Config {
  178480. sqlite3 *db; /* Database handle */
  178481. char *zDb; /* Database holding FTS index (e.g. "main") */
  178482. char *zName; /* Name of FTS index */
  178483. int nCol; /* Number of columns */
  178484. char **azCol; /* Column names */
  178485. u8 *abUnindexed; /* True for unindexed columns */
  178486. int nPrefix; /* Number of prefix indexes */
  178487. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  178488. int eContent; /* An FTS5_CONTENT value */
  178489. char *zContent; /* content table */
  178490. char *zContentRowid; /* "content_rowid=" option value */
  178491. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  178492. int eDetail; /* FTS5_DETAIL_XXX value */
  178493. char *zContentExprlist;
  178494. Fts5Tokenizer *pTok;
  178495. fts5_tokenizer *pTokApi;
  178496. /* Values loaded from the %_config table */
  178497. int iCookie; /* Incremented when %_config is modified */
  178498. int pgsz; /* Approximate page size used in %_data */
  178499. int nAutomerge; /* 'automerge' setting */
  178500. int nCrisisMerge; /* Maximum allowed segments per level */
  178501. int nUsermerge; /* 'usermerge' setting */
  178502. int nHashSize; /* Bytes of memory for in-memory hash */
  178503. char *zRank; /* Name of rank function */
  178504. char *zRankArgs; /* Arguments to rank function */
  178505. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  178506. char **pzErrmsg;
  178507. #ifdef SQLITE_DEBUG
  178508. int bPrefixIndex; /* True to use prefix-indexes */
  178509. #endif
  178510. };
  178511. /* Current expected value of %_config table 'version' field */
  178512. #define FTS5_CURRENT_VERSION 4
  178513. #define FTS5_CONTENT_NORMAL 0
  178514. #define FTS5_CONTENT_NONE 1
  178515. #define FTS5_CONTENT_EXTERNAL 2
  178516. #define FTS5_DETAIL_FULL 0
  178517. #define FTS5_DETAIL_NONE 1
  178518. #define FTS5_DETAIL_COLUMNS 2
  178519. static int sqlite3Fts5ConfigParse(
  178520. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  178521. );
  178522. static void sqlite3Fts5ConfigFree(Fts5Config*);
  178523. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  178524. static int sqlite3Fts5Tokenize(
  178525. Fts5Config *pConfig, /* FTS5 Configuration object */
  178526. int flags, /* FTS5_TOKENIZE_* flags */
  178527. const char *pText, int nText, /* Text to tokenize */
  178528. void *pCtx, /* Context passed to xToken() */
  178529. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  178530. );
  178531. static void sqlite3Fts5Dequote(char *z);
  178532. /* Load the contents of the %_config table */
  178533. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  178534. /* Set the value of a single config attribute */
  178535. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  178536. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  178537. /*
  178538. ** End of interface to code in fts5_config.c.
  178539. **************************************************************************/
  178540. /**************************************************************************
  178541. ** Interface to code in fts5_buffer.c.
  178542. */
  178543. /*
  178544. ** Buffer object for the incremental building of string data.
  178545. */
  178546. typedef struct Fts5Buffer Fts5Buffer;
  178547. struct Fts5Buffer {
  178548. u8 *p;
  178549. int n;
  178550. int nSpace;
  178551. };
  178552. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  178553. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  178554. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  178555. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  178556. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  178557. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  178558. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  178559. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  178560. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  178561. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  178562. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  178563. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  178564. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  178565. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  178566. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  178567. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  178568. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  178569. )
  178570. /* Write and decode big-endian 32-bit integer values */
  178571. static void sqlite3Fts5Put32(u8*, int);
  178572. static int sqlite3Fts5Get32(const u8*);
  178573. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  178574. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  178575. typedef struct Fts5PoslistReader Fts5PoslistReader;
  178576. struct Fts5PoslistReader {
  178577. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  178578. const u8 *a; /* Position list to iterate through */
  178579. int n; /* Size of buffer at a[] in bytes */
  178580. int i; /* Current offset in a[] */
  178581. u8 bFlag; /* For client use (any custom purpose) */
  178582. /* Output variables */
  178583. u8 bEof; /* Set to true at EOF */
  178584. i64 iPos; /* (iCol<<32) + iPos */
  178585. };
  178586. static int sqlite3Fts5PoslistReaderInit(
  178587. const u8 *a, int n, /* Poslist buffer to iterate through */
  178588. Fts5PoslistReader *pIter /* Iterator object to initialize */
  178589. );
  178590. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  178591. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  178592. struct Fts5PoslistWriter {
  178593. i64 iPrev;
  178594. };
  178595. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  178596. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  178597. static int sqlite3Fts5PoslistNext64(
  178598. const u8 *a, int n, /* Buffer containing poslist */
  178599. int *pi, /* IN/OUT: Offset within a[] */
  178600. i64 *piOff /* IN/OUT: Current offset */
  178601. );
  178602. /* Malloc utility */
  178603. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  178604. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  178605. /* Character set tests (like isspace(), isalpha() etc.) */
  178606. static int sqlite3Fts5IsBareword(char t);
  178607. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  178608. typedef struct Fts5Termset Fts5Termset;
  178609. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  178610. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  178611. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  178612. /*
  178613. ** End of interface to code in fts5_buffer.c.
  178614. **************************************************************************/
  178615. /**************************************************************************
  178616. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  178617. ** to access the data stored in the %_data table.
  178618. */
  178619. typedef struct Fts5Index Fts5Index;
  178620. typedef struct Fts5IndexIter Fts5IndexIter;
  178621. struct Fts5IndexIter {
  178622. i64 iRowid;
  178623. const u8 *pData;
  178624. int nData;
  178625. u8 bEof;
  178626. };
  178627. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  178628. /*
  178629. ** Values used as part of the flags argument passed to IndexQuery().
  178630. */
  178631. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  178632. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  178633. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  178634. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  178635. /* The following are used internally by the fts5_index.c module. They are
  178636. ** defined here only to make it easier to avoid clashes with the flags
  178637. ** above. */
  178638. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  178639. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  178640. /*
  178641. ** Create/destroy an Fts5Index object.
  178642. */
  178643. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  178644. static int sqlite3Fts5IndexClose(Fts5Index *p);
  178645. /*
  178646. ** Return a simple checksum value based on the arguments.
  178647. */
  178648. static u64 sqlite3Fts5IndexEntryCksum(
  178649. i64 iRowid,
  178650. int iCol,
  178651. int iPos,
  178652. int iIdx,
  178653. const char *pTerm,
  178654. int nTerm
  178655. );
  178656. /*
  178657. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  178658. ** size. Return the number of bytes in the nChar character prefix of the
  178659. ** buffer, or 0 if there are less than nChar characters in total.
  178660. */
  178661. static int sqlite3Fts5IndexCharlenToBytelen(
  178662. const char *p,
  178663. int nByte,
  178664. int nChar
  178665. );
  178666. /*
  178667. ** Open a new iterator to iterate though all rowids that match the
  178668. ** specified token or token prefix.
  178669. */
  178670. static int sqlite3Fts5IndexQuery(
  178671. Fts5Index *p, /* FTS index to query */
  178672. const char *pToken, int nToken, /* Token (or prefix) to query for */
  178673. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  178674. Fts5Colset *pColset, /* Match these columns only */
  178675. Fts5IndexIter **ppIter /* OUT: New iterator object */
  178676. );
  178677. /*
  178678. ** The various operations on open token or token prefix iterators opened
  178679. ** using sqlite3Fts5IndexQuery().
  178680. */
  178681. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  178682. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  178683. /*
  178684. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  178685. */
  178686. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  178687. /*
  178688. ** This interface is used by the fts5vocab module.
  178689. */
  178690. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  178691. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  178692. /*
  178693. ** Insert or remove data to or from the index. Each time a document is
  178694. ** added to or removed from the index, this function is called one or more
  178695. ** times.
  178696. **
  178697. ** For an insert, it must be called once for each token in the new document.
  178698. ** If the operation is a delete, it must be called (at least) once for each
  178699. ** unique token in the document with an iCol value less than zero. The iPos
  178700. ** argument is ignored for a delete.
  178701. */
  178702. static int sqlite3Fts5IndexWrite(
  178703. Fts5Index *p, /* Index to write to */
  178704. int iCol, /* Column token appears in (-ve -> delete) */
  178705. int iPos, /* Position of token within column */
  178706. const char *pToken, int nToken /* Token to add or remove to or from index */
  178707. );
  178708. /*
  178709. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  178710. ** document iDocid.
  178711. */
  178712. static int sqlite3Fts5IndexBeginWrite(
  178713. Fts5Index *p, /* Index to write to */
  178714. int bDelete, /* True if current operation is a delete */
  178715. i64 iDocid /* Docid to add or remove data from */
  178716. );
  178717. /*
  178718. ** Flush any data stored in the in-memory hash tables to the database.
  178719. ** Also close any open blob handles.
  178720. */
  178721. static int sqlite3Fts5IndexSync(Fts5Index *p);
  178722. /*
  178723. ** Discard any data stored in the in-memory hash tables. Do not write it
  178724. ** to the database. Additionally, assume that the contents of the %_data
  178725. ** table may have changed on disk. So any in-memory caches of %_data
  178726. ** records must be invalidated.
  178727. */
  178728. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  178729. /*
  178730. ** Get or set the "averages" values.
  178731. */
  178732. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  178733. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  178734. /*
  178735. ** Functions called by the storage module as part of integrity-check.
  178736. */
  178737. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  178738. /*
  178739. ** Called during virtual module initialization to register UDF
  178740. ** fts5_decode() with SQLite
  178741. */
  178742. static int sqlite3Fts5IndexInit(sqlite3*);
  178743. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  178744. /*
  178745. ** Return the total number of entries read from the %_data table by
  178746. ** this connection since it was created.
  178747. */
  178748. static int sqlite3Fts5IndexReads(Fts5Index *p);
  178749. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  178750. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  178751. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  178752. static int sqlite3Fts5IndexReset(Fts5Index *p);
  178753. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  178754. /*
  178755. ** End of interface to code in fts5_index.c.
  178756. **************************************************************************/
  178757. /**************************************************************************
  178758. ** Interface to code in fts5_varint.c.
  178759. */
  178760. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  178761. static int sqlite3Fts5GetVarintLen(u32 iVal);
  178762. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  178763. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  178764. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  178765. #define fts5GetVarint sqlite3Fts5GetVarint
  178766. #define fts5FastGetVarint32(a, iOff, nVal) { \
  178767. nVal = (a)[iOff++]; \
  178768. if( nVal & 0x80 ){ \
  178769. iOff--; \
  178770. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  178771. } \
  178772. }
  178773. /*
  178774. ** End of interface to code in fts5_varint.c.
  178775. **************************************************************************/
  178776. /**************************************************************************
  178777. ** Interface to code in fts5.c.
  178778. */
  178779. static int sqlite3Fts5GetTokenizer(
  178780. Fts5Global*,
  178781. const char **azArg,
  178782. int nArg,
  178783. Fts5Tokenizer**,
  178784. fts5_tokenizer**,
  178785. char **pzErr
  178786. );
  178787. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  178788. /*
  178789. ** End of interface to code in fts5.c.
  178790. **************************************************************************/
  178791. /**************************************************************************
  178792. ** Interface to code in fts5_hash.c.
  178793. */
  178794. typedef struct Fts5Hash Fts5Hash;
  178795. /*
  178796. ** Create a hash table, free a hash table.
  178797. */
  178798. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  178799. static void sqlite3Fts5HashFree(Fts5Hash*);
  178800. static int sqlite3Fts5HashWrite(
  178801. Fts5Hash*,
  178802. i64 iRowid, /* Rowid for this entry */
  178803. int iCol, /* Column token appears in (-ve -> delete) */
  178804. int iPos, /* Position of token within column */
  178805. char bByte,
  178806. const char *pToken, int nToken /* Token to add or remove to or from index */
  178807. );
  178808. /*
  178809. ** Empty (but do not delete) a hash table.
  178810. */
  178811. static void sqlite3Fts5HashClear(Fts5Hash*);
  178812. static int sqlite3Fts5HashQuery(
  178813. Fts5Hash*, /* Hash table to query */
  178814. const char *pTerm, int nTerm, /* Query term */
  178815. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  178816. int *pnDoclist /* OUT: Size of doclist in bytes */
  178817. );
  178818. static int sqlite3Fts5HashScanInit(
  178819. Fts5Hash*, /* Hash table to query */
  178820. const char *pTerm, int nTerm /* Query prefix */
  178821. );
  178822. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  178823. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  178824. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  178825. const char **pzTerm, /* OUT: term (nul-terminated) */
  178826. const u8 **ppDoclist, /* OUT: pointer to doclist */
  178827. int *pnDoclist /* OUT: size of doclist in bytes */
  178828. );
  178829. /*
  178830. ** End of interface to code in fts5_hash.c.
  178831. **************************************************************************/
  178832. /**************************************************************************
  178833. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  178834. ** code to access the data stored in the %_content and %_docsize tables.
  178835. */
  178836. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  178837. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  178838. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  178839. typedef struct Fts5Storage Fts5Storage;
  178840. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  178841. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  178842. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  178843. static int sqlite3Fts5DropAll(Fts5Config*);
  178844. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  178845. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  178846. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  178847. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  178848. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  178849. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  178850. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  178851. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  178852. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  178853. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  178854. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  178855. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  178856. static int sqlite3Fts5StorageConfigValue(
  178857. Fts5Storage *p, const char*, sqlite3_value*, int
  178858. );
  178859. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  178860. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  178861. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  178862. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  178863. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  178864. /*
  178865. ** End of interface to code in fts5_storage.c.
  178866. **************************************************************************/
  178867. /**************************************************************************
  178868. ** Interface to code in fts5_expr.c.
  178869. */
  178870. typedef struct Fts5Expr Fts5Expr;
  178871. typedef struct Fts5ExprNode Fts5ExprNode;
  178872. typedef struct Fts5Parse Fts5Parse;
  178873. typedef struct Fts5Token Fts5Token;
  178874. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  178875. typedef struct Fts5ExprNearset Fts5ExprNearset;
  178876. struct Fts5Token {
  178877. const char *p; /* Token text (not NULL terminated) */
  178878. int n; /* Size of buffer p in bytes */
  178879. };
  178880. /* Parse a MATCH expression. */
  178881. static int sqlite3Fts5ExprNew(
  178882. Fts5Config *pConfig,
  178883. int iCol, /* Column on LHS of MATCH operator */
  178884. const char *zExpr,
  178885. Fts5Expr **ppNew,
  178886. char **pzErr
  178887. );
  178888. /*
  178889. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  178890. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  178891. ** rc = sqlite3Fts5ExprNext(pExpr)
  178892. ** ){
  178893. ** // The document with rowid iRowid matches the expression!
  178894. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  178895. ** }
  178896. */
  178897. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  178898. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  178899. static int sqlite3Fts5ExprEof(Fts5Expr*);
  178900. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  178901. static void sqlite3Fts5ExprFree(Fts5Expr*);
  178902. /* Called during startup to register a UDF with SQLite */
  178903. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  178904. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  178905. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  178906. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  178907. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  178908. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  178909. static int sqlite3Fts5ExprPopulatePoslists(
  178910. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  178911. );
  178912. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  178913. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  178914. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  178915. /*******************************************
  178916. ** The fts5_expr.c API above this point is used by the other hand-written
  178917. ** C code in this module. The interfaces below this point are called by
  178918. ** the parser code in fts5parse.y. */
  178919. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  178920. static Fts5ExprNode *sqlite3Fts5ParseNode(
  178921. Fts5Parse *pParse,
  178922. int eType,
  178923. Fts5ExprNode *pLeft,
  178924. Fts5ExprNode *pRight,
  178925. Fts5ExprNearset *pNear
  178926. );
  178927. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  178928. Fts5Parse *pParse,
  178929. Fts5ExprNode *pLeft,
  178930. Fts5ExprNode *pRight
  178931. );
  178932. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  178933. Fts5Parse *pParse,
  178934. Fts5ExprPhrase *pPhrase,
  178935. Fts5Token *pToken,
  178936. int bPrefix
  178937. );
  178938. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
  178939. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  178940. Fts5Parse*,
  178941. Fts5ExprNearset*,
  178942. Fts5ExprPhrase*
  178943. );
  178944. static Fts5Colset *sqlite3Fts5ParseColset(
  178945. Fts5Parse*,
  178946. Fts5Colset*,
  178947. Fts5Token *
  178948. );
  178949. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  178950. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  178951. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  178952. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  178953. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  178954. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  178955. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  178956. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  178957. /*
  178958. ** End of interface to code in fts5_expr.c.
  178959. **************************************************************************/
  178960. /**************************************************************************
  178961. ** Interface to code in fts5_aux.c.
  178962. */
  178963. static int sqlite3Fts5AuxInit(fts5_api*);
  178964. /*
  178965. ** End of interface to code in fts5_aux.c.
  178966. **************************************************************************/
  178967. /**************************************************************************
  178968. ** Interface to code in fts5_tokenizer.c.
  178969. */
  178970. static int sqlite3Fts5TokenizerInit(fts5_api*);
  178971. /*
  178972. ** End of interface to code in fts5_tokenizer.c.
  178973. **************************************************************************/
  178974. /**************************************************************************
  178975. ** Interface to code in fts5_vocab.c.
  178976. */
  178977. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  178978. /*
  178979. ** End of interface to code in fts5_vocab.c.
  178980. **************************************************************************/
  178981. /**************************************************************************
  178982. ** Interface to automatically generated code in fts5_unicode2.c.
  178983. */
  178984. static int sqlite3Fts5UnicodeIsalnum(int c);
  178985. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  178986. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  178987. /*
  178988. ** End of interface to code in fts5_unicode2.c.
  178989. **************************************************************************/
  178990. #endif
  178991. #define FTS5_OR 1
  178992. #define FTS5_AND 2
  178993. #define FTS5_NOT 3
  178994. #define FTS5_TERM 4
  178995. #define FTS5_COLON 5
  178996. #define FTS5_MINUS 6
  178997. #define FTS5_LCP 7
  178998. #define FTS5_RCP 8
  178999. #define FTS5_STRING 9
  179000. #define FTS5_LP 10
  179001. #define FTS5_RP 11
  179002. #define FTS5_CARET 12
  179003. #define FTS5_COMMA 13
  179004. #define FTS5_PLUS 14
  179005. #define FTS5_STAR 15
  179006. /*
  179007. ** 2000-05-29
  179008. **
  179009. ** The author disclaims copyright to this source code. In place of
  179010. ** a legal notice, here is a blessing:
  179011. **
  179012. ** May you do good and not evil.
  179013. ** May you find forgiveness for yourself and forgive others.
  179014. ** May you share freely, never taking more than you give.
  179015. **
  179016. *************************************************************************
  179017. ** Driver template for the LEMON parser generator.
  179018. **
  179019. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  179020. ** this template to construct a parser. The "lemon" program inserts text
  179021. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  179022. ** interstitial "-" characters) contained in this template is changed into
  179023. ** the value of the %name directive from the grammar. Otherwise, the content
  179024. ** of this template is copied straight through into the generate parser
  179025. ** source file.
  179026. **
  179027. ** The following is the concatenation of all %include directives from the
  179028. ** input grammar file:
  179029. */
  179030. /* #include <stdio.h> */
  179031. /************ Begin %include sections from the grammar ************************/
  179032. /* #include "fts5Int.h" */
  179033. /* #include "fts5parse.h" */
  179034. /*
  179035. ** Disable all error recovery processing in the parser push-down
  179036. ** automaton.
  179037. */
  179038. #define fts5YYNOERRORRECOVERY 1
  179039. /*
  179040. ** Make fts5yytestcase() the same as testcase()
  179041. */
  179042. #define fts5yytestcase(X) testcase(X)
  179043. /*
  179044. ** Indicate that sqlite3ParserFree() will never be called with a null
  179045. ** pointer.
  179046. */
  179047. #define fts5YYPARSEFREENOTNULL 1
  179048. /*
  179049. ** Alternative datatype for the argument to the malloc() routine passed
  179050. ** into sqlite3ParserAlloc(). The default is size_t.
  179051. */
  179052. #define fts5YYMALLOCARGTYPE u64
  179053. /**************** End of %include directives **********************************/
  179054. /* These constants specify the various numeric values for terminal symbols
  179055. ** in a format understandable to "makeheaders". This section is blank unless
  179056. ** "lemon" is run with the "-m" command-line option.
  179057. ***************** Begin makeheaders token definitions *************************/
  179058. /**************** End makeheaders token definitions ***************************/
  179059. /* The next sections is a series of control #defines.
  179060. ** various aspects of the generated parser.
  179061. ** fts5YYCODETYPE is the data type used to store the integer codes
  179062. ** that represent terminal and non-terminal symbols.
  179063. ** "unsigned char" is used if there are fewer than
  179064. ** 256 symbols. Larger types otherwise.
  179065. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  179066. ** any terminal or nonterminal symbol.
  179067. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  179068. ** (also known as: "terminal symbols") have fall-back
  179069. ** values which should be used if the original symbol
  179070. ** would not parse. This permits keywords to sometimes
  179071. ** be used as identifiers, for example.
  179072. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  179073. ** that indicate what to do in response to the next
  179074. ** token.
  179075. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  179076. ** symbols. Background: A "minor type" is a semantic
  179077. ** value associated with a terminal or non-terminal
  179078. ** symbols. For example, for an "ID" terminal symbol,
  179079. ** the minor type might be the name of the identifier.
  179080. ** Each non-terminal can have a different minor type.
  179081. ** Terminal symbols all have the same minor type, though.
  179082. ** This macros defines the minor type for terminal
  179083. ** symbols.
  179084. ** fts5YYMINORTYPE is the data type used for all minor types.
  179085. ** This is typically a union of many types, one of
  179086. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  179087. ** for terminal symbols is called "fts5yy0".
  179088. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  179089. ** zero the stack is dynamically sized using realloc()
  179090. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  179091. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  179092. ** sqlite3Fts5ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  179093. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  179094. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  179095. ** sqlite3Fts5ParserCTX_* As sqlite3Fts5ParserARG_ except for %extra_context
  179096. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  179097. ** defined, then do no error processing.
  179098. ** fts5YYNSTATE the combined number of states.
  179099. ** fts5YYNRULE the number of rules in the grammar
  179100. ** fts5YYNFTS5TOKEN Number of terminal symbols
  179101. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  179102. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  179103. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  179104. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  179105. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  179106. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  179107. ** fts5YY_MIN_REDUCE Minimum value for reduce actions
  179108. ** fts5YY_MAX_REDUCE Maximum value for reduce actions
  179109. */
  179110. #ifndef INTERFACE
  179111. # define INTERFACE 1
  179112. #endif
  179113. /************* Begin control #defines *****************************************/
  179114. #define fts5YYCODETYPE unsigned char
  179115. #define fts5YYNOCODE 27
  179116. #define fts5YYACTIONTYPE unsigned char
  179117. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  179118. typedef union {
  179119. int fts5yyinit;
  179120. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  179121. int fts5yy4;
  179122. Fts5Colset* fts5yy11;
  179123. Fts5ExprNode* fts5yy24;
  179124. Fts5ExprNearset* fts5yy46;
  179125. Fts5ExprPhrase* fts5yy53;
  179126. } fts5YYMINORTYPE;
  179127. #ifndef fts5YYSTACKDEPTH
  179128. #define fts5YYSTACKDEPTH 100
  179129. #endif
  179130. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  179131. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  179132. #define sqlite3Fts5ParserARG_PARAM ,pParse
  179133. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
  179134. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
  179135. #define sqlite3Fts5ParserCTX_SDECL
  179136. #define sqlite3Fts5ParserCTX_PDECL
  179137. #define sqlite3Fts5ParserCTX_PARAM
  179138. #define sqlite3Fts5ParserCTX_FETCH
  179139. #define sqlite3Fts5ParserCTX_STORE
  179140. #define fts5YYNSTATE 35
  179141. #define fts5YYNRULE 28
  179142. #define fts5YYNFTS5TOKEN 16
  179143. #define fts5YY_MAX_SHIFT 34
  179144. #define fts5YY_MIN_SHIFTREDUCE 52
  179145. #define fts5YY_MAX_SHIFTREDUCE 79
  179146. #define fts5YY_ERROR_ACTION 80
  179147. #define fts5YY_ACCEPT_ACTION 81
  179148. #define fts5YY_NO_ACTION 82
  179149. #define fts5YY_MIN_REDUCE 83
  179150. #define fts5YY_MAX_REDUCE 110
  179151. /************* End control #defines *******************************************/
  179152. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  179153. ** otherwise.
  179154. **
  179155. ** Applications can choose to define fts5yytestcase() in the %include section
  179156. ** to a macro that can assist in verifying code coverage. For production
  179157. ** code the fts5yytestcase() macro should be turned off. But it is useful
  179158. ** for testing.
  179159. */
  179160. #ifndef fts5yytestcase
  179161. # define fts5yytestcase(X)
  179162. #endif
  179163. /* Next are the tables used to determine what action to take based on the
  179164. ** current state and lookahead token. These tables are used to implement
  179165. ** functions that take a state number and lookahead value and return an
  179166. ** action integer.
  179167. **
  179168. ** Suppose the action integer is N. Then the action is determined as
  179169. ** follows
  179170. **
  179171. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  179172. ** token onto the stack and goto state N.
  179173. **
  179174. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  179175. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  179176. **
  179177. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  179178. **
  179179. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  179180. **
  179181. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  179182. ** slots in the fts5yy_action[] table.
  179183. **
  179184. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  179185. ** and fts5YY_MAX_REDUCE
  179186. **
  179187. ** The action table is constructed as a single large table named fts5yy_action[].
  179188. ** Given state S and lookahead X, the action is computed as either:
  179189. **
  179190. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  179191. ** (B) N = fts5yy_default[S]
  179192. **
  179193. ** The (A) formula is preferred. The B formula is used instead if
  179194. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
  179195. **
  179196. ** The formulas above are for computing the action when the lookahead is
  179197. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  179198. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  179199. ** the fts5yy_shift_ofst[] array.
  179200. **
  179201. ** The following are the tables generated in this section:
  179202. **
  179203. ** fts5yy_action[] A single table containing all actions.
  179204. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  179205. ** fts5yy_action. Used to detect hash collisions.
  179206. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  179207. ** shifting terminals.
  179208. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  179209. ** shifting non-terminals after a reduce.
  179210. ** fts5yy_default[] Default action for each state.
  179211. **
  179212. *********** Begin parsing tables **********************************************/
  179213. #define fts5YY_ACTTAB_COUNT (105)
  179214. static const fts5YYACTIONTYPE fts5yy_action[] = {
  179215. /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18,
  179216. /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6,
  179217. /* 20 */ 28, 14, 98, 14, 26, 31, 92, 96, 6, 28,
  179218. /* 30 */ 108, 98, 25, 26, 21, 96, 6, 28, 78, 98,
  179219. /* 40 */ 58, 26, 29, 96, 6, 28, 107, 98, 22, 26,
  179220. /* 50 */ 24, 16, 12, 11, 1, 13, 13, 24, 16, 23,
  179221. /* 60 */ 11, 33, 34, 13, 97, 8, 27, 32, 98, 7,
  179222. /* 70 */ 26, 3, 4, 5, 3, 4, 5, 3, 83, 4,
  179223. /* 80 */ 5, 3, 63, 5, 3, 62, 12, 2, 86, 13,
  179224. /* 90 */ 9, 30, 10, 10, 54, 57, 75, 78, 78, 53,
  179225. /* 100 */ 57, 15, 82, 82, 71,
  179226. };
  179227. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  179228. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  179229. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  179230. /* 20 */ 20, 9, 22, 9, 24, 13, 17, 18, 19, 20,
  179231. /* 30 */ 26, 22, 24, 24, 17, 18, 19, 20, 15, 22,
  179232. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  179233. /* 50 */ 6, 7, 9, 9, 10, 12, 12, 6, 7, 21,
  179234. /* 60 */ 9, 24, 25, 12, 18, 5, 20, 14, 22, 5,
  179235. /* 70 */ 24, 3, 1, 2, 3, 1, 2, 3, 0, 1,
  179236. /* 80 */ 2, 3, 11, 2, 3, 11, 9, 10, 5, 12,
  179237. /* 90 */ 23, 24, 10, 10, 8, 9, 9, 15, 15, 8,
  179238. /* 100 */ 9, 9, 27, 27, 11, 27, 27, 27, 27, 27,
  179239. /* 110 */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  179240. /* 120 */ 27,
  179241. };
  179242. #define fts5YY_SHIFT_COUNT (34)
  179243. #define fts5YY_SHIFT_MIN (0)
  179244. #define fts5YY_SHIFT_MAX (93)
  179245. static const unsigned char fts5yy_shift_ofst[] = {
  179246. /* 0 */ 44, 44, 44, 44, 44, 44, 51, 77, 43, 12,
  179247. /* 10 */ 14, 83, 82, 14, 23, 23, 31, 31, 71, 74,
  179248. /* 20 */ 78, 81, 86, 91, 6, 53, 53, 60, 64, 68,
  179249. /* 30 */ 53, 87, 92, 53, 93,
  179250. };
  179251. #define fts5YY_REDUCE_COUNT (17)
  179252. #define fts5YY_REDUCE_MIN (-17)
  179253. #define fts5YY_REDUCE_MAX (67)
  179254. static const signed char fts5yy_reduce_ofst[] = {
  179255. /* 0 */ -16, -8, 0, 9, 17, 25, 46, -17, -17, 37,
  179256. /* 10 */ 67, 4, 4, 8, 4, 20, 27, 38,
  179257. };
  179258. static const fts5YYACTIONTYPE fts5yy_default[] = {
  179259. /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105,
  179260. /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80,
  179261. /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90,
  179262. /* 30 */ 103, 80, 80, 104, 80,
  179263. };
  179264. /********** End of lemon-generated parsing tables *****************************/
  179265. /* The next table maps tokens (terminal symbols) into fallback tokens.
  179266. ** If a construct like the following:
  179267. **
  179268. ** %fallback ID X Y Z.
  179269. **
  179270. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  179271. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  179272. ** but it does not parse, the type of the token is changed to ID and
  179273. ** the parse is retried before an error is thrown.
  179274. **
  179275. ** This feature can be used, for example, to cause some keywords in a language
  179276. ** to revert to identifiers if they keyword does not apply in the context where
  179277. ** it appears.
  179278. */
  179279. #ifdef fts5YYFALLBACK
  179280. static const fts5YYCODETYPE fts5yyFallback[] = {
  179281. };
  179282. #endif /* fts5YYFALLBACK */
  179283. /* The following structure represents a single element of the
  179284. ** parser's stack. Information stored includes:
  179285. **
  179286. ** + The state number for the parser at this level of the stack.
  179287. **
  179288. ** + The value of the token stored at this level of the stack.
  179289. ** (In other words, the "major" token.)
  179290. **
  179291. ** + The semantic value stored at this level of the stack. This is
  179292. ** the information used by the action routines in the grammar.
  179293. ** It is sometimes called the "minor" token.
  179294. **
  179295. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  179296. ** actually contains the reduce action for the second half of the
  179297. ** SHIFTREDUCE.
  179298. */
  179299. struct fts5yyStackEntry {
  179300. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  179301. fts5YYCODETYPE major; /* The major token value. This is the code
  179302. ** number for the token at this stack level */
  179303. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  179304. ** is the value of the token */
  179305. };
  179306. typedef struct fts5yyStackEntry fts5yyStackEntry;
  179307. /* The state of the parser is completely contained in an instance of
  179308. ** the following structure */
  179309. struct fts5yyParser {
  179310. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  179311. #ifdef fts5YYTRACKMAXSTACKDEPTH
  179312. int fts5yyhwm; /* High-water mark of the stack */
  179313. #endif
  179314. #ifndef fts5YYNOERRORRECOVERY
  179315. int fts5yyerrcnt; /* Shifts left before out of the error */
  179316. #endif
  179317. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  179318. sqlite3Fts5ParserCTX_SDECL /* A place to hold %extra_context */
  179319. #if fts5YYSTACKDEPTH<=0
  179320. int fts5yystksz; /* Current side of the stack */
  179321. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  179322. fts5yyStackEntry fts5yystk0; /* First stack entry */
  179323. #else
  179324. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  179325. fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
  179326. #endif
  179327. };
  179328. typedef struct fts5yyParser fts5yyParser;
  179329. #ifndef NDEBUG
  179330. /* #include <stdio.h> */
  179331. static FILE *fts5yyTraceFILE = 0;
  179332. static char *fts5yyTracePrompt = 0;
  179333. #endif /* NDEBUG */
  179334. #ifndef NDEBUG
  179335. /*
  179336. ** Turn parser tracing on by giving a stream to which to write the trace
  179337. ** and a prompt to preface each trace message. Tracing is turned off
  179338. ** by making either argument NULL
  179339. **
  179340. ** Inputs:
  179341. ** <ul>
  179342. ** <li> A FILE* to which trace output should be written.
  179343. ** If NULL, then tracing is turned off.
  179344. ** <li> A prefix string written at the beginning of every
  179345. ** line of trace output. If NULL, then tracing is
  179346. ** turned off.
  179347. ** </ul>
  179348. **
  179349. ** Outputs:
  179350. ** None.
  179351. */
  179352. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  179353. fts5yyTraceFILE = TraceFILE;
  179354. fts5yyTracePrompt = zTracePrompt;
  179355. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  179356. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  179357. }
  179358. #endif /* NDEBUG */
  179359. #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
  179360. /* For tracing shifts, the names of all terminals and nonterminals
  179361. ** are required. The following table supplies these names */
  179362. static const char *const fts5yyTokenName[] = {
  179363. /* 0 */ "$",
  179364. /* 1 */ "OR",
  179365. /* 2 */ "AND",
  179366. /* 3 */ "NOT",
  179367. /* 4 */ "TERM",
  179368. /* 5 */ "COLON",
  179369. /* 6 */ "MINUS",
  179370. /* 7 */ "LCP",
  179371. /* 8 */ "RCP",
  179372. /* 9 */ "STRING",
  179373. /* 10 */ "LP",
  179374. /* 11 */ "RP",
  179375. /* 12 */ "CARET",
  179376. /* 13 */ "COMMA",
  179377. /* 14 */ "PLUS",
  179378. /* 15 */ "STAR",
  179379. /* 16 */ "input",
  179380. /* 17 */ "expr",
  179381. /* 18 */ "cnearset",
  179382. /* 19 */ "exprlist",
  179383. /* 20 */ "colset",
  179384. /* 21 */ "colsetlist",
  179385. /* 22 */ "nearset",
  179386. /* 23 */ "nearphrases",
  179387. /* 24 */ "phrase",
  179388. /* 25 */ "neardist_opt",
  179389. /* 26 */ "star_opt",
  179390. };
  179391. #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
  179392. #ifndef NDEBUG
  179393. /* For tracing reduce actions, the names of all rules are required.
  179394. */
  179395. static const char *const fts5yyRuleName[] = {
  179396. /* 0 */ "input ::= expr",
  179397. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  179398. /* 2 */ "colset ::= LCP colsetlist RCP",
  179399. /* 3 */ "colset ::= STRING",
  179400. /* 4 */ "colset ::= MINUS STRING",
  179401. /* 5 */ "colsetlist ::= colsetlist STRING",
  179402. /* 6 */ "colsetlist ::= STRING",
  179403. /* 7 */ "expr ::= expr AND expr",
  179404. /* 8 */ "expr ::= expr OR expr",
  179405. /* 9 */ "expr ::= expr NOT expr",
  179406. /* 10 */ "expr ::= colset COLON LP expr RP",
  179407. /* 11 */ "expr ::= LP expr RP",
  179408. /* 12 */ "expr ::= exprlist",
  179409. /* 13 */ "exprlist ::= cnearset",
  179410. /* 14 */ "exprlist ::= exprlist cnearset",
  179411. /* 15 */ "cnearset ::= nearset",
  179412. /* 16 */ "cnearset ::= colset COLON nearset",
  179413. /* 17 */ "nearset ::= phrase",
  179414. /* 18 */ "nearset ::= CARET phrase",
  179415. /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  179416. /* 20 */ "nearphrases ::= phrase",
  179417. /* 21 */ "nearphrases ::= nearphrases phrase",
  179418. /* 22 */ "neardist_opt ::=",
  179419. /* 23 */ "neardist_opt ::= COMMA STRING",
  179420. /* 24 */ "phrase ::= phrase PLUS STRING star_opt",
  179421. /* 25 */ "phrase ::= STRING star_opt",
  179422. /* 26 */ "star_opt ::= STAR",
  179423. /* 27 */ "star_opt ::=",
  179424. };
  179425. #endif /* NDEBUG */
  179426. #if fts5YYSTACKDEPTH<=0
  179427. /*
  179428. ** Try to increase the size of the parser stack. Return the number
  179429. ** of errors. Return 0 on success.
  179430. */
  179431. static int fts5yyGrowStack(fts5yyParser *p){
  179432. int newSize;
  179433. int idx;
  179434. fts5yyStackEntry *pNew;
  179435. newSize = p->fts5yystksz*2 + 100;
  179436. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  179437. if( p->fts5yystack==&p->fts5yystk0 ){
  179438. pNew = malloc(newSize*sizeof(pNew[0]));
  179439. if( pNew ) pNew[0] = p->fts5yystk0;
  179440. }else{
  179441. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  179442. }
  179443. if( pNew ){
  179444. p->fts5yystack = pNew;
  179445. p->fts5yytos = &p->fts5yystack[idx];
  179446. #ifndef NDEBUG
  179447. if( fts5yyTraceFILE ){
  179448. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  179449. fts5yyTracePrompt, p->fts5yystksz, newSize);
  179450. }
  179451. #endif
  179452. p->fts5yystksz = newSize;
  179453. }
  179454. return pNew==0;
  179455. }
  179456. #endif
  179457. /* Datatype of the argument to the memory allocated passed as the
  179458. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  179459. ** putting an appropriate #define in the %include section of the input
  179460. ** grammar.
  179461. */
  179462. #ifndef fts5YYMALLOCARGTYPE
  179463. # define fts5YYMALLOCARGTYPE size_t
  179464. #endif
  179465. /* Initialize a new parser that has already been allocated.
  179466. */
  179467. static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
  179468. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
  179469. sqlite3Fts5ParserCTX_STORE
  179470. #ifdef fts5YYTRACKMAXSTACKDEPTH
  179471. fts5yypParser->fts5yyhwm = 0;
  179472. #endif
  179473. #if fts5YYSTACKDEPTH<=0
  179474. fts5yypParser->fts5yytos = NULL;
  179475. fts5yypParser->fts5yystack = NULL;
  179476. fts5yypParser->fts5yystksz = 0;
  179477. if( fts5yyGrowStack(fts5yypParser) ){
  179478. fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;
  179479. fts5yypParser->fts5yystksz = 1;
  179480. }
  179481. #endif
  179482. #ifndef fts5YYNOERRORRECOVERY
  179483. fts5yypParser->fts5yyerrcnt = -1;
  179484. #endif
  179485. fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
  179486. fts5yypParser->fts5yystack[0].stateno = 0;
  179487. fts5yypParser->fts5yystack[0].major = 0;
  179488. #if fts5YYSTACKDEPTH>0
  179489. fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
  179490. #endif
  179491. }
  179492. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  179493. /*
  179494. ** This function allocates a new parser.
  179495. ** The only argument is a pointer to a function which works like
  179496. ** malloc.
  179497. **
  179498. ** Inputs:
  179499. ** A pointer to the function used to allocate memory.
  179500. **
  179501. ** Outputs:
  179502. ** A pointer to a parser. This pointer is used in subsequent calls
  179503. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  179504. */
  179505. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
  179506. fts5yyParser *fts5yypParser;
  179507. fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  179508. if( fts5yypParser ){
  179509. sqlite3Fts5ParserCTX_STORE
  179510. sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
  179511. }
  179512. return (void*)fts5yypParser;
  179513. }
  179514. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  179515. /* The following function deletes the "minor type" or semantic value
  179516. ** associated with a symbol. The symbol can be either a terminal
  179517. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  179518. ** a pointer to the value to be deleted. The code used to do the
  179519. ** deletions is derived from the %destructor and/or %token_destructor
  179520. ** directives of the input grammar.
  179521. */
  179522. static void fts5yy_destructor(
  179523. fts5yyParser *fts5yypParser, /* The parser */
  179524. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  179525. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  179526. ){
  179527. sqlite3Fts5ParserARG_FETCH
  179528. sqlite3Fts5ParserCTX_FETCH
  179529. switch( fts5yymajor ){
  179530. /* Here is inserted the actions which take place when a
  179531. ** terminal or non-terminal is destroyed. This can happen
  179532. ** when the symbol is popped from the stack during a
  179533. ** reduce or during error processing or when a parser is
  179534. ** being destroyed before it is finished parsing.
  179535. **
  179536. ** Note: during a reduce, the only symbols destroyed are those
  179537. ** which appear on the RHS of the rule, but which are *not* used
  179538. ** inside the C code.
  179539. */
  179540. /********* Begin destructor definitions ***************************************/
  179541. case 16: /* input */
  179542. {
  179543. (void)pParse;
  179544. }
  179545. break;
  179546. case 17: /* expr */
  179547. case 18: /* cnearset */
  179548. case 19: /* exprlist */
  179549. {
  179550. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  179551. }
  179552. break;
  179553. case 20: /* colset */
  179554. case 21: /* colsetlist */
  179555. {
  179556. sqlite3_free((fts5yypminor->fts5yy11));
  179557. }
  179558. break;
  179559. case 22: /* nearset */
  179560. case 23: /* nearphrases */
  179561. {
  179562. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  179563. }
  179564. break;
  179565. case 24: /* phrase */
  179566. {
  179567. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  179568. }
  179569. break;
  179570. /********* End destructor definitions *****************************************/
  179571. default: break; /* If no destructor action specified: do nothing */
  179572. }
  179573. }
  179574. /*
  179575. ** Pop the parser's stack once.
  179576. **
  179577. ** If there is a destructor routine associated with the token which
  179578. ** is popped from the stack, then call it.
  179579. */
  179580. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  179581. fts5yyStackEntry *fts5yytos;
  179582. assert( pParser->fts5yytos!=0 );
  179583. assert( pParser->fts5yytos > pParser->fts5yystack );
  179584. fts5yytos = pParser->fts5yytos--;
  179585. #ifndef NDEBUG
  179586. if( fts5yyTraceFILE ){
  179587. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  179588. fts5yyTracePrompt,
  179589. fts5yyTokenName[fts5yytos->major]);
  179590. }
  179591. #endif
  179592. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  179593. }
  179594. /*
  179595. ** Clear all secondary memory allocations from the parser
  179596. */
  179597. static void sqlite3Fts5ParserFinalize(void *p){
  179598. fts5yyParser *pParser = (fts5yyParser*)p;
  179599. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  179600. #if fts5YYSTACKDEPTH<=0
  179601. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  179602. #endif
  179603. }
  179604. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  179605. /*
  179606. ** Deallocate and destroy a parser. Destructors are called for
  179607. ** all stack elements before shutting the parser down.
  179608. **
  179609. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  179610. ** is defined in a %include section of the input grammar) then it is
  179611. ** assumed that the input pointer is never NULL.
  179612. */
  179613. static void sqlite3Fts5ParserFree(
  179614. void *p, /* The parser to be deleted */
  179615. void (*freeProc)(void*) /* Function used to reclaim memory */
  179616. ){
  179617. #ifndef fts5YYPARSEFREENEVERNULL
  179618. if( p==0 ) return;
  179619. #endif
  179620. sqlite3Fts5ParserFinalize(p);
  179621. (*freeProc)(p);
  179622. }
  179623. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  179624. /*
  179625. ** Return the peak depth of the stack for a parser.
  179626. */
  179627. #ifdef fts5YYTRACKMAXSTACKDEPTH
  179628. static int sqlite3Fts5ParserStackPeak(void *p){
  179629. fts5yyParser *pParser = (fts5yyParser*)p;
  179630. return pParser->fts5yyhwm;
  179631. }
  179632. #endif
  179633. /* This array of booleans keeps track of the parser statement
  179634. ** coverage. The element fts5yycoverage[X][Y] is set when the parser
  179635. ** is in state X and has a lookahead token Y. In a well-tested
  179636. ** systems, every element of this matrix should end up being set.
  179637. */
  179638. #if defined(fts5YYCOVERAGE)
  179639. static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
  179640. #endif
  179641. /*
  179642. ** Write into out a description of every state/lookahead combination that
  179643. **
  179644. ** (1) has not been used by the parser, and
  179645. ** (2) is not a syntax error.
  179646. **
  179647. ** Return the number of missed state/lookahead combinations.
  179648. */
  179649. #if defined(fts5YYCOVERAGE)
  179650. static int sqlite3Fts5ParserCoverage(FILE *out){
  179651. int stateno, iLookAhead, i;
  179652. int nMissed = 0;
  179653. for(stateno=0; stateno<fts5YYNSTATE; stateno++){
  179654. i = fts5yy_shift_ofst[stateno];
  179655. for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
  179656. if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  179657. if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  179658. if( out ){
  179659. fprintf(out,"State %d lookahead %s %s\n", stateno,
  179660. fts5yyTokenName[iLookAhead],
  179661. fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  179662. }
  179663. }
  179664. }
  179665. return nMissed;
  179666. }
  179667. #endif
  179668. /*
  179669. ** Find the appropriate action for a parser given the terminal
  179670. ** look-ahead token iLookAhead.
  179671. */
  179672. static fts5YYACTIONTYPE fts5yy_find_shift_action(
  179673. fts5YYCODETYPE iLookAhead, /* The look-ahead token */
  179674. fts5YYACTIONTYPE stateno /* Current state number */
  179675. ){
  179676. int i;
  179677. if( stateno>fts5YY_MAX_SHIFT ) return stateno;
  179678. assert( stateno <= fts5YY_SHIFT_COUNT );
  179679. #if defined(fts5YYCOVERAGE)
  179680. fts5yycoverage[stateno][iLookAhead] = 1;
  179681. #endif
  179682. do{
  179683. i = fts5yy_shift_ofst[stateno];
  179684. assert( i>=0 );
  179685. assert( i+fts5YYNFTS5TOKEN<=(int)sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0]) );
  179686. assert( iLookAhead!=fts5YYNOCODE );
  179687. assert( iLookAhead < fts5YYNFTS5TOKEN );
  179688. i += iLookAhead;
  179689. if( fts5yy_lookahead[i]!=iLookAhead ){
  179690. #ifdef fts5YYFALLBACK
  179691. fts5YYCODETYPE iFallback; /* Fallback token */
  179692. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  179693. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  179694. #ifndef NDEBUG
  179695. if( fts5yyTraceFILE ){
  179696. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  179697. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  179698. }
  179699. #endif
  179700. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  179701. iLookAhead = iFallback;
  179702. continue;
  179703. }
  179704. #endif
  179705. #ifdef fts5YYWILDCARD
  179706. {
  179707. int j = i - iLookAhead + fts5YYWILDCARD;
  179708. if(
  179709. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  179710. j>=0 &&
  179711. #endif
  179712. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  179713. j<fts5YY_ACTTAB_COUNT &&
  179714. #endif
  179715. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  179716. ){
  179717. #ifndef NDEBUG
  179718. if( fts5yyTraceFILE ){
  179719. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  179720. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  179721. fts5yyTokenName[fts5YYWILDCARD]);
  179722. }
  179723. #endif /* NDEBUG */
  179724. return fts5yy_action[j];
  179725. }
  179726. }
  179727. #endif /* fts5YYWILDCARD */
  179728. return fts5yy_default[stateno];
  179729. }else{
  179730. return fts5yy_action[i];
  179731. }
  179732. }while(1);
  179733. }
  179734. /*
  179735. ** Find the appropriate action for a parser given the non-terminal
  179736. ** look-ahead token iLookAhead.
  179737. */
  179738. static int fts5yy_find_reduce_action(
  179739. fts5YYACTIONTYPE stateno, /* Current state number */
  179740. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  179741. ){
  179742. int i;
  179743. #ifdef fts5YYERRORSYMBOL
  179744. if( stateno>fts5YY_REDUCE_COUNT ){
  179745. return fts5yy_default[stateno];
  179746. }
  179747. #else
  179748. assert( stateno<=fts5YY_REDUCE_COUNT );
  179749. #endif
  179750. i = fts5yy_reduce_ofst[stateno];
  179751. assert( iLookAhead!=fts5YYNOCODE );
  179752. i += iLookAhead;
  179753. #ifdef fts5YYERRORSYMBOL
  179754. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  179755. return fts5yy_default[stateno];
  179756. }
  179757. #else
  179758. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  179759. assert( fts5yy_lookahead[i]==iLookAhead );
  179760. #endif
  179761. return fts5yy_action[i];
  179762. }
  179763. /*
  179764. ** The following routine is called if the stack overflows.
  179765. */
  179766. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  179767. sqlite3Fts5ParserARG_FETCH
  179768. sqlite3Fts5ParserCTX_FETCH
  179769. #ifndef NDEBUG
  179770. if( fts5yyTraceFILE ){
  179771. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  179772. }
  179773. #endif
  179774. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  179775. /* Here code is inserted which will execute if the parser
  179776. ** stack every overflows */
  179777. /******** Begin %stack_overflow code ******************************************/
  179778. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  179779. /******** End %stack_overflow code ********************************************/
  179780. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  179781. sqlite3Fts5ParserCTX_STORE
  179782. }
  179783. /*
  179784. ** Print tracing information for a SHIFT action
  179785. */
  179786. #ifndef NDEBUG
  179787. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
  179788. if( fts5yyTraceFILE ){
  179789. if( fts5yyNewState<fts5YYNSTATE ){
  179790. fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
  179791. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  179792. fts5yyNewState);
  179793. }else{
  179794. fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  179795. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  179796. fts5yyNewState - fts5YY_MIN_REDUCE);
  179797. }
  179798. }
  179799. }
  179800. #else
  179801. # define fts5yyTraceShift(X,Y,Z)
  179802. #endif
  179803. /*
  179804. ** Perform a shift action.
  179805. */
  179806. static void fts5yy_shift(
  179807. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  179808. fts5YYACTIONTYPE fts5yyNewState, /* The new state to shift in */
  179809. fts5YYCODETYPE fts5yyMajor, /* The major token to shift in */
  179810. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  179811. ){
  179812. fts5yyStackEntry *fts5yytos;
  179813. fts5yypParser->fts5yytos++;
  179814. #ifdef fts5YYTRACKMAXSTACKDEPTH
  179815. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  179816. fts5yypParser->fts5yyhwm++;
  179817. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  179818. }
  179819. #endif
  179820. #if fts5YYSTACKDEPTH>0
  179821. if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
  179822. fts5yypParser->fts5yytos--;
  179823. fts5yyStackOverflow(fts5yypParser);
  179824. return;
  179825. }
  179826. #else
  179827. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  179828. if( fts5yyGrowStack(fts5yypParser) ){
  179829. fts5yypParser->fts5yytos--;
  179830. fts5yyStackOverflow(fts5yypParser);
  179831. return;
  179832. }
  179833. }
  179834. #endif
  179835. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  179836. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  179837. }
  179838. fts5yytos = fts5yypParser->fts5yytos;
  179839. fts5yytos->stateno = fts5yyNewState;
  179840. fts5yytos->major = fts5yyMajor;
  179841. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  179842. fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
  179843. }
  179844. /* The following table contains information about every rule that
  179845. ** is used during the reduce.
  179846. */
  179847. static const struct {
  179848. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  179849. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  179850. } fts5yyRuleInfo[] = {
  179851. { 16, -1 }, /* (0) input ::= expr */
  179852. { 20, -4 }, /* (1) colset ::= MINUS LCP colsetlist RCP */
  179853. { 20, -3 }, /* (2) colset ::= LCP colsetlist RCP */
  179854. { 20, -1 }, /* (3) colset ::= STRING */
  179855. { 20, -2 }, /* (4) colset ::= MINUS STRING */
  179856. { 21, -2 }, /* (5) colsetlist ::= colsetlist STRING */
  179857. { 21, -1 }, /* (6) colsetlist ::= STRING */
  179858. { 17, -3 }, /* (7) expr ::= expr AND expr */
  179859. { 17, -3 }, /* (8) expr ::= expr OR expr */
  179860. { 17, -3 }, /* (9) expr ::= expr NOT expr */
  179861. { 17, -5 }, /* (10) expr ::= colset COLON LP expr RP */
  179862. { 17, -3 }, /* (11) expr ::= LP expr RP */
  179863. { 17, -1 }, /* (12) expr ::= exprlist */
  179864. { 19, -1 }, /* (13) exprlist ::= cnearset */
  179865. { 19, -2 }, /* (14) exprlist ::= exprlist cnearset */
  179866. { 18, -1 }, /* (15) cnearset ::= nearset */
  179867. { 18, -3 }, /* (16) cnearset ::= colset COLON nearset */
  179868. { 22, -1 }, /* (17) nearset ::= phrase */
  179869. { 22, -2 }, /* (18) nearset ::= CARET phrase */
  179870. { 22, -5 }, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  179871. { 23, -1 }, /* (20) nearphrases ::= phrase */
  179872. { 23, -2 }, /* (21) nearphrases ::= nearphrases phrase */
  179873. { 25, 0 }, /* (22) neardist_opt ::= */
  179874. { 25, -2 }, /* (23) neardist_opt ::= COMMA STRING */
  179875. { 24, -4 }, /* (24) phrase ::= phrase PLUS STRING star_opt */
  179876. { 24, -2 }, /* (25) phrase ::= STRING star_opt */
  179877. { 26, -1 }, /* (26) star_opt ::= STAR */
  179878. { 26, 0 }, /* (27) star_opt ::= */
  179879. };
  179880. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  179881. /*
  179882. ** Perform a reduce action and the shift that must immediately
  179883. ** follow the reduce.
  179884. **
  179885. ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
  179886. ** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE
  179887. ** if the lookahead token has already been consumed. As this procedure is
  179888. ** only called from one place, optimizing compilers will in-line it, which
  179889. ** means that the extra parameters have no performance impact.
  179890. */
  179891. static fts5YYACTIONTYPE fts5yy_reduce(
  179892. fts5yyParser *fts5yypParser, /* The parser */
  179893. unsigned int fts5yyruleno, /* Number of the rule by which to reduce */
  179894. int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */
  179895. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */
  179896. sqlite3Fts5ParserCTX_PDECL /* %extra_context */
  179897. ){
  179898. int fts5yygoto; /* The next state */
  179899. int fts5yyact; /* The next action */
  179900. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  179901. int fts5yysize; /* Amount to pop the stack */
  179902. sqlite3Fts5ParserARG_FETCH
  179903. (void)fts5yyLookahead;
  179904. (void)fts5yyLookaheadToken;
  179905. fts5yymsp = fts5yypParser->fts5yytos;
  179906. #ifndef NDEBUG
  179907. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  179908. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  179909. if( fts5yysize ){
  179910. fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  179911. fts5yyTracePrompt,
  179912. fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
  179913. }else{
  179914. fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
  179915. fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
  179916. }
  179917. }
  179918. #endif /* NDEBUG */
  179919. /* Check that the stack is large enough to grow by a single entry
  179920. ** if the RHS of the rule is empty. This ensures that there is room
  179921. ** enough on the stack to push the LHS value */
  179922. if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
  179923. #ifdef fts5YYTRACKMAXSTACKDEPTH
  179924. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  179925. fts5yypParser->fts5yyhwm++;
  179926. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  179927. }
  179928. #endif
  179929. #if fts5YYSTACKDEPTH>0
  179930. if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
  179931. fts5yyStackOverflow(fts5yypParser);
  179932. /* The call to fts5yyStackOverflow() above pops the stack until it is
  179933. ** empty, causing the main parser loop to exit. So the return value
  179934. ** is never used and does not matter. */
  179935. return 0;
  179936. }
  179937. #else
  179938. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  179939. if( fts5yyGrowStack(fts5yypParser) ){
  179940. fts5yyStackOverflow(fts5yypParser);
  179941. /* The call to fts5yyStackOverflow() above pops the stack until it is
  179942. ** empty, causing the main parser loop to exit. So the return value
  179943. ** is never used and does not matter. */
  179944. return 0;
  179945. }
  179946. fts5yymsp = fts5yypParser->fts5yytos;
  179947. }
  179948. #endif
  179949. }
  179950. switch( fts5yyruleno ){
  179951. /* Beginning here are the reduction cases. A typical example
  179952. ** follows:
  179953. ** case 0:
  179954. ** #line <lineno> <grammarfile>
  179955. ** { ... } // User supplied code
  179956. ** #line <lineno> <thisfile>
  179957. ** break;
  179958. */
  179959. /********** Begin reduce actions **********************************************/
  179960. fts5YYMINORTYPE fts5yylhsminor;
  179961. case 0: /* input ::= expr */
  179962. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  179963. break;
  179964. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  179965. {
  179966. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  179967. }
  179968. break;
  179969. case 2: /* colset ::= LCP colsetlist RCP */
  179970. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  179971. break;
  179972. case 3: /* colset ::= STRING */
  179973. {
  179974. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  179975. }
  179976. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  179977. break;
  179978. case 4: /* colset ::= MINUS STRING */
  179979. {
  179980. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  179981. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  179982. }
  179983. break;
  179984. case 5: /* colsetlist ::= colsetlist STRING */
  179985. {
  179986. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  179987. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  179988. break;
  179989. case 6: /* colsetlist ::= STRING */
  179990. {
  179991. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  179992. }
  179993. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  179994. break;
  179995. case 7: /* expr ::= expr AND expr */
  179996. {
  179997. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  179998. }
  179999. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180000. break;
  180001. case 8: /* expr ::= expr OR expr */
  180002. {
  180003. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  180004. }
  180005. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180006. break;
  180007. case 9: /* expr ::= expr NOT expr */
  180008. {
  180009. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  180010. }
  180011. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180012. break;
  180013. case 10: /* expr ::= colset COLON LP expr RP */
  180014. {
  180015. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  180016. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  180017. }
  180018. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180019. break;
  180020. case 11: /* expr ::= LP expr RP */
  180021. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  180022. break;
  180023. case 12: /* expr ::= exprlist */
  180024. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  180025. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  180026. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180027. break;
  180028. case 14: /* exprlist ::= exprlist cnearset */
  180029. {
  180030. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  180031. }
  180032. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180033. break;
  180034. case 15: /* cnearset ::= nearset */
  180035. {
  180036. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  180037. }
  180038. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180039. break;
  180040. case 16: /* cnearset ::= colset COLON nearset */
  180041. {
  180042. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  180043. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  180044. }
  180045. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  180046. break;
  180047. case 17: /* nearset ::= phrase */
  180048. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  180049. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  180050. break;
  180051. case 18: /* nearset ::= CARET phrase */
  180052. {
  180053. sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
  180054. fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  180055. }
  180056. break;
  180057. case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  180058. {
  180059. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  180060. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  180061. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  180062. }
  180063. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  180064. break;
  180065. case 20: /* nearphrases ::= phrase */
  180066. {
  180067. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  180068. }
  180069. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  180070. break;
  180071. case 21: /* nearphrases ::= nearphrases phrase */
  180072. {
  180073. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  180074. }
  180075. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  180076. break;
  180077. case 22: /* neardist_opt ::= */
  180078. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  180079. break;
  180080. case 23: /* neardist_opt ::= COMMA STRING */
  180081. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  180082. break;
  180083. case 24: /* phrase ::= phrase PLUS STRING star_opt */
  180084. {
  180085. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  180086. }
  180087. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  180088. break;
  180089. case 25: /* phrase ::= STRING star_opt */
  180090. {
  180091. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  180092. }
  180093. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  180094. break;
  180095. case 26: /* star_opt ::= STAR */
  180096. { fts5yymsp[0].minor.fts5yy4 = 1; }
  180097. break;
  180098. case 27: /* star_opt ::= */
  180099. { fts5yymsp[1].minor.fts5yy4 = 0; }
  180100. break;
  180101. default:
  180102. break;
  180103. /********** End reduce actions ************************************************/
  180104. };
  180105. assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  180106. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  180107. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  180108. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  180109. /* There are no SHIFTREDUCE actions on nonterminals because the table
  180110. ** generator has simplified them to pure REDUCE actions. */
  180111. assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
  180112. /* It is not possible for a REDUCE to be followed by an error */
  180113. assert( fts5yyact!=fts5YY_ERROR_ACTION );
  180114. fts5yymsp += fts5yysize+1;
  180115. fts5yypParser->fts5yytos = fts5yymsp;
  180116. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  180117. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  180118. fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
  180119. return fts5yyact;
  180120. }
  180121. /*
  180122. ** The following code executes when the parse fails
  180123. */
  180124. #ifndef fts5YYNOERRORRECOVERY
  180125. static void fts5yy_parse_failed(
  180126. fts5yyParser *fts5yypParser /* The parser */
  180127. ){
  180128. sqlite3Fts5ParserARG_FETCH
  180129. sqlite3Fts5ParserCTX_FETCH
  180130. #ifndef NDEBUG
  180131. if( fts5yyTraceFILE ){
  180132. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  180133. }
  180134. #endif
  180135. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  180136. /* Here code is inserted which will be executed whenever the
  180137. ** parser fails */
  180138. /************ Begin %parse_failure code ***************************************/
  180139. /************ End %parse_failure code *****************************************/
  180140. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  180141. sqlite3Fts5ParserCTX_STORE
  180142. }
  180143. #endif /* fts5YYNOERRORRECOVERY */
  180144. /*
  180145. ** The following code executes when a syntax error first occurs.
  180146. */
  180147. static void fts5yy_syntax_error(
  180148. fts5yyParser *fts5yypParser, /* The parser */
  180149. int fts5yymajor, /* The major type of the error token */
  180150. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  180151. ){
  180152. sqlite3Fts5ParserARG_FETCH
  180153. sqlite3Fts5ParserCTX_FETCH
  180154. #define FTS5TOKEN fts5yyminor
  180155. /************ Begin %syntax_error code ****************************************/
  180156. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  180157. sqlite3Fts5ParseError(
  180158. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  180159. );
  180160. /************ End %syntax_error code ******************************************/
  180161. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  180162. sqlite3Fts5ParserCTX_STORE
  180163. }
  180164. /*
  180165. ** The following is executed when the parser accepts
  180166. */
  180167. static void fts5yy_accept(
  180168. fts5yyParser *fts5yypParser /* The parser */
  180169. ){
  180170. sqlite3Fts5ParserARG_FETCH
  180171. sqlite3Fts5ParserCTX_FETCH
  180172. #ifndef NDEBUG
  180173. if( fts5yyTraceFILE ){
  180174. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  180175. }
  180176. #endif
  180177. #ifndef fts5YYNOERRORRECOVERY
  180178. fts5yypParser->fts5yyerrcnt = -1;
  180179. #endif
  180180. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  180181. /* Here code is inserted which will be executed whenever the
  180182. ** parser accepts */
  180183. /*********** Begin %parse_accept code *****************************************/
  180184. /*********** End %parse_accept code *******************************************/
  180185. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  180186. sqlite3Fts5ParserCTX_STORE
  180187. }
  180188. /* The main parser program.
  180189. ** The first argument is a pointer to a structure obtained from
  180190. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  180191. ** The second argument is the major token number. The third is
  180192. ** the minor token. The fourth optional argument is whatever the
  180193. ** user wants (and specified in the grammar) and is available for
  180194. ** use by the action routines.
  180195. **
  180196. ** Inputs:
  180197. ** <ul>
  180198. ** <li> A pointer to the parser (an opaque structure.)
  180199. ** <li> The major token number.
  180200. ** <li> The minor token number.
  180201. ** <li> An option argument of a grammar-specified type.
  180202. ** </ul>
  180203. **
  180204. ** Outputs:
  180205. ** None.
  180206. */
  180207. static void sqlite3Fts5Parser(
  180208. void *fts5yyp, /* The parser */
  180209. int fts5yymajor, /* The major token code number */
  180210. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  180211. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  180212. ){
  180213. fts5YYMINORTYPE fts5yyminorunion;
  180214. fts5YYACTIONTYPE fts5yyact; /* The parser action. */
  180215. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  180216. int fts5yyendofinput; /* True if we are at the end of input */
  180217. #endif
  180218. #ifdef fts5YYERRORSYMBOL
  180219. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  180220. #endif
  180221. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp; /* The parser */
  180222. sqlite3Fts5ParserCTX_FETCH
  180223. sqlite3Fts5ParserARG_STORE
  180224. assert( fts5yypParser->fts5yytos!=0 );
  180225. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  180226. fts5yyendofinput = (fts5yymajor==0);
  180227. #endif
  180228. fts5yyact = fts5yypParser->fts5yytos->stateno;
  180229. #ifndef NDEBUG
  180230. if( fts5yyTraceFILE ){
  180231. if( fts5yyact < fts5YY_MIN_REDUCE ){
  180232. fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
  180233. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
  180234. }else{
  180235. fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  180236. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
  180237. }
  180238. }
  180239. #endif
  180240. do{
  180241. assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
  180242. fts5yyact = fts5yy_find_shift_action(fts5yymajor,fts5yyact);
  180243. if( fts5yyact >= fts5YY_MIN_REDUCE ){
  180244. fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,
  180245. fts5yyminor sqlite3Fts5ParserCTX_PARAM);
  180246. }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  180247. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
  180248. #ifndef fts5YYNOERRORRECOVERY
  180249. fts5yypParser->fts5yyerrcnt--;
  180250. #endif
  180251. break;
  180252. }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
  180253. fts5yypParser->fts5yytos--;
  180254. fts5yy_accept(fts5yypParser);
  180255. return;
  180256. }else{
  180257. assert( fts5yyact == fts5YY_ERROR_ACTION );
  180258. fts5yyminorunion.fts5yy0 = fts5yyminor;
  180259. #ifdef fts5YYERRORSYMBOL
  180260. int fts5yymx;
  180261. #endif
  180262. #ifndef NDEBUG
  180263. if( fts5yyTraceFILE ){
  180264. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  180265. }
  180266. #endif
  180267. #ifdef fts5YYERRORSYMBOL
  180268. /* A syntax error has occurred.
  180269. ** The response to an error depends upon whether or not the
  180270. ** grammar defines an error token "ERROR".
  180271. **
  180272. ** This is what we do if the grammar does define ERROR:
  180273. **
  180274. ** * Call the %syntax_error function.
  180275. **
  180276. ** * Begin popping the stack until we enter a state where
  180277. ** it is legal to shift the error symbol, then shift
  180278. ** the error symbol.
  180279. **
  180280. ** * Set the error count to three.
  180281. **
  180282. ** * Begin accepting and shifting new tokens. No new error
  180283. ** processing will occur until three tokens have been
  180284. ** shifted successfully.
  180285. **
  180286. */
  180287. if( fts5yypParser->fts5yyerrcnt<0 ){
  180288. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  180289. }
  180290. fts5yymx = fts5yypParser->fts5yytos->major;
  180291. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  180292. #ifndef NDEBUG
  180293. if( fts5yyTraceFILE ){
  180294. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  180295. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  180296. }
  180297. #endif
  180298. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  180299. fts5yymajor = fts5YYNOCODE;
  180300. }else{
  180301. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  180302. && fts5yymx != fts5YYERRORSYMBOL
  180303. && (fts5yyact = fts5yy_find_reduce_action(
  180304. fts5yypParser->fts5yytos->stateno,
  180305. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  180306. ){
  180307. fts5yy_pop_parser_stack(fts5yypParser);
  180308. }
  180309. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  180310. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  180311. fts5yy_parse_failed(fts5yypParser);
  180312. #ifndef fts5YYNOERRORRECOVERY
  180313. fts5yypParser->fts5yyerrcnt = -1;
  180314. #endif
  180315. fts5yymajor = fts5YYNOCODE;
  180316. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  180317. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  180318. }
  180319. }
  180320. fts5yypParser->fts5yyerrcnt = 3;
  180321. fts5yyerrorhit = 1;
  180322. if( fts5yymajor==fts5YYNOCODE ) break;
  180323. fts5yyact = fts5yypParser->fts5yytos->stateno;
  180324. #elif defined(fts5YYNOERRORRECOVERY)
  180325. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  180326. ** do any kind of error recovery. Instead, simply invoke the syntax
  180327. ** error routine and continue going as if nothing had happened.
  180328. **
  180329. ** Applications can set this macro (for example inside %include) if
  180330. ** they intend to abandon the parse upon the first syntax error seen.
  180331. */
  180332. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  180333. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  180334. break;
  180335. #else /* fts5YYERRORSYMBOL is not defined */
  180336. /* This is what we do if the grammar does not define ERROR:
  180337. **
  180338. ** * Report an error message, and throw away the input token.
  180339. **
  180340. ** * If the input token is $, then fail the parse.
  180341. **
  180342. ** As before, subsequent error messages are suppressed until
  180343. ** three input tokens have been successfully shifted.
  180344. */
  180345. if( fts5yypParser->fts5yyerrcnt<=0 ){
  180346. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  180347. }
  180348. fts5yypParser->fts5yyerrcnt = 3;
  180349. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  180350. if( fts5yyendofinput ){
  180351. fts5yy_parse_failed(fts5yypParser);
  180352. #ifndef fts5YYNOERRORRECOVERY
  180353. fts5yypParser->fts5yyerrcnt = -1;
  180354. #endif
  180355. }
  180356. break;
  180357. #endif
  180358. }
  180359. }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  180360. #ifndef NDEBUG
  180361. if( fts5yyTraceFILE ){
  180362. fts5yyStackEntry *i;
  180363. char cDiv = '[';
  180364. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  180365. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  180366. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  180367. cDiv = ' ';
  180368. }
  180369. fprintf(fts5yyTraceFILE,"]\n");
  180370. }
  180371. #endif
  180372. return;
  180373. }
  180374. /*
  180375. ** 2014 May 31
  180376. **
  180377. ** The author disclaims copyright to this source code. In place of
  180378. ** a legal notice, here is a blessing:
  180379. **
  180380. ** May you do good and not evil.
  180381. ** May you find forgiveness for yourself and forgive others.
  180382. ** May you share freely, never taking more than you give.
  180383. **
  180384. ******************************************************************************
  180385. */
  180386. /* #include "fts5Int.h" */
  180387. #include <math.h> /* amalgamator: keep */
  180388. /*
  180389. ** Object used to iterate through all "coalesced phrase instances" in
  180390. ** a single column of the current row. If the phrase instances in the
  180391. ** column being considered do not overlap, this object simply iterates
  180392. ** through them. Or, if they do overlap (share one or more tokens in
  180393. ** common), each set of overlapping instances is treated as a single
  180394. ** match. See documentation for the highlight() auxiliary function for
  180395. ** details.
  180396. **
  180397. ** Usage is:
  180398. **
  180399. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  180400. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  180401. ** rc = fts5CInstIterNext(&iter)
  180402. ** ){
  180403. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  180404. ** }
  180405. **
  180406. */
  180407. typedef struct CInstIter CInstIter;
  180408. struct CInstIter {
  180409. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  180410. Fts5Context *pFts; /* First arg to pass to pApi functions */
  180411. int iCol; /* Column to search */
  180412. int iInst; /* Next phrase instance index */
  180413. int nInst; /* Total number of phrase instances */
  180414. /* Output variables */
  180415. int iStart; /* First token in coalesced phrase instance */
  180416. int iEnd; /* Last token in coalesced phrase instance */
  180417. };
  180418. /*
  180419. ** Advance the iterator to the next coalesced phrase instance. Return
  180420. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  180421. */
  180422. static int fts5CInstIterNext(CInstIter *pIter){
  180423. int rc = SQLITE_OK;
  180424. pIter->iStart = -1;
  180425. pIter->iEnd = -1;
  180426. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  180427. int ip; int ic; int io;
  180428. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  180429. if( rc==SQLITE_OK ){
  180430. if( ic==pIter->iCol ){
  180431. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  180432. if( pIter->iStart<0 ){
  180433. pIter->iStart = io;
  180434. pIter->iEnd = iEnd;
  180435. }else if( io<=pIter->iEnd ){
  180436. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  180437. }else{
  180438. break;
  180439. }
  180440. }
  180441. pIter->iInst++;
  180442. }
  180443. }
  180444. return rc;
  180445. }
  180446. /*
  180447. ** Initialize the iterator object indicated by the final parameter to
  180448. ** iterate through coalesced phrase instances in column iCol.
  180449. */
  180450. static int fts5CInstIterInit(
  180451. const Fts5ExtensionApi *pApi,
  180452. Fts5Context *pFts,
  180453. int iCol,
  180454. CInstIter *pIter
  180455. ){
  180456. int rc;
  180457. memset(pIter, 0, sizeof(CInstIter));
  180458. pIter->pApi = pApi;
  180459. pIter->pFts = pFts;
  180460. pIter->iCol = iCol;
  180461. rc = pApi->xInstCount(pFts, &pIter->nInst);
  180462. if( rc==SQLITE_OK ){
  180463. rc = fts5CInstIterNext(pIter);
  180464. }
  180465. return rc;
  180466. }
  180467. /*************************************************************************
  180468. ** Start of highlight() implementation.
  180469. */
  180470. typedef struct HighlightContext HighlightContext;
  180471. struct HighlightContext {
  180472. CInstIter iter; /* Coalesced Instance Iterator */
  180473. int iPos; /* Current token offset in zIn[] */
  180474. int iRangeStart; /* First token to include */
  180475. int iRangeEnd; /* If non-zero, last token to include */
  180476. const char *zOpen; /* Opening highlight */
  180477. const char *zClose; /* Closing highlight */
  180478. const char *zIn; /* Input text */
  180479. int nIn; /* Size of input text in bytes */
  180480. int iOff; /* Current offset within zIn[] */
  180481. char *zOut; /* Output value */
  180482. };
  180483. /*
  180484. ** Append text to the HighlightContext output string - p->zOut. Argument
  180485. ** z points to a buffer containing n bytes of text to append. If n is
  180486. ** negative, everything up until the first '\0' is appended to the output.
  180487. **
  180488. ** If *pRc is set to any value other than SQLITE_OK when this function is
  180489. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  180490. ** *pRc is set to an error code before returning.
  180491. */
  180492. static void fts5HighlightAppend(
  180493. int *pRc,
  180494. HighlightContext *p,
  180495. const char *z, int n
  180496. ){
  180497. if( *pRc==SQLITE_OK ){
  180498. if( n<0 ) n = (int)strlen(z);
  180499. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  180500. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  180501. }
  180502. }
  180503. /*
  180504. ** Tokenizer callback used by implementation of highlight() function.
  180505. */
  180506. static int fts5HighlightCb(
  180507. void *pContext, /* Pointer to HighlightContext object */
  180508. int tflags, /* Mask of FTS5_TOKEN_* flags */
  180509. const char *pToken, /* Buffer containing token */
  180510. int nToken, /* Size of token in bytes */
  180511. int iStartOff, /* Start offset of token */
  180512. int iEndOff /* End offset of token */
  180513. ){
  180514. HighlightContext *p = (HighlightContext*)pContext;
  180515. int rc = SQLITE_OK;
  180516. int iPos;
  180517. UNUSED_PARAM2(pToken, nToken);
  180518. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  180519. iPos = p->iPos++;
  180520. if( p->iRangeEnd>0 ){
  180521. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  180522. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  180523. }
  180524. if( iPos==p->iter.iStart ){
  180525. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  180526. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  180527. p->iOff = iStartOff;
  180528. }
  180529. if( iPos==p->iter.iEnd ){
  180530. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  180531. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  180532. }
  180533. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  180534. fts5HighlightAppend(&rc, p, p->zClose, -1);
  180535. p->iOff = iEndOff;
  180536. if( rc==SQLITE_OK ){
  180537. rc = fts5CInstIterNext(&p->iter);
  180538. }
  180539. }
  180540. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  180541. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  180542. p->iOff = iEndOff;
  180543. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  180544. fts5HighlightAppend(&rc, p, p->zClose, -1);
  180545. }
  180546. }
  180547. return rc;
  180548. }
  180549. /*
  180550. ** Implementation of highlight() function.
  180551. */
  180552. static void fts5HighlightFunction(
  180553. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  180554. Fts5Context *pFts, /* First arg to pass to pApi functions */
  180555. sqlite3_context *pCtx, /* Context for returning result/error */
  180556. int nVal, /* Number of values in apVal[] array */
  180557. sqlite3_value **apVal /* Array of trailing arguments */
  180558. ){
  180559. HighlightContext ctx;
  180560. int rc;
  180561. int iCol;
  180562. if( nVal!=3 ){
  180563. const char *zErr = "wrong number of arguments to function highlight()";
  180564. sqlite3_result_error(pCtx, zErr, -1);
  180565. return;
  180566. }
  180567. iCol = sqlite3_value_int(apVal[0]);
  180568. memset(&ctx, 0, sizeof(HighlightContext));
  180569. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  180570. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  180571. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  180572. if( ctx.zIn ){
  180573. if( rc==SQLITE_OK ){
  180574. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  180575. }
  180576. if( rc==SQLITE_OK ){
  180577. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  180578. }
  180579. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  180580. if( rc==SQLITE_OK ){
  180581. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  180582. }
  180583. sqlite3_free(ctx.zOut);
  180584. }
  180585. if( rc!=SQLITE_OK ){
  180586. sqlite3_result_error_code(pCtx, rc);
  180587. }
  180588. }
  180589. /*
  180590. ** End of highlight() implementation.
  180591. **************************************************************************/
  180592. /*
  180593. ** Context object passed to the fts5SentenceFinderCb() function.
  180594. */
  180595. typedef struct Fts5SFinder Fts5SFinder;
  180596. struct Fts5SFinder {
  180597. int iPos; /* Current token position */
  180598. int nFirstAlloc; /* Allocated size of aFirst[] */
  180599. int nFirst; /* Number of entries in aFirst[] */
  180600. int *aFirst; /* Array of first token in each sentence */
  180601. const char *zDoc; /* Document being tokenized */
  180602. };
  180603. /*
  180604. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  180605. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  180606. ** error occurs.
  180607. */
  180608. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  180609. if( p->nFirstAlloc==p->nFirst ){
  180610. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  180611. int *aNew;
  180612. aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
  180613. if( aNew==0 ) return SQLITE_NOMEM;
  180614. p->aFirst = aNew;
  180615. p->nFirstAlloc = nNew;
  180616. }
  180617. p->aFirst[p->nFirst++] = iAdd;
  180618. return SQLITE_OK;
  180619. }
  180620. /*
  180621. ** This function is an xTokenize() callback used by the auxiliary snippet()
  180622. ** function. Its job is to identify tokens that are the first in a sentence.
  180623. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  180624. */
  180625. static int fts5SentenceFinderCb(
  180626. void *pContext, /* Pointer to HighlightContext object */
  180627. int tflags, /* Mask of FTS5_TOKEN_* flags */
  180628. const char *pToken, /* Buffer containing token */
  180629. int nToken, /* Size of token in bytes */
  180630. int iStartOff, /* Start offset of token */
  180631. int iEndOff /* End offset of token */
  180632. ){
  180633. int rc = SQLITE_OK;
  180634. UNUSED_PARAM2(pToken, nToken);
  180635. UNUSED_PARAM(iEndOff);
  180636. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  180637. Fts5SFinder *p = (Fts5SFinder*)pContext;
  180638. if( p->iPos>0 ){
  180639. int i;
  180640. char c = 0;
  180641. for(i=iStartOff-1; i>=0; i--){
  180642. c = p->zDoc[i];
  180643. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  180644. }
  180645. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  180646. rc = fts5SentenceFinderAdd(p, p->iPos);
  180647. }
  180648. }else{
  180649. rc = fts5SentenceFinderAdd(p, 0);
  180650. }
  180651. p->iPos++;
  180652. }
  180653. return rc;
  180654. }
  180655. static int fts5SnippetScore(
  180656. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  180657. Fts5Context *pFts, /* First arg to pass to pApi functions */
  180658. int nDocsize, /* Size of column in tokens */
  180659. unsigned char *aSeen, /* Array with one element per query phrase */
  180660. int iCol, /* Column to score */
  180661. int iPos, /* Starting offset to score */
  180662. int nToken, /* Max tokens per snippet */
  180663. int *pnScore, /* OUT: Score */
  180664. int *piPos /* OUT: Adjusted offset */
  180665. ){
  180666. int rc;
  180667. int i;
  180668. int ip = 0;
  180669. int ic = 0;
  180670. int iOff = 0;
  180671. int iFirst = -1;
  180672. int nInst;
  180673. int nScore = 0;
  180674. int iLast = 0;
  180675. rc = pApi->xInstCount(pFts, &nInst);
  180676. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  180677. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  180678. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
  180679. nScore += (aSeen[ip] ? 1 : 1000);
  180680. aSeen[ip] = 1;
  180681. if( iFirst<0 ) iFirst = iOff;
  180682. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  180683. }
  180684. }
  180685. *pnScore = nScore;
  180686. if( piPos ){
  180687. int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  180688. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  180689. if( iAdj<0 ) iAdj = 0;
  180690. *piPos = iAdj;
  180691. }
  180692. return rc;
  180693. }
  180694. /*
  180695. ** Return the value in pVal interpreted as utf-8 text. Except, if pVal
  180696. ** contains a NULL value, return a pointer to a static string zero
  180697. ** bytes in length instead of a NULL pointer.
  180698. */
  180699. static const char *fts5ValueToText(sqlite3_value *pVal){
  180700. const char *zRet = (const char*)sqlite3_value_text(pVal);
  180701. return zRet ? zRet : "";
  180702. }
  180703. /*
  180704. ** Implementation of snippet() function.
  180705. */
  180706. static void fts5SnippetFunction(
  180707. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  180708. Fts5Context *pFts, /* First arg to pass to pApi functions */
  180709. sqlite3_context *pCtx, /* Context for returning result/error */
  180710. int nVal, /* Number of values in apVal[] array */
  180711. sqlite3_value **apVal /* Array of trailing arguments */
  180712. ){
  180713. HighlightContext ctx;
  180714. int rc = SQLITE_OK; /* Return code */
  180715. int iCol; /* 1st argument to snippet() */
  180716. const char *zEllips; /* 4th argument to snippet() */
  180717. int nToken; /* 5th argument to snippet() */
  180718. int nInst = 0; /* Number of instance matches this row */
  180719. int i; /* Used to iterate through instances */
  180720. int nPhrase; /* Number of phrases in query */
  180721. unsigned char *aSeen; /* Array of "seen instance" flags */
  180722. int iBestCol; /* Column containing best snippet */
  180723. int iBestStart = 0; /* First token of best snippet */
  180724. int nBestScore = 0; /* Score of best snippet */
  180725. int nColSize = 0; /* Total size of iBestCol in tokens */
  180726. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  180727. int nCol;
  180728. if( nVal!=5 ){
  180729. const char *zErr = "wrong number of arguments to function snippet()";
  180730. sqlite3_result_error(pCtx, zErr, -1);
  180731. return;
  180732. }
  180733. nCol = pApi->xColumnCount(pFts);
  180734. memset(&ctx, 0, sizeof(HighlightContext));
  180735. iCol = sqlite3_value_int(apVal[0]);
  180736. ctx.zOpen = fts5ValueToText(apVal[1]);
  180737. ctx.zClose = fts5ValueToText(apVal[2]);
  180738. zEllips = fts5ValueToText(apVal[3]);
  180739. nToken = sqlite3_value_int(apVal[4]);
  180740. iBestCol = (iCol>=0 ? iCol : 0);
  180741. nPhrase = pApi->xPhraseCount(pFts);
  180742. aSeen = sqlite3_malloc(nPhrase);
  180743. if( aSeen==0 ){
  180744. rc = SQLITE_NOMEM;
  180745. }
  180746. if( rc==SQLITE_OK ){
  180747. rc = pApi->xInstCount(pFts, &nInst);
  180748. }
  180749. memset(&sFinder, 0, sizeof(Fts5SFinder));
  180750. for(i=0; i<nCol; i++){
  180751. if( iCol<0 || iCol==i ){
  180752. int nDoc;
  180753. int nDocsize;
  180754. int ii;
  180755. sFinder.iPos = 0;
  180756. sFinder.nFirst = 0;
  180757. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  180758. if( rc!=SQLITE_OK ) break;
  180759. rc = pApi->xTokenize(pFts,
  180760. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  180761. );
  180762. if( rc!=SQLITE_OK ) break;
  180763. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  180764. if( rc!=SQLITE_OK ) break;
  180765. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  180766. int ip, ic, io;
  180767. int iAdj;
  180768. int nScore;
  180769. int jj;
  180770. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  180771. if( ic!=i || rc!=SQLITE_OK ) continue;
  180772. memset(aSeen, 0, nPhrase);
  180773. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  180774. io, nToken, &nScore, &iAdj
  180775. );
  180776. if( rc==SQLITE_OK && nScore>nBestScore ){
  180777. nBestScore = nScore;
  180778. iBestCol = i;
  180779. iBestStart = iAdj;
  180780. nColSize = nDocsize;
  180781. }
  180782. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  180783. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  180784. if( sFinder.aFirst[jj+1]>io ) break;
  180785. }
  180786. if( sFinder.aFirst[jj]<io ){
  180787. memset(aSeen, 0, nPhrase);
  180788. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  180789. sFinder.aFirst[jj], nToken, &nScore, 0
  180790. );
  180791. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  180792. if( rc==SQLITE_OK && nScore>nBestScore ){
  180793. nBestScore = nScore;
  180794. iBestCol = i;
  180795. iBestStart = sFinder.aFirst[jj];
  180796. nColSize = nDocsize;
  180797. }
  180798. }
  180799. }
  180800. }
  180801. }
  180802. }
  180803. if( rc==SQLITE_OK ){
  180804. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  180805. }
  180806. if( rc==SQLITE_OK && nColSize==0 ){
  180807. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  180808. }
  180809. if( ctx.zIn ){
  180810. if( rc==SQLITE_OK ){
  180811. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  180812. }
  180813. ctx.iRangeStart = iBestStart;
  180814. ctx.iRangeEnd = iBestStart + nToken - 1;
  180815. if( iBestStart>0 ){
  180816. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  180817. }
  180818. /* Advance iterator ctx.iter so that it points to the first coalesced
  180819. ** phrase instance at or following position iBestStart. */
  180820. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  180821. rc = fts5CInstIterNext(&ctx.iter);
  180822. }
  180823. if( rc==SQLITE_OK ){
  180824. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  180825. }
  180826. if( ctx.iRangeEnd>=(nColSize-1) ){
  180827. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  180828. }else{
  180829. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  180830. }
  180831. }
  180832. if( rc==SQLITE_OK ){
  180833. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  180834. }else{
  180835. sqlite3_result_error_code(pCtx, rc);
  180836. }
  180837. sqlite3_free(ctx.zOut);
  180838. sqlite3_free(aSeen);
  180839. sqlite3_free(sFinder.aFirst);
  180840. }
  180841. /************************************************************************/
  180842. /*
  180843. ** The first time the bm25() function is called for a query, an instance
  180844. ** of the following structure is allocated and populated.
  180845. */
  180846. typedef struct Fts5Bm25Data Fts5Bm25Data;
  180847. struct Fts5Bm25Data {
  180848. int nPhrase; /* Number of phrases in query */
  180849. double avgdl; /* Average number of tokens in each row */
  180850. double *aIDF; /* IDF for each phrase */
  180851. double *aFreq; /* Array used to calculate phrase freq. */
  180852. };
  180853. /*
  180854. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  180855. ** table matched by each individual phrase within the query.
  180856. */
  180857. static int fts5CountCb(
  180858. const Fts5ExtensionApi *pApi,
  180859. Fts5Context *pFts,
  180860. void *pUserData /* Pointer to sqlite3_int64 variable */
  180861. ){
  180862. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  180863. UNUSED_PARAM2(pApi, pFts);
  180864. (*pn)++;
  180865. return SQLITE_OK;
  180866. }
  180867. /*
  180868. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  180869. ** If the object has not already been allocated, allocate and populate it
  180870. ** now.
  180871. */
  180872. static int fts5Bm25GetData(
  180873. const Fts5ExtensionApi *pApi,
  180874. Fts5Context *pFts,
  180875. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  180876. ){
  180877. int rc = SQLITE_OK; /* Return code */
  180878. Fts5Bm25Data *p; /* Object to return */
  180879. p = pApi->xGetAuxdata(pFts, 0);
  180880. if( p==0 ){
  180881. int nPhrase; /* Number of phrases in query */
  180882. sqlite3_int64 nRow = 0; /* Number of rows in table */
  180883. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  180884. int nByte; /* Bytes of space to allocate */
  180885. int i;
  180886. /* Allocate the Fts5Bm25Data object */
  180887. nPhrase = pApi->xPhraseCount(pFts);
  180888. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  180889. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  180890. if( p==0 ){
  180891. rc = SQLITE_NOMEM;
  180892. }else{
  180893. memset(p, 0, nByte);
  180894. p->nPhrase = nPhrase;
  180895. p->aIDF = (double*)&p[1];
  180896. p->aFreq = &p->aIDF[nPhrase];
  180897. }
  180898. /* Calculate the average document length for this FTS5 table */
  180899. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  180900. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  180901. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  180902. /* Calculate an IDF for each phrase in the query */
  180903. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  180904. sqlite3_int64 nHit = 0;
  180905. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  180906. if( rc==SQLITE_OK ){
  180907. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  180908. ** This is done using the standard BM25 formula as found on wikipedia:
  180909. **
  180910. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  180911. **
  180912. ** where "N" is the total number of documents in the set and nHit
  180913. ** is the number that contain at least one instance of the phrase
  180914. ** under consideration.
  180915. **
  180916. ** The problem with this is that if (N < 2*nHit), the IDF is
  180917. ** negative. Which is undesirable. So the mimimum allowable IDF is
  180918. ** (1e-6) - roughly the same as a term that appears in just over
  180919. ** half of set of 5,000,000 documents. */
  180920. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  180921. if( idf<=0.0 ) idf = 1e-6;
  180922. p->aIDF[i] = idf;
  180923. }
  180924. }
  180925. if( rc!=SQLITE_OK ){
  180926. sqlite3_free(p);
  180927. }else{
  180928. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  180929. }
  180930. if( rc!=SQLITE_OK ) p = 0;
  180931. }
  180932. *ppData = p;
  180933. return rc;
  180934. }
  180935. /*
  180936. ** Implementation of bm25() function.
  180937. */
  180938. static void fts5Bm25Function(
  180939. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  180940. Fts5Context *pFts, /* First arg to pass to pApi functions */
  180941. sqlite3_context *pCtx, /* Context for returning result/error */
  180942. int nVal, /* Number of values in apVal[] array */
  180943. sqlite3_value **apVal /* Array of trailing arguments */
  180944. ){
  180945. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  180946. const double b = 0.75; /* Constant "b" from BM25 formula */
  180947. int rc = SQLITE_OK; /* Error code */
  180948. double score = 0.0; /* SQL function return value */
  180949. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  180950. int i; /* Iterator variable */
  180951. int nInst = 0; /* Value returned by xInstCount() */
  180952. double D = 0.0; /* Total number of tokens in row */
  180953. double *aFreq = 0; /* Array of phrase freq. for current row */
  180954. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  180955. ** for each phrase in the query for the current row. */
  180956. rc = fts5Bm25GetData(pApi, pFts, &pData);
  180957. if( rc==SQLITE_OK ){
  180958. aFreq = pData->aFreq;
  180959. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  180960. rc = pApi->xInstCount(pFts, &nInst);
  180961. }
  180962. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  180963. int ip; int ic; int io;
  180964. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  180965. if( rc==SQLITE_OK ){
  180966. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  180967. aFreq[ip] += w;
  180968. }
  180969. }
  180970. /* Figure out the total size of the current row in tokens. */
  180971. if( rc==SQLITE_OK ){
  180972. int nTok;
  180973. rc = pApi->xColumnSize(pFts, -1, &nTok);
  180974. D = (double)nTok;
  180975. }
  180976. /* Determine the BM25 score for the current row. */
  180977. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  180978. score += pData->aIDF[i] * (
  180979. ( aFreq[i] * (k1 + 1.0) ) /
  180980. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  180981. );
  180982. }
  180983. /* If no error has occurred, return the calculated score. Otherwise,
  180984. ** throw an SQL exception. */
  180985. if( rc==SQLITE_OK ){
  180986. sqlite3_result_double(pCtx, -1.0 * score);
  180987. }else{
  180988. sqlite3_result_error_code(pCtx, rc);
  180989. }
  180990. }
  180991. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  180992. struct Builtin {
  180993. const char *zFunc; /* Function name (nul-terminated) */
  180994. void *pUserData; /* User-data pointer */
  180995. fts5_extension_function xFunc;/* Callback function */
  180996. void (*xDestroy)(void*); /* Destructor function */
  180997. } aBuiltin [] = {
  180998. { "snippet", 0, fts5SnippetFunction, 0 },
  180999. { "highlight", 0, fts5HighlightFunction, 0 },
  181000. { "bm25", 0, fts5Bm25Function, 0 },
  181001. };
  181002. int rc = SQLITE_OK; /* Return code */
  181003. int i; /* To iterate through builtin functions */
  181004. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  181005. rc = pApi->xCreateFunction(pApi,
  181006. aBuiltin[i].zFunc,
  181007. aBuiltin[i].pUserData,
  181008. aBuiltin[i].xFunc,
  181009. aBuiltin[i].xDestroy
  181010. );
  181011. }
  181012. return rc;
  181013. }
  181014. /*
  181015. ** 2014 May 31
  181016. **
  181017. ** The author disclaims copyright to this source code. In place of
  181018. ** a legal notice, here is a blessing:
  181019. **
  181020. ** May you do good and not evil.
  181021. ** May you find forgiveness for yourself and forgive others.
  181022. ** May you share freely, never taking more than you give.
  181023. **
  181024. ******************************************************************************
  181025. */
  181026. /* #include "fts5Int.h" */
  181027. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  181028. if( (u32)pBuf->nSpace<nByte ){
  181029. u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  181030. u8 *pNew;
  181031. while( nNew<nByte ){
  181032. nNew = nNew * 2;
  181033. }
  181034. pNew = sqlite3_realloc(pBuf->p, nNew);
  181035. if( pNew==0 ){
  181036. *pRc = SQLITE_NOMEM;
  181037. return 1;
  181038. }else{
  181039. pBuf->nSpace = nNew;
  181040. pBuf->p = pNew;
  181041. }
  181042. }
  181043. return 0;
  181044. }
  181045. /*
  181046. ** Encode value iVal as an SQLite varint and append it to the buffer object
  181047. ** pBuf. If an OOM error occurs, set the error code in p.
  181048. */
  181049. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  181050. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  181051. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  181052. }
  181053. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  181054. aBuf[0] = (iVal>>24) & 0x00FF;
  181055. aBuf[1] = (iVal>>16) & 0x00FF;
  181056. aBuf[2] = (iVal>> 8) & 0x00FF;
  181057. aBuf[3] = (iVal>> 0) & 0x00FF;
  181058. }
  181059. static int sqlite3Fts5Get32(const u8 *aBuf){
  181060. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  181061. }
  181062. /*
  181063. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  181064. ** the error code in p. If an error has already occurred when this function
  181065. ** is called, it is a no-op.
  181066. */
  181067. static void sqlite3Fts5BufferAppendBlob(
  181068. int *pRc,
  181069. Fts5Buffer *pBuf,
  181070. u32 nData,
  181071. const u8 *pData
  181072. ){
  181073. assert_nc( *pRc || nData>=0 );
  181074. if( nData ){
  181075. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  181076. memcpy(&pBuf->p[pBuf->n], pData, nData);
  181077. pBuf->n += nData;
  181078. }
  181079. }
  181080. /*
  181081. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  181082. ** ensures that the byte following the buffer data is set to 0x00, even
  181083. ** though this byte is not included in the pBuf->n count.
  181084. */
  181085. static void sqlite3Fts5BufferAppendString(
  181086. int *pRc,
  181087. Fts5Buffer *pBuf,
  181088. const char *zStr
  181089. ){
  181090. int nStr = (int)strlen(zStr);
  181091. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  181092. pBuf->n--;
  181093. }
  181094. /*
  181095. ** Argument zFmt is a printf() style format string. This function performs
  181096. ** the printf() style processing, then appends the results to buffer pBuf.
  181097. **
  181098. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  181099. ** following the buffer data is set to 0x00, even though this byte is not
  181100. ** included in the pBuf->n count.
  181101. */
  181102. static void sqlite3Fts5BufferAppendPrintf(
  181103. int *pRc,
  181104. Fts5Buffer *pBuf,
  181105. char *zFmt, ...
  181106. ){
  181107. if( *pRc==SQLITE_OK ){
  181108. char *zTmp;
  181109. va_list ap;
  181110. va_start(ap, zFmt);
  181111. zTmp = sqlite3_vmprintf(zFmt, ap);
  181112. va_end(ap);
  181113. if( zTmp==0 ){
  181114. *pRc = SQLITE_NOMEM;
  181115. }else{
  181116. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  181117. sqlite3_free(zTmp);
  181118. }
  181119. }
  181120. }
  181121. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  181122. char *zRet = 0;
  181123. if( *pRc==SQLITE_OK ){
  181124. va_list ap;
  181125. va_start(ap, zFmt);
  181126. zRet = sqlite3_vmprintf(zFmt, ap);
  181127. va_end(ap);
  181128. if( zRet==0 ){
  181129. *pRc = SQLITE_NOMEM;
  181130. }
  181131. }
  181132. return zRet;
  181133. }
  181134. /*
  181135. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  181136. */
  181137. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  181138. sqlite3_free(pBuf->p);
  181139. memset(pBuf, 0, sizeof(Fts5Buffer));
  181140. }
  181141. /*
  181142. ** Zero the contents of the buffer object. But do not free the associated
  181143. ** memory allocation.
  181144. */
  181145. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  181146. pBuf->n = 0;
  181147. }
  181148. /*
  181149. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  181150. ** the error code in p. If an error has already occurred when this function
  181151. ** is called, it is a no-op.
  181152. */
  181153. static void sqlite3Fts5BufferSet(
  181154. int *pRc,
  181155. Fts5Buffer *pBuf,
  181156. int nData,
  181157. const u8 *pData
  181158. ){
  181159. pBuf->n = 0;
  181160. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  181161. }
  181162. static int sqlite3Fts5PoslistNext64(
  181163. const u8 *a, int n, /* Buffer containing poslist */
  181164. int *pi, /* IN/OUT: Offset within a[] */
  181165. i64 *piOff /* IN/OUT: Current offset */
  181166. ){
  181167. int i = *pi;
  181168. if( i>=n ){
  181169. /* EOF */
  181170. *piOff = -1;
  181171. return 1;
  181172. }else{
  181173. i64 iOff = *piOff;
  181174. int iVal;
  181175. fts5FastGetVarint32(a, i, iVal);
  181176. if( iVal==1 ){
  181177. fts5FastGetVarint32(a, i, iVal);
  181178. iOff = ((i64)iVal) << 32;
  181179. fts5FastGetVarint32(a, i, iVal);
  181180. }
  181181. *piOff = iOff + (iVal-2);
  181182. *pi = i;
  181183. return 0;
  181184. }
  181185. }
  181186. /*
  181187. ** Advance the iterator object passed as the only argument. Return true
  181188. ** if the iterator reaches EOF, or false otherwise.
  181189. */
  181190. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  181191. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  181192. pIter->bEof = 1;
  181193. }
  181194. return pIter->bEof;
  181195. }
  181196. static int sqlite3Fts5PoslistReaderInit(
  181197. const u8 *a, int n, /* Poslist buffer to iterate through */
  181198. Fts5PoslistReader *pIter /* Iterator object to initialize */
  181199. ){
  181200. memset(pIter, 0, sizeof(*pIter));
  181201. pIter->a = a;
  181202. pIter->n = n;
  181203. sqlite3Fts5PoslistReaderNext(pIter);
  181204. return pIter->bEof;
  181205. }
  181206. /*
  181207. ** Append position iPos to the position list being accumulated in buffer
  181208. ** pBuf, which must be already be large enough to hold the new data.
  181209. ** The previous position written to this list is *piPrev. *piPrev is set
  181210. ** to iPos before returning.
  181211. */
  181212. static void sqlite3Fts5PoslistSafeAppend(
  181213. Fts5Buffer *pBuf,
  181214. i64 *piPrev,
  181215. i64 iPos
  181216. ){
  181217. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  181218. if( (iPos & colmask) != (*piPrev & colmask) ){
  181219. pBuf->p[pBuf->n++] = 1;
  181220. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  181221. *piPrev = (iPos & colmask);
  181222. }
  181223. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  181224. *piPrev = iPos;
  181225. }
  181226. static int sqlite3Fts5PoslistWriterAppend(
  181227. Fts5Buffer *pBuf,
  181228. Fts5PoslistWriter *pWriter,
  181229. i64 iPos
  181230. ){
  181231. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  181232. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  181233. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  181234. return SQLITE_OK;
  181235. }
  181236. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  181237. void *pRet = 0;
  181238. if( *pRc==SQLITE_OK ){
  181239. pRet = sqlite3_malloc(nByte);
  181240. if( pRet==0 ){
  181241. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  181242. }else{
  181243. memset(pRet, 0, nByte);
  181244. }
  181245. }
  181246. return pRet;
  181247. }
  181248. /*
  181249. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  181250. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  181251. ** the length of the string is determined using strlen().
  181252. **
  181253. ** It is the responsibility of the caller to eventually free the returned
  181254. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  181255. */
  181256. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  181257. char *zRet = 0;
  181258. if( *pRc==SQLITE_OK ){
  181259. if( nIn<0 ){
  181260. nIn = (int)strlen(pIn);
  181261. }
  181262. zRet = (char*)sqlite3_malloc(nIn+1);
  181263. if( zRet ){
  181264. memcpy(zRet, pIn, nIn);
  181265. zRet[nIn] = '\0';
  181266. }else{
  181267. *pRc = SQLITE_NOMEM;
  181268. }
  181269. }
  181270. return zRet;
  181271. }
  181272. /*
  181273. ** Return true if character 't' may be part of an FTS5 bareword, or false
  181274. ** otherwise. Characters that may be part of barewords:
  181275. **
  181276. ** * All non-ASCII characters,
  181277. ** * The 52 upper and lower case ASCII characters, and
  181278. ** * The 10 integer ASCII characters.
  181279. ** * The underscore character "_" (0x5F).
  181280. ** * The unicode "subsitute" character (0x1A).
  181281. */
  181282. static int sqlite3Fts5IsBareword(char t){
  181283. u8 aBareword[128] = {
  181284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  181285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  181286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  181287. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  181288. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  181289. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  181290. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  181291. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  181292. };
  181293. return (t & 0x80) || aBareword[(int)t];
  181294. }
  181295. /*************************************************************************
  181296. */
  181297. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  181298. struct Fts5TermsetEntry {
  181299. char *pTerm;
  181300. int nTerm;
  181301. int iIdx; /* Index (main or aPrefix[] entry) */
  181302. Fts5TermsetEntry *pNext;
  181303. };
  181304. struct Fts5Termset {
  181305. Fts5TermsetEntry *apHash[512];
  181306. };
  181307. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  181308. int rc = SQLITE_OK;
  181309. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  181310. return rc;
  181311. }
  181312. static int sqlite3Fts5TermsetAdd(
  181313. Fts5Termset *p,
  181314. int iIdx,
  181315. const char *pTerm, int nTerm,
  181316. int *pbPresent
  181317. ){
  181318. int rc = SQLITE_OK;
  181319. *pbPresent = 0;
  181320. if( p ){
  181321. int i;
  181322. u32 hash = 13;
  181323. Fts5TermsetEntry *pEntry;
  181324. /* Calculate a hash value for this term. This is the same hash checksum
  181325. ** used by the fts5_hash.c module. This is not important for correct
  181326. ** operation of the module, but is necessary to ensure that some tests
  181327. ** designed to produce hash table collisions really do work. */
  181328. for(i=nTerm-1; i>=0; i--){
  181329. hash = (hash << 3) ^ hash ^ pTerm[i];
  181330. }
  181331. hash = (hash << 3) ^ hash ^ iIdx;
  181332. hash = hash % ArraySize(p->apHash);
  181333. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  181334. if( pEntry->iIdx==iIdx
  181335. && pEntry->nTerm==nTerm
  181336. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  181337. ){
  181338. *pbPresent = 1;
  181339. break;
  181340. }
  181341. }
  181342. if( pEntry==0 ){
  181343. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  181344. if( pEntry ){
  181345. pEntry->pTerm = (char*)&pEntry[1];
  181346. pEntry->nTerm = nTerm;
  181347. pEntry->iIdx = iIdx;
  181348. memcpy(pEntry->pTerm, pTerm, nTerm);
  181349. pEntry->pNext = p->apHash[hash];
  181350. p->apHash[hash] = pEntry;
  181351. }
  181352. }
  181353. }
  181354. return rc;
  181355. }
  181356. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  181357. if( p ){
  181358. u32 i;
  181359. for(i=0; i<ArraySize(p->apHash); i++){
  181360. Fts5TermsetEntry *pEntry = p->apHash[i];
  181361. while( pEntry ){
  181362. Fts5TermsetEntry *pDel = pEntry;
  181363. pEntry = pEntry->pNext;
  181364. sqlite3_free(pDel);
  181365. }
  181366. }
  181367. sqlite3_free(p);
  181368. }
  181369. }
  181370. /*
  181371. ** 2014 Jun 09
  181372. **
  181373. ** The author disclaims copyright to this source code. In place of
  181374. ** a legal notice, here is a blessing:
  181375. **
  181376. ** May you do good and not evil.
  181377. ** May you find forgiveness for yourself and forgive others.
  181378. ** May you share freely, never taking more than you give.
  181379. **
  181380. ******************************************************************************
  181381. **
  181382. ** This is an SQLite module implementing full-text search.
  181383. */
  181384. /* #include "fts5Int.h" */
  181385. #define FTS5_DEFAULT_PAGE_SIZE 4050
  181386. #define FTS5_DEFAULT_AUTOMERGE 4
  181387. #define FTS5_DEFAULT_USERMERGE 4
  181388. #define FTS5_DEFAULT_CRISISMERGE 16
  181389. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  181390. /* Maximum allowed page size */
  181391. #define FTS5_MAX_PAGE_SIZE (128*1024)
  181392. static int fts5_iswhitespace(char x){
  181393. return (x==' ');
  181394. }
  181395. static int fts5_isopenquote(char x){
  181396. return (x=='"' || x=='\'' || x=='[' || x=='`');
  181397. }
  181398. /*
  181399. ** Argument pIn points to a character that is part of a nul-terminated
  181400. ** string. Return a pointer to the first character following *pIn in
  181401. ** the string that is not a white-space character.
  181402. */
  181403. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  181404. const char *p = pIn;
  181405. if( p ){
  181406. while( fts5_iswhitespace(*p) ){ p++; }
  181407. }
  181408. return p;
  181409. }
  181410. /*
  181411. ** Argument pIn points to a character that is part of a nul-terminated
  181412. ** string. Return a pointer to the first character following *pIn in
  181413. ** the string that is not a "bareword" character.
  181414. */
  181415. static const char *fts5ConfigSkipBareword(const char *pIn){
  181416. const char *p = pIn;
  181417. while ( sqlite3Fts5IsBareword(*p) ) p++;
  181418. if( p==pIn ) p = 0;
  181419. return p;
  181420. }
  181421. static int fts5_isdigit(char a){
  181422. return (a>='0' && a<='9');
  181423. }
  181424. static const char *fts5ConfigSkipLiteral(const char *pIn){
  181425. const char *p = pIn;
  181426. switch( *p ){
  181427. case 'n': case 'N':
  181428. if( sqlite3_strnicmp("null", p, 4)==0 ){
  181429. p = &p[4];
  181430. }else{
  181431. p = 0;
  181432. }
  181433. break;
  181434. case 'x': case 'X':
  181435. p++;
  181436. if( *p=='\'' ){
  181437. p++;
  181438. while( (*p>='a' && *p<='f')
  181439. || (*p>='A' && *p<='F')
  181440. || (*p>='0' && *p<='9')
  181441. ){
  181442. p++;
  181443. }
  181444. if( *p=='\'' && 0==((p-pIn)%2) ){
  181445. p++;
  181446. }else{
  181447. p = 0;
  181448. }
  181449. }else{
  181450. p = 0;
  181451. }
  181452. break;
  181453. case '\'':
  181454. p++;
  181455. while( p ){
  181456. if( *p=='\'' ){
  181457. p++;
  181458. if( *p!='\'' ) break;
  181459. }
  181460. p++;
  181461. if( *p==0 ) p = 0;
  181462. }
  181463. break;
  181464. default:
  181465. /* maybe a number */
  181466. if( *p=='+' || *p=='-' ) p++;
  181467. while( fts5_isdigit(*p) ) p++;
  181468. /* At this point, if the literal was an integer, the parse is
  181469. ** finished. Or, if it is a floating point value, it may continue
  181470. ** with either a decimal point or an 'E' character. */
  181471. if( *p=='.' && fts5_isdigit(p[1]) ){
  181472. p += 2;
  181473. while( fts5_isdigit(*p) ) p++;
  181474. }
  181475. if( p==pIn ) p = 0;
  181476. break;
  181477. }
  181478. return p;
  181479. }
  181480. /*
  181481. ** The first character of the string pointed to by argument z is guaranteed
  181482. ** to be an open-quote character (see function fts5_isopenquote()).
  181483. **
  181484. ** This function searches for the corresponding close-quote character within
  181485. ** the string and, if found, dequotes the string in place and adds a new
  181486. ** nul-terminator byte.
  181487. **
  181488. ** If the close-quote is found, the value returned is the byte offset of
  181489. ** the character immediately following it. Or, if the close-quote is not
  181490. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  181491. ** undefined state.
  181492. */
  181493. static int fts5Dequote(char *z){
  181494. char q;
  181495. int iIn = 1;
  181496. int iOut = 0;
  181497. q = z[0];
  181498. /* Set stack variable q to the close-quote character */
  181499. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  181500. if( q=='[' ) q = ']';
  181501. while( ALWAYS(z[iIn]) ){
  181502. if( z[iIn]==q ){
  181503. if( z[iIn+1]!=q ){
  181504. /* Character iIn was the close quote. */
  181505. iIn++;
  181506. break;
  181507. }else{
  181508. /* Character iIn and iIn+1 form an escaped quote character. Skip
  181509. ** the input cursor past both and copy a single quote character
  181510. ** to the output buffer. */
  181511. iIn += 2;
  181512. z[iOut++] = q;
  181513. }
  181514. }else{
  181515. z[iOut++] = z[iIn++];
  181516. }
  181517. }
  181518. z[iOut] = '\0';
  181519. return iIn;
  181520. }
  181521. /*
  181522. ** Convert an SQL-style quoted string into a normal string by removing
  181523. ** the quote characters. The conversion is done in-place. If the
  181524. ** input does not begin with a quote character, then this routine
  181525. ** is a no-op.
  181526. **
  181527. ** Examples:
  181528. **
  181529. ** "abc" becomes abc
  181530. ** 'xyz' becomes xyz
  181531. ** [pqr] becomes pqr
  181532. ** `mno` becomes mno
  181533. */
  181534. static void sqlite3Fts5Dequote(char *z){
  181535. char quote; /* Quote character (if any ) */
  181536. assert( 0==fts5_iswhitespace(z[0]) );
  181537. quote = z[0];
  181538. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  181539. fts5Dequote(z);
  181540. }
  181541. }
  181542. struct Fts5Enum {
  181543. const char *zName;
  181544. int eVal;
  181545. };
  181546. typedef struct Fts5Enum Fts5Enum;
  181547. static int fts5ConfigSetEnum(
  181548. const Fts5Enum *aEnum,
  181549. const char *zEnum,
  181550. int *peVal
  181551. ){
  181552. int nEnum = (int)strlen(zEnum);
  181553. int i;
  181554. int iVal = -1;
  181555. for(i=0; aEnum[i].zName; i++){
  181556. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  181557. if( iVal>=0 ) return SQLITE_ERROR;
  181558. iVal = aEnum[i].eVal;
  181559. }
  181560. }
  181561. *peVal = iVal;
  181562. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  181563. }
  181564. /*
  181565. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  181566. ** configuration object pConfig as appropriate.
  181567. **
  181568. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  181569. ** an error occurs, an SQLite error code is returned and an error message
  181570. ** may be left in *pzErr. It is the responsibility of the caller to
  181571. ** eventually free any such error message using sqlite3_free().
  181572. */
  181573. static int fts5ConfigParseSpecial(
  181574. Fts5Global *pGlobal,
  181575. Fts5Config *pConfig, /* Configuration object to update */
  181576. const char *zCmd, /* Special command to parse */
  181577. const char *zArg, /* Argument to parse */
  181578. char **pzErr /* OUT: Error message */
  181579. ){
  181580. int rc = SQLITE_OK;
  181581. int nCmd = (int)strlen(zCmd);
  181582. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  181583. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  181584. const char *p;
  181585. int bFirst = 1;
  181586. if( pConfig->aPrefix==0 ){
  181587. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  181588. if( rc ) return rc;
  181589. }
  181590. p = zArg;
  181591. while( 1 ){
  181592. int nPre = 0;
  181593. while( p[0]==' ' ) p++;
  181594. if( bFirst==0 && p[0]==',' ){
  181595. p++;
  181596. while( p[0]==' ' ) p++;
  181597. }else if( p[0]=='\0' ){
  181598. break;
  181599. }
  181600. if( p[0]<'0' || p[0]>'9' ){
  181601. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  181602. rc = SQLITE_ERROR;
  181603. break;
  181604. }
  181605. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  181606. *pzErr = sqlite3_mprintf(
  181607. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  181608. );
  181609. rc = SQLITE_ERROR;
  181610. break;
  181611. }
  181612. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  181613. nPre = nPre*10 + (p[0] - '0');
  181614. p++;
  181615. }
  181616. if( nPre<=0 || nPre>=1000 ){
  181617. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  181618. rc = SQLITE_ERROR;
  181619. break;
  181620. }
  181621. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  181622. pConfig->nPrefix++;
  181623. bFirst = 0;
  181624. }
  181625. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  181626. return rc;
  181627. }
  181628. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  181629. const char *p = (const char*)zArg;
  181630. int nArg = (int)strlen(zArg) + 1;
  181631. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  181632. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  181633. char *pSpace = pDel;
  181634. if( azArg && pSpace ){
  181635. if( pConfig->pTok ){
  181636. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  181637. rc = SQLITE_ERROR;
  181638. }else{
  181639. for(nArg=0; p && *p; nArg++){
  181640. const char *p2 = fts5ConfigSkipWhitespace(p);
  181641. if( *p2=='\'' ){
  181642. p = fts5ConfigSkipLiteral(p2);
  181643. }else{
  181644. p = fts5ConfigSkipBareword(p2);
  181645. }
  181646. if( p ){
  181647. memcpy(pSpace, p2, p-p2);
  181648. azArg[nArg] = pSpace;
  181649. sqlite3Fts5Dequote(pSpace);
  181650. pSpace += (p - p2) + 1;
  181651. p = fts5ConfigSkipWhitespace(p);
  181652. }
  181653. }
  181654. if( p==0 ){
  181655. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  181656. rc = SQLITE_ERROR;
  181657. }else{
  181658. rc = sqlite3Fts5GetTokenizer(pGlobal,
  181659. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  181660. pzErr
  181661. );
  181662. }
  181663. }
  181664. }
  181665. sqlite3_free(azArg);
  181666. sqlite3_free(pDel);
  181667. return rc;
  181668. }
  181669. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  181670. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  181671. *pzErr = sqlite3_mprintf("multiple content=... directives");
  181672. rc = SQLITE_ERROR;
  181673. }else{
  181674. if( zArg[0] ){
  181675. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  181676. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  181677. }else{
  181678. pConfig->eContent = FTS5_CONTENT_NONE;
  181679. }
  181680. }
  181681. return rc;
  181682. }
  181683. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  181684. if( pConfig->zContentRowid ){
  181685. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  181686. rc = SQLITE_ERROR;
  181687. }else{
  181688. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  181689. }
  181690. return rc;
  181691. }
  181692. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  181693. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  181694. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  181695. rc = SQLITE_ERROR;
  181696. }else{
  181697. pConfig->bColumnsize = (zArg[0]=='1');
  181698. }
  181699. return rc;
  181700. }
  181701. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  181702. const Fts5Enum aDetail[] = {
  181703. { "none", FTS5_DETAIL_NONE },
  181704. { "full", FTS5_DETAIL_FULL },
  181705. { "columns", FTS5_DETAIL_COLUMNS },
  181706. { 0, 0 }
  181707. };
  181708. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  181709. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  181710. }
  181711. return rc;
  181712. }
  181713. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  181714. return SQLITE_ERROR;
  181715. }
  181716. /*
  181717. ** Allocate an instance of the default tokenizer ("simple") at
  181718. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  181719. ** code if an error occurs.
  181720. */
  181721. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  181722. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  181723. return sqlite3Fts5GetTokenizer(
  181724. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  181725. );
  181726. }
  181727. /*
  181728. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  181729. ** Return a pointer to the character immediately following the last in
  181730. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  181731. ** to find close-quote character).
  181732. **
  181733. ** Before returning, set pzOut to point to a new buffer containing a
  181734. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  181735. ** quoted, *pbQuoted is also set to 1 before returning.
  181736. **
  181737. ** If *pRc is other than SQLITE_OK when this function is called, it is
  181738. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  181739. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  181740. ** set if a parse error (failed to find close quote) occurs.
  181741. */
  181742. static const char *fts5ConfigGobbleWord(
  181743. int *pRc, /* IN/OUT: Error code */
  181744. const char *zIn, /* Buffer to gobble string/bareword from */
  181745. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  181746. int *pbQuoted /* OUT: Set to true if dequoting required */
  181747. ){
  181748. const char *zRet = 0;
  181749. int nIn = (int)strlen(zIn);
  181750. char *zOut = sqlite3_malloc(nIn+1);
  181751. assert( *pRc==SQLITE_OK );
  181752. *pbQuoted = 0;
  181753. *pzOut = 0;
  181754. if( zOut==0 ){
  181755. *pRc = SQLITE_NOMEM;
  181756. }else{
  181757. memcpy(zOut, zIn, nIn+1);
  181758. if( fts5_isopenquote(zOut[0]) ){
  181759. int ii = fts5Dequote(zOut);
  181760. zRet = &zIn[ii];
  181761. *pbQuoted = 1;
  181762. }else{
  181763. zRet = fts5ConfigSkipBareword(zIn);
  181764. if( zRet ){
  181765. zOut[zRet-zIn] = '\0';
  181766. }
  181767. }
  181768. }
  181769. if( zRet==0 ){
  181770. sqlite3_free(zOut);
  181771. }else{
  181772. *pzOut = zOut;
  181773. }
  181774. return zRet;
  181775. }
  181776. static int fts5ConfigParseColumn(
  181777. Fts5Config *p,
  181778. char *zCol,
  181779. char *zArg,
  181780. char **pzErr
  181781. ){
  181782. int rc = SQLITE_OK;
  181783. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  181784. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  181785. ){
  181786. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  181787. rc = SQLITE_ERROR;
  181788. }else if( zArg ){
  181789. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  181790. p->abUnindexed[p->nCol] = 1;
  181791. }else{
  181792. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  181793. rc = SQLITE_ERROR;
  181794. }
  181795. }
  181796. p->azCol[p->nCol++] = zCol;
  181797. return rc;
  181798. }
  181799. /*
  181800. ** Populate the Fts5Config.zContentExprlist string.
  181801. */
  181802. static int fts5ConfigMakeExprlist(Fts5Config *p){
  181803. int i;
  181804. int rc = SQLITE_OK;
  181805. Fts5Buffer buf = {0, 0, 0};
  181806. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  181807. if( p->eContent!=FTS5_CONTENT_NONE ){
  181808. for(i=0; i<p->nCol; i++){
  181809. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  181810. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  181811. }else{
  181812. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  181813. }
  181814. }
  181815. }
  181816. assert( p->zContentExprlist==0 );
  181817. p->zContentExprlist = (char*)buf.p;
  181818. return rc;
  181819. }
  181820. /*
  181821. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  181822. ** or xConnect method of the virtual table. This function attempts to
  181823. ** allocate an instance of Fts5Config containing the results of parsing
  181824. ** those arguments.
  181825. **
  181826. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  181827. ** new Fts5Config object. If an error occurs, an SQLite error code is
  181828. ** returned, *ppOut is set to NULL and an error message may be left in
  181829. ** *pzErr. It is the responsibility of the caller to eventually free any
  181830. ** such error message using sqlite3_free().
  181831. */
  181832. static int sqlite3Fts5ConfigParse(
  181833. Fts5Global *pGlobal,
  181834. sqlite3 *db,
  181835. int nArg, /* Number of arguments */
  181836. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  181837. Fts5Config **ppOut, /* OUT: Results of parse */
  181838. char **pzErr /* OUT: Error message */
  181839. ){
  181840. int rc = SQLITE_OK; /* Return code */
  181841. Fts5Config *pRet; /* New object to return */
  181842. int i;
  181843. int nByte;
  181844. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  181845. if( pRet==0 ) return SQLITE_NOMEM;
  181846. memset(pRet, 0, sizeof(Fts5Config));
  181847. pRet->db = db;
  181848. pRet->iCookie = -1;
  181849. nByte = nArg * (sizeof(char*) + sizeof(u8));
  181850. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  181851. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  181852. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  181853. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  181854. pRet->bColumnsize = 1;
  181855. pRet->eDetail = FTS5_DETAIL_FULL;
  181856. #ifdef SQLITE_DEBUG
  181857. pRet->bPrefixIndex = 1;
  181858. #endif
  181859. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  181860. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  181861. rc = SQLITE_ERROR;
  181862. }
  181863. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  181864. const char *zOrig = azArg[i];
  181865. const char *z;
  181866. char *zOne = 0;
  181867. char *zTwo = 0;
  181868. int bOption = 0;
  181869. int bMustBeCol = 0;
  181870. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  181871. z = fts5ConfigSkipWhitespace(z);
  181872. if( z && *z=='=' ){
  181873. bOption = 1;
  181874. z++;
  181875. if( bMustBeCol ) z = 0;
  181876. }
  181877. z = fts5ConfigSkipWhitespace(z);
  181878. if( z && z[0] ){
  181879. int bDummy;
  181880. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  181881. if( z && z[0] ) z = 0;
  181882. }
  181883. if( rc==SQLITE_OK ){
  181884. if( z==0 ){
  181885. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  181886. rc = SQLITE_ERROR;
  181887. }else{
  181888. if( bOption ){
  181889. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  181890. }else{
  181891. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  181892. zOne = 0;
  181893. }
  181894. }
  181895. }
  181896. sqlite3_free(zOne);
  181897. sqlite3_free(zTwo);
  181898. }
  181899. /* If a tokenizer= option was successfully parsed, the tokenizer has
  181900. ** already been allocated. Otherwise, allocate an instance of the default
  181901. ** tokenizer (unicode61) now. */
  181902. if( rc==SQLITE_OK && pRet->pTok==0 ){
  181903. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  181904. }
  181905. /* If no zContent option was specified, fill in the default values. */
  181906. if( rc==SQLITE_OK && pRet->zContent==0 ){
  181907. const char *zTail = 0;
  181908. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  181909. || pRet->eContent==FTS5_CONTENT_NONE
  181910. );
  181911. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  181912. zTail = "content";
  181913. }else if( pRet->bColumnsize ){
  181914. zTail = "docsize";
  181915. }
  181916. if( zTail ){
  181917. pRet->zContent = sqlite3Fts5Mprintf(
  181918. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  181919. );
  181920. }
  181921. }
  181922. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  181923. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  181924. }
  181925. /* Formulate the zContentExprlist text */
  181926. if( rc==SQLITE_OK ){
  181927. rc = fts5ConfigMakeExprlist(pRet);
  181928. }
  181929. if( rc!=SQLITE_OK ){
  181930. sqlite3Fts5ConfigFree(pRet);
  181931. *ppOut = 0;
  181932. }
  181933. return rc;
  181934. }
  181935. /*
  181936. ** Free the configuration object passed as the only argument.
  181937. */
  181938. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  181939. if( pConfig ){
  181940. int i;
  181941. if( pConfig->pTok ){
  181942. pConfig->pTokApi->xDelete(pConfig->pTok);
  181943. }
  181944. sqlite3_free(pConfig->zDb);
  181945. sqlite3_free(pConfig->zName);
  181946. for(i=0; i<pConfig->nCol; i++){
  181947. sqlite3_free(pConfig->azCol[i]);
  181948. }
  181949. sqlite3_free(pConfig->azCol);
  181950. sqlite3_free(pConfig->aPrefix);
  181951. sqlite3_free(pConfig->zRank);
  181952. sqlite3_free(pConfig->zRankArgs);
  181953. sqlite3_free(pConfig->zContent);
  181954. sqlite3_free(pConfig->zContentRowid);
  181955. sqlite3_free(pConfig->zContentExprlist);
  181956. sqlite3_free(pConfig);
  181957. }
  181958. }
  181959. /*
  181960. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  181961. ** object passed as the only argument. Return SQLITE_OK if successful, or
  181962. ** an SQLite error code if an error occurs.
  181963. */
  181964. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  181965. int i;
  181966. int rc = SQLITE_OK;
  181967. char *zSql;
  181968. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  181969. for(i=0; zSql && i<pConfig->nCol; i++){
  181970. const char *zSep = (i==0?"":", ");
  181971. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  181972. }
  181973. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  181974. zSql, pConfig->zName, FTS5_RANK_NAME
  181975. );
  181976. assert( zSql || rc==SQLITE_NOMEM );
  181977. if( zSql ){
  181978. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  181979. sqlite3_free(zSql);
  181980. }
  181981. return rc;
  181982. }
  181983. /*
  181984. ** Tokenize the text passed via the second and third arguments.
  181985. **
  181986. ** The callback is invoked once for each token in the input text. The
  181987. ** arguments passed to it are, in order:
  181988. **
  181989. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  181990. ** const char *pToken // Pointer to buffer containing token
  181991. ** int nToken // Size of token in bytes
  181992. ** int iStart // Byte offset of start of token within input text
  181993. ** int iEnd // Byte offset of end of token within input text
  181994. ** int iPos // Position of token in input (first token is 0)
  181995. **
  181996. ** If the callback returns a non-zero value the tokenization is abandoned
  181997. ** and no further callbacks are issued.
  181998. **
  181999. ** This function returns SQLITE_OK if successful or an SQLite error code
  182000. ** if an error occurs. If the tokenization was abandoned early because
  182001. ** the callback returned SQLITE_DONE, this is not an error and this function
  182002. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  182003. ** because the callback returned another non-zero value, it is assumed
  182004. ** to be an SQLite error code and returned to the caller.
  182005. */
  182006. static int sqlite3Fts5Tokenize(
  182007. Fts5Config *pConfig, /* FTS5 Configuration object */
  182008. int flags, /* FTS5_TOKENIZE_* flags */
  182009. const char *pText, int nText, /* Text to tokenize */
  182010. void *pCtx, /* Context passed to xToken() */
  182011. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  182012. ){
  182013. if( pText==0 ) return SQLITE_OK;
  182014. return pConfig->pTokApi->xTokenize(
  182015. pConfig->pTok, pCtx, flags, pText, nText, xToken
  182016. );
  182017. }
  182018. /*
  182019. ** Argument pIn points to the first character in what is expected to be
  182020. ** a comma-separated list of SQL literals followed by a ')' character.
  182021. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  182022. ** NULL to indicate a parse error.
  182023. */
  182024. static const char *fts5ConfigSkipArgs(const char *pIn){
  182025. const char *p = pIn;
  182026. while( 1 ){
  182027. p = fts5ConfigSkipWhitespace(p);
  182028. p = fts5ConfigSkipLiteral(p);
  182029. p = fts5ConfigSkipWhitespace(p);
  182030. if( p==0 || *p==')' ) break;
  182031. if( *p!=',' ){
  182032. p = 0;
  182033. break;
  182034. }
  182035. p++;
  182036. }
  182037. return p;
  182038. }
  182039. /*
  182040. ** Parameter zIn contains a rank() function specification. The format of
  182041. ** this is:
  182042. **
  182043. ** + Bareword (function name)
  182044. ** + Open parenthesis - "("
  182045. ** + Zero or more SQL literals in a comma separated list
  182046. ** + Close parenthesis - ")"
  182047. */
  182048. static int sqlite3Fts5ConfigParseRank(
  182049. const char *zIn, /* Input string */
  182050. char **pzRank, /* OUT: Rank function name */
  182051. char **pzRankArgs /* OUT: Rank function arguments */
  182052. ){
  182053. const char *p = zIn;
  182054. const char *pRank;
  182055. char *zRank = 0;
  182056. char *zRankArgs = 0;
  182057. int rc = SQLITE_OK;
  182058. *pzRank = 0;
  182059. *pzRankArgs = 0;
  182060. if( p==0 ){
  182061. rc = SQLITE_ERROR;
  182062. }else{
  182063. p = fts5ConfigSkipWhitespace(p);
  182064. pRank = p;
  182065. p = fts5ConfigSkipBareword(p);
  182066. if( p ){
  182067. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  182068. if( zRank ) memcpy(zRank, pRank, p-pRank);
  182069. }else{
  182070. rc = SQLITE_ERROR;
  182071. }
  182072. if( rc==SQLITE_OK ){
  182073. p = fts5ConfigSkipWhitespace(p);
  182074. if( *p!='(' ) rc = SQLITE_ERROR;
  182075. p++;
  182076. }
  182077. if( rc==SQLITE_OK ){
  182078. const char *pArgs;
  182079. p = fts5ConfigSkipWhitespace(p);
  182080. pArgs = p;
  182081. if( *p!=')' ){
  182082. p = fts5ConfigSkipArgs(p);
  182083. if( p==0 ){
  182084. rc = SQLITE_ERROR;
  182085. }else{
  182086. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  182087. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  182088. }
  182089. }
  182090. }
  182091. }
  182092. if( rc!=SQLITE_OK ){
  182093. sqlite3_free(zRank);
  182094. assert( zRankArgs==0 );
  182095. }else{
  182096. *pzRank = zRank;
  182097. *pzRankArgs = zRankArgs;
  182098. }
  182099. return rc;
  182100. }
  182101. static int sqlite3Fts5ConfigSetValue(
  182102. Fts5Config *pConfig,
  182103. const char *zKey,
  182104. sqlite3_value *pVal,
  182105. int *pbBadkey
  182106. ){
  182107. int rc = SQLITE_OK;
  182108. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  182109. int pgsz = 0;
  182110. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  182111. pgsz = sqlite3_value_int(pVal);
  182112. }
  182113. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  182114. *pbBadkey = 1;
  182115. }else{
  182116. pConfig->pgsz = pgsz;
  182117. }
  182118. }
  182119. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  182120. int nHashSize = -1;
  182121. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  182122. nHashSize = sqlite3_value_int(pVal);
  182123. }
  182124. if( nHashSize<=0 ){
  182125. *pbBadkey = 1;
  182126. }else{
  182127. pConfig->nHashSize = nHashSize;
  182128. }
  182129. }
  182130. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  182131. int nAutomerge = -1;
  182132. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  182133. nAutomerge = sqlite3_value_int(pVal);
  182134. }
  182135. if( nAutomerge<0 || nAutomerge>64 ){
  182136. *pbBadkey = 1;
  182137. }else{
  182138. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  182139. pConfig->nAutomerge = nAutomerge;
  182140. }
  182141. }
  182142. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  182143. int nUsermerge = -1;
  182144. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  182145. nUsermerge = sqlite3_value_int(pVal);
  182146. }
  182147. if( nUsermerge<2 || nUsermerge>16 ){
  182148. *pbBadkey = 1;
  182149. }else{
  182150. pConfig->nUsermerge = nUsermerge;
  182151. }
  182152. }
  182153. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  182154. int nCrisisMerge = -1;
  182155. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  182156. nCrisisMerge = sqlite3_value_int(pVal);
  182157. }
  182158. if( nCrisisMerge<0 ){
  182159. *pbBadkey = 1;
  182160. }else{
  182161. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  182162. pConfig->nCrisisMerge = nCrisisMerge;
  182163. }
  182164. }
  182165. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  182166. const char *zIn = (const char*)sqlite3_value_text(pVal);
  182167. char *zRank;
  182168. char *zRankArgs;
  182169. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  182170. if( rc==SQLITE_OK ){
  182171. sqlite3_free(pConfig->zRank);
  182172. sqlite3_free(pConfig->zRankArgs);
  182173. pConfig->zRank = zRank;
  182174. pConfig->zRankArgs = zRankArgs;
  182175. }else if( rc==SQLITE_ERROR ){
  182176. rc = SQLITE_OK;
  182177. *pbBadkey = 1;
  182178. }
  182179. }else{
  182180. *pbBadkey = 1;
  182181. }
  182182. return rc;
  182183. }
  182184. /*
  182185. ** Load the contents of the %_config table into memory.
  182186. */
  182187. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  182188. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  182189. char *zSql;
  182190. sqlite3_stmt *p = 0;
  182191. int rc = SQLITE_OK;
  182192. int iVersion = 0;
  182193. /* Set default values */
  182194. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  182195. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  182196. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  182197. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  182198. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  182199. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  182200. if( zSql ){
  182201. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  182202. sqlite3_free(zSql);
  182203. }
  182204. assert( rc==SQLITE_OK || p==0 );
  182205. if( rc==SQLITE_OK ){
  182206. while( SQLITE_ROW==sqlite3_step(p) ){
  182207. const char *zK = (const char*)sqlite3_column_text(p, 0);
  182208. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  182209. if( 0==sqlite3_stricmp(zK, "version") ){
  182210. iVersion = sqlite3_value_int(pVal);
  182211. }else{
  182212. int bDummy = 0;
  182213. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  182214. }
  182215. }
  182216. rc = sqlite3_finalize(p);
  182217. }
  182218. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  182219. rc = SQLITE_ERROR;
  182220. if( pConfig->pzErrmsg ){
  182221. assert( 0==*pConfig->pzErrmsg );
  182222. *pConfig->pzErrmsg = sqlite3_mprintf(
  182223. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  182224. iVersion, FTS5_CURRENT_VERSION
  182225. );
  182226. }
  182227. }
  182228. if( rc==SQLITE_OK ){
  182229. pConfig->iCookie = iCookie;
  182230. }
  182231. return rc;
  182232. }
  182233. /*
  182234. ** 2014 May 31
  182235. **
  182236. ** The author disclaims copyright to this source code. In place of
  182237. ** a legal notice, here is a blessing:
  182238. **
  182239. ** May you do good and not evil.
  182240. ** May you find forgiveness for yourself and forgive others.
  182241. ** May you share freely, never taking more than you give.
  182242. **
  182243. ******************************************************************************
  182244. **
  182245. */
  182246. /* #include "fts5Int.h" */
  182247. /* #include "fts5parse.h" */
  182248. /*
  182249. ** All token types in the generated fts5parse.h file are greater than 0.
  182250. */
  182251. #define FTS5_EOF 0
  182252. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  182253. typedef struct Fts5ExprTerm Fts5ExprTerm;
  182254. /*
  182255. ** Functions generated by lemon from fts5parse.y.
  182256. */
  182257. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  182258. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  182259. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  182260. #ifndef NDEBUG
  182261. /* #include <stdio.h> */
  182262. static void sqlite3Fts5ParserTrace(FILE*, char*);
  182263. #endif
  182264. struct Fts5Expr {
  182265. Fts5Index *pIndex;
  182266. Fts5Config *pConfig;
  182267. Fts5ExprNode *pRoot;
  182268. int bDesc; /* Iterate in descending rowid order */
  182269. int nPhrase; /* Number of phrases in expression */
  182270. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  182271. };
  182272. /*
  182273. ** eType:
  182274. ** Expression node type. Always one of:
  182275. **
  182276. ** FTS5_AND (nChild, apChild valid)
  182277. ** FTS5_OR (nChild, apChild valid)
  182278. ** FTS5_NOT (nChild, apChild valid)
  182279. ** FTS5_STRING (pNear valid)
  182280. ** FTS5_TERM (pNear valid)
  182281. */
  182282. struct Fts5ExprNode {
  182283. int eType; /* Node type */
  182284. int bEof; /* True at EOF */
  182285. int bNomatch; /* True if entry is not a match */
  182286. /* Next method for this node. */
  182287. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  182288. i64 iRowid; /* Current rowid */
  182289. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  182290. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  182291. ** AND or OR nodes, it contains 2 or more entries. */
  182292. int nChild; /* Number of child nodes */
  182293. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  182294. };
  182295. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  182296. /*
  182297. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  182298. ** used as if it has the same signature as the xNext() methods themselves.
  182299. */
  182300. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  182301. /*
  182302. ** An instance of the following structure represents a single search term
  182303. ** or term prefix.
  182304. */
  182305. struct Fts5ExprTerm {
  182306. u8 bPrefix; /* True for a prefix term */
  182307. u8 bFirst; /* True if token must be first in column */
  182308. char *zTerm; /* nul-terminated term */
  182309. Fts5IndexIter *pIter; /* Iterator for this term */
  182310. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  182311. };
  182312. /*
  182313. ** A phrase. One or more terms that must appear in a contiguous sequence
  182314. ** within a document for it to match.
  182315. */
  182316. struct Fts5ExprPhrase {
  182317. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  182318. Fts5Buffer poslist; /* Current position list */
  182319. int nTerm; /* Number of entries in aTerm[] */
  182320. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  182321. };
  182322. /*
  182323. ** One or more phrases that must appear within a certain token distance of
  182324. ** each other within each matching document.
  182325. */
  182326. struct Fts5ExprNearset {
  182327. int nNear; /* NEAR parameter */
  182328. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  182329. int nPhrase; /* Number of entries in aPhrase[] array */
  182330. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  182331. };
  182332. /*
  182333. ** Parse context.
  182334. */
  182335. struct Fts5Parse {
  182336. Fts5Config *pConfig;
  182337. char *zErr;
  182338. int rc;
  182339. int nPhrase; /* Size of apPhrase array */
  182340. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  182341. Fts5ExprNode *pExpr; /* Result of a successful parse */
  182342. };
  182343. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  182344. va_list ap;
  182345. va_start(ap, zFmt);
  182346. if( pParse->rc==SQLITE_OK ){
  182347. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  182348. pParse->rc = SQLITE_ERROR;
  182349. }
  182350. va_end(ap);
  182351. }
  182352. static int fts5ExprIsspace(char t){
  182353. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  182354. }
  182355. /*
  182356. ** Read the first token from the nul-terminated string at *pz.
  182357. */
  182358. static int fts5ExprGetToken(
  182359. Fts5Parse *pParse,
  182360. const char **pz, /* IN/OUT: Pointer into buffer */
  182361. Fts5Token *pToken
  182362. ){
  182363. const char *z = *pz;
  182364. int tok;
  182365. /* Skip past any whitespace */
  182366. while( fts5ExprIsspace(*z) ) z++;
  182367. pToken->p = z;
  182368. pToken->n = 1;
  182369. switch( *z ){
  182370. case '(': tok = FTS5_LP; break;
  182371. case ')': tok = FTS5_RP; break;
  182372. case '{': tok = FTS5_LCP; break;
  182373. case '}': tok = FTS5_RCP; break;
  182374. case ':': tok = FTS5_COLON; break;
  182375. case ',': tok = FTS5_COMMA; break;
  182376. case '+': tok = FTS5_PLUS; break;
  182377. case '*': tok = FTS5_STAR; break;
  182378. case '-': tok = FTS5_MINUS; break;
  182379. case '^': tok = FTS5_CARET; break;
  182380. case '\0': tok = FTS5_EOF; break;
  182381. case '"': {
  182382. const char *z2;
  182383. tok = FTS5_STRING;
  182384. for(z2=&z[1]; 1; z2++){
  182385. if( z2[0]=='"' ){
  182386. z2++;
  182387. if( z2[0]!='"' ) break;
  182388. }
  182389. if( z2[0]=='\0' ){
  182390. sqlite3Fts5ParseError(pParse, "unterminated string");
  182391. return FTS5_EOF;
  182392. }
  182393. }
  182394. pToken->n = (z2 - z);
  182395. break;
  182396. }
  182397. default: {
  182398. const char *z2;
  182399. if( sqlite3Fts5IsBareword(z[0])==0 ){
  182400. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  182401. return FTS5_EOF;
  182402. }
  182403. tok = FTS5_STRING;
  182404. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  182405. pToken->n = (z2 - z);
  182406. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  182407. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  182408. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  182409. break;
  182410. }
  182411. }
  182412. *pz = &pToken->p[pToken->n];
  182413. return tok;
  182414. }
  182415. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  182416. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  182417. static int sqlite3Fts5ExprNew(
  182418. Fts5Config *pConfig, /* FTS5 Configuration */
  182419. int iCol,
  182420. const char *zExpr, /* Expression text */
  182421. Fts5Expr **ppNew,
  182422. char **pzErr
  182423. ){
  182424. Fts5Parse sParse;
  182425. Fts5Token token;
  182426. const char *z = zExpr;
  182427. int t; /* Next token type */
  182428. void *pEngine;
  182429. Fts5Expr *pNew;
  182430. *ppNew = 0;
  182431. *pzErr = 0;
  182432. memset(&sParse, 0, sizeof(sParse));
  182433. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  182434. if( pEngine==0 ){ return SQLITE_NOMEM; }
  182435. sParse.pConfig = pConfig;
  182436. do {
  182437. t = fts5ExprGetToken(&sParse, &z, &token);
  182438. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  182439. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  182440. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  182441. /* If the LHS of the MATCH expression was a user column, apply the
  182442. ** implicit column-filter. */
  182443. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  182444. int n = sizeof(Fts5Colset);
  182445. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  182446. if( pColset ){
  182447. pColset->nCol = 1;
  182448. pColset->aiCol[0] = iCol;
  182449. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  182450. }
  182451. }
  182452. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  182453. if( sParse.rc==SQLITE_OK ){
  182454. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  182455. if( pNew==0 ){
  182456. sParse.rc = SQLITE_NOMEM;
  182457. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  182458. }else{
  182459. if( !sParse.pExpr ){
  182460. const int nByte = sizeof(Fts5ExprNode);
  182461. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  182462. if( pNew->pRoot ){
  182463. pNew->pRoot->bEof = 1;
  182464. }
  182465. }else{
  182466. pNew->pRoot = sParse.pExpr;
  182467. }
  182468. pNew->pIndex = 0;
  182469. pNew->pConfig = pConfig;
  182470. pNew->apExprPhrase = sParse.apPhrase;
  182471. pNew->nPhrase = sParse.nPhrase;
  182472. sParse.apPhrase = 0;
  182473. }
  182474. }else{
  182475. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  182476. }
  182477. sqlite3_free(sParse.apPhrase);
  182478. *pzErr = sParse.zErr;
  182479. return sParse.rc;
  182480. }
  182481. /*
  182482. ** Free the expression node object passed as the only argument.
  182483. */
  182484. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  182485. if( p ){
  182486. int i;
  182487. for(i=0; i<p->nChild; i++){
  182488. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  182489. }
  182490. sqlite3Fts5ParseNearsetFree(p->pNear);
  182491. sqlite3_free(p);
  182492. }
  182493. }
  182494. /*
  182495. ** Free the expression object passed as the only argument.
  182496. */
  182497. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  182498. if( p ){
  182499. sqlite3Fts5ParseNodeFree(p->pRoot);
  182500. sqlite3_free(p->apExprPhrase);
  182501. sqlite3_free(p);
  182502. }
  182503. }
  182504. /*
  182505. ** Argument pTerm must be a synonym iterator. Return the current rowid
  182506. ** that it points to.
  182507. */
  182508. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  182509. i64 iRet = 0;
  182510. int bRetValid = 0;
  182511. Fts5ExprTerm *p;
  182512. assert( pTerm->pSynonym );
  182513. assert( bDesc==0 || bDesc==1 );
  182514. for(p=pTerm; p; p=p->pSynonym){
  182515. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  182516. i64 iRowid = p->pIter->iRowid;
  182517. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  182518. iRet = iRowid;
  182519. bRetValid = 1;
  182520. }
  182521. }
  182522. }
  182523. if( pbEof && bRetValid==0 ) *pbEof = 1;
  182524. return iRet;
  182525. }
  182526. /*
  182527. ** Argument pTerm must be a synonym iterator.
  182528. */
  182529. static int fts5ExprSynonymList(
  182530. Fts5ExprTerm *pTerm,
  182531. i64 iRowid,
  182532. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  182533. u8 **pa, int *pn
  182534. ){
  182535. Fts5PoslistReader aStatic[4];
  182536. Fts5PoslistReader *aIter = aStatic;
  182537. int nIter = 0;
  182538. int nAlloc = 4;
  182539. int rc = SQLITE_OK;
  182540. Fts5ExprTerm *p;
  182541. assert( pTerm->pSynonym );
  182542. for(p=pTerm; p; p=p->pSynonym){
  182543. Fts5IndexIter *pIter = p->pIter;
  182544. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  182545. if( pIter->nData==0 ) continue;
  182546. if( nIter==nAlloc ){
  182547. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  182548. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  182549. if( aNew==0 ){
  182550. rc = SQLITE_NOMEM;
  182551. goto synonym_poslist_out;
  182552. }
  182553. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  182554. nAlloc = nAlloc*2;
  182555. if( aIter!=aStatic ) sqlite3_free(aIter);
  182556. aIter = aNew;
  182557. }
  182558. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  182559. assert( aIter[nIter].bEof==0 );
  182560. nIter++;
  182561. }
  182562. }
  182563. if( nIter==1 ){
  182564. *pa = (u8*)aIter[0].a;
  182565. *pn = aIter[0].n;
  182566. }else{
  182567. Fts5PoslistWriter writer = {0};
  182568. i64 iPrev = -1;
  182569. fts5BufferZero(pBuf);
  182570. while( 1 ){
  182571. int i;
  182572. i64 iMin = FTS5_LARGEST_INT64;
  182573. for(i=0; i<nIter; i++){
  182574. if( aIter[i].bEof==0 ){
  182575. if( aIter[i].iPos==iPrev ){
  182576. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  182577. }
  182578. if( aIter[i].iPos<iMin ){
  182579. iMin = aIter[i].iPos;
  182580. }
  182581. }
  182582. }
  182583. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  182584. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  182585. iPrev = iMin;
  182586. }
  182587. if( rc==SQLITE_OK ){
  182588. *pa = pBuf->p;
  182589. *pn = pBuf->n;
  182590. }
  182591. }
  182592. synonym_poslist_out:
  182593. if( aIter!=aStatic ) sqlite3_free(aIter);
  182594. return rc;
  182595. }
  182596. /*
  182597. ** All individual term iterators in pPhrase are guaranteed to be valid and
  182598. ** pointing to the same rowid when this function is called. This function
  182599. ** checks if the current rowid really is a match, and if so populates
  182600. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  182601. ** is set to true if this is really a match, or false otherwise.
  182602. **
  182603. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  182604. ** otherwise. It is not considered an error code if the current rowid is
  182605. ** not a match.
  182606. */
  182607. static int fts5ExprPhraseIsMatch(
  182608. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  182609. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  182610. int *pbMatch /* OUT: Set to true if really a match */
  182611. ){
  182612. Fts5PoslistWriter writer = {0};
  182613. Fts5PoslistReader aStatic[4];
  182614. Fts5PoslistReader *aIter = aStatic;
  182615. int i;
  182616. int rc = SQLITE_OK;
  182617. int bFirst = pPhrase->aTerm[0].bFirst;
  182618. fts5BufferZero(&pPhrase->poslist);
  182619. /* If the aStatic[] array is not large enough, allocate a large array
  182620. ** using sqlite3_malloc(). This approach could be improved upon. */
  182621. if( pPhrase->nTerm>ArraySize(aStatic) ){
  182622. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  182623. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  182624. if( !aIter ) return SQLITE_NOMEM;
  182625. }
  182626. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  182627. /* Initialize a term iterator for each term in the phrase */
  182628. for(i=0; i<pPhrase->nTerm; i++){
  182629. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  182630. int n = 0;
  182631. int bFlag = 0;
  182632. u8 *a = 0;
  182633. if( pTerm->pSynonym ){
  182634. Fts5Buffer buf = {0, 0, 0};
  182635. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  182636. if( rc ){
  182637. sqlite3_free(a);
  182638. goto ismatch_out;
  182639. }
  182640. if( a==buf.p ) bFlag = 1;
  182641. }else{
  182642. a = (u8*)pTerm->pIter->pData;
  182643. n = pTerm->pIter->nData;
  182644. }
  182645. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  182646. aIter[i].bFlag = (u8)bFlag;
  182647. if( aIter[i].bEof ) goto ismatch_out;
  182648. }
  182649. while( 1 ){
  182650. int bMatch;
  182651. i64 iPos = aIter[0].iPos;
  182652. do {
  182653. bMatch = 1;
  182654. for(i=0; i<pPhrase->nTerm; i++){
  182655. Fts5PoslistReader *pPos = &aIter[i];
  182656. i64 iAdj = iPos + i;
  182657. if( pPos->iPos!=iAdj ){
  182658. bMatch = 0;
  182659. while( pPos->iPos<iAdj ){
  182660. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  182661. }
  182662. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  182663. }
  182664. }
  182665. }while( bMatch==0 );
  182666. /* Append position iPos to the output */
  182667. if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
  182668. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  182669. if( rc!=SQLITE_OK ) goto ismatch_out;
  182670. }
  182671. for(i=0; i<pPhrase->nTerm; i++){
  182672. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  182673. }
  182674. }
  182675. ismatch_out:
  182676. *pbMatch = (pPhrase->poslist.n>0);
  182677. for(i=0; i<pPhrase->nTerm; i++){
  182678. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  182679. }
  182680. if( aIter!=aStatic ) sqlite3_free(aIter);
  182681. return rc;
  182682. }
  182683. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  182684. struct Fts5LookaheadReader {
  182685. const u8 *a; /* Buffer containing position list */
  182686. int n; /* Size of buffer a[] in bytes */
  182687. int i; /* Current offset in position list */
  182688. i64 iPos; /* Current position */
  182689. i64 iLookahead; /* Next position */
  182690. };
  182691. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  182692. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  182693. p->iPos = p->iLookahead;
  182694. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  182695. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  182696. }
  182697. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  182698. }
  182699. static int fts5LookaheadReaderInit(
  182700. const u8 *a, int n, /* Buffer to read position list from */
  182701. Fts5LookaheadReader *p /* Iterator object to initialize */
  182702. ){
  182703. memset(p, 0, sizeof(Fts5LookaheadReader));
  182704. p->a = a;
  182705. p->n = n;
  182706. fts5LookaheadReaderNext(p);
  182707. return fts5LookaheadReaderNext(p);
  182708. }
  182709. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  182710. struct Fts5NearTrimmer {
  182711. Fts5LookaheadReader reader; /* Input iterator */
  182712. Fts5PoslistWriter writer; /* Writer context */
  182713. Fts5Buffer *pOut; /* Output poslist */
  182714. };
  182715. /*
  182716. ** The near-set object passed as the first argument contains more than
  182717. ** one phrase. All phrases currently point to the same row. The
  182718. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  182719. ** tests if the current row contains instances of each phrase sufficiently
  182720. ** close together to meet the NEAR constraint. Non-zero is returned if it
  182721. ** does, or zero otherwise.
  182722. **
  182723. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  182724. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  182725. ** occurs within this function (*pRc) is set accordingly before returning.
  182726. ** The return value is undefined in both these cases.
  182727. **
  182728. ** If no error occurs and non-zero (a match) is returned, the position-list
  182729. ** of each phrase object is edited to contain only those entries that
  182730. ** meet the constraint before returning.
  182731. */
  182732. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  182733. Fts5NearTrimmer aStatic[4];
  182734. Fts5NearTrimmer *a = aStatic;
  182735. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  182736. int i;
  182737. int rc = *pRc;
  182738. int bMatch;
  182739. assert( pNear->nPhrase>1 );
  182740. /* If the aStatic[] array is not large enough, allocate a large array
  182741. ** using sqlite3_malloc(). This approach could be improved upon. */
  182742. if( pNear->nPhrase>ArraySize(aStatic) ){
  182743. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  182744. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  182745. }else{
  182746. memset(aStatic, 0, sizeof(aStatic));
  182747. }
  182748. if( rc!=SQLITE_OK ){
  182749. *pRc = rc;
  182750. return 0;
  182751. }
  182752. /* Initialize a lookahead iterator for each phrase. After passing the
  182753. ** buffer and buffer size to the lookaside-reader init function, zero
  182754. ** the phrase poslist buffer. The new poslist for the phrase (containing
  182755. ** the same entries as the original with some entries removed on account
  182756. ** of the NEAR constraint) is written over the original even as it is
  182757. ** being read. This is safe as the entries for the new poslist are a
  182758. ** subset of the old, so it is not possible for data yet to be read to
  182759. ** be overwritten. */
  182760. for(i=0; i<pNear->nPhrase; i++){
  182761. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  182762. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  182763. pPoslist->n = 0;
  182764. a[i].pOut = pPoslist;
  182765. }
  182766. while( 1 ){
  182767. int iAdv;
  182768. i64 iMin;
  182769. i64 iMax;
  182770. /* This block advances the phrase iterators until they point to a set of
  182771. ** entries that together comprise a match. */
  182772. iMax = a[0].reader.iPos;
  182773. do {
  182774. bMatch = 1;
  182775. for(i=0; i<pNear->nPhrase; i++){
  182776. Fts5LookaheadReader *pPos = &a[i].reader;
  182777. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  182778. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  182779. bMatch = 0;
  182780. while( pPos->iPos<iMin ){
  182781. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  182782. }
  182783. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  182784. }
  182785. }
  182786. }while( bMatch==0 );
  182787. /* Add an entry to each output position list */
  182788. for(i=0; i<pNear->nPhrase; i++){
  182789. i64 iPos = a[i].reader.iPos;
  182790. Fts5PoslistWriter *pWriter = &a[i].writer;
  182791. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  182792. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  182793. }
  182794. }
  182795. iAdv = 0;
  182796. iMin = a[0].reader.iLookahead;
  182797. for(i=0; i<pNear->nPhrase; i++){
  182798. if( a[i].reader.iLookahead < iMin ){
  182799. iMin = a[i].reader.iLookahead;
  182800. iAdv = i;
  182801. }
  182802. }
  182803. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  182804. }
  182805. ismatch_out: {
  182806. int bRet = a[0].pOut->n>0;
  182807. *pRc = rc;
  182808. if( a!=aStatic ) sqlite3_free(a);
  182809. return bRet;
  182810. }
  182811. }
  182812. /*
  182813. ** Advance iterator pIter until it points to a value equal to or laster
  182814. ** than the initial value of *piLast. If this means the iterator points
  182815. ** to a value laster than *piLast, update *piLast to the new lastest value.
  182816. **
  182817. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  182818. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  182819. ** are set, return a non-zero value. Otherwise, return zero.
  182820. */
  182821. static int fts5ExprAdvanceto(
  182822. Fts5IndexIter *pIter, /* Iterator to advance */
  182823. int bDesc, /* True if iterator is "rowid DESC" */
  182824. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  182825. int *pRc, /* OUT: Error code */
  182826. int *pbEof /* OUT: Set to true if EOF */
  182827. ){
  182828. i64 iLast = *piLast;
  182829. i64 iRowid;
  182830. iRowid = pIter->iRowid;
  182831. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  182832. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  182833. if( rc || sqlite3Fts5IterEof(pIter) ){
  182834. *pRc = rc;
  182835. *pbEof = 1;
  182836. return 1;
  182837. }
  182838. iRowid = pIter->iRowid;
  182839. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  182840. }
  182841. *piLast = iRowid;
  182842. return 0;
  182843. }
  182844. static int fts5ExprSynonymAdvanceto(
  182845. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  182846. int bDesc, /* True if iterator is "rowid DESC" */
  182847. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  182848. int *pRc /* OUT: Error code */
  182849. ){
  182850. int rc = SQLITE_OK;
  182851. i64 iLast = *piLast;
  182852. Fts5ExprTerm *p;
  182853. int bEof = 0;
  182854. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  182855. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  182856. i64 iRowid = p->pIter->iRowid;
  182857. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  182858. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  182859. }
  182860. }
  182861. }
  182862. if( rc!=SQLITE_OK ){
  182863. *pRc = rc;
  182864. bEof = 1;
  182865. }else{
  182866. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  182867. }
  182868. return bEof;
  182869. }
  182870. static int fts5ExprNearTest(
  182871. int *pRc,
  182872. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  182873. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  182874. ){
  182875. Fts5ExprNearset *pNear = pNode->pNear;
  182876. int rc = *pRc;
  182877. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  182878. Fts5ExprTerm *pTerm;
  182879. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  182880. pPhrase->poslist.n = 0;
  182881. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  182882. Fts5IndexIter *pIter = pTerm->pIter;
  182883. if( sqlite3Fts5IterEof(pIter)==0 ){
  182884. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  182885. pPhrase->poslist.n = 1;
  182886. }
  182887. }
  182888. }
  182889. return pPhrase->poslist.n;
  182890. }else{
  182891. int i;
  182892. /* Check that each phrase in the nearset matches the current row.
  182893. ** Populate the pPhrase->poslist buffers at the same time. If any
  182894. ** phrase is not a match, break out of the loop early. */
  182895. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  182896. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  182897. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
  182898. || pNear->pColset || pPhrase->aTerm[0].bFirst
  182899. ){
  182900. int bMatch = 0;
  182901. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  182902. if( bMatch==0 ) break;
  182903. }else{
  182904. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  182905. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  182906. }
  182907. }
  182908. *pRc = rc;
  182909. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  182910. return 1;
  182911. }
  182912. return 0;
  182913. }
  182914. }
  182915. /*
  182916. ** Initialize all term iterators in the pNear object. If any term is found
  182917. ** to match no documents at all, return immediately without initializing any
  182918. ** further iterators.
  182919. **
  182920. ** If an error occurs, return an SQLite error code. Otherwise, return
  182921. ** SQLITE_OK. It is not considered an error if some term matches zero
  182922. ** documents.
  182923. */
  182924. static int fts5ExprNearInitAll(
  182925. Fts5Expr *pExpr,
  182926. Fts5ExprNode *pNode
  182927. ){
  182928. Fts5ExprNearset *pNear = pNode->pNear;
  182929. int i;
  182930. assert( pNode->bNomatch==0 );
  182931. for(i=0; i<pNear->nPhrase; i++){
  182932. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  182933. if( pPhrase->nTerm==0 ){
  182934. pNode->bEof = 1;
  182935. return SQLITE_OK;
  182936. }else{
  182937. int j;
  182938. for(j=0; j<pPhrase->nTerm; j++){
  182939. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  182940. Fts5ExprTerm *p;
  182941. int bHit = 0;
  182942. for(p=pTerm; p; p=p->pSynonym){
  182943. int rc;
  182944. if( p->pIter ){
  182945. sqlite3Fts5IterClose(p->pIter);
  182946. p->pIter = 0;
  182947. }
  182948. rc = sqlite3Fts5IndexQuery(
  182949. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  182950. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  182951. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  182952. pNear->pColset,
  182953. &p->pIter
  182954. );
  182955. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  182956. if( rc!=SQLITE_OK ) return rc;
  182957. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  182958. bHit = 1;
  182959. }
  182960. }
  182961. if( bHit==0 ){
  182962. pNode->bEof = 1;
  182963. return SQLITE_OK;
  182964. }
  182965. }
  182966. }
  182967. }
  182968. pNode->bEof = 0;
  182969. return SQLITE_OK;
  182970. }
  182971. /*
  182972. ** If pExpr is an ASC iterator, this function returns a value with the
  182973. ** same sign as:
  182974. **
  182975. ** (iLhs - iRhs)
  182976. **
  182977. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  182978. **
  182979. ** (iRhs - iLhs)
  182980. */
  182981. static int fts5RowidCmp(
  182982. Fts5Expr *pExpr,
  182983. i64 iLhs,
  182984. i64 iRhs
  182985. ){
  182986. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  182987. if( pExpr->bDesc==0 ){
  182988. if( iLhs<iRhs ) return -1;
  182989. return (iLhs > iRhs);
  182990. }else{
  182991. if( iLhs>iRhs ) return -1;
  182992. return (iLhs < iRhs);
  182993. }
  182994. }
  182995. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  182996. int i;
  182997. pNode->bEof = 1;
  182998. pNode->bNomatch = 0;
  182999. for(i=0; i<pNode->nChild; i++){
  183000. fts5ExprSetEof(pNode->apChild[i]);
  183001. }
  183002. }
  183003. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  183004. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  183005. Fts5ExprNearset *pNear = pNode->pNear;
  183006. int i;
  183007. for(i=0; i<pNear->nPhrase; i++){
  183008. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  183009. pPhrase->poslist.n = 0;
  183010. }
  183011. }else{
  183012. int i;
  183013. for(i=0; i<pNode->nChild; i++){
  183014. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  183015. }
  183016. }
  183017. }
  183018. /*
  183019. ** Compare the values currently indicated by the two nodes as follows:
  183020. **
  183021. ** res = (*p1) - (*p2)
  183022. **
  183023. ** Nodes that point to values that come later in the iteration order are
  183024. ** considered to be larger. Nodes at EOF are the largest of all.
  183025. **
  183026. ** This means that if the iteration order is ASC, then numerically larger
  183027. ** rowids are considered larger. Or if it is the default DESC, numerically
  183028. ** smaller rowids are larger.
  183029. */
  183030. static int fts5NodeCompare(
  183031. Fts5Expr *pExpr,
  183032. Fts5ExprNode *p1,
  183033. Fts5ExprNode *p2
  183034. ){
  183035. if( p2->bEof ) return -1;
  183036. if( p1->bEof ) return +1;
  183037. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  183038. }
  183039. /*
  183040. ** All individual term iterators in pNear are guaranteed to be valid when
  183041. ** this function is called. This function checks if all term iterators
  183042. ** point to the same rowid, and if not, advances them until they do.
  183043. ** If an EOF is reached before this happens, *pbEof is set to true before
  183044. ** returning.
  183045. **
  183046. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  183047. ** otherwise. It is not considered an error code if an iterator reaches
  183048. ** EOF.
  183049. */
  183050. static int fts5ExprNodeTest_STRING(
  183051. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  183052. Fts5ExprNode *pNode
  183053. ){
  183054. Fts5ExprNearset *pNear = pNode->pNear;
  183055. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  183056. int rc = SQLITE_OK;
  183057. i64 iLast; /* Lastest rowid any iterator points to */
  183058. int i, j; /* Phrase and token index, respectively */
  183059. int bMatch; /* True if all terms are at the same rowid */
  183060. const int bDesc = pExpr->bDesc;
  183061. /* Check that this node should not be FTS5_TERM */
  183062. assert( pNear->nPhrase>1
  183063. || pNear->apPhrase[0]->nTerm>1
  183064. || pNear->apPhrase[0]->aTerm[0].pSynonym
  183065. || pNear->apPhrase[0]->aTerm[0].bFirst
  183066. );
  183067. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  183068. ** iterator skips through rowids in the default ascending order, this means
  183069. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  183070. ** means the minimum rowid. */
  183071. if( pLeft->aTerm[0].pSynonym ){
  183072. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  183073. }else{
  183074. iLast = pLeft->aTerm[0].pIter->iRowid;
  183075. }
  183076. do {
  183077. bMatch = 1;
  183078. for(i=0; i<pNear->nPhrase; i++){
  183079. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  183080. for(j=0; j<pPhrase->nTerm; j++){
  183081. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  183082. if( pTerm->pSynonym ){
  183083. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  183084. if( iRowid==iLast ) continue;
  183085. bMatch = 0;
  183086. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  183087. pNode->bNomatch = 0;
  183088. pNode->bEof = 1;
  183089. return rc;
  183090. }
  183091. }else{
  183092. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  183093. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  183094. bMatch = 0;
  183095. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  183096. return rc;
  183097. }
  183098. }
  183099. }
  183100. }
  183101. }while( bMatch==0 );
  183102. pNode->iRowid = iLast;
  183103. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  183104. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  183105. return rc;
  183106. }
  183107. /*
  183108. ** Advance the first term iterator in the first phrase of pNear. Set output
  183109. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  183110. **
  183111. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  183112. ** occurs.
  183113. */
  183114. static int fts5ExprNodeNext_STRING(
  183115. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  183116. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  183117. int bFromValid,
  183118. i64 iFrom
  183119. ){
  183120. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  183121. int rc = SQLITE_OK;
  183122. pNode->bNomatch = 0;
  183123. if( pTerm->pSynonym ){
  183124. int bEof = 1;
  183125. Fts5ExprTerm *p;
  183126. /* Find the firstest rowid any synonym points to. */
  183127. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  183128. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  183129. ** is valid - each iterator that points to a rowid before iFrom. */
  183130. for(p=pTerm; p; p=p->pSynonym){
  183131. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  183132. i64 ii = p->pIter->iRowid;
  183133. if( ii==iRowid
  183134. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  183135. ){
  183136. if( bFromValid ){
  183137. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  183138. }else{
  183139. rc = sqlite3Fts5IterNext(p->pIter);
  183140. }
  183141. if( rc!=SQLITE_OK ) break;
  183142. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  183143. bEof = 0;
  183144. }
  183145. }else{
  183146. bEof = 0;
  183147. }
  183148. }
  183149. }
  183150. /* Set the EOF flag if either all synonym iterators are at EOF or an
  183151. ** error has occurred. */
  183152. pNode->bEof = (rc || bEof);
  183153. }else{
  183154. Fts5IndexIter *pIter = pTerm->pIter;
  183155. assert( Fts5NodeIsString(pNode) );
  183156. if( bFromValid ){
  183157. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  183158. }else{
  183159. rc = sqlite3Fts5IterNext(pIter);
  183160. }
  183161. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  183162. }
  183163. if( pNode->bEof==0 ){
  183164. assert( rc==SQLITE_OK );
  183165. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  183166. }
  183167. return rc;
  183168. }
  183169. static int fts5ExprNodeTest_TERM(
  183170. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  183171. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  183172. ){
  183173. /* As this "NEAR" object is actually a single phrase that consists
  183174. ** of a single term only, grab pointers into the poslist managed by the
  183175. ** fts5_index.c iterator object. This is much faster than synthesizing
  183176. ** a new poslist the way we have to for more complicated phrase or NEAR
  183177. ** expressions. */
  183178. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  183179. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  183180. assert( pNode->eType==FTS5_TERM );
  183181. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  183182. assert( pPhrase->aTerm[0].pSynonym==0 );
  183183. pPhrase->poslist.n = pIter->nData;
  183184. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  183185. pPhrase->poslist.p = (u8*)pIter->pData;
  183186. }
  183187. pNode->iRowid = pIter->iRowid;
  183188. pNode->bNomatch = (pPhrase->poslist.n==0);
  183189. return SQLITE_OK;
  183190. }
  183191. /*
  183192. ** xNext() method for a node of type FTS5_TERM.
  183193. */
  183194. static int fts5ExprNodeNext_TERM(
  183195. Fts5Expr *pExpr,
  183196. Fts5ExprNode *pNode,
  183197. int bFromValid,
  183198. i64 iFrom
  183199. ){
  183200. int rc;
  183201. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  183202. assert( pNode->bEof==0 );
  183203. if( bFromValid ){
  183204. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  183205. }else{
  183206. rc = sqlite3Fts5IterNext(pIter);
  183207. }
  183208. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  183209. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  183210. }else{
  183211. pNode->bEof = 1;
  183212. pNode->bNomatch = 0;
  183213. }
  183214. return rc;
  183215. }
  183216. static void fts5ExprNodeTest_OR(
  183217. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  183218. Fts5ExprNode *pNode /* Expression node to test */
  183219. ){
  183220. Fts5ExprNode *pNext = pNode->apChild[0];
  183221. int i;
  183222. for(i=1; i<pNode->nChild; i++){
  183223. Fts5ExprNode *pChild = pNode->apChild[i];
  183224. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  183225. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  183226. pNext = pChild;
  183227. }
  183228. }
  183229. pNode->iRowid = pNext->iRowid;
  183230. pNode->bEof = pNext->bEof;
  183231. pNode->bNomatch = pNext->bNomatch;
  183232. }
  183233. static int fts5ExprNodeNext_OR(
  183234. Fts5Expr *pExpr,
  183235. Fts5ExprNode *pNode,
  183236. int bFromValid,
  183237. i64 iFrom
  183238. ){
  183239. int i;
  183240. i64 iLast = pNode->iRowid;
  183241. for(i=0; i<pNode->nChild; i++){
  183242. Fts5ExprNode *p1 = pNode->apChild[i];
  183243. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  183244. if( p1->bEof==0 ){
  183245. if( (p1->iRowid==iLast)
  183246. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  183247. ){
  183248. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  183249. if( rc!=SQLITE_OK ){
  183250. pNode->bNomatch = 0;
  183251. return rc;
  183252. }
  183253. }
  183254. }
  183255. }
  183256. fts5ExprNodeTest_OR(pExpr, pNode);
  183257. return SQLITE_OK;
  183258. }
  183259. /*
  183260. ** Argument pNode is an FTS5_AND node.
  183261. */
  183262. static int fts5ExprNodeTest_AND(
  183263. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  183264. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  183265. ){
  183266. int iChild;
  183267. i64 iLast = pAnd->iRowid;
  183268. int rc = SQLITE_OK;
  183269. int bMatch;
  183270. assert( pAnd->bEof==0 );
  183271. do {
  183272. pAnd->bNomatch = 0;
  183273. bMatch = 1;
  183274. for(iChild=0; iChild<pAnd->nChild; iChild++){
  183275. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  183276. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  183277. if( cmp>0 ){
  183278. /* Advance pChild until it points to iLast or laster */
  183279. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  183280. if( rc!=SQLITE_OK ){
  183281. pAnd->bNomatch = 0;
  183282. return rc;
  183283. }
  183284. }
  183285. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  183286. ** the child node is guaranteed to have advanced at least as far as
  183287. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  183288. ** new lastest rowid seen so far. */
  183289. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  183290. if( pChild->bEof ){
  183291. fts5ExprSetEof(pAnd);
  183292. bMatch = 1;
  183293. break;
  183294. }else if( iLast!=pChild->iRowid ){
  183295. bMatch = 0;
  183296. iLast = pChild->iRowid;
  183297. }
  183298. if( pChild->bNomatch ){
  183299. pAnd->bNomatch = 1;
  183300. }
  183301. }
  183302. }while( bMatch==0 );
  183303. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  183304. fts5ExprNodeZeroPoslist(pAnd);
  183305. }
  183306. pAnd->iRowid = iLast;
  183307. return SQLITE_OK;
  183308. }
  183309. static int fts5ExprNodeNext_AND(
  183310. Fts5Expr *pExpr,
  183311. Fts5ExprNode *pNode,
  183312. int bFromValid,
  183313. i64 iFrom
  183314. ){
  183315. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  183316. if( rc==SQLITE_OK ){
  183317. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  183318. }else{
  183319. pNode->bNomatch = 0;
  183320. }
  183321. return rc;
  183322. }
  183323. static int fts5ExprNodeTest_NOT(
  183324. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  183325. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  183326. ){
  183327. int rc = SQLITE_OK;
  183328. Fts5ExprNode *p1 = pNode->apChild[0];
  183329. Fts5ExprNode *p2 = pNode->apChild[1];
  183330. assert( pNode->nChild==2 );
  183331. while( rc==SQLITE_OK && p1->bEof==0 ){
  183332. int cmp = fts5NodeCompare(pExpr, p1, p2);
  183333. if( cmp>0 ){
  183334. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  183335. cmp = fts5NodeCompare(pExpr, p1, p2);
  183336. }
  183337. assert( rc!=SQLITE_OK || cmp<=0 );
  183338. if( cmp || p2->bNomatch ) break;
  183339. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  183340. }
  183341. pNode->bEof = p1->bEof;
  183342. pNode->bNomatch = p1->bNomatch;
  183343. pNode->iRowid = p1->iRowid;
  183344. if( p1->bEof ){
  183345. fts5ExprNodeZeroPoslist(p2);
  183346. }
  183347. return rc;
  183348. }
  183349. static int fts5ExprNodeNext_NOT(
  183350. Fts5Expr *pExpr,
  183351. Fts5ExprNode *pNode,
  183352. int bFromValid,
  183353. i64 iFrom
  183354. ){
  183355. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  183356. if( rc==SQLITE_OK ){
  183357. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  183358. }
  183359. if( rc!=SQLITE_OK ){
  183360. pNode->bNomatch = 0;
  183361. }
  183362. return rc;
  183363. }
  183364. /*
  183365. ** If pNode currently points to a match, this function returns SQLITE_OK
  183366. ** without modifying it. Otherwise, pNode is advanced until it does point
  183367. ** to a match or EOF is reached.
  183368. */
  183369. static int fts5ExprNodeTest(
  183370. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  183371. Fts5ExprNode *pNode /* Expression node to test */
  183372. ){
  183373. int rc = SQLITE_OK;
  183374. if( pNode->bEof==0 ){
  183375. switch( pNode->eType ){
  183376. case FTS5_STRING: {
  183377. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  183378. break;
  183379. }
  183380. case FTS5_TERM: {
  183381. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  183382. break;
  183383. }
  183384. case FTS5_AND: {
  183385. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  183386. break;
  183387. }
  183388. case FTS5_OR: {
  183389. fts5ExprNodeTest_OR(pExpr, pNode);
  183390. break;
  183391. }
  183392. default: assert( pNode->eType==FTS5_NOT ); {
  183393. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  183394. break;
  183395. }
  183396. }
  183397. }
  183398. return rc;
  183399. }
  183400. /*
  183401. ** Set node pNode, which is part of expression pExpr, to point to the first
  183402. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  183403. **
  183404. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  183405. ** It is not an error if there are no matches.
  183406. */
  183407. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  183408. int rc = SQLITE_OK;
  183409. pNode->bEof = 0;
  183410. pNode->bNomatch = 0;
  183411. if( Fts5NodeIsString(pNode) ){
  183412. /* Initialize all term iterators in the NEAR object. */
  183413. rc = fts5ExprNearInitAll(pExpr, pNode);
  183414. }else if( pNode->xNext==0 ){
  183415. pNode->bEof = 1;
  183416. }else{
  183417. int i;
  183418. int nEof = 0;
  183419. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  183420. Fts5ExprNode *pChild = pNode->apChild[i];
  183421. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  183422. assert( pChild->bEof==0 || pChild->bEof==1 );
  183423. nEof += pChild->bEof;
  183424. }
  183425. pNode->iRowid = pNode->apChild[0]->iRowid;
  183426. switch( pNode->eType ){
  183427. case FTS5_AND:
  183428. if( nEof>0 ) fts5ExprSetEof(pNode);
  183429. break;
  183430. case FTS5_OR:
  183431. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  183432. break;
  183433. default:
  183434. assert( pNode->eType==FTS5_NOT );
  183435. pNode->bEof = pNode->apChild[0]->bEof;
  183436. break;
  183437. }
  183438. }
  183439. if( rc==SQLITE_OK ){
  183440. rc = fts5ExprNodeTest(pExpr, pNode);
  183441. }
  183442. return rc;
  183443. }
  183444. /*
  183445. ** Begin iterating through the set of documents in index pIdx matched by
  183446. ** the MATCH expression passed as the first argument. If the "bDesc"
  183447. ** parameter is passed a non-zero value, iteration is in descending rowid
  183448. ** order. Or, if it is zero, in ascending order.
  183449. **
  183450. ** If iterating in ascending rowid order (bDesc==0), the first document
  183451. ** visited is that with the smallest rowid that is larger than or equal
  183452. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  183453. ** then the first document visited must have a rowid smaller than or
  183454. ** equal to iFirst.
  183455. **
  183456. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  183457. ** is not considered an error if the query does not match any documents.
  183458. */
  183459. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  183460. Fts5ExprNode *pRoot = p->pRoot;
  183461. int rc; /* Return code */
  183462. p->pIndex = pIdx;
  183463. p->bDesc = bDesc;
  183464. rc = fts5ExprNodeFirst(p, pRoot);
  183465. /* If not at EOF but the current rowid occurs earlier than iFirst in
  183466. ** the iteration order, move to document iFirst or later. */
  183467. if( rc==SQLITE_OK
  183468. && 0==pRoot->bEof
  183469. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  183470. ){
  183471. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  183472. }
  183473. /* If the iterator is not at a real match, skip forward until it is. */
  183474. while( pRoot->bNomatch ){
  183475. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  183476. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  183477. }
  183478. return rc;
  183479. }
  183480. /*
  183481. ** Move to the next document
  183482. **
  183483. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  183484. ** is not considered an error if the query does not match any documents.
  183485. */
  183486. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  183487. int rc;
  183488. Fts5ExprNode *pRoot = p->pRoot;
  183489. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  183490. do {
  183491. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  183492. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  183493. }while( pRoot->bNomatch );
  183494. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  183495. pRoot->bEof = 1;
  183496. }
  183497. return rc;
  183498. }
  183499. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  183500. return p->pRoot->bEof;
  183501. }
  183502. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  183503. return p->pRoot->iRowid;
  183504. }
  183505. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  183506. int rc = SQLITE_OK;
  183507. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  183508. return rc;
  183509. }
  183510. /*
  183511. ** Free the phrase object passed as the only argument.
  183512. */
  183513. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  183514. if( pPhrase ){
  183515. int i;
  183516. for(i=0; i<pPhrase->nTerm; i++){
  183517. Fts5ExprTerm *pSyn;
  183518. Fts5ExprTerm *pNext;
  183519. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  183520. sqlite3_free(pTerm->zTerm);
  183521. sqlite3Fts5IterClose(pTerm->pIter);
  183522. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  183523. pNext = pSyn->pSynonym;
  183524. sqlite3Fts5IterClose(pSyn->pIter);
  183525. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  183526. sqlite3_free(pSyn);
  183527. }
  183528. }
  183529. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  183530. sqlite3_free(pPhrase);
  183531. }
  183532. }
  183533. /*
  183534. ** Set the "bFirst" flag on the first token of the phrase passed as the
  183535. ** only argument.
  183536. */
  183537. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
  183538. if( pPhrase && pPhrase->nTerm ){
  183539. pPhrase->aTerm[0].bFirst = 1;
  183540. }
  183541. }
  183542. /*
  183543. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  183544. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  183545. ** appended to it and the results returned.
  183546. **
  183547. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  183548. ** NULL returned.
  183549. */
  183550. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  183551. Fts5Parse *pParse, /* Parse context */
  183552. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  183553. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  183554. ){
  183555. const int SZALLOC = 8;
  183556. Fts5ExprNearset *pRet = 0;
  183557. if( pParse->rc==SQLITE_OK ){
  183558. if( pPhrase==0 ){
  183559. return pNear;
  183560. }
  183561. if( pNear==0 ){
  183562. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  183563. pRet = sqlite3_malloc(nByte);
  183564. if( pRet==0 ){
  183565. pParse->rc = SQLITE_NOMEM;
  183566. }else{
  183567. memset(pRet, 0, nByte);
  183568. }
  183569. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  183570. int nNew = pNear->nPhrase + SZALLOC;
  183571. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  183572. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  183573. if( pRet==0 ){
  183574. pParse->rc = SQLITE_NOMEM;
  183575. }
  183576. }else{
  183577. pRet = pNear;
  183578. }
  183579. }
  183580. if( pRet==0 ){
  183581. assert( pParse->rc!=SQLITE_OK );
  183582. sqlite3Fts5ParseNearsetFree(pNear);
  183583. sqlite3Fts5ParsePhraseFree(pPhrase);
  183584. }else{
  183585. if( pRet->nPhrase>0 ){
  183586. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  183587. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  183588. if( pPhrase->nTerm==0 ){
  183589. fts5ExprPhraseFree(pPhrase);
  183590. pRet->nPhrase--;
  183591. pParse->nPhrase--;
  183592. pPhrase = pLast;
  183593. }else if( pLast->nTerm==0 ){
  183594. fts5ExprPhraseFree(pLast);
  183595. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  183596. pParse->nPhrase--;
  183597. pRet->nPhrase--;
  183598. }
  183599. }
  183600. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  183601. }
  183602. return pRet;
  183603. }
  183604. typedef struct TokenCtx TokenCtx;
  183605. struct TokenCtx {
  183606. Fts5ExprPhrase *pPhrase;
  183607. int rc;
  183608. };
  183609. /*
  183610. ** Callback for tokenizing terms used by ParseTerm().
  183611. */
  183612. static int fts5ParseTokenize(
  183613. void *pContext, /* Pointer to Fts5InsertCtx object */
  183614. int tflags, /* Mask of FTS5_TOKEN_* flags */
  183615. const char *pToken, /* Buffer containing token */
  183616. int nToken, /* Size of token in bytes */
  183617. int iUnused1, /* Start offset of token */
  183618. int iUnused2 /* End offset of token */
  183619. ){
  183620. int rc = SQLITE_OK;
  183621. const int SZALLOC = 8;
  183622. TokenCtx *pCtx = (TokenCtx*)pContext;
  183623. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  183624. UNUSED_PARAM2(iUnused1, iUnused2);
  183625. /* If an error has already occurred, this is a no-op */
  183626. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  183627. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  183628. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  183629. Fts5ExprTerm *pSyn;
  183630. int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  183631. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  183632. if( pSyn==0 ){
  183633. rc = SQLITE_NOMEM;
  183634. }else{
  183635. memset(pSyn, 0, nByte);
  183636. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  183637. memcpy(pSyn->zTerm, pToken, nToken);
  183638. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  183639. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  183640. }
  183641. }else{
  183642. Fts5ExprTerm *pTerm;
  183643. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  183644. Fts5ExprPhrase *pNew;
  183645. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  183646. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  183647. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  183648. );
  183649. if( pNew==0 ){
  183650. rc = SQLITE_NOMEM;
  183651. }else{
  183652. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  183653. pCtx->pPhrase = pPhrase = pNew;
  183654. pNew->nTerm = nNew - SZALLOC;
  183655. }
  183656. }
  183657. if( rc==SQLITE_OK ){
  183658. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  183659. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  183660. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  183661. }
  183662. }
  183663. pCtx->rc = rc;
  183664. return rc;
  183665. }
  183666. /*
  183667. ** Free the phrase object passed as the only argument.
  183668. */
  183669. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  183670. fts5ExprPhraseFree(pPhrase);
  183671. }
  183672. /*
  183673. ** Free the phrase object passed as the second argument.
  183674. */
  183675. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  183676. if( pNear ){
  183677. int i;
  183678. for(i=0; i<pNear->nPhrase; i++){
  183679. fts5ExprPhraseFree(pNear->apPhrase[i]);
  183680. }
  183681. sqlite3_free(pNear->pColset);
  183682. sqlite3_free(pNear);
  183683. }
  183684. }
  183685. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  183686. assert( pParse->pExpr==0 );
  183687. pParse->pExpr = p;
  183688. }
  183689. /*
  183690. ** This function is called by the parser to process a string token. The
  183691. ** string may or may not be quoted. In any case it is tokenized and a
  183692. ** phrase object consisting of all tokens returned.
  183693. */
  183694. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  183695. Fts5Parse *pParse, /* Parse context */
  183696. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  183697. Fts5Token *pToken, /* String to tokenize */
  183698. int bPrefix /* True if there is a trailing "*" */
  183699. ){
  183700. Fts5Config *pConfig = pParse->pConfig;
  183701. TokenCtx sCtx; /* Context object passed to callback */
  183702. int rc; /* Tokenize return code */
  183703. char *z = 0;
  183704. memset(&sCtx, 0, sizeof(TokenCtx));
  183705. sCtx.pPhrase = pAppend;
  183706. rc = fts5ParseStringFromToken(pToken, &z);
  183707. if( rc==SQLITE_OK ){
  183708. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  183709. int n;
  183710. sqlite3Fts5Dequote(z);
  183711. n = (int)strlen(z);
  183712. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  183713. }
  183714. sqlite3_free(z);
  183715. if( rc || (rc = sCtx.rc) ){
  183716. pParse->rc = rc;
  183717. fts5ExprPhraseFree(sCtx.pPhrase);
  183718. sCtx.pPhrase = 0;
  183719. }else{
  183720. if( pAppend==0 ){
  183721. if( (pParse->nPhrase % 8)==0 ){
  183722. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  183723. Fts5ExprPhrase **apNew;
  183724. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  183725. if( apNew==0 ){
  183726. pParse->rc = SQLITE_NOMEM;
  183727. fts5ExprPhraseFree(sCtx.pPhrase);
  183728. return 0;
  183729. }
  183730. pParse->apPhrase = apNew;
  183731. }
  183732. pParse->nPhrase++;
  183733. }
  183734. if( sCtx.pPhrase==0 ){
  183735. /* This happens when parsing a token or quoted phrase that contains
  183736. ** no token characters at all. (e.g ... MATCH '""'). */
  183737. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  183738. }else if( sCtx.pPhrase->nTerm ){
  183739. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
  183740. }
  183741. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  183742. }
  183743. return sCtx.pPhrase;
  183744. }
  183745. /*
  183746. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  183747. ** expression passed as the second argument.
  183748. */
  183749. static int sqlite3Fts5ExprClonePhrase(
  183750. Fts5Expr *pExpr,
  183751. int iPhrase,
  183752. Fts5Expr **ppNew
  183753. ){
  183754. int rc = SQLITE_OK; /* Return code */
  183755. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  183756. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  183757. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  183758. pOrig = pExpr->apExprPhrase[iPhrase];
  183759. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  183760. if( rc==SQLITE_OK ){
  183761. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  183762. sizeof(Fts5ExprPhrase*));
  183763. }
  183764. if( rc==SQLITE_OK ){
  183765. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  183766. sizeof(Fts5ExprNode));
  183767. }
  183768. if( rc==SQLITE_OK ){
  183769. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  183770. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  183771. }
  183772. if( rc==SQLITE_OK ){
  183773. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  183774. if( pColsetOrig ){
  183775. int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  183776. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  183777. if( pColset ){
  183778. memcpy(pColset, pColsetOrig, nByte);
  183779. }
  183780. pNew->pRoot->pNear->pColset = pColset;
  183781. }
  183782. }
  183783. if( pOrig->nTerm ){
  183784. int i; /* Used to iterate through phrase terms */
  183785. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  183786. int tflags = 0;
  183787. Fts5ExprTerm *p;
  183788. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  183789. const char *zTerm = p->zTerm;
  183790. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  183791. 0, 0);
  183792. tflags = FTS5_TOKEN_COLOCATED;
  183793. }
  183794. if( rc==SQLITE_OK ){
  183795. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  183796. sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
  183797. }
  183798. }
  183799. }else{
  183800. /* This happens when parsing a token or quoted phrase that contains
  183801. ** no token characters at all. (e.g ... MATCH '""'). */
  183802. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  183803. }
  183804. if( rc==SQLITE_OK ){
  183805. /* All the allocations succeeded. Put the expression object together. */
  183806. pNew->pIndex = pExpr->pIndex;
  183807. pNew->pConfig = pExpr->pConfig;
  183808. pNew->nPhrase = 1;
  183809. pNew->apExprPhrase[0] = sCtx.pPhrase;
  183810. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  183811. pNew->pRoot->pNear->nPhrase = 1;
  183812. sCtx.pPhrase->pNode = pNew->pRoot;
  183813. if( pOrig->nTerm==1
  183814. && pOrig->aTerm[0].pSynonym==0
  183815. && pOrig->aTerm[0].bFirst==0
  183816. ){
  183817. pNew->pRoot->eType = FTS5_TERM;
  183818. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  183819. }else{
  183820. pNew->pRoot->eType = FTS5_STRING;
  183821. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  183822. }
  183823. }else{
  183824. sqlite3Fts5ExprFree(pNew);
  183825. fts5ExprPhraseFree(sCtx.pPhrase);
  183826. pNew = 0;
  183827. }
  183828. *ppNew = pNew;
  183829. return rc;
  183830. }
  183831. /*
  183832. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  183833. ** is expected. If token pTok does not contain "NEAR", store an error
  183834. ** in the pParse object.
  183835. */
  183836. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  183837. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  183838. sqlite3Fts5ParseError(
  183839. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  183840. );
  183841. }
  183842. }
  183843. static void sqlite3Fts5ParseSetDistance(
  183844. Fts5Parse *pParse,
  183845. Fts5ExprNearset *pNear,
  183846. Fts5Token *p
  183847. ){
  183848. if( pNear ){
  183849. int nNear = 0;
  183850. int i;
  183851. if( p->n ){
  183852. for(i=0; i<p->n; i++){
  183853. char c = (char)p->p[i];
  183854. if( c<'0' || c>'9' ){
  183855. sqlite3Fts5ParseError(
  183856. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  183857. );
  183858. return;
  183859. }
  183860. nNear = nNear * 10 + (p->p[i] - '0');
  183861. }
  183862. }else{
  183863. nNear = FTS5_DEFAULT_NEARDIST;
  183864. }
  183865. pNear->nNear = nNear;
  183866. }
  183867. }
  183868. /*
  183869. ** The second argument passed to this function may be NULL, or it may be
  183870. ** an existing Fts5Colset object. This function returns a pointer to
  183871. ** a new colset object containing the contents of (p) with new value column
  183872. ** number iCol appended.
  183873. **
  183874. ** If an OOM error occurs, store an error code in pParse and return NULL.
  183875. ** The old colset object (if any) is not freed in this case.
  183876. */
  183877. static Fts5Colset *fts5ParseColset(
  183878. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  183879. Fts5Colset *p, /* Existing colset object */
  183880. int iCol /* New column to add to colset object */
  183881. ){
  183882. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  183883. Fts5Colset *pNew; /* New colset object to return */
  183884. assert( pParse->rc==SQLITE_OK );
  183885. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  183886. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  183887. if( pNew==0 ){
  183888. pParse->rc = SQLITE_NOMEM;
  183889. }else{
  183890. int *aiCol = pNew->aiCol;
  183891. int i, j;
  183892. for(i=0; i<nCol; i++){
  183893. if( aiCol[i]==iCol ) return pNew;
  183894. if( aiCol[i]>iCol ) break;
  183895. }
  183896. for(j=nCol; j>i; j--){
  183897. aiCol[j] = aiCol[j-1];
  183898. }
  183899. aiCol[i] = iCol;
  183900. pNew->nCol = nCol+1;
  183901. #ifndef NDEBUG
  183902. /* Check that the array is in order and contains no duplicate entries. */
  183903. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  183904. #endif
  183905. }
  183906. return pNew;
  183907. }
  183908. /*
  183909. ** Allocate and return an Fts5Colset object specifying the inverse of
  183910. ** the colset passed as the second argument. Free the colset passed
  183911. ** as the second argument before returning.
  183912. */
  183913. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  183914. Fts5Colset *pRet;
  183915. int nCol = pParse->pConfig->nCol;
  183916. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  183917. sizeof(Fts5Colset) + sizeof(int)*nCol
  183918. );
  183919. if( pRet ){
  183920. int i;
  183921. int iOld = 0;
  183922. for(i=0; i<nCol; i++){
  183923. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  183924. pRet->aiCol[pRet->nCol++] = i;
  183925. }else{
  183926. iOld++;
  183927. }
  183928. }
  183929. }
  183930. sqlite3_free(p);
  183931. return pRet;
  183932. }
  183933. static Fts5Colset *sqlite3Fts5ParseColset(
  183934. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  183935. Fts5Colset *pColset, /* Existing colset object */
  183936. Fts5Token *p
  183937. ){
  183938. Fts5Colset *pRet = 0;
  183939. int iCol;
  183940. char *z; /* Dequoted copy of token p */
  183941. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  183942. if( pParse->rc==SQLITE_OK ){
  183943. Fts5Config *pConfig = pParse->pConfig;
  183944. sqlite3Fts5Dequote(z);
  183945. for(iCol=0; iCol<pConfig->nCol; iCol++){
  183946. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  183947. }
  183948. if( iCol==pConfig->nCol ){
  183949. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  183950. }else{
  183951. pRet = fts5ParseColset(pParse, pColset, iCol);
  183952. }
  183953. sqlite3_free(z);
  183954. }
  183955. if( pRet==0 ){
  183956. assert( pParse->rc!=SQLITE_OK );
  183957. sqlite3_free(pColset);
  183958. }
  183959. return pRet;
  183960. }
  183961. /*
  183962. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  183963. ** SQLITE_OK when this function is called, NULL is returned.
  183964. **
  183965. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  183966. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  183967. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  183968. */
  183969. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  183970. Fts5Colset *pRet;
  183971. if( pOrig ){
  183972. int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  183973. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  183974. if( pRet ){
  183975. memcpy(pRet, pOrig, nByte);
  183976. }
  183977. }else{
  183978. pRet = 0;
  183979. }
  183980. return pRet;
  183981. }
  183982. /*
  183983. ** Remove from colset pColset any columns that are not also in colset pMerge.
  183984. */
  183985. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  183986. int iIn = 0; /* Next input in pColset */
  183987. int iMerge = 0; /* Next input in pMerge */
  183988. int iOut = 0; /* Next output slot in pColset */
  183989. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  183990. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  183991. if( iDiff==0 ){
  183992. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  183993. iMerge++;
  183994. iIn++;
  183995. }else if( iDiff>0 ){
  183996. iMerge++;
  183997. }else{
  183998. iIn++;
  183999. }
  184000. }
  184001. pColset->nCol = iOut;
  184002. }
  184003. /*
  184004. ** Recursively apply colset pColset to expression node pNode and all of
  184005. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  184006. ** of pColset. This function may use the spare copy and set (*ppFree) to
  184007. ** zero, or it may create copies of pColset using fts5CloneColset().
  184008. */
  184009. static void fts5ParseSetColset(
  184010. Fts5Parse *pParse,
  184011. Fts5ExprNode *pNode,
  184012. Fts5Colset *pColset,
  184013. Fts5Colset **ppFree
  184014. ){
  184015. if( pParse->rc==SQLITE_OK ){
  184016. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  184017. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  184018. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  184019. );
  184020. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  184021. Fts5ExprNearset *pNear = pNode->pNear;
  184022. if( pNear->pColset ){
  184023. fts5MergeColset(pNear->pColset, pColset);
  184024. if( pNear->pColset->nCol==0 ){
  184025. pNode->eType = FTS5_EOF;
  184026. pNode->xNext = 0;
  184027. }
  184028. }else if( *ppFree ){
  184029. pNear->pColset = pColset;
  184030. *ppFree = 0;
  184031. }else{
  184032. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  184033. }
  184034. }else{
  184035. int i;
  184036. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  184037. for(i=0; i<pNode->nChild; i++){
  184038. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  184039. }
  184040. }
  184041. }
  184042. }
  184043. /*
  184044. ** Apply colset pColset to expression node pExpr and all of its descendents.
  184045. */
  184046. static void sqlite3Fts5ParseSetColset(
  184047. Fts5Parse *pParse,
  184048. Fts5ExprNode *pExpr,
  184049. Fts5Colset *pColset
  184050. ){
  184051. Fts5Colset *pFree = pColset;
  184052. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  184053. pParse->rc = SQLITE_ERROR;
  184054. pParse->zErr = sqlite3_mprintf(
  184055. "fts5: column queries are not supported (detail=none)"
  184056. );
  184057. }else{
  184058. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  184059. }
  184060. sqlite3_free(pFree);
  184061. }
  184062. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  184063. switch( pNode->eType ){
  184064. case FTS5_STRING: {
  184065. Fts5ExprNearset *pNear = pNode->pNear;
  184066. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  184067. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  184068. && pNear->apPhrase[0]->aTerm[0].bFirst==0
  184069. ){
  184070. pNode->eType = FTS5_TERM;
  184071. pNode->xNext = fts5ExprNodeNext_TERM;
  184072. }else{
  184073. pNode->xNext = fts5ExprNodeNext_STRING;
  184074. }
  184075. break;
  184076. };
  184077. case FTS5_OR: {
  184078. pNode->xNext = fts5ExprNodeNext_OR;
  184079. break;
  184080. };
  184081. case FTS5_AND: {
  184082. pNode->xNext = fts5ExprNodeNext_AND;
  184083. break;
  184084. };
  184085. default: assert( pNode->eType==FTS5_NOT ); {
  184086. pNode->xNext = fts5ExprNodeNext_NOT;
  184087. break;
  184088. };
  184089. }
  184090. }
  184091. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  184092. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  184093. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  184094. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  184095. p->nChild += pSub->nChild;
  184096. sqlite3_free(pSub);
  184097. }else{
  184098. p->apChild[p->nChild++] = pSub;
  184099. }
  184100. }
  184101. /*
  184102. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  184103. ** OOM error), leave an error code in pParse and return NULL.
  184104. */
  184105. static Fts5ExprNode *sqlite3Fts5ParseNode(
  184106. Fts5Parse *pParse, /* Parse context */
  184107. int eType, /* FTS5_STRING, AND, OR or NOT */
  184108. Fts5ExprNode *pLeft, /* Left hand child expression */
  184109. Fts5ExprNode *pRight, /* Right hand child expression */
  184110. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  184111. ){
  184112. Fts5ExprNode *pRet = 0;
  184113. if( pParse->rc==SQLITE_OK ){
  184114. int nChild = 0; /* Number of children of returned node */
  184115. int nByte; /* Bytes of space to allocate for this node */
  184116. assert( (eType!=FTS5_STRING && !pNear)
  184117. || (eType==FTS5_STRING && !pLeft && !pRight)
  184118. );
  184119. if( eType==FTS5_STRING && pNear==0 ) return 0;
  184120. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  184121. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  184122. if( eType==FTS5_NOT ){
  184123. nChild = 2;
  184124. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  184125. nChild = 2;
  184126. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  184127. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  184128. }
  184129. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  184130. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  184131. if( pRet ){
  184132. pRet->eType = eType;
  184133. pRet->pNear = pNear;
  184134. fts5ExprAssignXNext(pRet);
  184135. if( eType==FTS5_STRING ){
  184136. int iPhrase;
  184137. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  184138. pNear->apPhrase[iPhrase]->pNode = pRet;
  184139. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  184140. pRet->xNext = 0;
  184141. pRet->eType = FTS5_EOF;
  184142. }
  184143. }
  184144. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  184145. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  184146. if( pNear->nPhrase!=1
  184147. || pPhrase->nTerm>1
  184148. || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
  184149. ){
  184150. assert( pParse->rc==SQLITE_OK );
  184151. pParse->rc = SQLITE_ERROR;
  184152. assert( pParse->zErr==0 );
  184153. pParse->zErr = sqlite3_mprintf(
  184154. "fts5: %s queries are not supported (detail!=full)",
  184155. pNear->nPhrase==1 ? "phrase": "NEAR"
  184156. );
  184157. sqlite3_free(pRet);
  184158. pRet = 0;
  184159. }
  184160. }
  184161. }else{
  184162. fts5ExprAddChildren(pRet, pLeft);
  184163. fts5ExprAddChildren(pRet, pRight);
  184164. }
  184165. }
  184166. }
  184167. if( pRet==0 ){
  184168. assert( pParse->rc!=SQLITE_OK );
  184169. sqlite3Fts5ParseNodeFree(pLeft);
  184170. sqlite3Fts5ParseNodeFree(pRight);
  184171. sqlite3Fts5ParseNearsetFree(pNear);
  184172. }
  184173. return pRet;
  184174. }
  184175. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  184176. Fts5Parse *pParse, /* Parse context */
  184177. Fts5ExprNode *pLeft, /* Left hand child expression */
  184178. Fts5ExprNode *pRight /* Right hand child expression */
  184179. ){
  184180. Fts5ExprNode *pRet = 0;
  184181. Fts5ExprNode *pPrev;
  184182. if( pParse->rc ){
  184183. sqlite3Fts5ParseNodeFree(pLeft);
  184184. sqlite3Fts5ParseNodeFree(pRight);
  184185. }else{
  184186. assert( pLeft->eType==FTS5_STRING
  184187. || pLeft->eType==FTS5_TERM
  184188. || pLeft->eType==FTS5_EOF
  184189. || pLeft->eType==FTS5_AND
  184190. );
  184191. assert( pRight->eType==FTS5_STRING
  184192. || pRight->eType==FTS5_TERM
  184193. || pRight->eType==FTS5_EOF
  184194. );
  184195. if( pLeft->eType==FTS5_AND ){
  184196. pPrev = pLeft->apChild[pLeft->nChild-1];
  184197. }else{
  184198. pPrev = pLeft;
  184199. }
  184200. assert( pPrev->eType==FTS5_STRING
  184201. || pPrev->eType==FTS5_TERM
  184202. || pPrev->eType==FTS5_EOF
  184203. );
  184204. if( pRight->eType==FTS5_EOF ){
  184205. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  184206. sqlite3Fts5ParseNodeFree(pRight);
  184207. pRet = pLeft;
  184208. pParse->nPhrase--;
  184209. }
  184210. else if( pPrev->eType==FTS5_EOF ){
  184211. Fts5ExprPhrase **ap;
  184212. if( pPrev==pLeft ){
  184213. pRet = pRight;
  184214. }else{
  184215. pLeft->apChild[pLeft->nChild-1] = pRight;
  184216. pRet = pLeft;
  184217. }
  184218. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  184219. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  184220. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  184221. pParse->nPhrase--;
  184222. sqlite3Fts5ParseNodeFree(pPrev);
  184223. }
  184224. else{
  184225. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  184226. }
  184227. }
  184228. return pRet;
  184229. }
  184230. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  184231. int nByte = 0;
  184232. Fts5ExprTerm *p;
  184233. char *zQuoted;
  184234. /* Determine the maximum amount of space required. */
  184235. for(p=pTerm; p; p=p->pSynonym){
  184236. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  184237. }
  184238. zQuoted = sqlite3_malloc(nByte);
  184239. if( zQuoted ){
  184240. int i = 0;
  184241. for(p=pTerm; p; p=p->pSynonym){
  184242. char *zIn = p->zTerm;
  184243. zQuoted[i++] = '"';
  184244. while( *zIn ){
  184245. if( *zIn=='"' ) zQuoted[i++] = '"';
  184246. zQuoted[i++] = *zIn++;
  184247. }
  184248. zQuoted[i++] = '"';
  184249. if( p->pSynonym ) zQuoted[i++] = '|';
  184250. }
  184251. if( pTerm->bPrefix ){
  184252. zQuoted[i++] = ' ';
  184253. zQuoted[i++] = '*';
  184254. }
  184255. zQuoted[i++] = '\0';
  184256. }
  184257. return zQuoted;
  184258. }
  184259. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  184260. char *zNew;
  184261. va_list ap;
  184262. va_start(ap, zFmt);
  184263. zNew = sqlite3_vmprintf(zFmt, ap);
  184264. va_end(ap);
  184265. if( zApp && zNew ){
  184266. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  184267. sqlite3_free(zNew);
  184268. zNew = zNew2;
  184269. }
  184270. sqlite3_free(zApp);
  184271. return zNew;
  184272. }
  184273. /*
  184274. ** Compose a tcl-readable representation of expression pExpr. Return a
  184275. ** pointer to a buffer containing that representation. It is the
  184276. ** responsibility of the caller to at some point free the buffer using
  184277. ** sqlite3_free().
  184278. */
  184279. static char *fts5ExprPrintTcl(
  184280. Fts5Config *pConfig,
  184281. const char *zNearsetCmd,
  184282. Fts5ExprNode *pExpr
  184283. ){
  184284. char *zRet = 0;
  184285. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  184286. Fts5ExprNearset *pNear = pExpr->pNear;
  184287. int i;
  184288. int iTerm;
  184289. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  184290. if( zRet==0 ) return 0;
  184291. if( pNear->pColset ){
  184292. int *aiCol = pNear->pColset->aiCol;
  184293. int nCol = pNear->pColset->nCol;
  184294. if( nCol==1 ){
  184295. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  184296. }else{
  184297. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  184298. for(i=1; i<pNear->pColset->nCol; i++){
  184299. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  184300. }
  184301. zRet = fts5PrintfAppend(zRet, "} ");
  184302. }
  184303. if( zRet==0 ) return 0;
  184304. }
  184305. if( pNear->nPhrase>1 ){
  184306. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  184307. if( zRet==0 ) return 0;
  184308. }
  184309. zRet = fts5PrintfAppend(zRet, "--");
  184310. if( zRet==0 ) return 0;
  184311. for(i=0; i<pNear->nPhrase; i++){
  184312. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  184313. zRet = fts5PrintfAppend(zRet, " {");
  184314. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  184315. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  184316. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  184317. if( pPhrase->aTerm[iTerm].bPrefix ){
  184318. zRet = fts5PrintfAppend(zRet, "*");
  184319. }
  184320. }
  184321. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  184322. if( zRet==0 ) return 0;
  184323. }
  184324. }else{
  184325. char const *zOp = 0;
  184326. int i;
  184327. switch( pExpr->eType ){
  184328. case FTS5_AND: zOp = "AND"; break;
  184329. case FTS5_NOT: zOp = "NOT"; break;
  184330. default:
  184331. assert( pExpr->eType==FTS5_OR );
  184332. zOp = "OR";
  184333. break;
  184334. }
  184335. zRet = sqlite3_mprintf("%s", zOp);
  184336. for(i=0; zRet && i<pExpr->nChild; i++){
  184337. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  184338. if( !z ){
  184339. sqlite3_free(zRet);
  184340. zRet = 0;
  184341. }else{
  184342. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  184343. }
  184344. }
  184345. }
  184346. return zRet;
  184347. }
  184348. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  184349. char *zRet = 0;
  184350. if( pExpr->eType==0 ){
  184351. return sqlite3_mprintf("\"\"");
  184352. }else
  184353. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  184354. Fts5ExprNearset *pNear = pExpr->pNear;
  184355. int i;
  184356. int iTerm;
  184357. if( pNear->pColset ){
  184358. int iCol = pNear->pColset->aiCol[0];
  184359. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  184360. if( zRet==0 ) return 0;
  184361. }
  184362. if( pNear->nPhrase>1 ){
  184363. zRet = fts5PrintfAppend(zRet, "NEAR(");
  184364. if( zRet==0 ) return 0;
  184365. }
  184366. for(i=0; i<pNear->nPhrase; i++){
  184367. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  184368. if( i!=0 ){
  184369. zRet = fts5PrintfAppend(zRet, " ");
  184370. if( zRet==0 ) return 0;
  184371. }
  184372. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  184373. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  184374. if( zTerm ){
  184375. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  184376. sqlite3_free(zTerm);
  184377. }
  184378. if( zTerm==0 || zRet==0 ){
  184379. sqlite3_free(zRet);
  184380. return 0;
  184381. }
  184382. }
  184383. }
  184384. if( pNear->nPhrase>1 ){
  184385. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  184386. if( zRet==0 ) return 0;
  184387. }
  184388. }else{
  184389. char const *zOp = 0;
  184390. int i;
  184391. switch( pExpr->eType ){
  184392. case FTS5_AND: zOp = " AND "; break;
  184393. case FTS5_NOT: zOp = " NOT "; break;
  184394. default:
  184395. assert( pExpr->eType==FTS5_OR );
  184396. zOp = " OR ";
  184397. break;
  184398. }
  184399. for(i=0; i<pExpr->nChild; i++){
  184400. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  184401. if( z==0 ){
  184402. sqlite3_free(zRet);
  184403. zRet = 0;
  184404. }else{
  184405. int e = pExpr->apChild[i]->eType;
  184406. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  184407. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  184408. (i==0 ? "" : zOp),
  184409. (b?"(":""), z, (b?")":"")
  184410. );
  184411. }
  184412. if( zRet==0 ) break;
  184413. }
  184414. }
  184415. return zRet;
  184416. }
  184417. /*
  184418. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  184419. ** and fts5_expr_tcl() (bTcl!=0).
  184420. */
  184421. static void fts5ExprFunction(
  184422. sqlite3_context *pCtx, /* Function call context */
  184423. int nArg, /* Number of args */
  184424. sqlite3_value **apVal, /* Function arguments */
  184425. int bTcl
  184426. ){
  184427. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  184428. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  184429. const char *zExpr = 0;
  184430. char *zErr = 0;
  184431. Fts5Expr *pExpr = 0;
  184432. int rc;
  184433. int i;
  184434. const char **azConfig; /* Array of arguments for Fts5Config */
  184435. const char *zNearsetCmd = "nearset";
  184436. int nConfig; /* Size of azConfig[] */
  184437. Fts5Config *pConfig = 0;
  184438. int iArg = 1;
  184439. if( nArg<1 ){
  184440. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  184441. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  184442. );
  184443. sqlite3_result_error(pCtx, zErr, -1);
  184444. sqlite3_free(zErr);
  184445. return;
  184446. }
  184447. if( bTcl && nArg>1 ){
  184448. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  184449. iArg = 2;
  184450. }
  184451. nConfig = 3 + (nArg-iArg);
  184452. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  184453. if( azConfig==0 ){
  184454. sqlite3_result_error_nomem(pCtx);
  184455. return;
  184456. }
  184457. azConfig[0] = 0;
  184458. azConfig[1] = "main";
  184459. azConfig[2] = "tbl";
  184460. for(i=3; iArg<nArg; iArg++){
  184461. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  184462. }
  184463. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  184464. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  184465. if( rc==SQLITE_OK ){
  184466. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  184467. }
  184468. if( rc==SQLITE_OK ){
  184469. char *zText;
  184470. if( pExpr->pRoot->xNext==0 ){
  184471. zText = sqlite3_mprintf("");
  184472. }else if( bTcl ){
  184473. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  184474. }else{
  184475. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  184476. }
  184477. if( zText==0 ){
  184478. rc = SQLITE_NOMEM;
  184479. }else{
  184480. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  184481. sqlite3_free(zText);
  184482. }
  184483. }
  184484. if( rc!=SQLITE_OK ){
  184485. if( zErr ){
  184486. sqlite3_result_error(pCtx, zErr, -1);
  184487. sqlite3_free(zErr);
  184488. }else{
  184489. sqlite3_result_error_code(pCtx, rc);
  184490. }
  184491. }
  184492. sqlite3_free((void *)azConfig);
  184493. sqlite3Fts5ConfigFree(pConfig);
  184494. sqlite3Fts5ExprFree(pExpr);
  184495. }
  184496. static void fts5ExprFunctionHr(
  184497. sqlite3_context *pCtx, /* Function call context */
  184498. int nArg, /* Number of args */
  184499. sqlite3_value **apVal /* Function arguments */
  184500. ){
  184501. fts5ExprFunction(pCtx, nArg, apVal, 0);
  184502. }
  184503. static void fts5ExprFunctionTcl(
  184504. sqlite3_context *pCtx, /* Function call context */
  184505. int nArg, /* Number of args */
  184506. sqlite3_value **apVal /* Function arguments */
  184507. ){
  184508. fts5ExprFunction(pCtx, nArg, apVal, 1);
  184509. }
  184510. /*
  184511. ** The implementation of an SQLite user-defined-function that accepts a
  184512. ** single integer as an argument. If the integer is an alpha-numeric
  184513. ** unicode code point, 1 is returned. Otherwise 0.
  184514. */
  184515. static void fts5ExprIsAlnum(
  184516. sqlite3_context *pCtx, /* Function call context */
  184517. int nArg, /* Number of args */
  184518. sqlite3_value **apVal /* Function arguments */
  184519. ){
  184520. int iCode;
  184521. if( nArg!=1 ){
  184522. sqlite3_result_error(pCtx,
  184523. "wrong number of arguments to function fts5_isalnum", -1
  184524. );
  184525. return;
  184526. }
  184527. iCode = sqlite3_value_int(apVal[0]);
  184528. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  184529. }
  184530. static void fts5ExprFold(
  184531. sqlite3_context *pCtx, /* Function call context */
  184532. int nArg, /* Number of args */
  184533. sqlite3_value **apVal /* Function arguments */
  184534. ){
  184535. if( nArg!=1 && nArg!=2 ){
  184536. sqlite3_result_error(pCtx,
  184537. "wrong number of arguments to function fts5_fold", -1
  184538. );
  184539. }else{
  184540. int iCode;
  184541. int bRemoveDiacritics = 0;
  184542. iCode = sqlite3_value_int(apVal[0]);
  184543. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  184544. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  184545. }
  184546. }
  184547. /*
  184548. ** This is called during initialization to register the fts5_expr() scalar
  184549. ** UDF with the SQLite handle passed as the only argument.
  184550. */
  184551. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  184552. struct Fts5ExprFunc {
  184553. const char *z;
  184554. void (*x)(sqlite3_context*,int,sqlite3_value**);
  184555. } aFunc[] = {
  184556. { "fts5_expr", fts5ExprFunctionHr },
  184557. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  184558. { "fts5_isalnum", fts5ExprIsAlnum },
  184559. { "fts5_fold", fts5ExprFold },
  184560. };
  184561. int i;
  184562. int rc = SQLITE_OK;
  184563. void *pCtx = (void*)pGlobal;
  184564. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  184565. struct Fts5ExprFunc *p = &aFunc[i];
  184566. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  184567. }
  184568. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  184569. #ifndef NDEBUG
  184570. (void)sqlite3Fts5ParserTrace;
  184571. #endif
  184572. return rc;
  184573. }
  184574. /*
  184575. ** Return the number of phrases in expression pExpr.
  184576. */
  184577. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  184578. return (pExpr ? pExpr->nPhrase : 0);
  184579. }
  184580. /*
  184581. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  184582. */
  184583. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  184584. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  184585. return pExpr->apExprPhrase[iPhrase]->nTerm;
  184586. }
  184587. /*
  184588. ** This function is used to access the current position list for phrase
  184589. ** iPhrase.
  184590. */
  184591. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  184592. int nRet;
  184593. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  184594. Fts5ExprNode *pNode = pPhrase->pNode;
  184595. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  184596. *pa = pPhrase->poslist.p;
  184597. nRet = pPhrase->poslist.n;
  184598. }else{
  184599. *pa = 0;
  184600. nRet = 0;
  184601. }
  184602. return nRet;
  184603. }
  184604. struct Fts5PoslistPopulator {
  184605. Fts5PoslistWriter writer;
  184606. int bOk; /* True if ok to populate */
  184607. int bMiss;
  184608. };
  184609. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  184610. Fts5PoslistPopulator *pRet;
  184611. pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  184612. if( pRet ){
  184613. int i;
  184614. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  184615. for(i=0; i<pExpr->nPhrase; i++){
  184616. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  184617. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  184618. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  184619. if( bLive &&
  184620. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  184621. ){
  184622. pRet[i].bMiss = 1;
  184623. }else{
  184624. pBuf->n = 0;
  184625. }
  184626. }
  184627. }
  184628. return pRet;
  184629. }
  184630. struct Fts5ExprCtx {
  184631. Fts5Expr *pExpr;
  184632. Fts5PoslistPopulator *aPopulator;
  184633. i64 iOff;
  184634. };
  184635. typedef struct Fts5ExprCtx Fts5ExprCtx;
  184636. /*
  184637. ** TODO: Make this more efficient!
  184638. */
  184639. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  184640. int i;
  184641. for(i=0; i<pColset->nCol; i++){
  184642. if( pColset->aiCol[i]==iCol ) return 1;
  184643. }
  184644. return 0;
  184645. }
  184646. static int fts5ExprPopulatePoslistsCb(
  184647. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  184648. int tflags, /* Mask of FTS5_TOKEN_* flags */
  184649. const char *pToken, /* Pointer to buffer containing token */
  184650. int nToken, /* Size of token in bytes */
  184651. int iUnused1, /* Byte offset of token within input text */
  184652. int iUnused2 /* Byte offset of end of token within input text */
  184653. ){
  184654. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  184655. Fts5Expr *pExpr = p->pExpr;
  184656. int i;
  184657. UNUSED_PARAM2(iUnused1, iUnused2);
  184658. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  184659. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  184660. for(i=0; i<pExpr->nPhrase; i++){
  184661. Fts5ExprTerm *pTerm;
  184662. if( p->aPopulator[i].bOk==0 ) continue;
  184663. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  184664. int nTerm = (int)strlen(pTerm->zTerm);
  184665. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  184666. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  184667. ){
  184668. int rc = sqlite3Fts5PoslistWriterAppend(
  184669. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  184670. );
  184671. if( rc ) return rc;
  184672. break;
  184673. }
  184674. }
  184675. }
  184676. return SQLITE_OK;
  184677. }
  184678. static int sqlite3Fts5ExprPopulatePoslists(
  184679. Fts5Config *pConfig,
  184680. Fts5Expr *pExpr,
  184681. Fts5PoslistPopulator *aPopulator,
  184682. int iCol,
  184683. const char *z, int n
  184684. ){
  184685. int i;
  184686. Fts5ExprCtx sCtx;
  184687. sCtx.pExpr = pExpr;
  184688. sCtx.aPopulator = aPopulator;
  184689. sCtx.iOff = (((i64)iCol) << 32) - 1;
  184690. for(i=0; i<pExpr->nPhrase; i++){
  184691. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  184692. Fts5Colset *pColset = pNode->pNear->pColset;
  184693. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  184694. || aPopulator[i].bMiss
  184695. ){
  184696. aPopulator[i].bOk = 0;
  184697. }else{
  184698. aPopulator[i].bOk = 1;
  184699. }
  184700. }
  184701. return sqlite3Fts5Tokenize(pConfig,
  184702. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  184703. );
  184704. }
  184705. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  184706. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  184707. pNode->pNear->apPhrase[0]->poslist.n = 0;
  184708. }else{
  184709. int i;
  184710. for(i=0; i<pNode->nChild; i++){
  184711. fts5ExprClearPoslists(pNode->apChild[i]);
  184712. }
  184713. }
  184714. }
  184715. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  184716. pNode->iRowid = iRowid;
  184717. pNode->bEof = 0;
  184718. switch( pNode->eType ){
  184719. case FTS5_TERM:
  184720. case FTS5_STRING:
  184721. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  184722. case FTS5_AND: {
  184723. int i;
  184724. for(i=0; i<pNode->nChild; i++){
  184725. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  184726. fts5ExprClearPoslists(pNode);
  184727. return 0;
  184728. }
  184729. }
  184730. break;
  184731. }
  184732. case FTS5_OR: {
  184733. int i;
  184734. int bRet = 0;
  184735. for(i=0; i<pNode->nChild; i++){
  184736. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  184737. bRet = 1;
  184738. }
  184739. }
  184740. return bRet;
  184741. }
  184742. default: {
  184743. assert( pNode->eType==FTS5_NOT );
  184744. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  184745. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  184746. ){
  184747. fts5ExprClearPoslists(pNode);
  184748. return 0;
  184749. }
  184750. break;
  184751. }
  184752. }
  184753. return 1;
  184754. }
  184755. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  184756. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  184757. }
  184758. /*
  184759. ** This function is only called for detail=columns tables.
  184760. */
  184761. static int sqlite3Fts5ExprPhraseCollist(
  184762. Fts5Expr *pExpr,
  184763. int iPhrase,
  184764. const u8 **ppCollist,
  184765. int *pnCollist
  184766. ){
  184767. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  184768. Fts5ExprNode *pNode = pPhrase->pNode;
  184769. int rc = SQLITE_OK;
  184770. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  184771. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  184772. if( pNode->bEof==0
  184773. && pNode->iRowid==pExpr->pRoot->iRowid
  184774. && pPhrase->poslist.n>0
  184775. ){
  184776. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  184777. if( pTerm->pSynonym ){
  184778. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  184779. rc = fts5ExprSynonymList(
  184780. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  184781. );
  184782. }else{
  184783. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  184784. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  184785. }
  184786. }else{
  184787. *ppCollist = 0;
  184788. *pnCollist = 0;
  184789. }
  184790. return rc;
  184791. }
  184792. /*
  184793. ** 2014 August 11
  184794. **
  184795. ** The author disclaims copyright to this source code. In place of
  184796. ** a legal notice, here is a blessing:
  184797. **
  184798. ** May you do good and not evil.
  184799. ** May you find forgiveness for yourself and forgive others.
  184800. ** May you share freely, never taking more than you give.
  184801. **
  184802. ******************************************************************************
  184803. **
  184804. */
  184805. /* #include "fts5Int.h" */
  184806. typedef struct Fts5HashEntry Fts5HashEntry;
  184807. /*
  184808. ** This file contains the implementation of an in-memory hash table used
  184809. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  184810. ** segment.
  184811. */
  184812. struct Fts5Hash {
  184813. int eDetail; /* Copy of Fts5Config.eDetail */
  184814. int *pnByte; /* Pointer to bytes counter */
  184815. int nEntry; /* Number of entries currently in hash */
  184816. int nSlot; /* Size of aSlot[] array */
  184817. Fts5HashEntry *pScan; /* Current ordered scan item */
  184818. Fts5HashEntry **aSlot; /* Array of hash slots */
  184819. };
  184820. /*
  184821. ** Each entry in the hash table is represented by an object of the
  184822. ** following type. Each object, its key (a nul-terminated string) and
  184823. ** its current data are stored in a single memory allocation. The
  184824. ** key immediately follows the object in memory. The position list
  184825. ** data immediately follows the key data in memory.
  184826. **
  184827. ** The data that follows the key is in a similar, but not identical format
  184828. ** to the doclist data stored in the database. It is:
  184829. **
  184830. ** * Rowid, as a varint
  184831. ** * Position list, without 0x00 terminator.
  184832. ** * Size of previous position list and rowid, as a 4 byte
  184833. ** big-endian integer.
  184834. **
  184835. ** iRowidOff:
  184836. ** Offset of last rowid written to data area. Relative to first byte of
  184837. ** structure.
  184838. **
  184839. ** nData:
  184840. ** Bytes of data written since iRowidOff.
  184841. */
  184842. struct Fts5HashEntry {
  184843. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  184844. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  184845. int nAlloc; /* Total size of allocation */
  184846. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  184847. int nData; /* Total bytes of data (incl. structure) */
  184848. int nKey; /* Length of key in bytes */
  184849. u8 bDel; /* Set delete-flag @ iSzPoslist */
  184850. u8 bContent; /* Set content-flag (detail=none mode) */
  184851. i16 iCol; /* Column of last value written */
  184852. int iPos; /* Position of last value written */
  184853. i64 iRowid; /* Rowid of last value written */
  184854. };
  184855. /*
  184856. ** Eqivalent to:
  184857. **
  184858. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  184859. */
  184860. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  184861. /*
  184862. ** Allocate a new hash table.
  184863. */
  184864. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  184865. int rc = SQLITE_OK;
  184866. Fts5Hash *pNew;
  184867. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  184868. if( pNew==0 ){
  184869. rc = SQLITE_NOMEM;
  184870. }else{
  184871. int nByte;
  184872. memset(pNew, 0, sizeof(Fts5Hash));
  184873. pNew->pnByte = pnByte;
  184874. pNew->eDetail = pConfig->eDetail;
  184875. pNew->nSlot = 1024;
  184876. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  184877. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  184878. if( pNew->aSlot==0 ){
  184879. sqlite3_free(pNew);
  184880. *ppNew = 0;
  184881. rc = SQLITE_NOMEM;
  184882. }else{
  184883. memset(pNew->aSlot, 0, nByte);
  184884. }
  184885. }
  184886. return rc;
  184887. }
  184888. /*
  184889. ** Free a hash table object.
  184890. */
  184891. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  184892. if( pHash ){
  184893. sqlite3Fts5HashClear(pHash);
  184894. sqlite3_free(pHash->aSlot);
  184895. sqlite3_free(pHash);
  184896. }
  184897. }
  184898. /*
  184899. ** Empty (but do not delete) a hash table.
  184900. */
  184901. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  184902. int i;
  184903. for(i=0; i<pHash->nSlot; i++){
  184904. Fts5HashEntry *pNext;
  184905. Fts5HashEntry *pSlot;
  184906. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  184907. pNext = pSlot->pHashNext;
  184908. sqlite3_free(pSlot);
  184909. }
  184910. }
  184911. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  184912. pHash->nEntry = 0;
  184913. }
  184914. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  184915. int i;
  184916. unsigned int h = 13;
  184917. for(i=n-1; i>=0; i--){
  184918. h = (h << 3) ^ h ^ p[i];
  184919. }
  184920. return (h % nSlot);
  184921. }
  184922. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  184923. int i;
  184924. unsigned int h = 13;
  184925. for(i=n-1; i>=0; i--){
  184926. h = (h << 3) ^ h ^ p[i];
  184927. }
  184928. h = (h << 3) ^ h ^ b;
  184929. return (h % nSlot);
  184930. }
  184931. /*
  184932. ** Resize the hash table by doubling the number of slots.
  184933. */
  184934. static int fts5HashResize(Fts5Hash *pHash){
  184935. int nNew = pHash->nSlot*2;
  184936. int i;
  184937. Fts5HashEntry **apNew;
  184938. Fts5HashEntry **apOld = pHash->aSlot;
  184939. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  184940. if( !apNew ) return SQLITE_NOMEM;
  184941. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  184942. for(i=0; i<pHash->nSlot; i++){
  184943. while( apOld[i] ){
  184944. unsigned int iHash;
  184945. Fts5HashEntry *p = apOld[i];
  184946. apOld[i] = p->pHashNext;
  184947. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
  184948. (int)strlen(fts5EntryKey(p)));
  184949. p->pHashNext = apNew[iHash];
  184950. apNew[iHash] = p;
  184951. }
  184952. }
  184953. sqlite3_free(apOld);
  184954. pHash->nSlot = nNew;
  184955. pHash->aSlot = apNew;
  184956. return SQLITE_OK;
  184957. }
  184958. static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
  184959. if( p->iSzPoslist ){
  184960. u8 *pPtr = (u8*)p;
  184961. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  184962. assert( p->nData==p->iSzPoslist );
  184963. if( p->bDel ){
  184964. pPtr[p->nData++] = 0x00;
  184965. if( p->bContent ){
  184966. pPtr[p->nData++] = 0x00;
  184967. }
  184968. }
  184969. }else{
  184970. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  184971. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  184972. assert( p->bDel==0 || p->bDel==1 );
  184973. if( nPos<=127 ){
  184974. pPtr[p->iSzPoslist] = (u8)nPos;
  184975. }else{
  184976. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  184977. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  184978. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  184979. p->nData += (nByte-1);
  184980. }
  184981. }
  184982. p->iSzPoslist = 0;
  184983. p->bDel = 0;
  184984. p->bContent = 0;
  184985. }
  184986. }
  184987. /*
  184988. ** Add an entry to the in-memory hash table. The key is the concatenation
  184989. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  184990. **
  184991. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  184992. **
  184993. ** Or, if iCol is negative, then the value is a delete marker.
  184994. */
  184995. static int sqlite3Fts5HashWrite(
  184996. Fts5Hash *pHash,
  184997. i64 iRowid, /* Rowid for this entry */
  184998. int iCol, /* Column token appears in (-ve -> delete) */
  184999. int iPos, /* Position of token within column */
  185000. char bByte, /* First byte of token */
  185001. const char *pToken, int nToken /* Token to add or remove to or from index */
  185002. ){
  185003. unsigned int iHash;
  185004. Fts5HashEntry *p;
  185005. u8 *pPtr;
  185006. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  185007. int bNew; /* If non-delete entry should be written */
  185008. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  185009. /* Attempt to locate an existing hash entry */
  185010. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  185011. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  185012. char *zKey = fts5EntryKey(p);
  185013. if( zKey[0]==bByte
  185014. && p->nKey==nToken
  185015. && memcmp(&zKey[1], pToken, nToken)==0
  185016. ){
  185017. break;
  185018. }
  185019. }
  185020. /* If an existing hash entry cannot be found, create a new one. */
  185021. if( p==0 ){
  185022. /* Figure out how much space to allocate */
  185023. char *zKey;
  185024. int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  185025. if( nByte<128 ) nByte = 128;
  185026. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  185027. if( (pHash->nEntry*2)>=pHash->nSlot ){
  185028. int rc = fts5HashResize(pHash);
  185029. if( rc!=SQLITE_OK ) return rc;
  185030. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  185031. }
  185032. /* Allocate new Fts5HashEntry and add it to the hash table. */
  185033. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  185034. if( !p ) return SQLITE_NOMEM;
  185035. memset(p, 0, sizeof(Fts5HashEntry));
  185036. p->nAlloc = nByte;
  185037. zKey = fts5EntryKey(p);
  185038. zKey[0] = bByte;
  185039. memcpy(&zKey[1], pToken, nToken);
  185040. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  185041. p->nKey = nToken;
  185042. zKey[nToken+1] = '\0';
  185043. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  185044. p->pHashNext = pHash->aSlot[iHash];
  185045. pHash->aSlot[iHash] = p;
  185046. pHash->nEntry++;
  185047. /* Add the first rowid field to the hash-entry */
  185048. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  185049. p->iRowid = iRowid;
  185050. p->iSzPoslist = p->nData;
  185051. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  185052. p->nData += 1;
  185053. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  185054. }
  185055. nIncr += p->nData;
  185056. }else{
  185057. /* Appending to an existing hash-entry. Check that there is enough
  185058. ** space to append the largest possible new entry. Worst case scenario
  185059. ** is:
  185060. **
  185061. ** + 9 bytes for a new rowid,
  185062. ** + 4 byte reserved for the "poslist size" varint.
  185063. ** + 1 byte for a "new column" byte,
  185064. ** + 3 bytes for a new column number (16-bit max) as a varint,
  185065. ** + 5 bytes for the new position offset (32-bit max).
  185066. */
  185067. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  185068. int nNew = p->nAlloc * 2;
  185069. Fts5HashEntry *pNew;
  185070. Fts5HashEntry **pp;
  185071. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  185072. if( pNew==0 ) return SQLITE_NOMEM;
  185073. pNew->nAlloc = nNew;
  185074. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  185075. *pp = pNew;
  185076. p = pNew;
  185077. }
  185078. nIncr -= p->nData;
  185079. }
  185080. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  185081. pPtr = (u8*)p;
  185082. /* If this is a new rowid, append the 4-byte size field for the previous
  185083. ** entry, and the new rowid for this entry. */
  185084. if( iRowid!=p->iRowid ){
  185085. fts5HashAddPoslistSize(pHash, p);
  185086. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  185087. p->iRowid = iRowid;
  185088. bNew = 1;
  185089. p->iSzPoslist = p->nData;
  185090. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  185091. p->nData += 1;
  185092. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  185093. p->iPos = 0;
  185094. }
  185095. }
  185096. if( iCol>=0 ){
  185097. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  185098. p->bContent = 1;
  185099. }else{
  185100. /* Append a new column value, if necessary */
  185101. assert( iCol>=p->iCol );
  185102. if( iCol!=p->iCol ){
  185103. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  185104. pPtr[p->nData++] = 0x01;
  185105. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  185106. p->iCol = (i16)iCol;
  185107. p->iPos = 0;
  185108. }else{
  185109. bNew = 1;
  185110. p->iCol = (i16)(iPos = iCol);
  185111. }
  185112. }
  185113. /* Append the new position offset, if necessary */
  185114. if( bNew ){
  185115. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  185116. p->iPos = iPos;
  185117. }
  185118. }
  185119. }else{
  185120. /* This is a delete. Set the delete flag. */
  185121. p->bDel = 1;
  185122. }
  185123. nIncr += p->nData;
  185124. *pHash->pnByte += nIncr;
  185125. return SQLITE_OK;
  185126. }
  185127. /*
  185128. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  185129. ** each sorted in key order. This function merges the two lists into a
  185130. ** single list and returns a pointer to its first element.
  185131. */
  185132. static Fts5HashEntry *fts5HashEntryMerge(
  185133. Fts5HashEntry *pLeft,
  185134. Fts5HashEntry *pRight
  185135. ){
  185136. Fts5HashEntry *p1 = pLeft;
  185137. Fts5HashEntry *p2 = pRight;
  185138. Fts5HashEntry *pRet = 0;
  185139. Fts5HashEntry **ppOut = &pRet;
  185140. while( p1 || p2 ){
  185141. if( p1==0 ){
  185142. *ppOut = p2;
  185143. p2 = 0;
  185144. }else if( p2==0 ){
  185145. *ppOut = p1;
  185146. p1 = 0;
  185147. }else{
  185148. int i = 0;
  185149. char *zKey1 = fts5EntryKey(p1);
  185150. char *zKey2 = fts5EntryKey(p2);
  185151. while( zKey1[i]==zKey2[i] ) i++;
  185152. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  185153. /* p2 is smaller */
  185154. *ppOut = p2;
  185155. ppOut = &p2->pScanNext;
  185156. p2 = p2->pScanNext;
  185157. }else{
  185158. /* p1 is smaller */
  185159. *ppOut = p1;
  185160. ppOut = &p1->pScanNext;
  185161. p1 = p1->pScanNext;
  185162. }
  185163. *ppOut = 0;
  185164. }
  185165. }
  185166. return pRet;
  185167. }
  185168. /*
  185169. ** Extract all tokens from hash table iHash and link them into a list
  185170. ** in sorted order. The hash table is cleared before returning. It is
  185171. ** the responsibility of the caller to free the elements of the returned
  185172. ** list.
  185173. */
  185174. static int fts5HashEntrySort(
  185175. Fts5Hash *pHash,
  185176. const char *pTerm, int nTerm, /* Query prefix, if any */
  185177. Fts5HashEntry **ppSorted
  185178. ){
  185179. const int nMergeSlot = 32;
  185180. Fts5HashEntry **ap;
  185181. Fts5HashEntry *pList;
  185182. int iSlot;
  185183. int i;
  185184. *ppSorted = 0;
  185185. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  185186. if( !ap ) return SQLITE_NOMEM;
  185187. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  185188. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  185189. Fts5HashEntry *pIter;
  185190. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  185191. if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
  185192. Fts5HashEntry *pEntry = pIter;
  185193. pEntry->pScanNext = 0;
  185194. for(i=0; ap[i]; i++){
  185195. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  185196. ap[i] = 0;
  185197. }
  185198. ap[i] = pEntry;
  185199. }
  185200. }
  185201. }
  185202. pList = 0;
  185203. for(i=0; i<nMergeSlot; i++){
  185204. pList = fts5HashEntryMerge(pList, ap[i]);
  185205. }
  185206. pHash->nEntry = 0;
  185207. sqlite3_free(ap);
  185208. *ppSorted = pList;
  185209. return SQLITE_OK;
  185210. }
  185211. /*
  185212. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  185213. */
  185214. static int sqlite3Fts5HashQuery(
  185215. Fts5Hash *pHash, /* Hash table to query */
  185216. const char *pTerm, int nTerm, /* Query term */
  185217. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  185218. int *pnDoclist /* OUT: Size of doclist in bytes */
  185219. ){
  185220. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  185221. char *zKey = 0;
  185222. Fts5HashEntry *p;
  185223. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  185224. zKey = fts5EntryKey(p);
  185225. if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
  185226. }
  185227. if( p ){
  185228. fts5HashAddPoslistSize(pHash, p);
  185229. *ppDoclist = (const u8*)&zKey[nTerm+1];
  185230. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  185231. }else{
  185232. *ppDoclist = 0;
  185233. *pnDoclist = 0;
  185234. }
  185235. return SQLITE_OK;
  185236. }
  185237. static int sqlite3Fts5HashScanInit(
  185238. Fts5Hash *p, /* Hash table to query */
  185239. const char *pTerm, int nTerm /* Query prefix */
  185240. ){
  185241. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  185242. }
  185243. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  185244. assert( !sqlite3Fts5HashScanEof(p) );
  185245. p->pScan = p->pScan->pScanNext;
  185246. }
  185247. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  185248. return (p->pScan==0);
  185249. }
  185250. static void sqlite3Fts5HashScanEntry(
  185251. Fts5Hash *pHash,
  185252. const char **pzTerm, /* OUT: term (nul-terminated) */
  185253. const u8 **ppDoclist, /* OUT: pointer to doclist */
  185254. int *pnDoclist /* OUT: size of doclist in bytes */
  185255. ){
  185256. Fts5HashEntry *p;
  185257. if( (p = pHash->pScan) ){
  185258. char *zKey = fts5EntryKey(p);
  185259. int nTerm = (int)strlen(zKey);
  185260. fts5HashAddPoslistSize(pHash, p);
  185261. *pzTerm = zKey;
  185262. *ppDoclist = (const u8*)&zKey[nTerm+1];
  185263. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  185264. }else{
  185265. *pzTerm = 0;
  185266. *ppDoclist = 0;
  185267. *pnDoclist = 0;
  185268. }
  185269. }
  185270. /*
  185271. ** 2014 May 31
  185272. **
  185273. ** The author disclaims copyright to this source code. In place of
  185274. ** a legal notice, here is a blessing:
  185275. **
  185276. ** May you do good and not evil.
  185277. ** May you find forgiveness for yourself and forgive others.
  185278. ** May you share freely, never taking more than you give.
  185279. **
  185280. ******************************************************************************
  185281. **
  185282. ** Low level access to the FTS index stored in the database file. The
  185283. ** routines in this file file implement all read and write access to the
  185284. ** %_data table. Other parts of the system access this functionality via
  185285. ** the interface defined in fts5Int.h.
  185286. */
  185287. /* #include "fts5Int.h" */
  185288. /*
  185289. ** Overview:
  185290. **
  185291. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  185292. ** As well as the main term index, there may be up to 31 prefix indexes.
  185293. ** The format is similar to FTS3/4, except that:
  185294. **
  185295. ** * all segment b-tree leaf data is stored in fixed size page records
  185296. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  185297. ** taken to ensure it is possible to iterate in either direction through
  185298. ** the entries in a doclist, or to seek to a specific entry within a
  185299. ** doclist, without loading it into memory.
  185300. **
  185301. ** * large doclists that span many pages have associated "doclist index"
  185302. ** records that contain a copy of the first rowid on each page spanned by
  185303. ** the doclist. This is used to speed up seek operations, and merges of
  185304. ** large doclists with very small doclists.
  185305. **
  185306. ** * extra fields in the "structure record" record the state of ongoing
  185307. ** incremental merge operations.
  185308. **
  185309. */
  185310. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  185311. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  185312. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  185313. #define FTS5_MAIN_PREFIX '0'
  185314. #if FTS5_MAX_PREFIX_INDEXES > 31
  185315. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  185316. #endif
  185317. /*
  185318. ** Details:
  185319. **
  185320. ** The %_data table managed by this module,
  185321. **
  185322. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  185323. **
  185324. ** , contains the following 5 types of records. See the comments surrounding
  185325. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  185326. ** assigned to each fo them.
  185327. **
  185328. ** 1. Structure Records:
  185329. **
  185330. ** The set of segments that make up an index - the index structure - are
  185331. ** recorded in a single record within the %_data table. The record consists
  185332. ** of a single 32-bit configuration cookie value followed by a list of
  185333. ** SQLite varints. If the FTS table features more than one index (because
  185334. ** there are one or more prefix indexes), it is guaranteed that all share
  185335. ** the same cookie value.
  185336. **
  185337. ** Immediately following the configuration cookie, the record begins with
  185338. ** three varints:
  185339. **
  185340. ** + number of levels,
  185341. ** + total number of segments on all levels,
  185342. ** + value of write counter.
  185343. **
  185344. ** Then, for each level from 0 to nMax:
  185345. **
  185346. ** + number of input segments in ongoing merge.
  185347. ** + total number of segments in level.
  185348. ** + for each segment from oldest to newest:
  185349. ** + segment id (always > 0)
  185350. ** + first leaf page number (often 1, always greater than 0)
  185351. ** + final leaf page number
  185352. **
  185353. ** 2. The Averages Record:
  185354. **
  185355. ** A single record within the %_data table. The data is a list of varints.
  185356. ** The first value is the number of rows in the index. Then, for each column
  185357. ** from left to right, the total number of tokens in the column for all
  185358. ** rows of the table.
  185359. **
  185360. ** 3. Segment leaves:
  185361. **
  185362. ** TERM/DOCLIST FORMAT:
  185363. **
  185364. ** Most of each segment leaf is taken up by term/doclist data. The
  185365. ** general format of term/doclist, starting with the first term
  185366. ** on the leaf page, is:
  185367. **
  185368. ** varint : size of first term
  185369. ** blob: first term data
  185370. ** doclist: first doclist
  185371. ** zero-or-more {
  185372. ** varint: number of bytes in common with previous term
  185373. ** varint: number of bytes of new term data (nNew)
  185374. ** blob: nNew bytes of new term data
  185375. ** doclist: next doclist
  185376. ** }
  185377. **
  185378. ** doclist format:
  185379. **
  185380. ** varint: first rowid
  185381. ** poslist: first poslist
  185382. ** zero-or-more {
  185383. ** varint: rowid delta (always > 0)
  185384. ** poslist: next poslist
  185385. ** }
  185386. **
  185387. ** poslist format:
  185388. **
  185389. ** varint: size of poslist in bytes multiplied by 2, not including
  185390. ** this field. Plus 1 if this entry carries the "delete" flag.
  185391. ** collist: collist for column 0
  185392. ** zero-or-more {
  185393. ** 0x01 byte
  185394. ** varint: column number (I)
  185395. ** collist: collist for column I
  185396. ** }
  185397. **
  185398. ** collist format:
  185399. **
  185400. ** varint: first offset + 2
  185401. ** zero-or-more {
  185402. ** varint: offset delta + 2
  185403. ** }
  185404. **
  185405. ** PAGE FORMAT
  185406. **
  185407. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  185408. ** unsigned integer fields in big-endian format. They are:
  185409. **
  185410. ** * The byte offset of the first rowid on the page, if it exists
  185411. ** and occurs before the first term (otherwise 0).
  185412. **
  185413. ** * The byte offset of the start of the page footer. If the page
  185414. ** footer is 0 bytes in size, then this field is the same as the
  185415. ** size of the leaf page in bytes.
  185416. **
  185417. ** The page footer consists of a single varint for each term located
  185418. ** on the page. Each varint is the byte offset of the current term
  185419. ** within the page, delta-compressed against the previous value. In
  185420. ** other words, the first varint in the footer is the byte offset of
  185421. ** the first term, the second is the byte offset of the second less that
  185422. ** of the first, and so on.
  185423. **
  185424. ** The term/doclist format described above is accurate if the entire
  185425. ** term/doclist data fits on a single leaf page. If this is not the case,
  185426. ** the format is changed in two ways:
  185427. **
  185428. ** + if the first rowid on a page occurs before the first term, it
  185429. ** is stored as a literal value:
  185430. **
  185431. ** varint: first rowid
  185432. **
  185433. ** + the first term on each page is stored in the same way as the
  185434. ** very first term of the segment:
  185435. **
  185436. ** varint : size of first term
  185437. ** blob: first term data
  185438. **
  185439. ** 5. Segment doclist indexes:
  185440. **
  185441. ** Doclist indexes are themselves b-trees, however they usually consist of
  185442. ** a single leaf record only. The format of each doclist index leaf page
  185443. ** is:
  185444. **
  185445. ** * Flags byte. Bits are:
  185446. ** 0x01: Clear if leaf is also the root page, otherwise set.
  185447. **
  185448. ** * Page number of fts index leaf page. As a varint.
  185449. **
  185450. ** * First rowid on page indicated by previous field. As a varint.
  185451. **
  185452. ** * A list of varints, one for each subsequent termless page. A
  185453. ** positive delta if the termless page contains at least one rowid,
  185454. ** or an 0x00 byte otherwise.
  185455. **
  185456. ** Internal doclist index nodes are:
  185457. **
  185458. ** * Flags byte. Bits are:
  185459. ** 0x01: Clear for root page, otherwise set.
  185460. **
  185461. ** * Page number of first child page. As a varint.
  185462. **
  185463. ** * Copy of first rowid on page indicated by previous field. As a varint.
  185464. **
  185465. ** * A list of delta-encoded varints - the first rowid on each subsequent
  185466. ** child page.
  185467. **
  185468. */
  185469. /*
  185470. ** Rowids for the averages and structure records in the %_data table.
  185471. */
  185472. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  185473. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  185474. /*
  185475. ** Macros determining the rowids used by segment leaves and dlidx leaves
  185476. ** and nodes. All nodes and leaves are stored in the %_data table with large
  185477. ** positive rowids.
  185478. **
  185479. ** Each segment has a unique non-zero 16-bit id.
  185480. **
  185481. ** The rowid for each segment leaf is found by passing the segment id and
  185482. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  185483. ** sequentially starting from 1.
  185484. */
  185485. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  185486. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  185487. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  185488. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  185489. #define fts5_dri(segid, dlidx, height, pgno) ( \
  185490. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  185491. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  185492. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  185493. ((i64)(pgno)) \
  185494. )
  185495. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  185496. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  185497. /*
  185498. ** Maximum segments permitted in a single index
  185499. */
  185500. #define FTS5_MAX_SEGMENT 2000
  185501. #ifdef SQLITE_DEBUG
  185502. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  185503. #endif
  185504. /*
  185505. ** Each time a blob is read from the %_data table, it is padded with this
  185506. ** many zero bytes. This makes it easier to decode the various record formats
  185507. ** without overreading if the records are corrupt.
  185508. */
  185509. #define FTS5_DATA_ZERO_PADDING 8
  185510. #define FTS5_DATA_PADDING 20
  185511. typedef struct Fts5Data Fts5Data;
  185512. typedef struct Fts5DlidxIter Fts5DlidxIter;
  185513. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  185514. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  185515. typedef struct Fts5Iter Fts5Iter;
  185516. typedef struct Fts5PageWriter Fts5PageWriter;
  185517. typedef struct Fts5SegIter Fts5SegIter;
  185518. typedef struct Fts5DoclistIter Fts5DoclistIter;
  185519. typedef struct Fts5SegWriter Fts5SegWriter;
  185520. typedef struct Fts5Structure Fts5Structure;
  185521. typedef struct Fts5StructureLevel Fts5StructureLevel;
  185522. typedef struct Fts5StructureSegment Fts5StructureSegment;
  185523. struct Fts5Data {
  185524. u8 *p; /* Pointer to buffer containing record */
  185525. int nn; /* Size of record in bytes */
  185526. int szLeaf; /* Size of leaf without page-index */
  185527. };
  185528. /*
  185529. ** One object per %_data table.
  185530. */
  185531. struct Fts5Index {
  185532. Fts5Config *pConfig; /* Virtual table configuration */
  185533. char *zDataTbl; /* Name of %_data table */
  185534. int nWorkUnit; /* Leaf pages in a "unit" of work */
  185535. /*
  185536. ** Variables related to the accumulation of tokens and doclists within the
  185537. ** in-memory hash tables before they are flushed to disk.
  185538. */
  185539. Fts5Hash *pHash; /* Hash table for in-memory data */
  185540. int nPendingData; /* Current bytes of pending data */
  185541. i64 iWriteRowid; /* Rowid for current doc being written */
  185542. int bDelete; /* Current write is a delete */
  185543. /* Error state. */
  185544. int rc; /* Current error code */
  185545. /* State used by the fts5DataXXX() functions. */
  185546. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  185547. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  185548. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  185549. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  185550. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  185551. sqlite3_stmt *pIdxSelect;
  185552. int nRead; /* Total number of blocks read */
  185553. sqlite3_stmt *pDataVersion;
  185554. i64 iStructVersion; /* data_version when pStruct read */
  185555. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  185556. };
  185557. struct Fts5DoclistIter {
  185558. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  185559. /* Output variables. aPoslist==0 at EOF */
  185560. i64 iRowid;
  185561. u8 *aPoslist;
  185562. int nPoslist;
  185563. int nSize;
  185564. };
  185565. /*
  185566. ** The contents of the "structure" record for each index are represented
  185567. ** using an Fts5Structure record in memory. Which uses instances of the
  185568. ** other Fts5StructureXXX types as components.
  185569. */
  185570. struct Fts5StructureSegment {
  185571. int iSegid; /* Segment id */
  185572. int pgnoFirst; /* First leaf page number in segment */
  185573. int pgnoLast; /* Last leaf page number in segment */
  185574. };
  185575. struct Fts5StructureLevel {
  185576. int nMerge; /* Number of segments in incr-merge */
  185577. int nSeg; /* Total number of segments on level */
  185578. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  185579. };
  185580. struct Fts5Structure {
  185581. int nRef; /* Object reference count */
  185582. u64 nWriteCounter; /* Total leaves written to level 0 */
  185583. int nSegment; /* Total segments in this structure */
  185584. int nLevel; /* Number of levels in this index */
  185585. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  185586. };
  185587. /*
  185588. ** An object of type Fts5SegWriter is used to write to segments.
  185589. */
  185590. struct Fts5PageWriter {
  185591. int pgno; /* Page number for this page */
  185592. int iPrevPgidx; /* Previous value written into pgidx */
  185593. Fts5Buffer buf; /* Buffer containing leaf data */
  185594. Fts5Buffer pgidx; /* Buffer containing page-index */
  185595. Fts5Buffer term; /* Buffer containing previous term on page */
  185596. };
  185597. struct Fts5DlidxWriter {
  185598. int pgno; /* Page number for this page */
  185599. int bPrevValid; /* True if iPrev is valid */
  185600. i64 iPrev; /* Previous rowid value written to page */
  185601. Fts5Buffer buf; /* Buffer containing page data */
  185602. };
  185603. struct Fts5SegWriter {
  185604. int iSegid; /* Segid to write to */
  185605. Fts5PageWriter writer; /* PageWriter object */
  185606. i64 iPrevRowid; /* Previous rowid written to current leaf */
  185607. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  185608. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  185609. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  185610. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  185611. int nLeafWritten; /* Number of leaf pages written */
  185612. int nEmpty; /* Number of contiguous term-less nodes */
  185613. int nDlidx; /* Allocated size of aDlidx[] array */
  185614. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  185615. /* Values to insert into the %_idx table */
  185616. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  185617. int iBtPage; /* Page number corresponding to btterm */
  185618. };
  185619. typedef struct Fts5CResult Fts5CResult;
  185620. struct Fts5CResult {
  185621. u16 iFirst; /* aSeg[] index of firstest iterator */
  185622. u8 bTermEq; /* True if the terms are equal */
  185623. };
  185624. /*
  185625. ** Object for iterating through a single segment, visiting each term/rowid
  185626. ** pair in the segment.
  185627. **
  185628. ** pSeg:
  185629. ** The segment to iterate through.
  185630. **
  185631. ** iLeafPgno:
  185632. ** Current leaf page number within segment.
  185633. **
  185634. ** iLeafOffset:
  185635. ** Byte offset within the current leaf that is the first byte of the
  185636. ** position list data (one byte passed the position-list size field).
  185637. ** rowid field of the current entry. Usually this is the size field of the
  185638. ** position list data. The exception is if the rowid for the current entry
  185639. ** is the last thing on the leaf page.
  185640. **
  185641. ** pLeaf:
  185642. ** Buffer containing current leaf page data. Set to NULL at EOF.
  185643. **
  185644. ** iTermLeafPgno, iTermLeafOffset:
  185645. ** Leaf page number containing the last term read from the segment. And
  185646. ** the offset immediately following the term data.
  185647. **
  185648. ** flags:
  185649. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  185650. **
  185651. ** FTS5_SEGITER_ONETERM:
  185652. ** If set, set the iterator to point to EOF after the current doclist
  185653. ** has been exhausted. Do not proceed to the next term in the segment.
  185654. **
  185655. ** FTS5_SEGITER_REVERSE:
  185656. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  185657. ** it is set, iterate through rowid in descending order instead of the
  185658. ** default ascending order.
  185659. **
  185660. ** iRowidOffset/nRowidOffset/aRowidOffset:
  185661. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  185662. **
  185663. ** For each rowid on the page corresponding to the current term, the
  185664. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  185665. ** start of the "position-list-size" field within the page.
  185666. **
  185667. ** iTermIdx:
  185668. ** Index of current term on iTermLeafPgno.
  185669. */
  185670. struct Fts5SegIter {
  185671. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  185672. int flags; /* Mask of configuration flags */
  185673. int iLeafPgno; /* Current leaf page number */
  185674. Fts5Data *pLeaf; /* Current leaf data */
  185675. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  185676. int iLeafOffset; /* Byte offset within current leaf */
  185677. /* Next method */
  185678. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  185679. /* The page and offset from which the current term was read. The offset
  185680. ** is the offset of the first rowid in the current doclist. */
  185681. int iTermLeafPgno;
  185682. int iTermLeafOffset;
  185683. int iPgidxOff; /* Next offset in pgidx */
  185684. int iEndofDoclist;
  185685. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  185686. int iRowidOffset; /* Current entry in aRowidOffset[] */
  185687. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  185688. int *aRowidOffset; /* Array of offset to rowid fields */
  185689. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  185690. /* Variables populated based on current entry. */
  185691. Fts5Buffer term; /* Current term */
  185692. i64 iRowid; /* Current rowid */
  185693. int nPos; /* Number of bytes in current position list */
  185694. u8 bDel; /* True if the delete flag is set */
  185695. };
  185696. /*
  185697. ** Argument is a pointer to an Fts5Data structure that contains a
  185698. ** leaf page.
  185699. */
  185700. #define ASSERT_SZLEAF_OK(x) assert( \
  185701. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  185702. )
  185703. #define FTS5_SEGITER_ONETERM 0x01
  185704. #define FTS5_SEGITER_REVERSE 0x02
  185705. /*
  185706. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  185707. ** page. This macro evaluates to true if the leaf contains no terms, or
  185708. ** false if it contains at least one term.
  185709. */
  185710. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  185711. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  185712. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  185713. /*
  185714. ** Object for iterating through the merged results of one or more segments,
  185715. ** visiting each term/rowid pair in the merged data.
  185716. **
  185717. ** nSeg is always a power of two greater than or equal to the number of
  185718. ** segments that this object is merging data from. Both the aSeg[] and
  185719. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  185720. ** with zeroed objects - these are handled as if they were iterators opened
  185721. ** on empty segments.
  185722. **
  185723. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  185724. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  185725. ** comparison in this context is the index of the iterator that currently
  185726. ** points to the smaller term/rowid combination. Iterators at EOF are
  185727. ** considered to be greater than all other iterators.
  185728. **
  185729. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  185730. ** the smallest key overall. aFirst[0] is unused.
  185731. **
  185732. ** poslist:
  185733. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  185734. ** There is no way to tell if this is populated or not.
  185735. */
  185736. struct Fts5Iter {
  185737. Fts5IndexIter base; /* Base class containing output vars */
  185738. Fts5Index *pIndex; /* Index that owns this iterator */
  185739. Fts5Structure *pStruct; /* Database structure for this iterator */
  185740. Fts5Buffer poslist; /* Buffer containing current poslist */
  185741. Fts5Colset *pColset; /* Restrict matches to these columns */
  185742. /* Invoked to set output variables. */
  185743. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  185744. int nSeg; /* Size of aSeg[] array */
  185745. int bRev; /* True to iterate in reverse order */
  185746. u8 bSkipEmpty; /* True to skip deleted entries */
  185747. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  185748. Fts5CResult *aFirst; /* Current merge state (see above) */
  185749. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  185750. };
  185751. /*
  185752. ** An instance of the following type is used to iterate through the contents
  185753. ** of a doclist-index record.
  185754. **
  185755. ** pData:
  185756. ** Record containing the doclist-index data.
  185757. **
  185758. ** bEof:
  185759. ** Set to true once iterator has reached EOF.
  185760. **
  185761. ** iOff:
  185762. ** Set to the current offset within record pData.
  185763. */
  185764. struct Fts5DlidxLvl {
  185765. Fts5Data *pData; /* Data for current page of this level */
  185766. int iOff; /* Current offset into pData */
  185767. int bEof; /* At EOF already */
  185768. int iFirstOff; /* Used by reverse iterators */
  185769. /* Output variables */
  185770. int iLeafPgno; /* Page number of current leaf page */
  185771. i64 iRowid; /* First rowid on leaf iLeafPgno */
  185772. };
  185773. struct Fts5DlidxIter {
  185774. int nLvl;
  185775. int iSegid;
  185776. Fts5DlidxLvl aLvl[1];
  185777. };
  185778. static void fts5PutU16(u8 *aOut, u16 iVal){
  185779. aOut[0] = (iVal>>8);
  185780. aOut[1] = (iVal&0xFF);
  185781. }
  185782. static u16 fts5GetU16(const u8 *aIn){
  185783. return ((u16)aIn[0] << 8) + aIn[1];
  185784. }
  185785. /*
  185786. ** Allocate and return a buffer at least nByte bytes in size.
  185787. **
  185788. ** If an OOM error is encountered, return NULL and set the error code in
  185789. ** the Fts5Index handle passed as the first argument.
  185790. */
  185791. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  185792. return sqlite3Fts5MallocZero(&p->rc, nByte);
  185793. }
  185794. /*
  185795. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  185796. **
  185797. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  185798. ** +ve if pRight is smaller than pLeft. In other words:
  185799. **
  185800. ** res = *pLeft - *pRight
  185801. */
  185802. #ifdef SQLITE_DEBUG
  185803. static int fts5BufferCompareBlob(
  185804. Fts5Buffer *pLeft, /* Left hand side of comparison */
  185805. const u8 *pRight, int nRight /* Right hand side of comparison */
  185806. ){
  185807. int nCmp = MIN(pLeft->n, nRight);
  185808. int res = memcmp(pLeft->p, pRight, nCmp);
  185809. return (res==0 ? (pLeft->n - nRight) : res);
  185810. }
  185811. #endif
  185812. /*
  185813. ** Compare the contents of the two buffers using memcmp(). If one buffer
  185814. ** is a prefix of the other, it is considered the lesser.
  185815. **
  185816. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  185817. ** +ve if pRight is smaller than pLeft. In other words:
  185818. **
  185819. ** res = *pLeft - *pRight
  185820. */
  185821. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  185822. int nCmp = MIN(pLeft->n, pRight->n);
  185823. int res = memcmp(pLeft->p, pRight->p, nCmp);
  185824. return (res==0 ? (pLeft->n - pRight->n) : res);
  185825. }
  185826. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  185827. int ret;
  185828. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  185829. return ret;
  185830. }
  185831. /*
  185832. ** Close the read-only blob handle, if it is open.
  185833. */
  185834. static void fts5CloseReader(Fts5Index *p){
  185835. if( p->pReader ){
  185836. sqlite3_blob *pReader = p->pReader;
  185837. p->pReader = 0;
  185838. sqlite3_blob_close(pReader);
  185839. }
  185840. }
  185841. /*
  185842. ** Retrieve a record from the %_data table.
  185843. **
  185844. ** If an error occurs, NULL is returned and an error left in the
  185845. ** Fts5Index object.
  185846. */
  185847. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  185848. Fts5Data *pRet = 0;
  185849. if( p->rc==SQLITE_OK ){
  185850. int rc = SQLITE_OK;
  185851. if( p->pReader ){
  185852. /* This call may return SQLITE_ABORT if there has been a savepoint
  185853. ** rollback since it was last used. In this case a new blob handle
  185854. ** is required. */
  185855. sqlite3_blob *pBlob = p->pReader;
  185856. p->pReader = 0;
  185857. rc = sqlite3_blob_reopen(pBlob, iRowid);
  185858. assert( p->pReader==0 );
  185859. p->pReader = pBlob;
  185860. if( rc!=SQLITE_OK ){
  185861. fts5CloseReader(p);
  185862. }
  185863. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  185864. }
  185865. /* If the blob handle is not open at this point, open it and seek
  185866. ** to the requested entry. */
  185867. if( p->pReader==0 && rc==SQLITE_OK ){
  185868. Fts5Config *pConfig = p->pConfig;
  185869. rc = sqlite3_blob_open(pConfig->db,
  185870. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  185871. );
  185872. }
  185873. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  185874. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  185875. ** All the reasons those functions might return SQLITE_ERROR - missing
  185876. ** table, missing row, non-blob/text in block column - indicate
  185877. ** backing store corruption. */
  185878. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  185879. if( rc==SQLITE_OK ){
  185880. u8 *aOut = 0; /* Read blob data into this buffer */
  185881. int nByte = sqlite3_blob_bytes(p->pReader);
  185882. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  185883. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  185884. if( pRet ){
  185885. pRet->nn = nByte;
  185886. aOut = pRet->p = (u8*)&pRet[1];
  185887. }else{
  185888. rc = SQLITE_NOMEM;
  185889. }
  185890. if( rc==SQLITE_OK ){
  185891. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  185892. }
  185893. if( rc!=SQLITE_OK ){
  185894. sqlite3_free(pRet);
  185895. pRet = 0;
  185896. }else{
  185897. /* TODO1: Fix this */
  185898. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  185899. }
  185900. }
  185901. p->rc = rc;
  185902. p->nRead++;
  185903. }
  185904. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  185905. return pRet;
  185906. }
  185907. /*
  185908. ** Release a reference to data record returned by an earlier call to
  185909. ** fts5DataRead().
  185910. */
  185911. static void fts5DataRelease(Fts5Data *pData){
  185912. sqlite3_free(pData);
  185913. }
  185914. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  185915. Fts5Data *pRet = fts5DataRead(p, iRowid);
  185916. if( pRet ){
  185917. if( pRet->szLeaf>pRet->nn ){
  185918. p->rc = FTS5_CORRUPT;
  185919. fts5DataRelease(pRet);
  185920. pRet = 0;
  185921. }
  185922. }
  185923. return pRet;
  185924. }
  185925. static int fts5IndexPrepareStmt(
  185926. Fts5Index *p,
  185927. sqlite3_stmt **ppStmt,
  185928. char *zSql
  185929. ){
  185930. if( p->rc==SQLITE_OK ){
  185931. if( zSql ){
  185932. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  185933. SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
  185934. }else{
  185935. p->rc = SQLITE_NOMEM;
  185936. }
  185937. }
  185938. sqlite3_free(zSql);
  185939. return p->rc;
  185940. }
  185941. /*
  185942. ** INSERT OR REPLACE a record into the %_data table.
  185943. */
  185944. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  185945. if( p->rc!=SQLITE_OK ) return;
  185946. if( p->pWriter==0 ){
  185947. Fts5Config *pConfig = p->pConfig;
  185948. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  185949. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  185950. pConfig->zDb, pConfig->zName
  185951. ));
  185952. if( p->rc ) return;
  185953. }
  185954. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  185955. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  185956. sqlite3_step(p->pWriter);
  185957. p->rc = sqlite3_reset(p->pWriter);
  185958. sqlite3_bind_null(p->pWriter, 2);
  185959. }
  185960. /*
  185961. ** Execute the following SQL:
  185962. **
  185963. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  185964. */
  185965. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  185966. if( p->rc!=SQLITE_OK ) return;
  185967. if( p->pDeleter==0 ){
  185968. int rc;
  185969. Fts5Config *pConfig = p->pConfig;
  185970. char *zSql = sqlite3_mprintf(
  185971. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  185972. pConfig->zDb, pConfig->zName
  185973. );
  185974. if( zSql==0 ){
  185975. rc = SQLITE_NOMEM;
  185976. }else{
  185977. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  185978. SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
  185979. sqlite3_free(zSql);
  185980. }
  185981. if( rc!=SQLITE_OK ){
  185982. p->rc = rc;
  185983. return;
  185984. }
  185985. }
  185986. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  185987. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  185988. sqlite3_step(p->pDeleter);
  185989. p->rc = sqlite3_reset(p->pDeleter);
  185990. }
  185991. /*
  185992. ** Remove all records associated with segment iSegid.
  185993. */
  185994. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  185995. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  185996. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  185997. fts5DataDelete(p, iFirst, iLast);
  185998. if( p->pIdxDeleter==0 ){
  185999. Fts5Config *pConfig = p->pConfig;
  186000. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  186001. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  186002. pConfig->zDb, pConfig->zName
  186003. ));
  186004. }
  186005. if( p->rc==SQLITE_OK ){
  186006. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  186007. sqlite3_step(p->pIdxDeleter);
  186008. p->rc = sqlite3_reset(p->pIdxDeleter);
  186009. }
  186010. }
  186011. /*
  186012. ** Release a reference to an Fts5Structure object returned by an earlier
  186013. ** call to fts5StructureRead() or fts5StructureDecode().
  186014. */
  186015. static void fts5StructureRelease(Fts5Structure *pStruct){
  186016. if( pStruct && 0>=(--pStruct->nRef) ){
  186017. int i;
  186018. assert( pStruct->nRef==0 );
  186019. for(i=0; i<pStruct->nLevel; i++){
  186020. sqlite3_free(pStruct->aLevel[i].aSeg);
  186021. }
  186022. sqlite3_free(pStruct);
  186023. }
  186024. }
  186025. static void fts5StructureRef(Fts5Structure *pStruct){
  186026. pStruct->nRef++;
  186027. }
  186028. /*
  186029. ** Deserialize and return the structure record currently stored in serialized
  186030. ** form within buffer pData/nData.
  186031. **
  186032. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  186033. ** are over-allocated by one slot. This allows the structure contents
  186034. ** to be more easily edited.
  186035. **
  186036. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  186037. ** returned. Otherwise, *ppOut is set to point to the new object and
  186038. ** SQLITE_OK returned.
  186039. */
  186040. static int fts5StructureDecode(
  186041. const u8 *pData, /* Buffer containing serialized structure */
  186042. int nData, /* Size of buffer pData in bytes */
  186043. int *piCookie, /* Configuration cookie value */
  186044. Fts5Structure **ppOut /* OUT: Deserialized object */
  186045. ){
  186046. int rc = SQLITE_OK;
  186047. int i = 0;
  186048. int iLvl;
  186049. int nLevel = 0;
  186050. int nSegment = 0;
  186051. int nByte; /* Bytes of space to allocate at pRet */
  186052. Fts5Structure *pRet = 0; /* Structure object to return */
  186053. /* Grab the cookie value */
  186054. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  186055. i = 4;
  186056. /* Read the total number of levels and segments from the start of the
  186057. ** structure record. */
  186058. i += fts5GetVarint32(&pData[i], nLevel);
  186059. i += fts5GetVarint32(&pData[i], nSegment);
  186060. nByte = (
  186061. sizeof(Fts5Structure) + /* Main structure */
  186062. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  186063. );
  186064. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  186065. if( pRet ){
  186066. pRet->nRef = 1;
  186067. pRet->nLevel = nLevel;
  186068. pRet->nSegment = nSegment;
  186069. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  186070. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  186071. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  186072. int nTotal = 0;
  186073. int iSeg;
  186074. if( i>=nData ){
  186075. rc = FTS5_CORRUPT;
  186076. }else{
  186077. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  186078. i += fts5GetVarint32(&pData[i], nTotal);
  186079. assert( nTotal>=pLvl->nMerge );
  186080. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  186081. nTotal * sizeof(Fts5StructureSegment)
  186082. );
  186083. }
  186084. if( rc==SQLITE_OK ){
  186085. pLvl->nSeg = nTotal;
  186086. for(iSeg=0; iSeg<nTotal; iSeg++){
  186087. if( i>=nData ){
  186088. rc = FTS5_CORRUPT;
  186089. break;
  186090. }
  186091. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  186092. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  186093. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  186094. }
  186095. }
  186096. }
  186097. if( rc!=SQLITE_OK ){
  186098. fts5StructureRelease(pRet);
  186099. pRet = 0;
  186100. }
  186101. }
  186102. *ppOut = pRet;
  186103. return rc;
  186104. }
  186105. /*
  186106. **
  186107. */
  186108. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  186109. if( *pRc==SQLITE_OK ){
  186110. Fts5Structure *pStruct = *ppStruct;
  186111. int nLevel = pStruct->nLevel;
  186112. int nByte = (
  186113. sizeof(Fts5Structure) + /* Main structure */
  186114. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  186115. );
  186116. pStruct = sqlite3_realloc(pStruct, nByte);
  186117. if( pStruct ){
  186118. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  186119. pStruct->nLevel++;
  186120. *ppStruct = pStruct;
  186121. }else{
  186122. *pRc = SQLITE_NOMEM;
  186123. }
  186124. }
  186125. }
  186126. /*
  186127. ** Extend level iLvl so that there is room for at least nExtra more
  186128. ** segments.
  186129. */
  186130. static void fts5StructureExtendLevel(
  186131. int *pRc,
  186132. Fts5Structure *pStruct,
  186133. int iLvl,
  186134. int nExtra,
  186135. int bInsert
  186136. ){
  186137. if( *pRc==SQLITE_OK ){
  186138. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  186139. Fts5StructureSegment *aNew;
  186140. int nByte;
  186141. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  186142. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  186143. if( aNew ){
  186144. if( bInsert==0 ){
  186145. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  186146. }else{
  186147. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  186148. memmove(&aNew[nExtra], aNew, nMove);
  186149. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  186150. }
  186151. pLvl->aSeg = aNew;
  186152. }else{
  186153. *pRc = SQLITE_NOMEM;
  186154. }
  186155. }
  186156. }
  186157. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  186158. Fts5Structure *pRet = 0;
  186159. Fts5Config *pConfig = p->pConfig;
  186160. int iCookie; /* Configuration cookie */
  186161. Fts5Data *pData;
  186162. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  186163. if( p->rc==SQLITE_OK ){
  186164. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  186165. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  186166. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  186167. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  186168. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  186169. }
  186170. fts5DataRelease(pData);
  186171. if( p->rc!=SQLITE_OK ){
  186172. fts5StructureRelease(pRet);
  186173. pRet = 0;
  186174. }
  186175. }
  186176. return pRet;
  186177. }
  186178. static i64 fts5IndexDataVersion(Fts5Index *p){
  186179. i64 iVersion = 0;
  186180. if( p->rc==SQLITE_OK ){
  186181. if( p->pDataVersion==0 ){
  186182. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  186183. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  186184. );
  186185. if( p->rc ) return 0;
  186186. }
  186187. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  186188. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  186189. }
  186190. p->rc = sqlite3_reset(p->pDataVersion);
  186191. }
  186192. return iVersion;
  186193. }
  186194. /*
  186195. ** Read, deserialize and return the structure record.
  186196. **
  186197. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  186198. ** are over-allocated as described for function fts5StructureDecode()
  186199. ** above.
  186200. **
  186201. ** If an error occurs, NULL is returned and an error code left in the
  186202. ** Fts5Index handle. If an error has already occurred when this function
  186203. ** is called, it is a no-op.
  186204. */
  186205. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  186206. if( p->pStruct==0 ){
  186207. p->iStructVersion = fts5IndexDataVersion(p);
  186208. if( p->rc==SQLITE_OK ){
  186209. p->pStruct = fts5StructureReadUncached(p);
  186210. }
  186211. }
  186212. #if 0
  186213. else{
  186214. Fts5Structure *pTest = fts5StructureReadUncached(p);
  186215. if( pTest ){
  186216. int i, j;
  186217. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  186218. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  186219. for(i=0; i<pTest->nLevel; i++){
  186220. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  186221. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  186222. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  186223. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  186224. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  186225. assert_nc( p1->iSegid==p2->iSegid );
  186226. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  186227. assert_nc( p1->pgnoLast==p2->pgnoLast );
  186228. }
  186229. }
  186230. fts5StructureRelease(pTest);
  186231. }
  186232. }
  186233. #endif
  186234. if( p->rc!=SQLITE_OK ) return 0;
  186235. assert( p->iStructVersion!=0 );
  186236. assert( p->pStruct!=0 );
  186237. fts5StructureRef(p->pStruct);
  186238. return p->pStruct;
  186239. }
  186240. static void fts5StructureInvalidate(Fts5Index *p){
  186241. if( p->pStruct ){
  186242. fts5StructureRelease(p->pStruct);
  186243. p->pStruct = 0;
  186244. }
  186245. }
  186246. /*
  186247. ** Return the total number of segments in index structure pStruct. This
  186248. ** function is only ever used as part of assert() conditions.
  186249. */
  186250. #ifdef SQLITE_DEBUG
  186251. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  186252. int nSegment = 0; /* Total number of segments */
  186253. if( pStruct ){
  186254. int iLvl; /* Used to iterate through levels */
  186255. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  186256. nSegment += pStruct->aLevel[iLvl].nSeg;
  186257. }
  186258. }
  186259. return nSegment;
  186260. }
  186261. #endif
  186262. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  186263. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  186264. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  186265. (pBuf)->n += nBlob; \
  186266. }
  186267. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  186268. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  186269. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  186270. }
  186271. /*
  186272. ** Serialize and store the "structure" record.
  186273. **
  186274. ** If an error occurs, leave an error code in the Fts5Index object. If an
  186275. ** error has already occurred, this function is a no-op.
  186276. */
  186277. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  186278. if( p->rc==SQLITE_OK ){
  186279. Fts5Buffer buf; /* Buffer to serialize record into */
  186280. int iLvl; /* Used to iterate through levels */
  186281. int iCookie; /* Cookie value to store */
  186282. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  186283. memset(&buf, 0, sizeof(Fts5Buffer));
  186284. /* Append the current configuration cookie */
  186285. iCookie = p->pConfig->iCookie;
  186286. if( iCookie<0 ) iCookie = 0;
  186287. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  186288. sqlite3Fts5Put32(buf.p, iCookie);
  186289. buf.n = 4;
  186290. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  186291. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  186292. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  186293. }
  186294. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  186295. int iSeg; /* Used to iterate through segments */
  186296. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  186297. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  186298. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  186299. assert( pLvl->nMerge<=pLvl->nSeg );
  186300. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  186301. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  186302. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  186303. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  186304. }
  186305. }
  186306. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  186307. fts5BufferFree(&buf);
  186308. }
  186309. }
  186310. #if 0
  186311. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  186312. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  186313. int rc = SQLITE_OK;
  186314. Fts5Buffer buf;
  186315. memset(&buf, 0, sizeof(buf));
  186316. fts5DebugStructure(&rc, &buf, pStruct);
  186317. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  186318. fflush(stdout);
  186319. fts5BufferFree(&buf);
  186320. }
  186321. #else
  186322. # define fts5PrintStructure(x,y)
  186323. #endif
  186324. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  186325. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  186326. }
  186327. /*
  186328. ** Return a copy of index structure pStruct. Except, promote as many
  186329. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  186330. ** returned.
  186331. */
  186332. static void fts5StructurePromoteTo(
  186333. Fts5Index *p,
  186334. int iPromote,
  186335. int szPromote,
  186336. Fts5Structure *pStruct
  186337. ){
  186338. int il, is;
  186339. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  186340. if( pOut->nMerge==0 ){
  186341. for(il=iPromote+1; il<pStruct->nLevel; il++){
  186342. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  186343. if( pLvl->nMerge ) return;
  186344. for(is=pLvl->nSeg-1; is>=0; is--){
  186345. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  186346. if( sz>szPromote ) return;
  186347. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  186348. if( p->rc ) return;
  186349. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  186350. pOut->nSeg++;
  186351. pLvl->nSeg--;
  186352. }
  186353. }
  186354. }
  186355. }
  186356. /*
  186357. ** A new segment has just been written to level iLvl of index structure
  186358. ** pStruct. This function determines if any segments should be promoted
  186359. ** as a result. Segments are promoted in two scenarios:
  186360. **
  186361. ** a) If the segment just written is smaller than one or more segments
  186362. ** within the previous populated level, it is promoted to the previous
  186363. ** populated level.
  186364. **
  186365. ** b) If the segment just written is larger than the newest segment on
  186366. ** the next populated level, then that segment, and any other adjacent
  186367. ** segments that are also smaller than the one just written, are
  186368. ** promoted.
  186369. **
  186370. ** If one or more segments are promoted, the structure object is updated
  186371. ** to reflect this.
  186372. */
  186373. static void fts5StructurePromote(
  186374. Fts5Index *p, /* FTS5 backend object */
  186375. int iLvl, /* Index level just updated */
  186376. Fts5Structure *pStruct /* Index structure */
  186377. ){
  186378. if( p->rc==SQLITE_OK ){
  186379. int iTst;
  186380. int iPromote = -1;
  186381. int szPromote = 0; /* Promote anything this size or smaller */
  186382. Fts5StructureSegment *pSeg; /* Segment just written */
  186383. int szSeg; /* Size of segment just written */
  186384. int nSeg = pStruct->aLevel[iLvl].nSeg;
  186385. if( nSeg==0 ) return;
  186386. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  186387. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  186388. /* Check for condition (a) */
  186389. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  186390. if( iTst>=0 ){
  186391. int i;
  186392. int szMax = 0;
  186393. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  186394. assert( pTst->nMerge==0 );
  186395. for(i=0; i<pTst->nSeg; i++){
  186396. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  186397. if( sz>szMax ) szMax = sz;
  186398. }
  186399. if( szMax>=szSeg ){
  186400. /* Condition (a) is true. Promote the newest segment on level
  186401. ** iLvl to level iTst. */
  186402. iPromote = iTst;
  186403. szPromote = szMax;
  186404. }
  186405. }
  186406. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  186407. ** is a no-op if it is not. */
  186408. if( iPromote<0 ){
  186409. iPromote = iLvl;
  186410. szPromote = szSeg;
  186411. }
  186412. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  186413. }
  186414. }
  186415. /*
  186416. ** Advance the iterator passed as the only argument. If the end of the
  186417. ** doclist-index page is reached, return non-zero.
  186418. */
  186419. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  186420. Fts5Data *pData = pLvl->pData;
  186421. if( pLvl->iOff==0 ){
  186422. assert( pLvl->bEof==0 );
  186423. pLvl->iOff = 1;
  186424. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  186425. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  186426. pLvl->iFirstOff = pLvl->iOff;
  186427. }else{
  186428. int iOff;
  186429. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  186430. if( pData->p[iOff] ) break;
  186431. }
  186432. if( iOff<pData->nn ){
  186433. i64 iVal;
  186434. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  186435. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  186436. pLvl->iRowid += iVal;
  186437. pLvl->iOff = iOff;
  186438. }else{
  186439. pLvl->bEof = 1;
  186440. }
  186441. }
  186442. return pLvl->bEof;
  186443. }
  186444. /*
  186445. ** Advance the iterator passed as the only argument.
  186446. */
  186447. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  186448. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  186449. assert( iLvl<pIter->nLvl );
  186450. if( fts5DlidxLvlNext(pLvl) ){
  186451. if( (iLvl+1) < pIter->nLvl ){
  186452. fts5DlidxIterNextR(p, pIter, iLvl+1);
  186453. if( pLvl[1].bEof==0 ){
  186454. fts5DataRelease(pLvl->pData);
  186455. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  186456. pLvl->pData = fts5DataRead(p,
  186457. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  186458. );
  186459. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  186460. }
  186461. }
  186462. }
  186463. return pIter->aLvl[0].bEof;
  186464. }
  186465. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  186466. return fts5DlidxIterNextR(p, pIter, 0);
  186467. }
  186468. /*
  186469. ** The iterator passed as the first argument has the following fields set
  186470. ** as follows. This function sets up the rest of the iterator so that it
  186471. ** points to the first rowid in the doclist-index.
  186472. **
  186473. ** pData:
  186474. ** pointer to doclist-index record,
  186475. **
  186476. ** When this function is called pIter->iLeafPgno is the page number the
  186477. ** doclist is associated with (the one featuring the term).
  186478. */
  186479. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  186480. int i;
  186481. for(i=0; i<pIter->nLvl; i++){
  186482. fts5DlidxLvlNext(&pIter->aLvl[i]);
  186483. }
  186484. return pIter->aLvl[0].bEof;
  186485. }
  186486. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  186487. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  186488. }
  186489. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  186490. int i;
  186491. /* Advance each level to the last entry on the last page */
  186492. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  186493. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  186494. while( fts5DlidxLvlNext(pLvl)==0 );
  186495. pLvl->bEof = 0;
  186496. if( i>0 ){
  186497. Fts5DlidxLvl *pChild = &pLvl[-1];
  186498. fts5DataRelease(pChild->pData);
  186499. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  186500. pChild->pData = fts5DataRead(p,
  186501. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  186502. );
  186503. }
  186504. }
  186505. }
  186506. /*
  186507. ** Move the iterator passed as the only argument to the previous entry.
  186508. */
  186509. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  186510. int iOff = pLvl->iOff;
  186511. assert( pLvl->bEof==0 );
  186512. if( iOff<=pLvl->iFirstOff ){
  186513. pLvl->bEof = 1;
  186514. }else{
  186515. u8 *a = pLvl->pData->p;
  186516. i64 iVal;
  186517. int iLimit;
  186518. int ii;
  186519. int nZero = 0;
  186520. /* Currently iOff points to the first byte of a varint. This block
  186521. ** decrements iOff until it points to the first byte of the previous
  186522. ** varint. Taking care not to read any memory locations that occur
  186523. ** before the buffer in memory. */
  186524. iLimit = (iOff>9 ? iOff-9 : 0);
  186525. for(iOff--; iOff>iLimit; iOff--){
  186526. if( (a[iOff-1] & 0x80)==0 ) break;
  186527. }
  186528. fts5GetVarint(&a[iOff], (u64*)&iVal);
  186529. pLvl->iRowid -= iVal;
  186530. pLvl->iLeafPgno--;
  186531. /* Skip backwards past any 0x00 varints. */
  186532. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  186533. nZero++;
  186534. }
  186535. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  186536. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  186537. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  186538. ** bytes before a[ii]. */
  186539. int bZero = 0; /* True if last 0x00 counts */
  186540. if( (ii-8)>=pLvl->iFirstOff ){
  186541. int j;
  186542. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  186543. bZero = (j>8);
  186544. }
  186545. if( bZero==0 ) nZero--;
  186546. }
  186547. pLvl->iLeafPgno -= nZero;
  186548. pLvl->iOff = iOff - nZero;
  186549. }
  186550. return pLvl->bEof;
  186551. }
  186552. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  186553. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  186554. assert( iLvl<pIter->nLvl );
  186555. if( fts5DlidxLvlPrev(pLvl) ){
  186556. if( (iLvl+1) < pIter->nLvl ){
  186557. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  186558. if( pLvl[1].bEof==0 ){
  186559. fts5DataRelease(pLvl->pData);
  186560. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  186561. pLvl->pData = fts5DataRead(p,
  186562. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  186563. );
  186564. if( pLvl->pData ){
  186565. while( fts5DlidxLvlNext(pLvl)==0 );
  186566. pLvl->bEof = 0;
  186567. }
  186568. }
  186569. }
  186570. }
  186571. return pIter->aLvl[0].bEof;
  186572. }
  186573. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  186574. return fts5DlidxIterPrevR(p, pIter, 0);
  186575. }
  186576. /*
  186577. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  186578. */
  186579. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  186580. if( pIter ){
  186581. int i;
  186582. for(i=0; i<pIter->nLvl; i++){
  186583. fts5DataRelease(pIter->aLvl[i].pData);
  186584. }
  186585. sqlite3_free(pIter);
  186586. }
  186587. }
  186588. static Fts5DlidxIter *fts5DlidxIterInit(
  186589. Fts5Index *p, /* Fts5 Backend to iterate within */
  186590. int bRev, /* True for ORDER BY ASC */
  186591. int iSegid, /* Segment id */
  186592. int iLeafPg /* Leaf page number to load dlidx for */
  186593. ){
  186594. Fts5DlidxIter *pIter = 0;
  186595. int i;
  186596. int bDone = 0;
  186597. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  186598. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  186599. Fts5DlidxIter *pNew;
  186600. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  186601. if( pNew==0 ){
  186602. p->rc = SQLITE_NOMEM;
  186603. }else{
  186604. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  186605. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  186606. pIter = pNew;
  186607. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  186608. pLvl->pData = fts5DataRead(p, iRowid);
  186609. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  186610. bDone = 1;
  186611. }
  186612. pIter->nLvl = i+1;
  186613. }
  186614. }
  186615. if( p->rc==SQLITE_OK ){
  186616. pIter->iSegid = iSegid;
  186617. if( bRev==0 ){
  186618. fts5DlidxIterFirst(pIter);
  186619. }else{
  186620. fts5DlidxIterLast(p, pIter);
  186621. }
  186622. }
  186623. if( p->rc!=SQLITE_OK ){
  186624. fts5DlidxIterFree(pIter);
  186625. pIter = 0;
  186626. }
  186627. return pIter;
  186628. }
  186629. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  186630. return pIter->aLvl[0].iRowid;
  186631. }
  186632. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  186633. return pIter->aLvl[0].iLeafPgno;
  186634. }
  186635. /*
  186636. ** Load the next leaf page into the segment iterator.
  186637. */
  186638. static void fts5SegIterNextPage(
  186639. Fts5Index *p, /* FTS5 backend object */
  186640. Fts5SegIter *pIter /* Iterator to advance to next page */
  186641. ){
  186642. Fts5Data *pLeaf;
  186643. Fts5StructureSegment *pSeg = pIter->pSeg;
  186644. fts5DataRelease(pIter->pLeaf);
  186645. pIter->iLeafPgno++;
  186646. if( pIter->pNextLeaf ){
  186647. pIter->pLeaf = pIter->pNextLeaf;
  186648. pIter->pNextLeaf = 0;
  186649. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  186650. pIter->pLeaf = fts5LeafRead(p,
  186651. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  186652. );
  186653. }else{
  186654. pIter->pLeaf = 0;
  186655. }
  186656. pLeaf = pIter->pLeaf;
  186657. if( pLeaf ){
  186658. pIter->iPgidxOff = pLeaf->szLeaf;
  186659. if( fts5LeafIsTermless(pLeaf) ){
  186660. pIter->iEndofDoclist = pLeaf->nn+1;
  186661. }else{
  186662. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  186663. pIter->iEndofDoclist
  186664. );
  186665. }
  186666. }
  186667. }
  186668. /*
  186669. ** Argument p points to a buffer containing a varint to be interpreted as a
  186670. ** position list size field. Read the varint and return the number of bytes
  186671. ** read. Before returning, set *pnSz to the number of bytes in the position
  186672. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  186673. */
  186674. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  186675. int nSz;
  186676. int n = 0;
  186677. fts5FastGetVarint32(p, n, nSz);
  186678. assert_nc( nSz>=0 );
  186679. *pnSz = nSz/2;
  186680. *pbDel = nSz & 0x0001;
  186681. return n;
  186682. }
  186683. /*
  186684. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  186685. ** position-list size field. Read the value of the field and store it
  186686. ** in the following variables:
  186687. **
  186688. ** Fts5SegIter.nPos
  186689. ** Fts5SegIter.bDel
  186690. **
  186691. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  186692. ** position list content (if any).
  186693. */
  186694. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  186695. if( p->rc==SQLITE_OK ){
  186696. int iOff = pIter->iLeafOffset; /* Offset to read at */
  186697. ASSERT_SZLEAF_OK(pIter->pLeaf);
  186698. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  186699. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  186700. pIter->bDel = 0;
  186701. pIter->nPos = 1;
  186702. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  186703. pIter->bDel = 1;
  186704. iOff++;
  186705. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  186706. pIter->nPos = 1;
  186707. iOff++;
  186708. }else{
  186709. pIter->nPos = 0;
  186710. }
  186711. }
  186712. }else{
  186713. int nSz;
  186714. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  186715. pIter->bDel = (nSz & 0x0001);
  186716. pIter->nPos = nSz>>1;
  186717. assert_nc( pIter->nPos>=0 );
  186718. }
  186719. pIter->iLeafOffset = iOff;
  186720. }
  186721. }
  186722. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  186723. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  186724. int iOff = pIter->iLeafOffset;
  186725. ASSERT_SZLEAF_OK(pIter->pLeaf);
  186726. if( iOff>=pIter->pLeaf->szLeaf ){
  186727. fts5SegIterNextPage(p, pIter);
  186728. if( pIter->pLeaf==0 ){
  186729. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  186730. return;
  186731. }
  186732. iOff = 4;
  186733. a = pIter->pLeaf->p;
  186734. }
  186735. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  186736. pIter->iLeafOffset = iOff;
  186737. }
  186738. /*
  186739. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  186740. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  186741. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  186742. ** the first term in the segment).
  186743. **
  186744. ** This function populates:
  186745. **
  186746. ** Fts5SegIter.term
  186747. ** Fts5SegIter.rowid
  186748. **
  186749. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  186750. ** the first position list. The position list belonging to document
  186751. ** (Fts5SegIter.iRowid).
  186752. */
  186753. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  186754. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  186755. int iOff = pIter->iLeafOffset; /* Offset to read at */
  186756. int nNew; /* Bytes of new data */
  186757. iOff += fts5GetVarint32(&a[iOff], nNew);
  186758. if( iOff+nNew>pIter->pLeaf->nn ){
  186759. p->rc = FTS5_CORRUPT;
  186760. return;
  186761. }
  186762. pIter->term.n = nKeep;
  186763. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  186764. iOff += nNew;
  186765. pIter->iTermLeafOffset = iOff;
  186766. pIter->iTermLeafPgno = pIter->iLeafPgno;
  186767. pIter->iLeafOffset = iOff;
  186768. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  186769. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  186770. }else{
  186771. int nExtra;
  186772. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  186773. pIter->iEndofDoclist += nExtra;
  186774. }
  186775. fts5SegIterLoadRowid(p, pIter);
  186776. }
  186777. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  186778. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  186779. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  186780. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  186781. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  186782. pIter->xNext = fts5SegIterNext_Reverse;
  186783. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  186784. pIter->xNext = fts5SegIterNext_None;
  186785. }else{
  186786. pIter->xNext = fts5SegIterNext;
  186787. }
  186788. }
  186789. /*
  186790. ** Initialize the iterator object pIter to iterate through the entries in
  186791. ** segment pSeg. The iterator is left pointing to the first entry when
  186792. ** this function returns.
  186793. **
  186794. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  186795. ** an error has already occurred when this function is called, it is a no-op.
  186796. */
  186797. static void fts5SegIterInit(
  186798. Fts5Index *p, /* FTS index object */
  186799. Fts5StructureSegment *pSeg, /* Description of segment */
  186800. Fts5SegIter *pIter /* Object to populate */
  186801. ){
  186802. if( pSeg->pgnoFirst==0 ){
  186803. /* This happens if the segment is being used as an input to an incremental
  186804. ** merge and all data has already been "trimmed". See function
  186805. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  186806. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  186807. ** at EOF already. */
  186808. assert( pIter->pLeaf==0 );
  186809. return;
  186810. }
  186811. if( p->rc==SQLITE_OK ){
  186812. memset(pIter, 0, sizeof(*pIter));
  186813. fts5SegIterSetNext(p, pIter);
  186814. pIter->pSeg = pSeg;
  186815. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  186816. fts5SegIterNextPage(p, pIter);
  186817. }
  186818. if( p->rc==SQLITE_OK ){
  186819. pIter->iLeafOffset = 4;
  186820. assert_nc( pIter->pLeaf->nn>4 );
  186821. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  186822. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  186823. fts5SegIterLoadTerm(p, pIter, 0);
  186824. fts5SegIterLoadNPos(p, pIter);
  186825. }
  186826. }
  186827. /*
  186828. ** This function is only ever called on iterators created by calls to
  186829. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  186830. **
  186831. ** The iterator is in an unusual state when this function is called: the
  186832. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  186833. ** the position-list size field for the first relevant rowid on the page.
  186834. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  186835. **
  186836. ** This function advances the iterator so that it points to the last
  186837. ** relevant rowid on the page and, if necessary, initializes the
  186838. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  186839. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  186840. ** byte of the position list content associated with said rowid.
  186841. */
  186842. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  186843. int eDetail = p->pConfig->eDetail;
  186844. int n = pIter->pLeaf->szLeaf;
  186845. int i = pIter->iLeafOffset;
  186846. u8 *a = pIter->pLeaf->p;
  186847. int iRowidOffset = 0;
  186848. if( n>pIter->iEndofDoclist ){
  186849. n = pIter->iEndofDoclist;
  186850. }
  186851. ASSERT_SZLEAF_OK(pIter->pLeaf);
  186852. while( 1 ){
  186853. i64 iDelta = 0;
  186854. if( eDetail==FTS5_DETAIL_NONE ){
  186855. /* todo */
  186856. if( i<n && a[i]==0 ){
  186857. i++;
  186858. if( i<n && a[i]==0 ) i++;
  186859. }
  186860. }else{
  186861. int nPos;
  186862. int bDummy;
  186863. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  186864. i += nPos;
  186865. }
  186866. if( i>=n ) break;
  186867. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  186868. pIter->iRowid += iDelta;
  186869. /* If necessary, grow the pIter->aRowidOffset[] array. */
  186870. if( iRowidOffset>=pIter->nRowidOffset ){
  186871. int nNew = pIter->nRowidOffset + 8;
  186872. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  186873. if( aNew==0 ){
  186874. p->rc = SQLITE_NOMEM;
  186875. break;
  186876. }
  186877. pIter->aRowidOffset = aNew;
  186878. pIter->nRowidOffset = nNew;
  186879. }
  186880. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  186881. pIter->iLeafOffset = i;
  186882. }
  186883. pIter->iRowidOffset = iRowidOffset;
  186884. fts5SegIterLoadNPos(p, pIter);
  186885. }
  186886. /*
  186887. **
  186888. */
  186889. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  186890. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  186891. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  186892. fts5DataRelease(pIter->pLeaf);
  186893. pIter->pLeaf = 0;
  186894. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  186895. Fts5Data *pNew;
  186896. pIter->iLeafPgno--;
  186897. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  186898. pIter->pSeg->iSegid, pIter->iLeafPgno
  186899. ));
  186900. if( pNew ){
  186901. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  186902. ** thing on the page - i.e. the first rowid is on the following page.
  186903. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  186904. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  186905. assert( pIter->pLeaf==0 );
  186906. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  186907. pIter->pLeaf = pNew;
  186908. pIter->iLeafOffset = pIter->iTermLeafOffset;
  186909. }
  186910. }else{
  186911. int iRowidOff;
  186912. iRowidOff = fts5LeafFirstRowidOff(pNew);
  186913. if( iRowidOff ){
  186914. pIter->pLeaf = pNew;
  186915. pIter->iLeafOffset = iRowidOff;
  186916. }
  186917. }
  186918. if( pIter->pLeaf ){
  186919. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  186920. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  186921. break;
  186922. }else{
  186923. fts5DataRelease(pNew);
  186924. }
  186925. }
  186926. }
  186927. if( pIter->pLeaf ){
  186928. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  186929. fts5SegIterReverseInitPage(p, pIter);
  186930. }
  186931. }
  186932. /*
  186933. ** Return true if the iterator passed as the second argument currently
  186934. ** points to a delete marker. A delete marker is an entry with a 0 byte
  186935. ** position-list.
  186936. */
  186937. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  186938. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  186939. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  186940. }
  186941. /*
  186942. ** Advance iterator pIter to the next entry.
  186943. **
  186944. ** This version of fts5SegIterNext() is only used by reverse iterators.
  186945. */
  186946. static void fts5SegIterNext_Reverse(
  186947. Fts5Index *p, /* FTS5 backend object */
  186948. Fts5SegIter *pIter, /* Iterator to advance */
  186949. int *pbUnused /* Unused */
  186950. ){
  186951. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  186952. assert( pIter->pNextLeaf==0 );
  186953. UNUSED_PARAM(pbUnused);
  186954. if( pIter->iRowidOffset>0 ){
  186955. u8 *a = pIter->pLeaf->p;
  186956. int iOff;
  186957. i64 iDelta;
  186958. pIter->iRowidOffset--;
  186959. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  186960. fts5SegIterLoadNPos(p, pIter);
  186961. iOff = pIter->iLeafOffset;
  186962. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  186963. iOff += pIter->nPos;
  186964. }
  186965. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  186966. pIter->iRowid -= iDelta;
  186967. }else{
  186968. fts5SegIterReverseNewPage(p, pIter);
  186969. }
  186970. }
  186971. /*
  186972. ** Advance iterator pIter to the next entry.
  186973. **
  186974. ** This version of fts5SegIterNext() is only used if detail=none and the
  186975. ** iterator is not a reverse direction iterator.
  186976. */
  186977. static void fts5SegIterNext_None(
  186978. Fts5Index *p, /* FTS5 backend object */
  186979. Fts5SegIter *pIter, /* Iterator to advance */
  186980. int *pbNewTerm /* OUT: Set for new term */
  186981. ){
  186982. int iOff;
  186983. assert( p->rc==SQLITE_OK );
  186984. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  186985. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  186986. ASSERT_SZLEAF_OK(pIter->pLeaf);
  186987. iOff = pIter->iLeafOffset;
  186988. /* Next entry is on the next page */
  186989. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  186990. fts5SegIterNextPage(p, pIter);
  186991. if( p->rc || pIter->pLeaf==0 ) return;
  186992. pIter->iRowid = 0;
  186993. iOff = 4;
  186994. }
  186995. if( iOff<pIter->iEndofDoclist ){
  186996. /* Next entry is on the current page */
  186997. i64 iDelta;
  186998. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  186999. pIter->iLeafOffset = iOff;
  187000. pIter->iRowid += iDelta;
  187001. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  187002. if( pIter->pSeg ){
  187003. int nKeep = 0;
  187004. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  187005. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  187006. }
  187007. pIter->iLeafOffset = iOff;
  187008. fts5SegIterLoadTerm(p, pIter, nKeep);
  187009. }else{
  187010. const u8 *pList = 0;
  187011. const char *zTerm = 0;
  187012. int nList;
  187013. sqlite3Fts5HashScanNext(p->pHash);
  187014. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  187015. if( pList==0 ) goto next_none_eof;
  187016. pIter->pLeaf->p = (u8*)pList;
  187017. pIter->pLeaf->nn = nList;
  187018. pIter->pLeaf->szLeaf = nList;
  187019. pIter->iEndofDoclist = nList;
  187020. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  187021. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  187022. }
  187023. if( pbNewTerm ) *pbNewTerm = 1;
  187024. }else{
  187025. goto next_none_eof;
  187026. }
  187027. fts5SegIterLoadNPos(p, pIter);
  187028. return;
  187029. next_none_eof:
  187030. fts5DataRelease(pIter->pLeaf);
  187031. pIter->pLeaf = 0;
  187032. }
  187033. /*
  187034. ** Advance iterator pIter to the next entry.
  187035. **
  187036. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  187037. ** is not considered an error if the iterator reaches EOF. If an error has
  187038. ** already occurred when this function is called, it is a no-op.
  187039. */
  187040. static void fts5SegIterNext(
  187041. Fts5Index *p, /* FTS5 backend object */
  187042. Fts5SegIter *pIter, /* Iterator to advance */
  187043. int *pbNewTerm /* OUT: Set for new term */
  187044. ){
  187045. Fts5Data *pLeaf = pIter->pLeaf;
  187046. int iOff;
  187047. int bNewTerm = 0;
  187048. int nKeep = 0;
  187049. u8 *a;
  187050. int n;
  187051. assert( pbNewTerm==0 || *pbNewTerm==0 );
  187052. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  187053. /* Search for the end of the position list within the current page. */
  187054. a = pLeaf->p;
  187055. n = pLeaf->szLeaf;
  187056. ASSERT_SZLEAF_OK(pLeaf);
  187057. iOff = pIter->iLeafOffset + pIter->nPos;
  187058. if( iOff<n ){
  187059. /* The next entry is on the current page. */
  187060. assert_nc( iOff<=pIter->iEndofDoclist );
  187061. if( iOff>=pIter->iEndofDoclist ){
  187062. bNewTerm = 1;
  187063. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  187064. iOff += fts5GetVarint32(&a[iOff], nKeep);
  187065. }
  187066. }else{
  187067. u64 iDelta;
  187068. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  187069. pIter->iRowid += iDelta;
  187070. assert_nc( iDelta>0 );
  187071. }
  187072. pIter->iLeafOffset = iOff;
  187073. }else if( pIter->pSeg==0 ){
  187074. const u8 *pList = 0;
  187075. const char *zTerm = 0;
  187076. int nList = 0;
  187077. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  187078. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  187079. sqlite3Fts5HashScanNext(p->pHash);
  187080. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  187081. }
  187082. if( pList==0 ){
  187083. fts5DataRelease(pIter->pLeaf);
  187084. pIter->pLeaf = 0;
  187085. }else{
  187086. pIter->pLeaf->p = (u8*)pList;
  187087. pIter->pLeaf->nn = nList;
  187088. pIter->pLeaf->szLeaf = nList;
  187089. pIter->iEndofDoclist = nList+1;
  187090. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  187091. (u8*)zTerm);
  187092. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  187093. *pbNewTerm = 1;
  187094. }
  187095. }else{
  187096. iOff = 0;
  187097. /* Next entry is not on the current page */
  187098. while( iOff==0 ){
  187099. fts5SegIterNextPage(p, pIter);
  187100. pLeaf = pIter->pLeaf;
  187101. if( pLeaf==0 ) break;
  187102. ASSERT_SZLEAF_OK(pLeaf);
  187103. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  187104. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  187105. pIter->iLeafOffset = iOff;
  187106. if( pLeaf->nn>pLeaf->szLeaf ){
  187107. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  187108. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  187109. );
  187110. }
  187111. }
  187112. else if( pLeaf->nn>pLeaf->szLeaf ){
  187113. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  187114. &pLeaf->p[pLeaf->szLeaf], iOff
  187115. );
  187116. pIter->iLeafOffset = iOff;
  187117. pIter->iEndofDoclist = iOff;
  187118. bNewTerm = 1;
  187119. }
  187120. assert_nc( iOff<pLeaf->szLeaf );
  187121. if( iOff>pLeaf->szLeaf ){
  187122. p->rc = FTS5_CORRUPT;
  187123. return;
  187124. }
  187125. }
  187126. }
  187127. /* Check if the iterator is now at EOF. If so, return early. */
  187128. if( pIter->pLeaf ){
  187129. if( bNewTerm ){
  187130. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  187131. fts5DataRelease(pIter->pLeaf);
  187132. pIter->pLeaf = 0;
  187133. }else{
  187134. fts5SegIterLoadTerm(p, pIter, nKeep);
  187135. fts5SegIterLoadNPos(p, pIter);
  187136. if( pbNewTerm ) *pbNewTerm = 1;
  187137. }
  187138. }else{
  187139. /* The following could be done by calling fts5SegIterLoadNPos(). But
  187140. ** this block is particularly performance critical, so equivalent
  187141. ** code is inlined.
  187142. **
  187143. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  187144. ** detail=none mode. Not ideal.
  187145. */
  187146. int nSz;
  187147. assert( p->rc==SQLITE_OK );
  187148. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  187149. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  187150. pIter->bDel = (nSz & 0x0001);
  187151. pIter->nPos = nSz>>1;
  187152. assert_nc( pIter->nPos>=0 );
  187153. }
  187154. }
  187155. }
  187156. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  187157. #define fts5IndexSkipVarint(a, iOff) { \
  187158. int iEnd = iOff+9; \
  187159. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  187160. }
  187161. /*
  187162. ** Iterator pIter currently points to the first rowid in a doclist. This
  187163. ** function sets the iterator up so that iterates in reverse order through
  187164. ** the doclist.
  187165. */
  187166. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  187167. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  187168. Fts5Data *pLast = 0;
  187169. int pgnoLast = 0;
  187170. if( pDlidx ){
  187171. int iSegid = pIter->pSeg->iSegid;
  187172. pgnoLast = fts5DlidxIterPgno(pDlidx);
  187173. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  187174. }else{
  187175. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  187176. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  187177. ** position-list content for the current rowid. Back it up so that it
  187178. ** points to the start of the position-list size field. */
  187179. int iPoslist;
  187180. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  187181. iPoslist = pIter->iTermLeafOffset;
  187182. }else{
  187183. iPoslist = 4;
  187184. }
  187185. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  187186. pIter->iLeafOffset = iPoslist;
  187187. /* If this condition is true then the largest rowid for the current
  187188. ** term may not be stored on the current page. So search forward to
  187189. ** see where said rowid really is. */
  187190. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  187191. int pgno;
  187192. Fts5StructureSegment *pSeg = pIter->pSeg;
  187193. /* The last rowid in the doclist may not be on the current page. Search
  187194. ** forward to find the page containing the last rowid. */
  187195. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  187196. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  187197. Fts5Data *pNew = fts5DataRead(p, iAbs);
  187198. if( pNew ){
  187199. int iRowid, bTermless;
  187200. iRowid = fts5LeafFirstRowidOff(pNew);
  187201. bTermless = fts5LeafIsTermless(pNew);
  187202. if( iRowid ){
  187203. SWAPVAL(Fts5Data*, pNew, pLast);
  187204. pgnoLast = pgno;
  187205. }
  187206. fts5DataRelease(pNew);
  187207. if( bTermless==0 ) break;
  187208. }
  187209. }
  187210. }
  187211. }
  187212. /* If pLast is NULL at this point, then the last rowid for this doclist
  187213. ** lies on the page currently indicated by the iterator. In this case
  187214. ** pIter->iLeafOffset is already set to point to the position-list size
  187215. ** field associated with the first relevant rowid on the page.
  187216. **
  187217. ** Or, if pLast is non-NULL, then it is the page that contains the last
  187218. ** rowid. In this case configure the iterator so that it points to the
  187219. ** first rowid on this page.
  187220. */
  187221. if( pLast ){
  187222. int iOff;
  187223. fts5DataRelease(pIter->pLeaf);
  187224. pIter->pLeaf = pLast;
  187225. pIter->iLeafPgno = pgnoLast;
  187226. iOff = fts5LeafFirstRowidOff(pLast);
  187227. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  187228. pIter->iLeafOffset = iOff;
  187229. if( fts5LeafIsTermless(pLast) ){
  187230. pIter->iEndofDoclist = pLast->nn+1;
  187231. }else{
  187232. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  187233. }
  187234. }
  187235. fts5SegIterReverseInitPage(p, pIter);
  187236. }
  187237. /*
  187238. ** Iterator pIter currently points to the first rowid of a doclist.
  187239. ** There is a doclist-index associated with the final term on the current
  187240. ** page. If the current term is the last term on the page, load the
  187241. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  187242. */
  187243. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  187244. int iSeg = pIter->pSeg->iSegid;
  187245. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  187246. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  187247. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  187248. assert( pIter->pDlidx==0 );
  187249. /* Check if the current doclist ends on this page. If it does, return
  187250. ** early without loading the doclist-index (as it belongs to a different
  187251. ** term. */
  187252. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  187253. && pIter->iEndofDoclist<pLeaf->szLeaf
  187254. ){
  187255. return;
  187256. }
  187257. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  187258. }
  187259. /*
  187260. ** The iterator object passed as the second argument currently contains
  187261. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  187262. ** function searches the leaf page for a term matching (pTerm/nTerm).
  187263. **
  187264. ** If the specified term is found on the page, then the iterator is left
  187265. ** pointing to it. If argument bGe is zero and the term is not found,
  187266. ** the iterator is left pointing at EOF.
  187267. **
  187268. ** If bGe is non-zero and the specified term is not found, then the
  187269. ** iterator is left pointing to the smallest term in the segment that
  187270. ** is larger than the specified term, even if this term is not on the
  187271. ** current page.
  187272. */
  187273. static void fts5LeafSeek(
  187274. Fts5Index *p, /* Leave any error code here */
  187275. int bGe, /* True for a >= search */
  187276. Fts5SegIter *pIter, /* Iterator to seek */
  187277. const u8 *pTerm, int nTerm /* Term to search for */
  187278. ){
  187279. int iOff;
  187280. const u8 *a = pIter->pLeaf->p;
  187281. int szLeaf = pIter->pLeaf->szLeaf;
  187282. int n = pIter->pLeaf->nn;
  187283. int nMatch = 0;
  187284. int nKeep = 0;
  187285. int nNew = 0;
  187286. int iTermOff;
  187287. int iPgidx; /* Current offset in pgidx */
  187288. int bEndOfPage = 0;
  187289. assert( p->rc==SQLITE_OK );
  187290. iPgidx = szLeaf;
  187291. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  187292. iOff = iTermOff;
  187293. if( iOff>n ){
  187294. p->rc = FTS5_CORRUPT;
  187295. return;
  187296. }
  187297. while( 1 ){
  187298. /* Figure out how many new bytes are in this term */
  187299. fts5FastGetVarint32(a, iOff, nNew);
  187300. if( nKeep<nMatch ){
  187301. goto search_failed;
  187302. }
  187303. assert( nKeep>=nMatch );
  187304. if( nKeep==nMatch ){
  187305. int nCmp;
  187306. int i;
  187307. nCmp = MIN(nNew, nTerm-nMatch);
  187308. for(i=0; i<nCmp; i++){
  187309. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  187310. }
  187311. nMatch += i;
  187312. if( nTerm==nMatch ){
  187313. if( i==nNew ){
  187314. goto search_success;
  187315. }else{
  187316. goto search_failed;
  187317. }
  187318. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  187319. goto search_failed;
  187320. }
  187321. }
  187322. if( iPgidx>=n ){
  187323. bEndOfPage = 1;
  187324. break;
  187325. }
  187326. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  187327. iTermOff += nKeep;
  187328. iOff = iTermOff;
  187329. if( iOff>=n ){
  187330. p->rc = FTS5_CORRUPT;
  187331. return;
  187332. }
  187333. /* Read the nKeep field of the next term. */
  187334. fts5FastGetVarint32(a, iOff, nKeep);
  187335. }
  187336. search_failed:
  187337. if( bGe==0 ){
  187338. fts5DataRelease(pIter->pLeaf);
  187339. pIter->pLeaf = 0;
  187340. return;
  187341. }else if( bEndOfPage ){
  187342. do {
  187343. fts5SegIterNextPage(p, pIter);
  187344. if( pIter->pLeaf==0 ) return;
  187345. a = pIter->pLeaf->p;
  187346. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  187347. iPgidx = pIter->pLeaf->szLeaf;
  187348. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  187349. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  187350. p->rc = FTS5_CORRUPT;
  187351. }else{
  187352. nKeep = 0;
  187353. iTermOff = iOff;
  187354. n = pIter->pLeaf->nn;
  187355. iOff += fts5GetVarint32(&a[iOff], nNew);
  187356. break;
  187357. }
  187358. }
  187359. }while( 1 );
  187360. }
  187361. search_success:
  187362. pIter->iLeafOffset = iOff + nNew;
  187363. pIter->iTermLeafOffset = pIter->iLeafOffset;
  187364. pIter->iTermLeafPgno = pIter->iLeafPgno;
  187365. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  187366. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  187367. if( iPgidx>=n ){
  187368. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  187369. }else{
  187370. int nExtra;
  187371. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  187372. pIter->iEndofDoclist = iTermOff + nExtra;
  187373. }
  187374. pIter->iPgidxOff = iPgidx;
  187375. fts5SegIterLoadRowid(p, pIter);
  187376. fts5SegIterLoadNPos(p, pIter);
  187377. }
  187378. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  187379. if( p->pIdxSelect==0 ){
  187380. Fts5Config *pConfig = p->pConfig;
  187381. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  187382. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  187383. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  187384. pConfig->zDb, pConfig->zName
  187385. ));
  187386. }
  187387. return p->pIdxSelect;
  187388. }
  187389. /*
  187390. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  187391. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  187392. **
  187393. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  187394. ** an error has already occurred when this function is called, it is a no-op.
  187395. */
  187396. static void fts5SegIterSeekInit(
  187397. Fts5Index *p, /* FTS5 backend */
  187398. const u8 *pTerm, int nTerm, /* Term to seek to */
  187399. int flags, /* Mask of FTS5INDEX_XXX flags */
  187400. Fts5StructureSegment *pSeg, /* Description of segment */
  187401. Fts5SegIter *pIter /* Object to populate */
  187402. ){
  187403. int iPg = 1;
  187404. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  187405. int bDlidx = 0; /* True if there is a doclist-index */
  187406. sqlite3_stmt *pIdxSelect = 0;
  187407. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  187408. assert( pTerm && nTerm );
  187409. memset(pIter, 0, sizeof(*pIter));
  187410. pIter->pSeg = pSeg;
  187411. /* This block sets stack variable iPg to the leaf page number that may
  187412. ** contain term (pTerm/nTerm), if it is present in the segment. */
  187413. pIdxSelect = fts5IdxSelectStmt(p);
  187414. if( p->rc ) return;
  187415. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  187416. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  187417. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  187418. i64 val = sqlite3_column_int(pIdxSelect, 0);
  187419. iPg = (int)(val>>1);
  187420. bDlidx = (val & 0x0001);
  187421. }
  187422. p->rc = sqlite3_reset(pIdxSelect);
  187423. sqlite3_bind_null(pIdxSelect, 2);
  187424. if( iPg<pSeg->pgnoFirst ){
  187425. iPg = pSeg->pgnoFirst;
  187426. bDlidx = 0;
  187427. }
  187428. pIter->iLeafPgno = iPg - 1;
  187429. fts5SegIterNextPage(p, pIter);
  187430. if( pIter->pLeaf ){
  187431. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  187432. }
  187433. if( p->rc==SQLITE_OK && bGe==0 ){
  187434. pIter->flags |= FTS5_SEGITER_ONETERM;
  187435. if( pIter->pLeaf ){
  187436. if( flags & FTS5INDEX_QUERY_DESC ){
  187437. pIter->flags |= FTS5_SEGITER_REVERSE;
  187438. }
  187439. if( bDlidx ){
  187440. fts5SegIterLoadDlidx(p, pIter);
  187441. }
  187442. if( flags & FTS5INDEX_QUERY_DESC ){
  187443. fts5SegIterReverse(p, pIter);
  187444. }
  187445. }
  187446. }
  187447. fts5SegIterSetNext(p, pIter);
  187448. /* Either:
  187449. **
  187450. ** 1) an error has occurred, or
  187451. ** 2) the iterator points to EOF, or
  187452. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  187453. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  187454. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  187455. */
  187456. assert( p->rc!=SQLITE_OK /* 1 */
  187457. || pIter->pLeaf==0 /* 2 */
  187458. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  187459. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  187460. );
  187461. }
  187462. /*
  187463. ** Initialize the object pIter to point to term pTerm/nTerm within the
  187464. ** in-memory hash table. If there is no such term in the hash-table, the
  187465. ** iterator is set to EOF.
  187466. **
  187467. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  187468. ** an error has already occurred when this function is called, it is a no-op.
  187469. */
  187470. static void fts5SegIterHashInit(
  187471. Fts5Index *p, /* FTS5 backend */
  187472. const u8 *pTerm, int nTerm, /* Term to seek to */
  187473. int flags, /* Mask of FTS5INDEX_XXX flags */
  187474. Fts5SegIter *pIter /* Object to populate */
  187475. ){
  187476. const u8 *pList = 0;
  187477. int nList = 0;
  187478. const u8 *z = 0;
  187479. int n = 0;
  187480. assert( p->pHash );
  187481. assert( p->rc==SQLITE_OK );
  187482. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  187483. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  187484. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  187485. n = (z ? (int)strlen((const char*)z) : 0);
  187486. }else{
  187487. pIter->flags |= FTS5_SEGITER_ONETERM;
  187488. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  187489. z = pTerm;
  187490. n = nTerm;
  187491. }
  187492. if( pList ){
  187493. Fts5Data *pLeaf;
  187494. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  187495. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  187496. if( pLeaf==0 ) return;
  187497. pLeaf->p = (u8*)pList;
  187498. pLeaf->nn = pLeaf->szLeaf = nList;
  187499. pIter->pLeaf = pLeaf;
  187500. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  187501. pIter->iEndofDoclist = pLeaf->nn;
  187502. if( flags & FTS5INDEX_QUERY_DESC ){
  187503. pIter->flags |= FTS5_SEGITER_REVERSE;
  187504. fts5SegIterReverseInitPage(p, pIter);
  187505. }else{
  187506. fts5SegIterLoadNPos(p, pIter);
  187507. }
  187508. }
  187509. fts5SegIterSetNext(p, pIter);
  187510. }
  187511. /*
  187512. ** Zero the iterator passed as the only argument.
  187513. */
  187514. static void fts5SegIterClear(Fts5SegIter *pIter){
  187515. fts5BufferFree(&pIter->term);
  187516. fts5DataRelease(pIter->pLeaf);
  187517. fts5DataRelease(pIter->pNextLeaf);
  187518. fts5DlidxIterFree(pIter->pDlidx);
  187519. sqlite3_free(pIter->aRowidOffset);
  187520. memset(pIter, 0, sizeof(Fts5SegIter));
  187521. }
  187522. #ifdef SQLITE_DEBUG
  187523. /*
  187524. ** This function is used as part of the big assert() procedure implemented by
  187525. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  187526. ** in *pRes is the correct result of comparing the current positions of the
  187527. ** two iterators.
  187528. */
  187529. static void fts5AssertComparisonResult(
  187530. Fts5Iter *pIter,
  187531. Fts5SegIter *p1,
  187532. Fts5SegIter *p2,
  187533. Fts5CResult *pRes
  187534. ){
  187535. int i1 = p1 - pIter->aSeg;
  187536. int i2 = p2 - pIter->aSeg;
  187537. if( p1->pLeaf || p2->pLeaf ){
  187538. if( p1->pLeaf==0 ){
  187539. assert( pRes->iFirst==i2 );
  187540. }else if( p2->pLeaf==0 ){
  187541. assert( pRes->iFirst==i1 );
  187542. }else{
  187543. int nMin = MIN(p1->term.n, p2->term.n);
  187544. int res = memcmp(p1->term.p, p2->term.p, nMin);
  187545. if( res==0 ) res = p1->term.n - p2->term.n;
  187546. if( res==0 ){
  187547. assert( pRes->bTermEq==1 );
  187548. assert( p1->iRowid!=p2->iRowid );
  187549. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  187550. }else{
  187551. assert( pRes->bTermEq==0 );
  187552. }
  187553. if( res<0 ){
  187554. assert( pRes->iFirst==i1 );
  187555. }else{
  187556. assert( pRes->iFirst==i2 );
  187557. }
  187558. }
  187559. }
  187560. }
  187561. /*
  187562. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  187563. ** is compiled. In that case, this function is essentially an assert()
  187564. ** statement used to verify that the contents of the pIter->aFirst[] array
  187565. ** are correct.
  187566. */
  187567. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  187568. if( p->rc==SQLITE_OK ){
  187569. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  187570. int i;
  187571. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  187572. /* Check that pIter->iSwitchRowid is set correctly. */
  187573. for(i=0; i<pIter->nSeg; i++){
  187574. Fts5SegIter *p1 = &pIter->aSeg[i];
  187575. assert( p1==pFirst
  187576. || p1->pLeaf==0
  187577. || fts5BufferCompare(&pFirst->term, &p1->term)
  187578. || p1->iRowid==pIter->iSwitchRowid
  187579. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  187580. );
  187581. }
  187582. for(i=0; i<pIter->nSeg; i+=2){
  187583. Fts5SegIter *p1 = &pIter->aSeg[i];
  187584. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  187585. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  187586. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  187587. }
  187588. for(i=1; i<(pIter->nSeg / 2); i+=2){
  187589. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  187590. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  187591. Fts5CResult *pRes = &pIter->aFirst[i];
  187592. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  187593. }
  187594. }
  187595. }
  187596. #else
  187597. # define fts5AssertMultiIterSetup(x,y)
  187598. #endif
  187599. /*
  187600. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  187601. **
  187602. ** If the returned value is non-zero, then it is the index of an entry
  187603. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  187604. ** to a key that is a duplicate of another, higher priority,
  187605. ** segment-iterator in the pSeg->aSeg[] array.
  187606. */
  187607. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  187608. int i1; /* Index of left-hand Fts5SegIter */
  187609. int i2; /* Index of right-hand Fts5SegIter */
  187610. int iRes;
  187611. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  187612. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  187613. Fts5CResult *pRes = &pIter->aFirst[iOut];
  187614. assert( iOut<pIter->nSeg && iOut>0 );
  187615. assert( pIter->bRev==0 || pIter->bRev==1 );
  187616. if( iOut>=(pIter->nSeg/2) ){
  187617. i1 = (iOut - pIter->nSeg/2) * 2;
  187618. i2 = i1 + 1;
  187619. }else{
  187620. i1 = pIter->aFirst[iOut*2].iFirst;
  187621. i2 = pIter->aFirst[iOut*2+1].iFirst;
  187622. }
  187623. p1 = &pIter->aSeg[i1];
  187624. p2 = &pIter->aSeg[i2];
  187625. pRes->bTermEq = 0;
  187626. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  187627. iRes = i2;
  187628. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  187629. iRes = i1;
  187630. }else{
  187631. int res = fts5BufferCompare(&p1->term, &p2->term);
  187632. if( res==0 ){
  187633. assert( i2>i1 );
  187634. assert( i2!=0 );
  187635. pRes->bTermEq = 1;
  187636. if( p1->iRowid==p2->iRowid ){
  187637. p1->bDel = p2->bDel;
  187638. return i2;
  187639. }
  187640. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  187641. }
  187642. assert( res!=0 );
  187643. if( res<0 ){
  187644. iRes = i1;
  187645. }else{
  187646. iRes = i2;
  187647. }
  187648. }
  187649. pRes->iFirst = (u16)iRes;
  187650. return 0;
  187651. }
  187652. /*
  187653. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  187654. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  187655. */
  187656. static void fts5SegIterGotoPage(
  187657. Fts5Index *p, /* FTS5 backend object */
  187658. Fts5SegIter *pIter, /* Iterator to advance */
  187659. int iLeafPgno
  187660. ){
  187661. assert( iLeafPgno>pIter->iLeafPgno );
  187662. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  187663. p->rc = FTS5_CORRUPT;
  187664. }else{
  187665. fts5DataRelease(pIter->pNextLeaf);
  187666. pIter->pNextLeaf = 0;
  187667. pIter->iLeafPgno = iLeafPgno-1;
  187668. fts5SegIterNextPage(p, pIter);
  187669. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  187670. if( p->rc==SQLITE_OK ){
  187671. int iOff;
  187672. u8 *a = pIter->pLeaf->p;
  187673. int n = pIter->pLeaf->szLeaf;
  187674. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  187675. if( iOff<4 || iOff>=n ){
  187676. p->rc = FTS5_CORRUPT;
  187677. }else{
  187678. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  187679. pIter->iLeafOffset = iOff;
  187680. fts5SegIterLoadNPos(p, pIter);
  187681. }
  187682. }
  187683. }
  187684. }
  187685. /*
  187686. ** Advance the iterator passed as the second argument until it is at or
  187687. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  187688. ** always advanced at least once.
  187689. */
  187690. static void fts5SegIterNextFrom(
  187691. Fts5Index *p, /* FTS5 backend object */
  187692. Fts5SegIter *pIter, /* Iterator to advance */
  187693. i64 iMatch /* Advance iterator at least this far */
  187694. ){
  187695. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  187696. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  187697. int iLeafPgno = pIter->iLeafPgno;
  187698. int bMove = 1;
  187699. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  187700. assert( pIter->pDlidx );
  187701. assert( pIter->pLeaf );
  187702. if( bRev==0 ){
  187703. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  187704. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  187705. fts5DlidxIterNext(p, pDlidx);
  187706. }
  187707. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  187708. if( iLeafPgno>pIter->iLeafPgno ){
  187709. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  187710. bMove = 0;
  187711. }
  187712. }else{
  187713. assert( pIter->pNextLeaf==0 );
  187714. assert( iMatch<pIter->iRowid );
  187715. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  187716. fts5DlidxIterPrev(p, pDlidx);
  187717. }
  187718. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  187719. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  187720. if( iLeafPgno<pIter->iLeafPgno ){
  187721. pIter->iLeafPgno = iLeafPgno+1;
  187722. fts5SegIterReverseNewPage(p, pIter);
  187723. bMove = 0;
  187724. }
  187725. }
  187726. do{
  187727. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  187728. if( pIter->pLeaf==0 ) break;
  187729. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  187730. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  187731. bMove = 1;
  187732. }while( p->rc==SQLITE_OK );
  187733. }
  187734. /*
  187735. ** Free the iterator object passed as the second argument.
  187736. */
  187737. static void fts5MultiIterFree(Fts5Iter *pIter){
  187738. if( pIter ){
  187739. int i;
  187740. for(i=0; i<pIter->nSeg; i++){
  187741. fts5SegIterClear(&pIter->aSeg[i]);
  187742. }
  187743. fts5StructureRelease(pIter->pStruct);
  187744. fts5BufferFree(&pIter->poslist);
  187745. sqlite3_free(pIter);
  187746. }
  187747. }
  187748. static void fts5MultiIterAdvanced(
  187749. Fts5Index *p, /* FTS5 backend to iterate within */
  187750. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  187751. int iChanged, /* Index of sub-iterator just advanced */
  187752. int iMinset /* Minimum entry in aFirst[] to set */
  187753. ){
  187754. int i;
  187755. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  187756. int iEq;
  187757. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  187758. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  187759. assert( p->rc==SQLITE_OK );
  187760. pSeg->xNext(p, pSeg, 0);
  187761. i = pIter->nSeg + iEq;
  187762. }
  187763. }
  187764. }
  187765. /*
  187766. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  187767. ** points to the same term though - just a different rowid. This function
  187768. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  187769. ** If it does so successfully, 0 is returned. Otherwise 1.
  187770. **
  187771. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  187772. ** on the iterator instead. That function does the same as this one, except
  187773. ** that it deals with more complicated cases as well.
  187774. */
  187775. static int fts5MultiIterAdvanceRowid(
  187776. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  187777. int iChanged, /* Index of sub-iterator just advanced */
  187778. Fts5SegIter **ppFirst
  187779. ){
  187780. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  187781. if( pNew->iRowid==pIter->iSwitchRowid
  187782. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  187783. ){
  187784. int i;
  187785. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  187786. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  187787. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  187788. Fts5CResult *pRes = &pIter->aFirst[i];
  187789. assert( pNew->pLeaf );
  187790. assert( pRes->bTermEq==0 || pOther->pLeaf );
  187791. if( pRes->bTermEq ){
  187792. if( pNew->iRowid==pOther->iRowid ){
  187793. return 1;
  187794. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  187795. pIter->iSwitchRowid = pOther->iRowid;
  187796. pNew = pOther;
  187797. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  187798. pIter->iSwitchRowid = pOther->iRowid;
  187799. }
  187800. }
  187801. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  187802. if( i==1 ) break;
  187803. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  187804. }
  187805. }
  187806. *ppFirst = pNew;
  187807. return 0;
  187808. }
  187809. /*
  187810. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  187811. */
  187812. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  187813. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  187814. pIter->base.bEof = pSeg->pLeaf==0;
  187815. pIter->iSwitchRowid = pSeg->iRowid;
  187816. }
  187817. /*
  187818. ** Move the iterator to the next entry.
  187819. **
  187820. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  187821. ** considered an error if the iterator reaches EOF, or if it is already at
  187822. ** EOF when this function is called.
  187823. */
  187824. static void fts5MultiIterNext(
  187825. Fts5Index *p,
  187826. Fts5Iter *pIter,
  187827. int bFrom, /* True if argument iFrom is valid */
  187828. i64 iFrom /* Advance at least as far as this */
  187829. ){
  187830. int bUseFrom = bFrom;
  187831. assert( pIter->base.bEof==0 );
  187832. while( p->rc==SQLITE_OK ){
  187833. int iFirst = pIter->aFirst[1].iFirst;
  187834. int bNewTerm = 0;
  187835. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  187836. assert( p->rc==SQLITE_OK );
  187837. if( bUseFrom && pSeg->pDlidx ){
  187838. fts5SegIterNextFrom(p, pSeg, iFrom);
  187839. }else{
  187840. pSeg->xNext(p, pSeg, &bNewTerm);
  187841. }
  187842. if( pSeg->pLeaf==0 || bNewTerm
  187843. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  187844. ){
  187845. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  187846. fts5MultiIterSetEof(pIter);
  187847. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  187848. if( pSeg->pLeaf==0 ) return;
  187849. }
  187850. fts5AssertMultiIterSetup(p, pIter);
  187851. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  187852. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  187853. pIter->xSetOutputs(pIter, pSeg);
  187854. return;
  187855. }
  187856. bUseFrom = 0;
  187857. }
  187858. }
  187859. static void fts5MultiIterNext2(
  187860. Fts5Index *p,
  187861. Fts5Iter *pIter,
  187862. int *pbNewTerm /* OUT: True if *might* be new term */
  187863. ){
  187864. assert( pIter->bSkipEmpty );
  187865. if( p->rc==SQLITE_OK ){
  187866. *pbNewTerm = 0;
  187867. do{
  187868. int iFirst = pIter->aFirst[1].iFirst;
  187869. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  187870. int bNewTerm = 0;
  187871. assert( p->rc==SQLITE_OK );
  187872. pSeg->xNext(p, pSeg, &bNewTerm);
  187873. if( pSeg->pLeaf==0 || bNewTerm
  187874. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  187875. ){
  187876. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  187877. fts5MultiIterSetEof(pIter);
  187878. *pbNewTerm = 1;
  187879. }
  187880. fts5AssertMultiIterSetup(p, pIter);
  187881. }while( fts5MultiIterIsEmpty(p, pIter) );
  187882. }
  187883. }
  187884. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  187885. UNUSED_PARAM2(pUnused1, pUnused2);
  187886. }
  187887. static Fts5Iter *fts5MultiIterAlloc(
  187888. Fts5Index *p, /* FTS5 backend to iterate within */
  187889. int nSeg
  187890. ){
  187891. Fts5Iter *pNew;
  187892. int nSlot; /* Power of two >= nSeg */
  187893. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  187894. pNew = fts5IdxMalloc(p,
  187895. sizeof(Fts5Iter) + /* pNew */
  187896. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  187897. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  187898. );
  187899. if( pNew ){
  187900. pNew->nSeg = nSlot;
  187901. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  187902. pNew->pIndex = p;
  187903. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  187904. }
  187905. return pNew;
  187906. }
  187907. static void fts5PoslistCallback(
  187908. Fts5Index *pUnused,
  187909. void *pContext,
  187910. const u8 *pChunk, int nChunk
  187911. ){
  187912. UNUSED_PARAM(pUnused);
  187913. assert_nc( nChunk>=0 );
  187914. if( nChunk>0 ){
  187915. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  187916. }
  187917. }
  187918. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  187919. struct PoslistCallbackCtx {
  187920. Fts5Buffer *pBuf; /* Append to this buffer */
  187921. Fts5Colset *pColset; /* Restrict matches to this column */
  187922. int eState; /* See above */
  187923. };
  187924. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  187925. struct PoslistOffsetsCtx {
  187926. Fts5Buffer *pBuf; /* Append to this buffer */
  187927. Fts5Colset *pColset; /* Restrict matches to this column */
  187928. int iRead;
  187929. int iWrite;
  187930. };
  187931. /*
  187932. ** TODO: Make this more efficient!
  187933. */
  187934. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  187935. int i;
  187936. for(i=0; i<pColset->nCol; i++){
  187937. if( pColset->aiCol[i]==iCol ) return 1;
  187938. }
  187939. return 0;
  187940. }
  187941. static void fts5PoslistOffsetsCallback(
  187942. Fts5Index *pUnused,
  187943. void *pContext,
  187944. const u8 *pChunk, int nChunk
  187945. ){
  187946. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  187947. UNUSED_PARAM(pUnused);
  187948. assert_nc( nChunk>=0 );
  187949. if( nChunk>0 ){
  187950. int i = 0;
  187951. while( i<nChunk ){
  187952. int iVal;
  187953. i += fts5GetVarint32(&pChunk[i], iVal);
  187954. iVal += pCtx->iRead - 2;
  187955. pCtx->iRead = iVal;
  187956. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  187957. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  187958. pCtx->iWrite = iVal;
  187959. }
  187960. }
  187961. }
  187962. }
  187963. static void fts5PoslistFilterCallback(
  187964. Fts5Index *pUnused,
  187965. void *pContext,
  187966. const u8 *pChunk, int nChunk
  187967. ){
  187968. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  187969. UNUSED_PARAM(pUnused);
  187970. assert_nc( nChunk>=0 );
  187971. if( nChunk>0 ){
  187972. /* Search through to find the first varint with value 1. This is the
  187973. ** start of the next columns hits. */
  187974. int i = 0;
  187975. int iStart = 0;
  187976. if( pCtx->eState==2 ){
  187977. int iCol;
  187978. fts5FastGetVarint32(pChunk, i, iCol);
  187979. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  187980. pCtx->eState = 1;
  187981. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  187982. }else{
  187983. pCtx->eState = 0;
  187984. }
  187985. }
  187986. do {
  187987. while( i<nChunk && pChunk[i]!=0x01 ){
  187988. while( pChunk[i] & 0x80 ) i++;
  187989. i++;
  187990. }
  187991. if( pCtx->eState ){
  187992. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  187993. }
  187994. if( i<nChunk ){
  187995. int iCol;
  187996. iStart = i;
  187997. i++;
  187998. if( i>=nChunk ){
  187999. pCtx->eState = 2;
  188000. }else{
  188001. fts5FastGetVarint32(pChunk, i, iCol);
  188002. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  188003. if( pCtx->eState ){
  188004. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  188005. iStart = i;
  188006. }
  188007. }
  188008. }
  188009. }while( i<nChunk );
  188010. }
  188011. }
  188012. static void fts5ChunkIterate(
  188013. Fts5Index *p, /* Index object */
  188014. Fts5SegIter *pSeg, /* Poslist of this iterator */
  188015. void *pCtx, /* Context pointer for xChunk callback */
  188016. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  188017. ){
  188018. int nRem = pSeg->nPos; /* Number of bytes still to come */
  188019. Fts5Data *pData = 0;
  188020. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  188021. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  188022. int pgno = pSeg->iLeafPgno;
  188023. int pgnoSave = 0;
  188024. /* This function does notmwork with detail=none databases. */
  188025. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  188026. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  188027. pgnoSave = pgno+1;
  188028. }
  188029. while( 1 ){
  188030. xChunk(p, pCtx, pChunk, nChunk);
  188031. nRem -= nChunk;
  188032. fts5DataRelease(pData);
  188033. if( nRem<=0 ){
  188034. break;
  188035. }else{
  188036. pgno++;
  188037. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  188038. if( pData==0 ) break;
  188039. pChunk = &pData->p[4];
  188040. nChunk = MIN(nRem, pData->szLeaf - 4);
  188041. if( pgno==pgnoSave ){
  188042. assert( pSeg->pNextLeaf==0 );
  188043. pSeg->pNextLeaf = pData;
  188044. pData = 0;
  188045. }
  188046. }
  188047. }
  188048. }
  188049. /*
  188050. ** Iterator pIter currently points to a valid entry (not EOF). This
  188051. ** function appends the position list data for the current entry to
  188052. ** buffer pBuf. It does not make a copy of the position-list size
  188053. ** field.
  188054. */
  188055. static void fts5SegiterPoslist(
  188056. Fts5Index *p,
  188057. Fts5SegIter *pSeg,
  188058. Fts5Colset *pColset,
  188059. Fts5Buffer *pBuf
  188060. ){
  188061. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  188062. if( pColset==0 ){
  188063. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  188064. }else{
  188065. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  188066. PoslistCallbackCtx sCtx;
  188067. sCtx.pBuf = pBuf;
  188068. sCtx.pColset = pColset;
  188069. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  188070. assert( sCtx.eState==0 || sCtx.eState==1 );
  188071. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  188072. }else{
  188073. PoslistOffsetsCtx sCtx;
  188074. memset(&sCtx, 0, sizeof(sCtx));
  188075. sCtx.pBuf = pBuf;
  188076. sCtx.pColset = pColset;
  188077. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  188078. }
  188079. }
  188080. }
  188081. }
  188082. /*
  188083. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  188084. ** the position list contains entries for column iCol, then (*pa) is set
  188085. ** to point to the sub-position-list for that column and the number of
  188086. ** bytes in it returned. Or, if the argument position list does not
  188087. ** contain any entries for column iCol, return 0.
  188088. */
  188089. static int fts5IndexExtractCol(
  188090. const u8 **pa, /* IN/OUT: Pointer to poslist */
  188091. int n, /* IN: Size of poslist in bytes */
  188092. int iCol /* Column to extract from poslist */
  188093. ){
  188094. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  188095. const u8 *p = *pa;
  188096. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  188097. while( iCol>iCurrent ){
  188098. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  188099. ** not part of a varint. Note that it is not possible for a negative
  188100. ** or extremely large varint to occur within an uncorrupted position
  188101. ** list. So the last byte of each varint may be assumed to have a clear
  188102. ** 0x80 bit. */
  188103. while( *p!=0x01 ){
  188104. while( *p++ & 0x80 );
  188105. if( p>=pEnd ) return 0;
  188106. }
  188107. *pa = p++;
  188108. iCurrent = *p++;
  188109. if( iCurrent & 0x80 ){
  188110. p--;
  188111. p += fts5GetVarint32(p, iCurrent);
  188112. }
  188113. }
  188114. if( iCol!=iCurrent ) return 0;
  188115. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  188116. ** not part of a varint */
  188117. while( p<pEnd && *p!=0x01 ){
  188118. while( *p++ & 0x80 );
  188119. }
  188120. return p - (*pa);
  188121. }
  188122. static void fts5IndexExtractColset(
  188123. int *pRc,
  188124. Fts5Colset *pColset, /* Colset to filter on */
  188125. const u8 *pPos, int nPos, /* Position list */
  188126. Fts5Buffer *pBuf /* Output buffer */
  188127. ){
  188128. if( *pRc==SQLITE_OK ){
  188129. int i;
  188130. fts5BufferZero(pBuf);
  188131. for(i=0; i<pColset->nCol; i++){
  188132. const u8 *pSub = pPos;
  188133. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  188134. if( nSub ){
  188135. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  188136. }
  188137. }
  188138. }
  188139. }
  188140. /*
  188141. ** xSetOutputs callback used by detail=none tables.
  188142. */
  188143. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  188144. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  188145. pIter->base.iRowid = pSeg->iRowid;
  188146. pIter->base.nData = pSeg->nPos;
  188147. }
  188148. /*
  188149. ** xSetOutputs callback used by detail=full and detail=col tables when no
  188150. ** column filters are specified.
  188151. */
  188152. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  188153. pIter->base.iRowid = pSeg->iRowid;
  188154. pIter->base.nData = pSeg->nPos;
  188155. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  188156. assert( pIter->pColset==0 );
  188157. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  188158. /* All data is stored on the current page. Populate the output
  188159. ** variables to point into the body of the page object. */
  188160. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  188161. }else{
  188162. /* The data is distributed over two or more pages. Copy it into the
  188163. ** Fts5Iter.poslist buffer and then set the output pointer to point
  188164. ** to this buffer. */
  188165. fts5BufferZero(&pIter->poslist);
  188166. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  188167. pIter->base.pData = pIter->poslist.p;
  188168. }
  188169. }
  188170. /*
  188171. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  188172. ** against no columns at all).
  188173. */
  188174. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  188175. UNUSED_PARAM(pSeg);
  188176. pIter->base.nData = 0;
  188177. }
  188178. /*
  188179. ** xSetOutputs callback used by detail=col when there is a column filter
  188180. ** and there are 100 or more columns. Also called as a fallback from
  188181. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  188182. */
  188183. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  188184. fts5BufferZero(&pIter->poslist);
  188185. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  188186. pIter->base.iRowid = pSeg->iRowid;
  188187. pIter->base.pData = pIter->poslist.p;
  188188. pIter->base.nData = pIter->poslist.n;
  188189. }
  188190. /*
  188191. ** xSetOutputs callback used when:
  188192. **
  188193. ** * detail=col,
  188194. ** * there is a column filter, and
  188195. ** * the table contains 100 or fewer columns.
  188196. **
  188197. ** The last point is to ensure all column numbers are stored as
  188198. ** single-byte varints.
  188199. */
  188200. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  188201. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  188202. assert( pIter->pColset );
  188203. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  188204. fts5IterSetOutputs_Col(pIter, pSeg);
  188205. }else{
  188206. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  188207. u8 *pEnd = (u8*)&a[pSeg->nPos];
  188208. int iPrev = 0;
  188209. int *aiCol = pIter->pColset->aiCol;
  188210. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  188211. u8 *aOut = pIter->poslist.p;
  188212. int iPrevOut = 0;
  188213. pIter->base.iRowid = pSeg->iRowid;
  188214. while( a<pEnd ){
  188215. iPrev += (int)a++[0] - 2;
  188216. while( *aiCol<iPrev ){
  188217. aiCol++;
  188218. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  188219. }
  188220. if( *aiCol==iPrev ){
  188221. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  188222. iPrevOut = iPrev;
  188223. }
  188224. }
  188225. setoutputs_col_out:
  188226. pIter->base.pData = pIter->poslist.p;
  188227. pIter->base.nData = aOut - pIter->poslist.p;
  188228. }
  188229. }
  188230. /*
  188231. ** xSetOutputs callback used by detail=full when there is a column filter.
  188232. */
  188233. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  188234. Fts5Colset *pColset = pIter->pColset;
  188235. pIter->base.iRowid = pSeg->iRowid;
  188236. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  188237. assert( pColset );
  188238. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  188239. /* All data is stored on the current page. Populate the output
  188240. ** variables to point into the body of the page object. */
  188241. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  188242. if( pColset->nCol==1 ){
  188243. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  188244. pIter->base.pData = a;
  188245. }else{
  188246. int *pRc = &pIter->pIndex->rc;
  188247. fts5BufferZero(&pIter->poslist);
  188248. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  188249. pIter->base.pData = pIter->poslist.p;
  188250. pIter->base.nData = pIter->poslist.n;
  188251. }
  188252. }else{
  188253. /* The data is distributed over two or more pages. Copy it into the
  188254. ** Fts5Iter.poslist buffer and then set the output pointer to point
  188255. ** to this buffer. */
  188256. fts5BufferZero(&pIter->poslist);
  188257. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  188258. pIter->base.pData = pIter->poslist.p;
  188259. pIter->base.nData = pIter->poslist.n;
  188260. }
  188261. }
  188262. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  188263. if( *pRc==SQLITE_OK ){
  188264. Fts5Config *pConfig = pIter->pIndex->pConfig;
  188265. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  188266. pIter->xSetOutputs = fts5IterSetOutputs_None;
  188267. }
  188268. else if( pIter->pColset==0 ){
  188269. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  188270. }
  188271. else if( pIter->pColset->nCol==0 ){
  188272. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  188273. }
  188274. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  188275. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  188276. }
  188277. else{
  188278. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  188279. if( pConfig->nCol<=100 ){
  188280. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  188281. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  188282. }else{
  188283. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  188284. }
  188285. }
  188286. }
  188287. }
  188288. /*
  188289. ** Allocate a new Fts5Iter object.
  188290. **
  188291. ** The new object will be used to iterate through data in structure pStruct.
  188292. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  188293. ** is zero or greater, data from the first nSegment segments on level iLevel
  188294. ** is merged.
  188295. **
  188296. ** The iterator initially points to the first term/rowid entry in the
  188297. ** iterated data.
  188298. */
  188299. static void fts5MultiIterNew(
  188300. Fts5Index *p, /* FTS5 backend to iterate within */
  188301. Fts5Structure *pStruct, /* Structure of specific index */
  188302. int flags, /* FTS5INDEX_QUERY_XXX flags */
  188303. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  188304. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  188305. int iLevel, /* Level to iterate (-1 for all) */
  188306. int nSegment, /* Number of segments to merge (iLevel>=0) */
  188307. Fts5Iter **ppOut /* New object */
  188308. ){
  188309. int nSeg = 0; /* Number of segment-iters in use */
  188310. int iIter = 0; /* */
  188311. int iSeg; /* Used to iterate through segments */
  188312. Fts5StructureLevel *pLvl;
  188313. Fts5Iter *pNew;
  188314. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  188315. /* Allocate space for the new multi-seg-iterator. */
  188316. if( p->rc==SQLITE_OK ){
  188317. if( iLevel<0 ){
  188318. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  188319. nSeg = pStruct->nSegment;
  188320. nSeg += (p->pHash ? 1 : 0);
  188321. }else{
  188322. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  188323. }
  188324. }
  188325. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  188326. if( pNew==0 ) return;
  188327. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  188328. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  188329. pNew->pStruct = pStruct;
  188330. pNew->pColset = pColset;
  188331. fts5StructureRef(pStruct);
  188332. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  188333. fts5IterSetOutputCb(&p->rc, pNew);
  188334. }
  188335. /* Initialize each of the component segment iterators. */
  188336. if( p->rc==SQLITE_OK ){
  188337. if( iLevel<0 ){
  188338. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  188339. if( p->pHash ){
  188340. /* Add a segment iterator for the current contents of the hash table. */
  188341. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  188342. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  188343. }
  188344. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  188345. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  188346. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  188347. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  188348. if( pTerm==0 ){
  188349. fts5SegIterInit(p, pSeg, pIter);
  188350. }else{
  188351. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  188352. }
  188353. }
  188354. }
  188355. }else{
  188356. pLvl = &pStruct->aLevel[iLevel];
  188357. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  188358. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  188359. }
  188360. }
  188361. assert( iIter==nSeg );
  188362. }
  188363. /* If the above was successful, each component iterators now points
  188364. ** to the first entry in its segment. In this case initialize the
  188365. ** aFirst[] array. Or, if an error has occurred, free the iterator
  188366. ** object and set the output variable to NULL. */
  188367. if( p->rc==SQLITE_OK ){
  188368. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  188369. int iEq;
  188370. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  188371. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  188372. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  188373. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  188374. }
  188375. }
  188376. fts5MultiIterSetEof(pNew);
  188377. fts5AssertMultiIterSetup(p, pNew);
  188378. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  188379. fts5MultiIterNext(p, pNew, 0, 0);
  188380. }else if( pNew->base.bEof==0 ){
  188381. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  188382. pNew->xSetOutputs(pNew, pSeg);
  188383. }
  188384. }else{
  188385. fts5MultiIterFree(pNew);
  188386. *ppOut = 0;
  188387. }
  188388. }
  188389. /*
  188390. ** Create an Fts5Iter that iterates through the doclist provided
  188391. ** as the second argument.
  188392. */
  188393. static void fts5MultiIterNew2(
  188394. Fts5Index *p, /* FTS5 backend to iterate within */
  188395. Fts5Data *pData, /* Doclist to iterate through */
  188396. int bDesc, /* True for descending rowid order */
  188397. Fts5Iter **ppOut /* New object */
  188398. ){
  188399. Fts5Iter *pNew;
  188400. pNew = fts5MultiIterAlloc(p, 2);
  188401. if( pNew ){
  188402. Fts5SegIter *pIter = &pNew->aSeg[1];
  188403. pIter->flags = FTS5_SEGITER_ONETERM;
  188404. if( pData->szLeaf>0 ){
  188405. pIter->pLeaf = pData;
  188406. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  188407. pIter->iEndofDoclist = pData->nn;
  188408. pNew->aFirst[1].iFirst = 1;
  188409. if( bDesc ){
  188410. pNew->bRev = 1;
  188411. pIter->flags |= FTS5_SEGITER_REVERSE;
  188412. fts5SegIterReverseInitPage(p, pIter);
  188413. }else{
  188414. fts5SegIterLoadNPos(p, pIter);
  188415. }
  188416. pData = 0;
  188417. }else{
  188418. pNew->base.bEof = 1;
  188419. }
  188420. fts5SegIterSetNext(p, pIter);
  188421. *ppOut = pNew;
  188422. }
  188423. fts5DataRelease(pData);
  188424. }
  188425. /*
  188426. ** Return true if the iterator is at EOF or if an error has occurred.
  188427. ** False otherwise.
  188428. */
  188429. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  188430. assert( p->rc
  188431. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  188432. );
  188433. return (p->rc || pIter->base.bEof);
  188434. }
  188435. /*
  188436. ** Return the rowid of the entry that the iterator currently points
  188437. ** to. If the iterator points to EOF when this function is called the
  188438. ** results are undefined.
  188439. */
  188440. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  188441. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  188442. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  188443. }
  188444. /*
  188445. ** Move the iterator to the next entry at or following iMatch.
  188446. */
  188447. static void fts5MultiIterNextFrom(
  188448. Fts5Index *p,
  188449. Fts5Iter *pIter,
  188450. i64 iMatch
  188451. ){
  188452. while( 1 ){
  188453. i64 iRowid;
  188454. fts5MultiIterNext(p, pIter, 1, iMatch);
  188455. if( fts5MultiIterEof(p, pIter) ) break;
  188456. iRowid = fts5MultiIterRowid(pIter);
  188457. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  188458. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  188459. }
  188460. }
  188461. /*
  188462. ** Return a pointer to a buffer containing the term associated with the
  188463. ** entry that the iterator currently points to.
  188464. */
  188465. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  188466. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  188467. *pn = p->term.n;
  188468. return p->term.p;
  188469. }
  188470. /*
  188471. ** Allocate a new segment-id for the structure pStruct. The new segment
  188472. ** id must be between 1 and 65335 inclusive, and must not be used by
  188473. ** any currently existing segment. If a free segment id cannot be found,
  188474. ** SQLITE_FULL is returned.
  188475. **
  188476. ** If an error has already occurred, this function is a no-op. 0 is
  188477. ** returned in this case.
  188478. */
  188479. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  188480. int iSegid = 0;
  188481. if( p->rc==SQLITE_OK ){
  188482. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  188483. p->rc = SQLITE_FULL;
  188484. }else{
  188485. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  188486. ** array is 63 elements, or 252 bytes, in size. */
  188487. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  188488. int iLvl, iSeg;
  188489. int i;
  188490. u32 mask;
  188491. memset(aUsed, 0, sizeof(aUsed));
  188492. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  188493. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  188494. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  188495. if( iId<=FTS5_MAX_SEGMENT ){
  188496. aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
  188497. }
  188498. }
  188499. }
  188500. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  188501. mask = aUsed[i];
  188502. for(iSegid=0; mask & (1 << iSegid); iSegid++);
  188503. iSegid += 1 + i*32;
  188504. #ifdef SQLITE_DEBUG
  188505. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  188506. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  188507. assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  188508. }
  188509. }
  188510. assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  188511. {
  188512. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  188513. if( p->rc==SQLITE_OK ){
  188514. u8 aBlob[2] = {0xff, 0xff};
  188515. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  188516. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  188517. assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  188518. p->rc = sqlite3_reset(pIdxSelect);
  188519. sqlite3_bind_null(pIdxSelect, 2);
  188520. }
  188521. }
  188522. #endif
  188523. }
  188524. }
  188525. return iSegid;
  188526. }
  188527. /*
  188528. ** Discard all data currently cached in the hash-tables.
  188529. */
  188530. static void fts5IndexDiscardData(Fts5Index *p){
  188531. assert( p->pHash || p->nPendingData==0 );
  188532. if( p->pHash ){
  188533. sqlite3Fts5HashClear(p->pHash);
  188534. p->nPendingData = 0;
  188535. }
  188536. }
  188537. /*
  188538. ** Return the size of the prefix, in bytes, that buffer
  188539. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  188540. **
  188541. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  188542. ** than buffer (pOld/nOld).
  188543. */
  188544. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  188545. int i;
  188546. for(i=0; i<nOld; i++){
  188547. if( pOld[i]!=pNew[i] ) break;
  188548. }
  188549. return i;
  188550. }
  188551. static void fts5WriteDlidxClear(
  188552. Fts5Index *p,
  188553. Fts5SegWriter *pWriter,
  188554. int bFlush /* If true, write dlidx to disk */
  188555. ){
  188556. int i;
  188557. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  188558. for(i=0; i<pWriter->nDlidx; i++){
  188559. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  188560. if( pDlidx->buf.n==0 ) break;
  188561. if( bFlush ){
  188562. assert( pDlidx->pgno!=0 );
  188563. fts5DataWrite(p,
  188564. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  188565. pDlidx->buf.p, pDlidx->buf.n
  188566. );
  188567. }
  188568. sqlite3Fts5BufferZero(&pDlidx->buf);
  188569. pDlidx->bPrevValid = 0;
  188570. }
  188571. }
  188572. /*
  188573. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  188574. ** Any new array elements are zeroed before returning.
  188575. */
  188576. static int fts5WriteDlidxGrow(
  188577. Fts5Index *p,
  188578. Fts5SegWriter *pWriter,
  188579. int nLvl
  188580. ){
  188581. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  188582. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  188583. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  188584. );
  188585. if( aDlidx==0 ){
  188586. p->rc = SQLITE_NOMEM;
  188587. }else{
  188588. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  188589. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  188590. pWriter->aDlidx = aDlidx;
  188591. pWriter->nDlidx = nLvl;
  188592. }
  188593. }
  188594. return p->rc;
  188595. }
  188596. /*
  188597. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  188598. ** enough, flush it to disk and return 1. Otherwise discard it and return
  188599. ** zero.
  188600. */
  188601. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  188602. int bFlag = 0;
  188603. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  188604. ** to the database, also write the doclist-index to disk. */
  188605. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  188606. bFlag = 1;
  188607. }
  188608. fts5WriteDlidxClear(p, pWriter, bFlag);
  188609. pWriter->nEmpty = 0;
  188610. return bFlag;
  188611. }
  188612. /*
  188613. ** This function is called whenever processing of the doclist for the
  188614. ** last term on leaf page (pWriter->iBtPage) is completed.
  188615. **
  188616. ** The doclist-index for that term is currently stored in-memory within the
  188617. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  188618. ** writes it out to disk. Or, if it is too small to bother with, discards
  188619. ** it.
  188620. **
  188621. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  188622. */
  188623. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  188624. int bFlag;
  188625. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  188626. if( pWriter->iBtPage==0 ) return;
  188627. bFlag = fts5WriteFlushDlidx(p, pWriter);
  188628. if( p->rc==SQLITE_OK ){
  188629. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  188630. /* The following was already done in fts5WriteInit(): */
  188631. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  188632. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  188633. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  188634. sqlite3_step(p->pIdxWriter);
  188635. p->rc = sqlite3_reset(p->pIdxWriter);
  188636. sqlite3_bind_null(p->pIdxWriter, 2);
  188637. }
  188638. pWriter->iBtPage = 0;
  188639. }
  188640. /*
  188641. ** This is called once for each leaf page except the first that contains
  188642. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  188643. ** is larger than all terms written to earlier leaves, and equal to or
  188644. ** smaller than the first term on the new leaf.
  188645. **
  188646. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  188647. ** has already occurred when this function is called, it is a no-op.
  188648. */
  188649. static void fts5WriteBtreeTerm(
  188650. Fts5Index *p, /* FTS5 backend object */
  188651. Fts5SegWriter *pWriter, /* Writer object */
  188652. int nTerm, const u8 *pTerm /* First term on new page */
  188653. ){
  188654. fts5WriteFlushBtree(p, pWriter);
  188655. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  188656. pWriter->iBtPage = pWriter->writer.pgno;
  188657. }
  188658. /*
  188659. ** This function is called when flushing a leaf page that contains no
  188660. ** terms at all to disk.
  188661. */
  188662. static void fts5WriteBtreeNoTerm(
  188663. Fts5Index *p, /* FTS5 backend object */
  188664. Fts5SegWriter *pWriter /* Writer object */
  188665. ){
  188666. /* If there were no rowids on the leaf page either and the doclist-index
  188667. ** has already been started, append an 0x00 byte to it. */
  188668. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  188669. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  188670. assert( pDlidx->bPrevValid );
  188671. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  188672. }
  188673. /* Increment the "number of sequential leaves without a term" counter. */
  188674. pWriter->nEmpty++;
  188675. }
  188676. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  188677. i64 iRowid;
  188678. int iOff;
  188679. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  188680. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  188681. return iRowid;
  188682. }
  188683. /*
  188684. ** Rowid iRowid has just been appended to the current leaf page. It is the
  188685. ** first on the page. This function appends an appropriate entry to the current
  188686. ** doclist-index.
  188687. */
  188688. static void fts5WriteDlidxAppend(
  188689. Fts5Index *p,
  188690. Fts5SegWriter *pWriter,
  188691. i64 iRowid
  188692. ){
  188693. int i;
  188694. int bDone = 0;
  188695. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  188696. i64 iVal;
  188697. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  188698. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  188699. /* The current doclist-index page is full. Write it to disk and push
  188700. ** a copy of iRowid (which will become the first rowid on the next
  188701. ** doclist-index leaf page) up into the next level of the b-tree
  188702. ** hierarchy. If the node being flushed is currently the root node,
  188703. ** also push its first rowid upwards. */
  188704. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  188705. fts5DataWrite(p,
  188706. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  188707. pDlidx->buf.p, pDlidx->buf.n
  188708. );
  188709. fts5WriteDlidxGrow(p, pWriter, i+2);
  188710. pDlidx = &pWriter->aDlidx[i];
  188711. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  188712. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  188713. /* This was the root node. Push its first rowid up to the new root. */
  188714. pDlidx[1].pgno = pDlidx->pgno;
  188715. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  188716. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  188717. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  188718. pDlidx[1].bPrevValid = 1;
  188719. pDlidx[1].iPrev = iFirst;
  188720. }
  188721. sqlite3Fts5BufferZero(&pDlidx->buf);
  188722. pDlidx->bPrevValid = 0;
  188723. pDlidx->pgno++;
  188724. }else{
  188725. bDone = 1;
  188726. }
  188727. if( pDlidx->bPrevValid ){
  188728. iVal = iRowid - pDlidx->iPrev;
  188729. }else{
  188730. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  188731. assert( pDlidx->buf.n==0 );
  188732. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  188733. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  188734. iVal = iRowid;
  188735. }
  188736. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  188737. pDlidx->bPrevValid = 1;
  188738. pDlidx->iPrev = iRowid;
  188739. }
  188740. }
  188741. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  188742. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  188743. Fts5PageWriter *pPage = &pWriter->writer;
  188744. i64 iRowid;
  188745. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  188746. /* Set the szLeaf header field. */
  188747. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  188748. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  188749. if( pWriter->bFirstTermInPage ){
  188750. /* No term was written to this page. */
  188751. assert( pPage->pgidx.n==0 );
  188752. fts5WriteBtreeNoTerm(p, pWriter);
  188753. }else{
  188754. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  188755. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  188756. }
  188757. /* Write the page out to disk */
  188758. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  188759. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  188760. /* Initialize the next page. */
  188761. fts5BufferZero(&pPage->buf);
  188762. fts5BufferZero(&pPage->pgidx);
  188763. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  188764. pPage->iPrevPgidx = 0;
  188765. pPage->pgno++;
  188766. /* Increase the leaves written counter */
  188767. pWriter->nLeafWritten++;
  188768. /* The new leaf holds no terms or rowids */
  188769. pWriter->bFirstTermInPage = 1;
  188770. pWriter->bFirstRowidInPage = 1;
  188771. }
  188772. /*
  188773. ** Append term pTerm/nTerm to the segment being written by the writer passed
  188774. ** as the second argument.
  188775. **
  188776. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  188777. ** already occurred, this function is a no-op.
  188778. */
  188779. static void fts5WriteAppendTerm(
  188780. Fts5Index *p,
  188781. Fts5SegWriter *pWriter,
  188782. int nTerm, const u8 *pTerm
  188783. ){
  188784. int nPrefix; /* Bytes of prefix compression for term */
  188785. Fts5PageWriter *pPage = &pWriter->writer;
  188786. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  188787. assert( p->rc==SQLITE_OK );
  188788. assert( pPage->buf.n>=4 );
  188789. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  188790. /* If the current leaf page is full, flush it to disk. */
  188791. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  188792. if( pPage->buf.n>4 ){
  188793. fts5WriteFlushLeaf(p, pWriter);
  188794. }
  188795. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  188796. }
  188797. /* TODO1: Updating pgidx here. */
  188798. pPgidx->n += sqlite3Fts5PutVarint(
  188799. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  188800. );
  188801. pPage->iPrevPgidx = pPage->buf.n;
  188802. #if 0
  188803. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  188804. pPgidx->n += 2;
  188805. #endif
  188806. if( pWriter->bFirstTermInPage ){
  188807. nPrefix = 0;
  188808. if( pPage->pgno!=1 ){
  188809. /* This is the first term on a leaf that is not the leftmost leaf in
  188810. ** the segment b-tree. In this case it is necessary to add a term to
  188811. ** the b-tree hierarchy that is (a) larger than the largest term
  188812. ** already written to the segment and (b) smaller than or equal to
  188813. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  188814. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  188815. ** previous term.
  188816. **
  188817. ** Usually, the previous term is available in pPage->term. The exception
  188818. ** is if this is the first term written in an incremental-merge step.
  188819. ** In this case the previous term is not available, so just write a
  188820. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  188821. ** inefficient, but still correct. */
  188822. int n = nTerm;
  188823. if( pPage->term.n ){
  188824. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  188825. }
  188826. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  188827. pPage = &pWriter->writer;
  188828. }
  188829. }else{
  188830. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  188831. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  188832. }
  188833. /* Append the number of bytes of new data, then the term data itself
  188834. ** to the page. */
  188835. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  188836. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  188837. /* Update the Fts5PageWriter.term field. */
  188838. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  188839. pWriter->bFirstTermInPage = 0;
  188840. pWriter->bFirstRowidInPage = 0;
  188841. pWriter->bFirstRowidInDoclist = 1;
  188842. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  188843. pWriter->aDlidx[0].pgno = pPage->pgno;
  188844. }
  188845. /*
  188846. ** Append a rowid and position-list size field to the writers output.
  188847. */
  188848. static void fts5WriteAppendRowid(
  188849. Fts5Index *p,
  188850. Fts5SegWriter *pWriter,
  188851. i64 iRowid
  188852. ){
  188853. if( p->rc==SQLITE_OK ){
  188854. Fts5PageWriter *pPage = &pWriter->writer;
  188855. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  188856. fts5WriteFlushLeaf(p, pWriter);
  188857. }
  188858. /* If this is to be the first rowid written to the page, set the
  188859. ** rowid-pointer in the page-header. Also append a value to the dlidx
  188860. ** buffer, in case a doclist-index is required. */
  188861. if( pWriter->bFirstRowidInPage ){
  188862. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  188863. fts5WriteDlidxAppend(p, pWriter, iRowid);
  188864. }
  188865. /* Write the rowid. */
  188866. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  188867. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  188868. }else{
  188869. assert( p->rc || iRowid>pWriter->iPrevRowid );
  188870. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  188871. }
  188872. pWriter->iPrevRowid = iRowid;
  188873. pWriter->bFirstRowidInDoclist = 0;
  188874. pWriter->bFirstRowidInPage = 0;
  188875. }
  188876. }
  188877. static void fts5WriteAppendPoslistData(
  188878. Fts5Index *p,
  188879. Fts5SegWriter *pWriter,
  188880. const u8 *aData,
  188881. int nData
  188882. ){
  188883. Fts5PageWriter *pPage = &pWriter->writer;
  188884. const u8 *a = aData;
  188885. int n = nData;
  188886. assert( p->pConfig->pgsz>0 );
  188887. while( p->rc==SQLITE_OK
  188888. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  188889. ){
  188890. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  188891. int nCopy = 0;
  188892. while( nCopy<nReq ){
  188893. i64 dummy;
  188894. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  188895. }
  188896. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  188897. a += nCopy;
  188898. n -= nCopy;
  188899. fts5WriteFlushLeaf(p, pWriter);
  188900. }
  188901. if( n>0 ){
  188902. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  188903. }
  188904. }
  188905. /*
  188906. ** Flush any data cached by the writer object to the database. Free any
  188907. ** allocations associated with the writer.
  188908. */
  188909. static void fts5WriteFinish(
  188910. Fts5Index *p,
  188911. Fts5SegWriter *pWriter, /* Writer object */
  188912. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  188913. ){
  188914. int i;
  188915. Fts5PageWriter *pLeaf = &pWriter->writer;
  188916. if( p->rc==SQLITE_OK ){
  188917. assert( pLeaf->pgno>=1 );
  188918. if( pLeaf->buf.n>4 ){
  188919. fts5WriteFlushLeaf(p, pWriter);
  188920. }
  188921. *pnLeaf = pLeaf->pgno-1;
  188922. if( pLeaf->pgno>1 ){
  188923. fts5WriteFlushBtree(p, pWriter);
  188924. }
  188925. }
  188926. fts5BufferFree(&pLeaf->term);
  188927. fts5BufferFree(&pLeaf->buf);
  188928. fts5BufferFree(&pLeaf->pgidx);
  188929. fts5BufferFree(&pWriter->btterm);
  188930. for(i=0; i<pWriter->nDlidx; i++){
  188931. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  188932. }
  188933. sqlite3_free(pWriter->aDlidx);
  188934. }
  188935. static void fts5WriteInit(
  188936. Fts5Index *p,
  188937. Fts5SegWriter *pWriter,
  188938. int iSegid
  188939. ){
  188940. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  188941. memset(pWriter, 0, sizeof(Fts5SegWriter));
  188942. pWriter->iSegid = iSegid;
  188943. fts5WriteDlidxGrow(p, pWriter, 1);
  188944. pWriter->writer.pgno = 1;
  188945. pWriter->bFirstTermInPage = 1;
  188946. pWriter->iBtPage = 1;
  188947. assert( pWriter->writer.buf.n==0 );
  188948. assert( pWriter->writer.pgidx.n==0 );
  188949. /* Grow the two buffers to pgsz + padding bytes in size. */
  188950. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  188951. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  188952. if( p->pIdxWriter==0 ){
  188953. Fts5Config *pConfig = p->pConfig;
  188954. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  188955. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  188956. pConfig->zDb, pConfig->zName
  188957. ));
  188958. }
  188959. if( p->rc==SQLITE_OK ){
  188960. /* Initialize the 4-byte leaf-page header to 0x00. */
  188961. memset(pWriter->writer.buf.p, 0, 4);
  188962. pWriter->writer.buf.n = 4;
  188963. /* Bind the current output segment id to the index-writer. This is an
  188964. ** optimization over binding the same value over and over as rows are
  188965. ** inserted into %_idx by the current writer. */
  188966. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  188967. }
  188968. }
  188969. /*
  188970. ** Iterator pIter was used to iterate through the input segments of on an
  188971. ** incremental merge operation. This function is called if the incremental
  188972. ** merge step has finished but the input has not been completely exhausted.
  188973. */
  188974. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  188975. int i;
  188976. Fts5Buffer buf;
  188977. memset(&buf, 0, sizeof(Fts5Buffer));
  188978. for(i=0; i<pIter->nSeg; i++){
  188979. Fts5SegIter *pSeg = &pIter->aSeg[i];
  188980. if( pSeg->pSeg==0 ){
  188981. /* no-op */
  188982. }else if( pSeg->pLeaf==0 ){
  188983. /* All keys from this input segment have been transfered to the output.
  188984. ** Set both the first and last page-numbers to 0 to indicate that the
  188985. ** segment is now empty. */
  188986. pSeg->pSeg->pgnoLast = 0;
  188987. pSeg->pSeg->pgnoFirst = 0;
  188988. }else{
  188989. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  188990. i64 iLeafRowid;
  188991. Fts5Data *pData;
  188992. int iId = pSeg->pSeg->iSegid;
  188993. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  188994. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  188995. pData = fts5DataRead(p, iLeafRowid);
  188996. if( pData ){
  188997. fts5BufferZero(&buf);
  188998. fts5BufferGrow(&p->rc, &buf, pData->nn);
  188999. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  189000. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  189001. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  189002. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  189003. if( p->rc==SQLITE_OK ){
  189004. /* Set the szLeaf field */
  189005. fts5PutU16(&buf.p[2], (u16)buf.n);
  189006. }
  189007. /* Set up the new page-index array */
  189008. fts5BufferAppendVarint(&p->rc, &buf, 4);
  189009. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  189010. && pSeg->iEndofDoclist<pData->szLeaf
  189011. ){
  189012. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  189013. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  189014. fts5BufferAppendBlob(&p->rc, &buf,
  189015. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  189016. );
  189017. }
  189018. fts5DataRelease(pData);
  189019. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  189020. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  189021. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  189022. }
  189023. }
  189024. }
  189025. fts5BufferFree(&buf);
  189026. }
  189027. static void fts5MergeChunkCallback(
  189028. Fts5Index *p,
  189029. void *pCtx,
  189030. const u8 *pChunk, int nChunk
  189031. ){
  189032. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  189033. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  189034. }
  189035. /*
  189036. **
  189037. */
  189038. static void fts5IndexMergeLevel(
  189039. Fts5Index *p, /* FTS5 backend object */
  189040. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  189041. int iLvl, /* Level to read input from */
  189042. int *pnRem /* Write up to this many output leaves */
  189043. ){
  189044. Fts5Structure *pStruct = *ppStruct;
  189045. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  189046. Fts5StructureLevel *pLvlOut;
  189047. Fts5Iter *pIter = 0; /* Iterator to read input data */
  189048. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  189049. int nInput; /* Number of input segments */
  189050. Fts5SegWriter writer; /* Writer object */
  189051. Fts5StructureSegment *pSeg; /* Output segment */
  189052. Fts5Buffer term;
  189053. int bOldest; /* True if the output segment is the oldest */
  189054. int eDetail = p->pConfig->eDetail;
  189055. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  189056. int bTermWritten = 0; /* True if current term already output */
  189057. assert( iLvl<pStruct->nLevel );
  189058. assert( pLvl->nMerge<=pLvl->nSeg );
  189059. memset(&writer, 0, sizeof(Fts5SegWriter));
  189060. memset(&term, 0, sizeof(Fts5Buffer));
  189061. if( pLvl->nMerge ){
  189062. pLvlOut = &pStruct->aLevel[iLvl+1];
  189063. assert( pLvlOut->nSeg>0 );
  189064. nInput = pLvl->nMerge;
  189065. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  189066. fts5WriteInit(p, &writer, pSeg->iSegid);
  189067. writer.writer.pgno = pSeg->pgnoLast+1;
  189068. writer.iBtPage = 0;
  189069. }else{
  189070. int iSegid = fts5AllocateSegid(p, pStruct);
  189071. /* Extend the Fts5Structure object as required to ensure the output
  189072. ** segment exists. */
  189073. if( iLvl==pStruct->nLevel-1 ){
  189074. fts5StructureAddLevel(&p->rc, ppStruct);
  189075. pStruct = *ppStruct;
  189076. }
  189077. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  189078. if( p->rc ) return;
  189079. pLvl = &pStruct->aLevel[iLvl];
  189080. pLvlOut = &pStruct->aLevel[iLvl+1];
  189081. fts5WriteInit(p, &writer, iSegid);
  189082. /* Add the new segment to the output level */
  189083. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  189084. pLvlOut->nSeg++;
  189085. pSeg->pgnoFirst = 1;
  189086. pSeg->iSegid = iSegid;
  189087. pStruct->nSegment++;
  189088. /* Read input from all segments in the input level */
  189089. nInput = pLvl->nSeg;
  189090. }
  189091. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  189092. assert( iLvl>=0 );
  189093. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  189094. fts5MultiIterEof(p, pIter)==0;
  189095. fts5MultiIterNext(p, pIter, 0, 0)
  189096. ){
  189097. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  189098. int nPos; /* position-list size field value */
  189099. int nTerm;
  189100. const u8 *pTerm;
  189101. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  189102. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  189103. if( pnRem && writer.nLeafWritten>nRem ){
  189104. break;
  189105. }
  189106. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  189107. bTermWritten =0;
  189108. }
  189109. /* Check for key annihilation. */
  189110. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  189111. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  189112. /* This is a new term. Append a term to the output segment. */
  189113. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  189114. bTermWritten = 1;
  189115. }
  189116. /* Append the rowid to the output */
  189117. /* WRITEPOSLISTSIZE */
  189118. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  189119. if( eDetail==FTS5_DETAIL_NONE ){
  189120. if( pSegIter->bDel ){
  189121. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  189122. if( pSegIter->nPos>0 ){
  189123. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  189124. }
  189125. }
  189126. }else{
  189127. /* Append the position-list data to the output */
  189128. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  189129. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  189130. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  189131. }
  189132. }
  189133. /* Flush the last leaf page to disk. Set the output segment b-tree height
  189134. ** and last leaf page number at the same time. */
  189135. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  189136. if( fts5MultiIterEof(p, pIter) ){
  189137. int i;
  189138. /* Remove the redundant segments from the %_data table */
  189139. for(i=0; i<nInput; i++){
  189140. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  189141. }
  189142. /* Remove the redundant segments from the input level */
  189143. if( pLvl->nSeg!=nInput ){
  189144. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  189145. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  189146. }
  189147. pStruct->nSegment -= nInput;
  189148. pLvl->nSeg -= nInput;
  189149. pLvl->nMerge = 0;
  189150. if( pSeg->pgnoLast==0 ){
  189151. pLvlOut->nSeg--;
  189152. pStruct->nSegment--;
  189153. }
  189154. }else{
  189155. assert( pSeg->pgnoLast>0 );
  189156. fts5TrimSegments(p, pIter);
  189157. pLvl->nMerge = nInput;
  189158. }
  189159. fts5MultiIterFree(pIter);
  189160. fts5BufferFree(&term);
  189161. if( pnRem ) *pnRem -= writer.nLeafWritten;
  189162. }
  189163. /*
  189164. ** Do up to nPg pages of automerge work on the index.
  189165. **
  189166. ** Return true if any changes were actually made, or false otherwise.
  189167. */
  189168. static int fts5IndexMerge(
  189169. Fts5Index *p, /* FTS5 backend object */
  189170. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  189171. int nPg, /* Pages of work to do */
  189172. int nMin /* Minimum number of segments to merge */
  189173. ){
  189174. int nRem = nPg;
  189175. int bRet = 0;
  189176. Fts5Structure *pStruct = *ppStruct;
  189177. while( nRem>0 && p->rc==SQLITE_OK ){
  189178. int iLvl; /* To iterate through levels */
  189179. int iBestLvl = 0; /* Level offering the most input segments */
  189180. int nBest = 0; /* Number of input segments on best level */
  189181. /* Set iBestLvl to the level to read input segments from. */
  189182. assert( pStruct->nLevel>0 );
  189183. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  189184. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  189185. if( pLvl->nMerge ){
  189186. if( pLvl->nMerge>nBest ){
  189187. iBestLvl = iLvl;
  189188. nBest = pLvl->nMerge;
  189189. }
  189190. break;
  189191. }
  189192. if( pLvl->nSeg>nBest ){
  189193. nBest = pLvl->nSeg;
  189194. iBestLvl = iLvl;
  189195. }
  189196. }
  189197. /* If nBest is still 0, then the index must be empty. */
  189198. #ifdef SQLITE_DEBUG
  189199. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  189200. assert( pStruct->aLevel[iLvl].nSeg==0 );
  189201. }
  189202. #endif
  189203. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  189204. break;
  189205. }
  189206. bRet = 1;
  189207. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  189208. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  189209. fts5StructurePromote(p, iBestLvl+1, pStruct);
  189210. }
  189211. }
  189212. *ppStruct = pStruct;
  189213. return bRet;
  189214. }
  189215. /*
  189216. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  189217. ** segment. This function updates the write-counter accordingly and, if
  189218. ** necessary, performs incremental merge work.
  189219. **
  189220. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  189221. ** already occurred, this function is a no-op.
  189222. */
  189223. static void fts5IndexAutomerge(
  189224. Fts5Index *p, /* FTS5 backend object */
  189225. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  189226. int nLeaf /* Number of output leaves just written */
  189227. ){
  189228. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  189229. Fts5Structure *pStruct = *ppStruct;
  189230. u64 nWrite; /* Initial value of write-counter */
  189231. int nWork; /* Number of work-quanta to perform */
  189232. int nRem; /* Number of leaf pages left to write */
  189233. /* Update the write-counter. While doing so, set nWork. */
  189234. nWrite = pStruct->nWriteCounter;
  189235. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  189236. pStruct->nWriteCounter += nLeaf;
  189237. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  189238. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  189239. }
  189240. }
  189241. static void fts5IndexCrisismerge(
  189242. Fts5Index *p, /* FTS5 backend object */
  189243. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  189244. ){
  189245. const int nCrisis = p->pConfig->nCrisisMerge;
  189246. Fts5Structure *pStruct = *ppStruct;
  189247. int iLvl = 0;
  189248. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  189249. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  189250. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  189251. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  189252. fts5StructurePromote(p, iLvl+1, pStruct);
  189253. iLvl++;
  189254. }
  189255. *ppStruct = pStruct;
  189256. }
  189257. static int fts5IndexReturn(Fts5Index *p){
  189258. int rc = p->rc;
  189259. p->rc = SQLITE_OK;
  189260. return rc;
  189261. }
  189262. typedef struct Fts5FlushCtx Fts5FlushCtx;
  189263. struct Fts5FlushCtx {
  189264. Fts5Index *pIdx;
  189265. Fts5SegWriter writer;
  189266. };
  189267. /*
  189268. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  189269. ** in a 32-bit integer. Return the size of the largest prefix of this
  189270. ** list nMax bytes or less in size.
  189271. */
  189272. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  189273. int ret;
  189274. u32 dummy;
  189275. ret = fts5GetVarint32(aBuf, dummy);
  189276. if( ret<nMax ){
  189277. while( 1 ){
  189278. int i = fts5GetVarint32(&aBuf[ret], dummy);
  189279. if( (ret + i) > nMax ) break;
  189280. ret += i;
  189281. }
  189282. }
  189283. return ret;
  189284. }
  189285. /*
  189286. ** Flush the contents of in-memory hash table iHash to a new level-0
  189287. ** segment on disk. Also update the corresponding structure record.
  189288. **
  189289. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  189290. ** already occurred, this function is a no-op.
  189291. */
  189292. static void fts5FlushOneHash(Fts5Index *p){
  189293. Fts5Hash *pHash = p->pHash;
  189294. Fts5Structure *pStruct;
  189295. int iSegid;
  189296. int pgnoLast = 0; /* Last leaf page number in segment */
  189297. /* Obtain a reference to the index structure and allocate a new segment-id
  189298. ** for the new level-0 segment. */
  189299. pStruct = fts5StructureRead(p);
  189300. iSegid = fts5AllocateSegid(p, pStruct);
  189301. fts5StructureInvalidate(p);
  189302. if( iSegid ){
  189303. const int pgsz = p->pConfig->pgsz;
  189304. int eDetail = p->pConfig->eDetail;
  189305. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  189306. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  189307. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  189308. Fts5SegWriter writer;
  189309. fts5WriteInit(p, &writer, iSegid);
  189310. pBuf = &writer.writer.buf;
  189311. pPgidx = &writer.writer.pgidx;
  189312. /* fts5WriteInit() should have initialized the buffers to (most likely)
  189313. ** the maximum space required. */
  189314. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  189315. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  189316. /* Begin scanning through hash table entries. This loop runs once for each
  189317. ** term/doclist currently stored within the hash table. */
  189318. if( p->rc==SQLITE_OK ){
  189319. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  189320. }
  189321. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  189322. const char *zTerm; /* Buffer containing term */
  189323. const u8 *pDoclist; /* Pointer to doclist for this term */
  189324. int nDoclist; /* Size of doclist in bytes */
  189325. /* Write the term for this entry to disk. */
  189326. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  189327. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  189328. assert( writer.bFirstRowidInPage==0 );
  189329. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  189330. /* The entire doclist will fit on the current leaf. */
  189331. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  189332. }else{
  189333. i64 iRowid = 0;
  189334. i64 iDelta = 0;
  189335. int iOff = 0;
  189336. /* The entire doclist will not fit on this leaf. The following
  189337. ** loop iterates through the poslists that make up the current
  189338. ** doclist. */
  189339. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  189340. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  189341. iRowid += iDelta;
  189342. if( writer.bFirstRowidInPage ){
  189343. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  189344. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  189345. writer.bFirstRowidInPage = 0;
  189346. fts5WriteDlidxAppend(p, &writer, iRowid);
  189347. }else{
  189348. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  189349. }
  189350. assert( pBuf->n<=pBuf->nSpace );
  189351. if( eDetail==FTS5_DETAIL_NONE ){
  189352. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  189353. pBuf->p[pBuf->n++] = 0;
  189354. iOff++;
  189355. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  189356. pBuf->p[pBuf->n++] = 0;
  189357. iOff++;
  189358. }
  189359. }
  189360. if( (pBuf->n + pPgidx->n)>=pgsz ){
  189361. fts5WriteFlushLeaf(p, &writer);
  189362. }
  189363. }else{
  189364. int bDummy;
  189365. int nPos;
  189366. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  189367. nCopy += nPos;
  189368. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  189369. /* The entire poslist will fit on the current leaf. So copy
  189370. ** it in one go. */
  189371. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  189372. }else{
  189373. /* The entire poslist will not fit on this leaf. So it needs
  189374. ** to be broken into sections. The only qualification being
  189375. ** that each varint must be stored contiguously. */
  189376. const u8 *pPoslist = &pDoclist[iOff];
  189377. int iPos = 0;
  189378. while( p->rc==SQLITE_OK ){
  189379. int nSpace = pgsz - pBuf->n - pPgidx->n;
  189380. int n = 0;
  189381. if( (nCopy - iPos)<=nSpace ){
  189382. n = nCopy - iPos;
  189383. }else{
  189384. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  189385. }
  189386. assert( n>0 );
  189387. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  189388. iPos += n;
  189389. if( (pBuf->n + pPgidx->n)>=pgsz ){
  189390. fts5WriteFlushLeaf(p, &writer);
  189391. }
  189392. if( iPos>=nCopy ) break;
  189393. }
  189394. }
  189395. iOff += nCopy;
  189396. }
  189397. }
  189398. }
  189399. /* TODO2: Doclist terminator written here. */
  189400. /* pBuf->p[pBuf->n++] = '\0'; */
  189401. assert( pBuf->n<=pBuf->nSpace );
  189402. sqlite3Fts5HashScanNext(pHash);
  189403. }
  189404. sqlite3Fts5HashClear(pHash);
  189405. fts5WriteFinish(p, &writer, &pgnoLast);
  189406. /* Update the Fts5Structure. It is written back to the database by the
  189407. ** fts5StructureRelease() call below. */
  189408. if( pStruct->nLevel==0 ){
  189409. fts5StructureAddLevel(&p->rc, &pStruct);
  189410. }
  189411. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  189412. if( p->rc==SQLITE_OK ){
  189413. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  189414. pSeg->iSegid = iSegid;
  189415. pSeg->pgnoFirst = 1;
  189416. pSeg->pgnoLast = pgnoLast;
  189417. pStruct->nSegment++;
  189418. }
  189419. fts5StructurePromote(p, 0, pStruct);
  189420. }
  189421. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  189422. fts5IndexCrisismerge(p, &pStruct);
  189423. fts5StructureWrite(p, pStruct);
  189424. fts5StructureRelease(pStruct);
  189425. }
  189426. /*
  189427. ** Flush any data stored in the in-memory hash tables to the database.
  189428. */
  189429. static void fts5IndexFlush(Fts5Index *p){
  189430. /* Unless it is empty, flush the hash table to disk */
  189431. if( p->nPendingData ){
  189432. assert( p->pHash );
  189433. p->nPendingData = 0;
  189434. fts5FlushOneHash(p);
  189435. }
  189436. }
  189437. static Fts5Structure *fts5IndexOptimizeStruct(
  189438. Fts5Index *p,
  189439. Fts5Structure *pStruct
  189440. ){
  189441. Fts5Structure *pNew = 0;
  189442. int nByte = sizeof(Fts5Structure);
  189443. int nSeg = pStruct->nSegment;
  189444. int i;
  189445. /* Figure out if this structure requires optimization. A structure does
  189446. ** not require optimization if either:
  189447. **
  189448. ** + it consists of fewer than two segments, or
  189449. ** + all segments are on the same level, or
  189450. ** + all segments except one are currently inputs to a merge operation.
  189451. **
  189452. ** In the first case, return NULL. In the second, increment the ref-count
  189453. ** on *pStruct and return a copy of the pointer to it.
  189454. */
  189455. if( nSeg<2 ) return 0;
  189456. for(i=0; i<pStruct->nLevel; i++){
  189457. int nThis = pStruct->aLevel[i].nSeg;
  189458. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  189459. fts5StructureRef(pStruct);
  189460. return pStruct;
  189461. }
  189462. assert( pStruct->aLevel[i].nMerge<=nThis );
  189463. }
  189464. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  189465. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  189466. if( pNew ){
  189467. Fts5StructureLevel *pLvl;
  189468. nByte = nSeg * sizeof(Fts5StructureSegment);
  189469. pNew->nLevel = pStruct->nLevel+1;
  189470. pNew->nRef = 1;
  189471. pNew->nWriteCounter = pStruct->nWriteCounter;
  189472. pLvl = &pNew->aLevel[pStruct->nLevel];
  189473. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  189474. if( pLvl->aSeg ){
  189475. int iLvl, iSeg;
  189476. int iSegOut = 0;
  189477. /* Iterate through all segments, from oldest to newest. Add them to
  189478. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  189479. ** segment in the data structure. */
  189480. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  189481. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  189482. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  189483. iSegOut++;
  189484. }
  189485. }
  189486. pNew->nSegment = pLvl->nSeg = nSeg;
  189487. }else{
  189488. sqlite3_free(pNew);
  189489. pNew = 0;
  189490. }
  189491. }
  189492. return pNew;
  189493. }
  189494. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  189495. Fts5Structure *pStruct;
  189496. Fts5Structure *pNew = 0;
  189497. assert( p->rc==SQLITE_OK );
  189498. fts5IndexFlush(p);
  189499. pStruct = fts5StructureRead(p);
  189500. fts5StructureInvalidate(p);
  189501. if( pStruct ){
  189502. pNew = fts5IndexOptimizeStruct(p, pStruct);
  189503. }
  189504. fts5StructureRelease(pStruct);
  189505. assert( pNew==0 || pNew->nSegment>0 );
  189506. if( pNew ){
  189507. int iLvl;
  189508. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  189509. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  189510. int nRem = FTS5_OPT_WORK_UNIT;
  189511. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  189512. }
  189513. fts5StructureWrite(p, pNew);
  189514. fts5StructureRelease(pNew);
  189515. }
  189516. return fts5IndexReturn(p);
  189517. }
  189518. /*
  189519. ** This is called to implement the special "VALUES('merge', $nMerge)"
  189520. ** INSERT command.
  189521. */
  189522. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  189523. Fts5Structure *pStruct = fts5StructureRead(p);
  189524. if( pStruct ){
  189525. int nMin = p->pConfig->nUsermerge;
  189526. fts5StructureInvalidate(p);
  189527. if( nMerge<0 ){
  189528. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  189529. fts5StructureRelease(pStruct);
  189530. pStruct = pNew;
  189531. nMin = 2;
  189532. nMerge = nMerge*-1;
  189533. }
  189534. if( pStruct && pStruct->nLevel ){
  189535. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  189536. fts5StructureWrite(p, pStruct);
  189537. }
  189538. }
  189539. fts5StructureRelease(pStruct);
  189540. }
  189541. return fts5IndexReturn(p);
  189542. }
  189543. static void fts5AppendRowid(
  189544. Fts5Index *p,
  189545. i64 iDelta,
  189546. Fts5Iter *pUnused,
  189547. Fts5Buffer *pBuf
  189548. ){
  189549. UNUSED_PARAM(pUnused);
  189550. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  189551. }
  189552. static void fts5AppendPoslist(
  189553. Fts5Index *p,
  189554. i64 iDelta,
  189555. Fts5Iter *pMulti,
  189556. Fts5Buffer *pBuf
  189557. ){
  189558. int nData = pMulti->base.nData;
  189559. assert( nData>0 );
  189560. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
  189561. fts5BufferSafeAppendVarint(pBuf, iDelta);
  189562. fts5BufferSafeAppendVarint(pBuf, nData*2);
  189563. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  189564. }
  189565. }
  189566. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  189567. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  189568. assert( pIter->aPoslist );
  189569. if( p>=pIter->aEof ){
  189570. pIter->aPoslist = 0;
  189571. }else{
  189572. i64 iDelta;
  189573. p += fts5GetVarint(p, (u64*)&iDelta);
  189574. pIter->iRowid += iDelta;
  189575. /* Read position list size */
  189576. if( p[0] & 0x80 ){
  189577. int nPos;
  189578. pIter->nSize = fts5GetVarint32(p, nPos);
  189579. pIter->nPoslist = (nPos>>1);
  189580. }else{
  189581. pIter->nPoslist = ((int)(p[0])) >> 1;
  189582. pIter->nSize = 1;
  189583. }
  189584. pIter->aPoslist = p;
  189585. }
  189586. }
  189587. static void fts5DoclistIterInit(
  189588. Fts5Buffer *pBuf,
  189589. Fts5DoclistIter *pIter
  189590. ){
  189591. memset(pIter, 0, sizeof(*pIter));
  189592. pIter->aPoslist = pBuf->p;
  189593. pIter->aEof = &pBuf->p[pBuf->n];
  189594. fts5DoclistIterNext(pIter);
  189595. }
  189596. #if 0
  189597. /*
  189598. ** Append a doclist to buffer pBuf.
  189599. **
  189600. ** This function assumes that space within the buffer has already been
  189601. ** allocated.
  189602. */
  189603. static void fts5MergeAppendDocid(
  189604. Fts5Buffer *pBuf, /* Buffer to write to */
  189605. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  189606. i64 iRowid /* Rowid to append */
  189607. ){
  189608. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  189609. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  189610. *piLastRowid = iRowid;
  189611. }
  189612. #endif
  189613. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  189614. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  189615. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  189616. (iLastRowid) = (iRowid); \
  189617. }
  189618. /*
  189619. ** Swap the contents of buffer *p1 with that of *p2.
  189620. */
  189621. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  189622. Fts5Buffer tmp = *p1;
  189623. *p1 = *p2;
  189624. *p2 = tmp;
  189625. }
  189626. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  189627. int i = *piOff;
  189628. if( i>=pBuf->n ){
  189629. *piOff = -1;
  189630. }else{
  189631. u64 iVal;
  189632. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  189633. *piRowid += iVal;
  189634. }
  189635. }
  189636. /*
  189637. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  189638. ** In this case the buffers consist of a delta-encoded list of rowids only.
  189639. */
  189640. static void fts5MergeRowidLists(
  189641. Fts5Index *p, /* FTS5 backend object */
  189642. Fts5Buffer *p1, /* First list to merge */
  189643. Fts5Buffer *p2 /* Second list to merge */
  189644. ){
  189645. int i1 = 0;
  189646. int i2 = 0;
  189647. i64 iRowid1 = 0;
  189648. i64 iRowid2 = 0;
  189649. i64 iOut = 0;
  189650. Fts5Buffer out;
  189651. memset(&out, 0, sizeof(out));
  189652. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  189653. if( p->rc ) return;
  189654. fts5NextRowid(p1, &i1, &iRowid1);
  189655. fts5NextRowid(p2, &i2, &iRowid2);
  189656. while( i1>=0 || i2>=0 ){
  189657. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  189658. assert( iOut==0 || iRowid1>iOut );
  189659. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  189660. iOut = iRowid1;
  189661. fts5NextRowid(p1, &i1, &iRowid1);
  189662. }else{
  189663. assert( iOut==0 || iRowid2>iOut );
  189664. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  189665. iOut = iRowid2;
  189666. if( i1>=0 && iRowid1==iRowid2 ){
  189667. fts5NextRowid(p1, &i1, &iRowid1);
  189668. }
  189669. fts5NextRowid(p2, &i2, &iRowid2);
  189670. }
  189671. }
  189672. fts5BufferSwap(&out, p1);
  189673. fts5BufferFree(&out);
  189674. }
  189675. /*
  189676. ** Buffers p1 and p2 contain doclists. This function merges the content
  189677. ** of the two doclists together and sets buffer p1 to the result before
  189678. ** returning.
  189679. **
  189680. ** If an error occurs, an error code is left in p->rc. If an error has
  189681. ** already occurred, this function is a no-op.
  189682. */
  189683. static void fts5MergePrefixLists(
  189684. Fts5Index *p, /* FTS5 backend object */
  189685. Fts5Buffer *p1, /* First list to merge */
  189686. Fts5Buffer *p2 /* Second list to merge */
  189687. ){
  189688. if( p2->n ){
  189689. i64 iLastRowid = 0;
  189690. Fts5DoclistIter i1;
  189691. Fts5DoclistIter i2;
  189692. Fts5Buffer out = {0, 0, 0};
  189693. Fts5Buffer tmp = {0, 0, 0};
  189694. /* The maximum size of the output is equal to the sum of the two
  189695. ** input sizes + 1 varint (9 bytes). The extra varint is because if the
  189696. ** first rowid in one input is a large negative number, and the first in
  189697. ** the other a non-negative number, the delta for the non-negative
  189698. ** number will be larger on disk than the literal integer value
  189699. ** was. */
  189700. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9) ) return;
  189701. fts5DoclistIterInit(p1, &i1);
  189702. fts5DoclistIterInit(p2, &i2);
  189703. while( 1 ){
  189704. if( i1.iRowid<i2.iRowid ){
  189705. /* Copy entry from i1 */
  189706. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  189707. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  189708. fts5DoclistIterNext(&i1);
  189709. if( i1.aPoslist==0 ) break;
  189710. }
  189711. else if( i2.iRowid!=i1.iRowid ){
  189712. /* Copy entry from i2 */
  189713. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  189714. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  189715. fts5DoclistIterNext(&i2);
  189716. if( i2.aPoslist==0 ) break;
  189717. }
  189718. else{
  189719. /* Merge the two position lists. */
  189720. i64 iPos1 = 0;
  189721. i64 iPos2 = 0;
  189722. int iOff1 = 0;
  189723. int iOff2 = 0;
  189724. u8 *a1 = &i1.aPoslist[i1.nSize];
  189725. u8 *a2 = &i2.aPoslist[i2.nSize];
  189726. i64 iPrev = 0;
  189727. Fts5PoslistWriter writer;
  189728. memset(&writer, 0, sizeof(writer));
  189729. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  189730. fts5BufferZero(&tmp);
  189731. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  189732. if( p->rc ) break;
  189733. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  189734. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  189735. assert( iPos1>=0 && iPos2>=0 );
  189736. if( iPos1<iPos2 ){
  189737. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  189738. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  189739. }else{
  189740. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  189741. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  189742. }
  189743. if( iPos1>=0 && iPos2>=0 ){
  189744. while( 1 ){
  189745. if( iPos1<iPos2 ){
  189746. if( iPos1!=iPrev ){
  189747. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  189748. }
  189749. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  189750. if( iPos1<0 ) break;
  189751. }else{
  189752. assert( iPos2!=iPrev );
  189753. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  189754. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  189755. if( iPos2<0 ) break;
  189756. }
  189757. }
  189758. }
  189759. if( iPos1>=0 ){
  189760. if( iPos1!=iPrev ){
  189761. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  189762. }
  189763. fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
  189764. }else{
  189765. assert( iPos2>=0 && iPos2!=iPrev );
  189766. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  189767. fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
  189768. }
  189769. /* WRITEPOSLISTSIZE */
  189770. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  189771. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  189772. fts5DoclistIterNext(&i1);
  189773. fts5DoclistIterNext(&i2);
  189774. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  189775. }
  189776. }
  189777. if( i1.aPoslist ){
  189778. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  189779. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  189780. }
  189781. else if( i2.aPoslist ){
  189782. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  189783. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  189784. }
  189785. assert( out.n<=(p1->n+p2->n+9) );
  189786. fts5BufferSet(&p->rc, p1, out.n, out.p);
  189787. fts5BufferFree(&tmp);
  189788. fts5BufferFree(&out);
  189789. }
  189790. }
  189791. static void fts5SetupPrefixIter(
  189792. Fts5Index *p, /* Index to read from */
  189793. int bDesc, /* True for "ORDER BY rowid DESC" */
  189794. const u8 *pToken, /* Buffer containing prefix to match */
  189795. int nToken, /* Size of buffer pToken in bytes */
  189796. Fts5Colset *pColset, /* Restrict matches to these columns */
  189797. Fts5Iter **ppIter /* OUT: New iterator */
  189798. ){
  189799. Fts5Structure *pStruct;
  189800. Fts5Buffer *aBuf;
  189801. const int nBuf = 32;
  189802. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  189803. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  189804. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  189805. xMerge = fts5MergeRowidLists;
  189806. xAppend = fts5AppendRowid;
  189807. }else{
  189808. xMerge = fts5MergePrefixLists;
  189809. xAppend = fts5AppendPoslist;
  189810. }
  189811. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  189812. pStruct = fts5StructureRead(p);
  189813. if( aBuf && pStruct ){
  189814. const int flags = FTS5INDEX_QUERY_SCAN
  189815. | FTS5INDEX_QUERY_SKIPEMPTY
  189816. | FTS5INDEX_QUERY_NOOUTPUT;
  189817. int i;
  189818. i64 iLastRowid = 0;
  189819. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  189820. Fts5Data *pData;
  189821. Fts5Buffer doclist;
  189822. int bNewTerm = 1;
  189823. memset(&doclist, 0, sizeof(doclist));
  189824. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  189825. fts5IterSetOutputCb(&p->rc, p1);
  189826. for( /* no-op */ ;
  189827. fts5MultiIterEof(p, p1)==0;
  189828. fts5MultiIterNext2(p, p1, &bNewTerm)
  189829. ){
  189830. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  189831. int nTerm = pSeg->term.n;
  189832. const u8 *pTerm = pSeg->term.p;
  189833. p1->xSetOutputs(p1, pSeg);
  189834. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  189835. if( bNewTerm ){
  189836. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  189837. }
  189838. if( p1->base.nData==0 ) continue;
  189839. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  189840. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  189841. assert( i<nBuf );
  189842. if( aBuf[i].n==0 ){
  189843. fts5BufferSwap(&doclist, &aBuf[i]);
  189844. fts5BufferZero(&doclist);
  189845. }else{
  189846. xMerge(p, &doclist, &aBuf[i]);
  189847. fts5BufferZero(&aBuf[i]);
  189848. }
  189849. }
  189850. iLastRowid = 0;
  189851. }
  189852. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  189853. iLastRowid = p1->base.iRowid;
  189854. }
  189855. for(i=0; i<nBuf; i++){
  189856. if( p->rc==SQLITE_OK ){
  189857. xMerge(p, &doclist, &aBuf[i]);
  189858. }
  189859. fts5BufferFree(&aBuf[i]);
  189860. }
  189861. fts5MultiIterFree(p1);
  189862. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  189863. if( pData ){
  189864. pData->p = (u8*)&pData[1];
  189865. pData->nn = pData->szLeaf = doclist.n;
  189866. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  189867. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  189868. }
  189869. fts5BufferFree(&doclist);
  189870. }
  189871. fts5StructureRelease(pStruct);
  189872. sqlite3_free(aBuf);
  189873. }
  189874. /*
  189875. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  189876. ** to the document with rowid iRowid.
  189877. */
  189878. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  189879. assert( p->rc==SQLITE_OK );
  189880. /* Allocate the hash table if it has not already been allocated */
  189881. if( p->pHash==0 ){
  189882. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  189883. }
  189884. /* Flush the hash table to disk if required */
  189885. if( iRowid<p->iWriteRowid
  189886. || (iRowid==p->iWriteRowid && p->bDelete==0)
  189887. || (p->nPendingData > p->pConfig->nHashSize)
  189888. ){
  189889. fts5IndexFlush(p);
  189890. }
  189891. p->iWriteRowid = iRowid;
  189892. p->bDelete = bDelete;
  189893. return fts5IndexReturn(p);
  189894. }
  189895. /*
  189896. ** Commit data to disk.
  189897. */
  189898. static int sqlite3Fts5IndexSync(Fts5Index *p){
  189899. assert( p->rc==SQLITE_OK );
  189900. fts5IndexFlush(p);
  189901. fts5CloseReader(p);
  189902. return fts5IndexReturn(p);
  189903. }
  189904. /*
  189905. ** Discard any data stored in the in-memory hash tables. Do not write it
  189906. ** to the database. Additionally, assume that the contents of the %_data
  189907. ** table may have changed on disk. So any in-memory caches of %_data
  189908. ** records must be invalidated.
  189909. */
  189910. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  189911. fts5CloseReader(p);
  189912. fts5IndexDiscardData(p);
  189913. fts5StructureInvalidate(p);
  189914. /* assert( p->rc==SQLITE_OK ); */
  189915. return SQLITE_OK;
  189916. }
  189917. /*
  189918. ** The %_data table is completely empty when this function is called. This
  189919. ** function populates it with the initial structure objects for each index,
  189920. ** and the initial version of the "averages" record (a zero-byte blob).
  189921. */
  189922. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  189923. Fts5Structure s;
  189924. fts5StructureInvalidate(p);
  189925. memset(&s, 0, sizeof(Fts5Structure));
  189926. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  189927. fts5StructureWrite(p, &s);
  189928. return fts5IndexReturn(p);
  189929. }
  189930. /*
  189931. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  189932. ** and initialize the underlying %_data table.
  189933. **
  189934. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  189935. ** Otherwise, set *pp to NULL and return an SQLite error code.
  189936. */
  189937. static int sqlite3Fts5IndexOpen(
  189938. Fts5Config *pConfig,
  189939. int bCreate,
  189940. Fts5Index **pp,
  189941. char **pzErr
  189942. ){
  189943. int rc = SQLITE_OK;
  189944. Fts5Index *p; /* New object */
  189945. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  189946. if( rc==SQLITE_OK ){
  189947. p->pConfig = pConfig;
  189948. p->nWorkUnit = FTS5_WORK_UNIT;
  189949. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  189950. if( p->zDataTbl && bCreate ){
  189951. rc = sqlite3Fts5CreateTable(
  189952. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  189953. );
  189954. if( rc==SQLITE_OK ){
  189955. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  189956. "segid, term, pgno, PRIMARY KEY(segid, term)",
  189957. 1, pzErr
  189958. );
  189959. }
  189960. if( rc==SQLITE_OK ){
  189961. rc = sqlite3Fts5IndexReinit(p);
  189962. }
  189963. }
  189964. }
  189965. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  189966. if( rc ){
  189967. sqlite3Fts5IndexClose(p);
  189968. *pp = 0;
  189969. }
  189970. return rc;
  189971. }
  189972. /*
  189973. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  189974. */
  189975. static int sqlite3Fts5IndexClose(Fts5Index *p){
  189976. int rc = SQLITE_OK;
  189977. if( p ){
  189978. assert( p->pReader==0 );
  189979. fts5StructureInvalidate(p);
  189980. sqlite3_finalize(p->pWriter);
  189981. sqlite3_finalize(p->pDeleter);
  189982. sqlite3_finalize(p->pIdxWriter);
  189983. sqlite3_finalize(p->pIdxDeleter);
  189984. sqlite3_finalize(p->pIdxSelect);
  189985. sqlite3_finalize(p->pDataVersion);
  189986. sqlite3Fts5HashFree(p->pHash);
  189987. sqlite3_free(p->zDataTbl);
  189988. sqlite3_free(p);
  189989. }
  189990. return rc;
  189991. }
  189992. /*
  189993. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  189994. ** size. Return the number of bytes in the nChar character prefix of the
  189995. ** buffer, or 0 if there are less than nChar characters in total.
  189996. */
  189997. static int sqlite3Fts5IndexCharlenToBytelen(
  189998. const char *p,
  189999. int nByte,
  190000. int nChar
  190001. ){
  190002. int n = 0;
  190003. int i;
  190004. for(i=0; i<nChar; i++){
  190005. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  190006. if( (unsigned char)p[n++]>=0xc0 ){
  190007. while( (p[n] & 0xc0)==0x80 ) n++;
  190008. }
  190009. }
  190010. return n;
  190011. }
  190012. /*
  190013. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  190014. ** unicode characters in the string.
  190015. */
  190016. static int fts5IndexCharlen(const char *pIn, int nIn){
  190017. int nChar = 0;
  190018. int i = 0;
  190019. while( i<nIn ){
  190020. if( (unsigned char)pIn[i++]>=0xc0 ){
  190021. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  190022. }
  190023. nChar++;
  190024. }
  190025. return nChar;
  190026. }
  190027. /*
  190028. ** Insert or remove data to or from the index. Each time a document is
  190029. ** added to or removed from the index, this function is called one or more
  190030. ** times.
  190031. **
  190032. ** For an insert, it must be called once for each token in the new document.
  190033. ** If the operation is a delete, it must be called (at least) once for each
  190034. ** unique token in the document with an iCol value less than zero. The iPos
  190035. ** argument is ignored for a delete.
  190036. */
  190037. static int sqlite3Fts5IndexWrite(
  190038. Fts5Index *p, /* Index to write to */
  190039. int iCol, /* Column token appears in (-ve -> delete) */
  190040. int iPos, /* Position of token within column */
  190041. const char *pToken, int nToken /* Token to add or remove to or from index */
  190042. ){
  190043. int i; /* Used to iterate through indexes */
  190044. int rc = SQLITE_OK; /* Return code */
  190045. Fts5Config *pConfig = p->pConfig;
  190046. assert( p->rc==SQLITE_OK );
  190047. assert( (iCol<0)==p->bDelete );
  190048. /* Add the entry to the main terms index. */
  190049. rc = sqlite3Fts5HashWrite(
  190050. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  190051. );
  190052. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  190053. const int nChar = pConfig->aPrefix[i];
  190054. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  190055. if( nByte ){
  190056. rc = sqlite3Fts5HashWrite(p->pHash,
  190057. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  190058. nByte
  190059. );
  190060. }
  190061. }
  190062. return rc;
  190063. }
  190064. /*
  190065. ** Open a new iterator to iterate though all rowid that match the
  190066. ** specified token or token prefix.
  190067. */
  190068. static int sqlite3Fts5IndexQuery(
  190069. Fts5Index *p, /* FTS index to query */
  190070. const char *pToken, int nToken, /* Token (or prefix) to query for */
  190071. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  190072. Fts5Colset *pColset, /* Match these columns only */
  190073. Fts5IndexIter **ppIter /* OUT: New iterator object */
  190074. ){
  190075. Fts5Config *pConfig = p->pConfig;
  190076. Fts5Iter *pRet = 0;
  190077. Fts5Buffer buf = {0, 0, 0};
  190078. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  190079. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  190080. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  190081. int iIdx = 0; /* Index to search */
  190082. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  190083. /* Figure out which index to search and set iIdx accordingly. If this
  190084. ** is a prefix query for which there is no prefix index, set iIdx to
  190085. ** greater than pConfig->nPrefix to indicate that the query will be
  190086. ** satisfied by scanning multiple terms in the main index.
  190087. **
  190088. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  190089. ** prefix-query. Instead of using a prefix-index (if one exists),
  190090. ** evaluate the prefix query using the main FTS index. This is used
  190091. ** for internal sanity checking by the integrity-check in debug
  190092. ** mode only. */
  190093. #ifdef SQLITE_DEBUG
  190094. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  190095. assert( flags & FTS5INDEX_QUERY_PREFIX );
  190096. iIdx = 1+pConfig->nPrefix;
  190097. }else
  190098. #endif
  190099. if( flags & FTS5INDEX_QUERY_PREFIX ){
  190100. int nChar = fts5IndexCharlen(pToken, nToken);
  190101. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  190102. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  190103. }
  190104. }
  190105. if( iIdx<=pConfig->nPrefix ){
  190106. /* Straight index lookup */
  190107. Fts5Structure *pStruct = fts5StructureRead(p);
  190108. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  190109. if( pStruct ){
  190110. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  190111. pColset, buf.p, nToken+1, -1, 0, &pRet
  190112. );
  190113. fts5StructureRelease(pStruct);
  190114. }
  190115. }else{
  190116. /* Scan multiple terms in the main index */
  190117. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  190118. buf.p[0] = FTS5_MAIN_PREFIX;
  190119. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  190120. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  190121. fts5IterSetOutputCb(&p->rc, pRet);
  190122. if( p->rc==SQLITE_OK ){
  190123. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  190124. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  190125. }
  190126. }
  190127. if( p->rc ){
  190128. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  190129. pRet = 0;
  190130. fts5CloseReader(p);
  190131. }
  190132. *ppIter = &pRet->base;
  190133. sqlite3Fts5BufferFree(&buf);
  190134. }
  190135. return fts5IndexReturn(p);
  190136. }
  190137. /*
  190138. ** Return true if the iterator passed as the only argument is at EOF.
  190139. */
  190140. /*
  190141. ** Move to the next matching rowid.
  190142. */
  190143. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  190144. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  190145. assert( pIter->pIndex->rc==SQLITE_OK );
  190146. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  190147. return fts5IndexReturn(pIter->pIndex);
  190148. }
  190149. /*
  190150. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  190151. */
  190152. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  190153. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  190154. Fts5Index *p = pIter->pIndex;
  190155. assert( pIter->pIndex->rc==SQLITE_OK );
  190156. fts5MultiIterNext(p, pIter, 0, 0);
  190157. if( p->rc==SQLITE_OK ){
  190158. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  190159. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  190160. fts5DataRelease(pSeg->pLeaf);
  190161. pSeg->pLeaf = 0;
  190162. pIter->base.bEof = 1;
  190163. }
  190164. }
  190165. return fts5IndexReturn(pIter->pIndex);
  190166. }
  190167. /*
  190168. ** Move to the next matching rowid that occurs at or after iMatch. The
  190169. ** definition of "at or after" depends on whether this iterator iterates
  190170. ** in ascending or descending rowid order.
  190171. */
  190172. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  190173. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  190174. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  190175. return fts5IndexReturn(pIter->pIndex);
  190176. }
  190177. /*
  190178. ** Return the current term.
  190179. */
  190180. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  190181. int n;
  190182. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  190183. *pn = n-1;
  190184. return &z[1];
  190185. }
  190186. /*
  190187. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  190188. */
  190189. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  190190. if( pIndexIter ){
  190191. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  190192. Fts5Index *pIndex = pIter->pIndex;
  190193. fts5MultiIterFree(pIter);
  190194. fts5CloseReader(pIndex);
  190195. }
  190196. }
  190197. /*
  190198. ** Read and decode the "averages" record from the database.
  190199. **
  190200. ** Parameter anSize must point to an array of size nCol, where nCol is
  190201. ** the number of user defined columns in the FTS table.
  190202. */
  190203. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  190204. int nCol = p->pConfig->nCol;
  190205. Fts5Data *pData;
  190206. *pnRow = 0;
  190207. memset(anSize, 0, sizeof(i64) * nCol);
  190208. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  190209. if( p->rc==SQLITE_OK && pData->nn ){
  190210. int i = 0;
  190211. int iCol;
  190212. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  190213. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  190214. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  190215. }
  190216. }
  190217. fts5DataRelease(pData);
  190218. return fts5IndexReturn(p);
  190219. }
  190220. /*
  190221. ** Replace the current "averages" record with the contents of the buffer
  190222. ** supplied as the second argument.
  190223. */
  190224. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  190225. assert( p->rc==SQLITE_OK );
  190226. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  190227. return fts5IndexReturn(p);
  190228. }
  190229. /*
  190230. ** Return the total number of blocks this module has read from the %_data
  190231. ** table since it was created.
  190232. */
  190233. static int sqlite3Fts5IndexReads(Fts5Index *p){
  190234. return p->nRead;
  190235. }
  190236. /*
  190237. ** Set the 32-bit cookie value stored at the start of all structure
  190238. ** records to the value passed as the second argument.
  190239. **
  190240. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  190241. ** occurs.
  190242. */
  190243. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  190244. int rc; /* Return code */
  190245. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  190246. u8 aCookie[4]; /* Binary representation of iNew */
  190247. sqlite3_blob *pBlob = 0;
  190248. assert( p->rc==SQLITE_OK );
  190249. sqlite3Fts5Put32(aCookie, iNew);
  190250. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  190251. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  190252. );
  190253. if( rc==SQLITE_OK ){
  190254. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  190255. rc = sqlite3_blob_close(pBlob);
  190256. }
  190257. return rc;
  190258. }
  190259. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  190260. Fts5Structure *pStruct;
  190261. pStruct = fts5StructureRead(p);
  190262. fts5StructureRelease(pStruct);
  190263. return fts5IndexReturn(p);
  190264. }
  190265. /*************************************************************************
  190266. **************************************************************************
  190267. ** Below this point is the implementation of the integrity-check
  190268. ** functionality.
  190269. */
  190270. /*
  190271. ** Return a simple checksum value based on the arguments.
  190272. */
  190273. static u64 sqlite3Fts5IndexEntryCksum(
  190274. i64 iRowid,
  190275. int iCol,
  190276. int iPos,
  190277. int iIdx,
  190278. const char *pTerm,
  190279. int nTerm
  190280. ){
  190281. int i;
  190282. u64 ret = iRowid;
  190283. ret += (ret<<3) + iCol;
  190284. ret += (ret<<3) + iPos;
  190285. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  190286. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  190287. return ret;
  190288. }
  190289. #ifdef SQLITE_DEBUG
  190290. /*
  190291. ** This function is purely an internal test. It does not contribute to
  190292. ** FTS functionality, or even the integrity-check, in any way.
  190293. **
  190294. ** Instead, it tests that the same set of pgno/rowid combinations are
  190295. ** visited regardless of whether the doclist-index identified by parameters
  190296. ** iSegid/iLeaf is iterated in forwards or reverse order.
  190297. */
  190298. static void fts5TestDlidxReverse(
  190299. Fts5Index *p,
  190300. int iSegid, /* Segment id to load from */
  190301. int iLeaf /* Load doclist-index for this leaf */
  190302. ){
  190303. Fts5DlidxIter *pDlidx = 0;
  190304. u64 cksum1 = 13;
  190305. u64 cksum2 = 13;
  190306. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  190307. fts5DlidxIterEof(p, pDlidx)==0;
  190308. fts5DlidxIterNext(p, pDlidx)
  190309. ){
  190310. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  190311. int pgno = fts5DlidxIterPgno(pDlidx);
  190312. assert( pgno>iLeaf );
  190313. cksum1 += iRowid + ((i64)pgno<<32);
  190314. }
  190315. fts5DlidxIterFree(pDlidx);
  190316. pDlidx = 0;
  190317. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  190318. fts5DlidxIterEof(p, pDlidx)==0;
  190319. fts5DlidxIterPrev(p, pDlidx)
  190320. ){
  190321. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  190322. int pgno = fts5DlidxIterPgno(pDlidx);
  190323. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  190324. cksum2 += iRowid + ((i64)pgno<<32);
  190325. }
  190326. fts5DlidxIterFree(pDlidx);
  190327. pDlidx = 0;
  190328. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  190329. }
  190330. static int fts5QueryCksum(
  190331. Fts5Index *p, /* Fts5 index object */
  190332. int iIdx,
  190333. const char *z, /* Index key to query for */
  190334. int n, /* Size of index key in bytes */
  190335. int flags, /* Flags for Fts5IndexQuery */
  190336. u64 *pCksum /* IN/OUT: Checksum value */
  190337. ){
  190338. int eDetail = p->pConfig->eDetail;
  190339. u64 cksum = *pCksum;
  190340. Fts5IndexIter *pIter = 0;
  190341. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  190342. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  190343. i64 rowid = pIter->iRowid;
  190344. if( eDetail==FTS5_DETAIL_NONE ){
  190345. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  190346. }else{
  190347. Fts5PoslistReader sReader;
  190348. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  190349. sReader.bEof==0;
  190350. sqlite3Fts5PoslistReaderNext(&sReader)
  190351. ){
  190352. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  190353. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  190354. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  190355. }
  190356. }
  190357. if( rc==SQLITE_OK ){
  190358. rc = sqlite3Fts5IterNext(pIter);
  190359. }
  190360. }
  190361. sqlite3Fts5IterClose(pIter);
  190362. *pCksum = cksum;
  190363. return rc;
  190364. }
  190365. /*
  190366. ** This function is also purely an internal test. It does not contribute to
  190367. ** FTS functionality, or even the integrity-check, in any way.
  190368. */
  190369. static void fts5TestTerm(
  190370. Fts5Index *p,
  190371. Fts5Buffer *pPrev, /* Previous term */
  190372. const char *z, int n, /* Possibly new term to test */
  190373. u64 expected,
  190374. u64 *pCksum
  190375. ){
  190376. int rc = p->rc;
  190377. if( pPrev->n==0 ){
  190378. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  190379. }else
  190380. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  190381. u64 cksum3 = *pCksum;
  190382. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  190383. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  190384. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  190385. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  190386. u64 ck1 = 0;
  190387. u64 ck2 = 0;
  190388. /* Check that the results returned for ASC and DESC queries are
  190389. ** the same. If not, call this corruption. */
  190390. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  190391. if( rc==SQLITE_OK ){
  190392. int f = flags|FTS5INDEX_QUERY_DESC;
  190393. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  190394. }
  190395. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  190396. /* If this is a prefix query, check that the results returned if the
  190397. ** the index is disabled are the same. In both ASC and DESC order.
  190398. **
  190399. ** This check may only be performed if the hash table is empty. This
  190400. ** is because the hash table only supports a single scan query at
  190401. ** a time, and the multi-iter loop from which this function is called
  190402. ** is already performing such a scan. */
  190403. if( p->nPendingData==0 ){
  190404. if( iIdx>0 && rc==SQLITE_OK ){
  190405. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  190406. ck2 = 0;
  190407. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  190408. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  190409. }
  190410. if( iIdx>0 && rc==SQLITE_OK ){
  190411. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  190412. ck2 = 0;
  190413. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  190414. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  190415. }
  190416. }
  190417. cksum3 ^= ck1;
  190418. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  190419. if( rc==SQLITE_OK && cksum3!=expected ){
  190420. rc = FTS5_CORRUPT;
  190421. }
  190422. *pCksum = cksum3;
  190423. }
  190424. p->rc = rc;
  190425. }
  190426. #else
  190427. # define fts5TestDlidxReverse(x,y,z)
  190428. # define fts5TestTerm(u,v,w,x,y,z)
  190429. #endif
  190430. /*
  190431. ** Check that:
  190432. **
  190433. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  190434. ** contain zero terms.
  190435. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  190436. ** contain zero rowids.
  190437. */
  190438. static void fts5IndexIntegrityCheckEmpty(
  190439. Fts5Index *p,
  190440. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  190441. int iFirst,
  190442. int iNoRowid,
  190443. int iLast
  190444. ){
  190445. int i;
  190446. /* Now check that the iter.nEmpty leaves following the current leaf
  190447. ** (a) exist and (b) contain no terms. */
  190448. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  190449. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  190450. if( pLeaf ){
  190451. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  190452. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  190453. }
  190454. fts5DataRelease(pLeaf);
  190455. }
  190456. }
  190457. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  190458. int iTermOff = 0;
  190459. int ii;
  190460. Fts5Buffer buf1 = {0,0,0};
  190461. Fts5Buffer buf2 = {0,0,0};
  190462. ii = pLeaf->szLeaf;
  190463. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  190464. int res;
  190465. int iOff;
  190466. int nIncr;
  190467. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  190468. iTermOff += nIncr;
  190469. iOff = iTermOff;
  190470. if( iOff>=pLeaf->szLeaf ){
  190471. p->rc = FTS5_CORRUPT;
  190472. }else if( iTermOff==nIncr ){
  190473. int nByte;
  190474. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  190475. if( (iOff+nByte)>pLeaf->szLeaf ){
  190476. p->rc = FTS5_CORRUPT;
  190477. }else{
  190478. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  190479. }
  190480. }else{
  190481. int nKeep, nByte;
  190482. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  190483. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  190484. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  190485. p->rc = FTS5_CORRUPT;
  190486. }else{
  190487. buf1.n = nKeep;
  190488. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  190489. }
  190490. if( p->rc==SQLITE_OK ){
  190491. res = fts5BufferCompare(&buf1, &buf2);
  190492. if( res<=0 ) p->rc = FTS5_CORRUPT;
  190493. }
  190494. }
  190495. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  190496. }
  190497. fts5BufferFree(&buf1);
  190498. fts5BufferFree(&buf2);
  190499. }
  190500. static void fts5IndexIntegrityCheckSegment(
  190501. Fts5Index *p, /* FTS5 backend object */
  190502. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  190503. ){
  190504. Fts5Config *pConfig = p->pConfig;
  190505. sqlite3_stmt *pStmt = 0;
  190506. int rc2;
  190507. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  190508. int iDlidxPrevLeaf = pSeg->pgnoLast;
  190509. if( pSeg->pgnoFirst==0 ) return;
  190510. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  190511. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  190512. pConfig->zDb, pConfig->zName, pSeg->iSegid
  190513. ));
  190514. /* Iterate through the b-tree hierarchy. */
  190515. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  190516. i64 iRow; /* Rowid for this leaf */
  190517. Fts5Data *pLeaf; /* Data for this leaf */
  190518. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  190519. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  190520. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  190521. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  190522. /* If the leaf in question has already been trimmed from the segment,
  190523. ** ignore this b-tree entry. Otherwise, load it into memory. */
  190524. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  190525. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  190526. pLeaf = fts5LeafRead(p, iRow);
  190527. if( pLeaf==0 ) break;
  190528. /* Check that the leaf contains at least one term, and that it is equal
  190529. ** to or larger than the split-key in zIdxTerm. Also check that if there
  190530. ** is also a rowid pointer within the leaf page header, it points to a
  190531. ** location before the term. */
  190532. if( pLeaf->nn<=pLeaf->szLeaf ){
  190533. p->rc = FTS5_CORRUPT;
  190534. }else{
  190535. int iOff; /* Offset of first term on leaf */
  190536. int iRowidOff; /* Offset of first rowid on leaf */
  190537. int nTerm; /* Size of term on leaf in bytes */
  190538. int res; /* Comparison of term and split-key */
  190539. iOff = fts5LeafFirstTermOff(pLeaf);
  190540. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  190541. if( iRowidOff>=iOff ){
  190542. p->rc = FTS5_CORRUPT;
  190543. }else{
  190544. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  190545. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  190546. if( res==0 ) res = nTerm - nIdxTerm;
  190547. if( res<0 ) p->rc = FTS5_CORRUPT;
  190548. }
  190549. fts5IntegrityCheckPgidx(p, pLeaf);
  190550. }
  190551. fts5DataRelease(pLeaf);
  190552. if( p->rc ) break;
  190553. /* Now check that the iter.nEmpty leaves following the current leaf
  190554. ** (a) exist and (b) contain no terms. */
  190555. fts5IndexIntegrityCheckEmpty(
  190556. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  190557. );
  190558. if( p->rc ) break;
  190559. /* If there is a doclist-index, check that it looks right. */
  190560. if( bIdxDlidx ){
  190561. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  190562. int iPrevLeaf = iIdxLeaf;
  190563. int iSegid = pSeg->iSegid;
  190564. int iPg = 0;
  190565. i64 iKey;
  190566. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  190567. fts5DlidxIterEof(p, pDlidx)==0;
  190568. fts5DlidxIterNext(p, pDlidx)
  190569. ){
  190570. /* Check any rowid-less pages that occur before the current leaf. */
  190571. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  190572. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  190573. pLeaf = fts5DataRead(p, iKey);
  190574. if( pLeaf ){
  190575. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  190576. fts5DataRelease(pLeaf);
  190577. }
  190578. }
  190579. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  190580. /* Check that the leaf page indicated by the iterator really does
  190581. ** contain the rowid suggested by the same. */
  190582. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  190583. pLeaf = fts5DataRead(p, iKey);
  190584. if( pLeaf ){
  190585. i64 iRowid;
  190586. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  190587. ASSERT_SZLEAF_OK(pLeaf);
  190588. if( iRowidOff>=pLeaf->szLeaf ){
  190589. p->rc = FTS5_CORRUPT;
  190590. }else{
  190591. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  190592. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  190593. }
  190594. fts5DataRelease(pLeaf);
  190595. }
  190596. }
  190597. iDlidxPrevLeaf = iPg;
  190598. fts5DlidxIterFree(pDlidx);
  190599. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  190600. }else{
  190601. iDlidxPrevLeaf = pSeg->pgnoLast;
  190602. /* TODO: Check there is no doclist index */
  190603. }
  190604. iIdxPrevLeaf = iIdxLeaf;
  190605. }
  190606. rc2 = sqlite3_finalize(pStmt);
  190607. if( p->rc==SQLITE_OK ) p->rc = rc2;
  190608. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  190609. #if 0
  190610. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  190611. p->rc = FTS5_CORRUPT;
  190612. }
  190613. #endif
  190614. }
  190615. /*
  190616. ** Run internal checks to ensure that the FTS index (a) is internally
  190617. ** consistent and (b) contains entries for which the XOR of the checksums
  190618. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  190619. **
  190620. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  190621. ** checksum does not match. Return SQLITE_OK if all checks pass without
  190622. ** error, or some other SQLite error code if another error (e.g. OOM)
  190623. ** occurs.
  190624. */
  190625. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  190626. int eDetail = p->pConfig->eDetail;
  190627. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  190628. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  190629. Fts5Iter *pIter; /* Used to iterate through entire index */
  190630. Fts5Structure *pStruct; /* Index structure */
  190631. #ifdef SQLITE_DEBUG
  190632. /* Used by extra internal tests only run if NDEBUG is not defined */
  190633. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  190634. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  190635. #endif
  190636. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  190637. /* Load the FTS index structure */
  190638. pStruct = fts5StructureRead(p);
  190639. /* Check that the internal nodes of each segment match the leaves */
  190640. if( pStruct ){
  190641. int iLvl, iSeg;
  190642. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  190643. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  190644. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  190645. fts5IndexIntegrityCheckSegment(p, pSeg);
  190646. }
  190647. }
  190648. }
  190649. /* The cksum argument passed to this function is a checksum calculated
  190650. ** based on all expected entries in the FTS index (including prefix index
  190651. ** entries). This block checks that a checksum calculated based on the
  190652. ** actual contents of FTS index is identical.
  190653. **
  190654. ** Two versions of the same checksum are calculated. The first (stack
  190655. ** variable cksum2) based on entries extracted from the full-text index
  190656. ** while doing a linear scan of each individual index in turn.
  190657. **
  190658. ** As each term visited by the linear scans, a separate query for the
  190659. ** same term is performed. cksum3 is calculated based on the entries
  190660. ** extracted by these queries.
  190661. */
  190662. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  190663. fts5MultiIterEof(p, pIter)==0;
  190664. fts5MultiIterNext(p, pIter, 0, 0)
  190665. ){
  190666. int n; /* Size of term in bytes */
  190667. i64 iPos = 0; /* Position read from poslist */
  190668. int iOff = 0; /* Offset within poslist */
  190669. i64 iRowid = fts5MultiIterRowid(pIter);
  190670. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  190671. /* If this is a new term, query for it. Update cksum3 with the results. */
  190672. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  190673. if( eDetail==FTS5_DETAIL_NONE ){
  190674. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  190675. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  190676. }
  190677. }else{
  190678. poslist.n = 0;
  190679. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  190680. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  190681. int iCol = FTS5_POS2COLUMN(iPos);
  190682. int iTokOff = FTS5_POS2OFFSET(iPos);
  190683. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  190684. }
  190685. }
  190686. }
  190687. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  190688. fts5MultiIterFree(pIter);
  190689. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  190690. fts5StructureRelease(pStruct);
  190691. #ifdef SQLITE_DEBUG
  190692. fts5BufferFree(&term);
  190693. #endif
  190694. fts5BufferFree(&poslist);
  190695. return fts5IndexReturn(p);
  190696. }
  190697. /*************************************************************************
  190698. **************************************************************************
  190699. ** Below this point is the implementation of the fts5_decode() scalar
  190700. ** function only.
  190701. */
  190702. /*
  190703. ** Decode a segment-data rowid from the %_data table. This function is
  190704. ** the opposite of macro FTS5_SEGMENT_ROWID().
  190705. */
  190706. static void fts5DecodeRowid(
  190707. i64 iRowid, /* Rowid from %_data table */
  190708. int *piSegid, /* OUT: Segment id */
  190709. int *pbDlidx, /* OUT: Dlidx flag */
  190710. int *piHeight, /* OUT: Height */
  190711. int *piPgno /* OUT: Page number */
  190712. ){
  190713. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  190714. iRowid >>= FTS5_DATA_PAGE_B;
  190715. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  190716. iRowid >>= FTS5_DATA_HEIGHT_B;
  190717. *pbDlidx = (int)(iRowid & 0x0001);
  190718. iRowid >>= FTS5_DATA_DLI_B;
  190719. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  190720. }
  190721. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  190722. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  190723. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  190724. if( iSegid==0 ){
  190725. if( iKey==FTS5_AVERAGES_ROWID ){
  190726. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  190727. }else{
  190728. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  190729. }
  190730. }
  190731. else{
  190732. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  190733. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  190734. );
  190735. }
  190736. }
  190737. static void fts5DebugStructure(
  190738. int *pRc, /* IN/OUT: error code */
  190739. Fts5Buffer *pBuf,
  190740. Fts5Structure *p
  190741. ){
  190742. int iLvl, iSeg; /* Iterate through levels, segments */
  190743. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  190744. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  190745. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  190746. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  190747. );
  190748. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  190749. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  190750. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  190751. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  190752. );
  190753. }
  190754. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  190755. }
  190756. }
  190757. /*
  190758. ** This is part of the fts5_decode() debugging aid.
  190759. **
  190760. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  190761. ** function appends a human-readable representation of the same object
  190762. ** to the buffer passed as the second argument.
  190763. */
  190764. static void fts5DecodeStructure(
  190765. int *pRc, /* IN/OUT: error code */
  190766. Fts5Buffer *pBuf,
  190767. const u8 *pBlob, int nBlob
  190768. ){
  190769. int rc; /* Return code */
  190770. Fts5Structure *p = 0; /* Decoded structure object */
  190771. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  190772. if( rc!=SQLITE_OK ){
  190773. *pRc = rc;
  190774. return;
  190775. }
  190776. fts5DebugStructure(pRc, pBuf, p);
  190777. fts5StructureRelease(p);
  190778. }
  190779. /*
  190780. ** This is part of the fts5_decode() debugging aid.
  190781. **
  190782. ** Arguments pBlob/nBlob contain an "averages" record. This function
  190783. ** appends a human-readable representation of record to the buffer passed
  190784. ** as the second argument.
  190785. */
  190786. static void fts5DecodeAverages(
  190787. int *pRc, /* IN/OUT: error code */
  190788. Fts5Buffer *pBuf,
  190789. const u8 *pBlob, int nBlob
  190790. ){
  190791. int i = 0;
  190792. const char *zSpace = "";
  190793. while( i<nBlob ){
  190794. u64 iVal;
  190795. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  190796. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  190797. zSpace = " ";
  190798. }
  190799. }
  190800. /*
  190801. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  190802. ** each varint and append its string representation to buffer pBuf. Return
  190803. ** after either the input buffer is exhausted or a 0 value is read.
  190804. **
  190805. ** The return value is the number of bytes read from the input buffer.
  190806. */
  190807. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  190808. int iOff = 0;
  190809. while( iOff<n ){
  190810. int iVal;
  190811. iOff += fts5GetVarint32(&a[iOff], iVal);
  190812. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  190813. }
  190814. return iOff;
  190815. }
  190816. /*
  190817. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  190818. ** may or may not finish within the buffer. This function appends a text
  190819. ** representation of the part of the doclist that is present to buffer
  190820. ** pBuf.
  190821. **
  190822. ** The return value is the number of bytes read from the input buffer.
  190823. */
  190824. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  190825. i64 iDocid = 0;
  190826. int iOff = 0;
  190827. if( n>0 ){
  190828. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  190829. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  190830. }
  190831. while( iOff<n ){
  190832. int nPos;
  190833. int bDel;
  190834. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  190835. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  190836. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  190837. if( iOff<n ){
  190838. i64 iDelta;
  190839. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  190840. iDocid += iDelta;
  190841. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  190842. }
  190843. }
  190844. return iOff;
  190845. }
  190846. /*
  190847. ** This function is part of the fts5_decode() debugging function. It is
  190848. ** only ever used with detail=none tables.
  190849. **
  190850. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  190851. ** tables. This function appends a human-readable version of that list to
  190852. ** buffer pBuf.
  190853. **
  190854. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  190855. ** no-op. If an OOM or other error occurs within this function, *pRc is
  190856. ** set to an SQLite error code before returning. The final state of buffer
  190857. ** pBuf is undefined in this case.
  190858. */
  190859. static void fts5DecodeRowidList(
  190860. int *pRc, /* IN/OUT: Error code */
  190861. Fts5Buffer *pBuf, /* Buffer to append text to */
  190862. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  190863. ){
  190864. int i = 0;
  190865. i64 iRowid = 0;
  190866. while( i<nData ){
  190867. const char *zApp = "";
  190868. u64 iVal;
  190869. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  190870. iRowid += iVal;
  190871. if( i<nData && pData[i]==0x00 ){
  190872. i++;
  190873. if( i<nData && pData[i]==0x00 ){
  190874. i++;
  190875. zApp = "+";
  190876. }else{
  190877. zApp = "*";
  190878. }
  190879. }
  190880. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  190881. }
  190882. }
  190883. /*
  190884. ** The implementation of user-defined scalar function fts5_decode().
  190885. */
  190886. static void fts5DecodeFunction(
  190887. sqlite3_context *pCtx, /* Function call context */
  190888. int nArg, /* Number of args (always 2) */
  190889. sqlite3_value **apVal /* Function arguments */
  190890. ){
  190891. i64 iRowid; /* Rowid for record being decoded */
  190892. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  190893. const u8 *aBlob; int n; /* Record to decode */
  190894. u8 *a = 0;
  190895. Fts5Buffer s; /* Build up text to return here */
  190896. int rc = SQLITE_OK; /* Return code */
  190897. int nSpace = 0;
  190898. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  190899. assert( nArg==2 );
  190900. UNUSED_PARAM(nArg);
  190901. memset(&s, 0, sizeof(Fts5Buffer));
  190902. iRowid = sqlite3_value_int64(apVal[0]);
  190903. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  190904. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  190905. ** buffer overreads even if the record is corrupt. */
  190906. n = sqlite3_value_bytes(apVal[1]);
  190907. aBlob = sqlite3_value_blob(apVal[1]);
  190908. nSpace = n + FTS5_DATA_ZERO_PADDING;
  190909. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  190910. if( a==0 ) goto decode_out;
  190911. memcpy(a, aBlob, n);
  190912. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  190913. fts5DebugRowid(&rc, &s, iRowid);
  190914. if( bDlidx ){
  190915. Fts5Data dlidx;
  190916. Fts5DlidxLvl lvl;
  190917. dlidx.p = a;
  190918. dlidx.nn = n;
  190919. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  190920. lvl.pData = &dlidx;
  190921. lvl.iLeafPgno = iPgno;
  190922. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  190923. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  190924. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  190925. );
  190926. }
  190927. }else if( iSegid==0 ){
  190928. if( iRowid==FTS5_AVERAGES_ROWID ){
  190929. fts5DecodeAverages(&rc, &s, a, n);
  190930. }else{
  190931. fts5DecodeStructure(&rc, &s, a, n);
  190932. }
  190933. }else if( eDetailNone ){
  190934. Fts5Buffer term; /* Current term read from page */
  190935. int szLeaf;
  190936. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  190937. int iTermOff;
  190938. int nKeep = 0;
  190939. int iOff;
  190940. memset(&term, 0, sizeof(Fts5Buffer));
  190941. /* Decode any entries that occur before the first term. */
  190942. if( szLeaf<n ){
  190943. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  190944. }else{
  190945. iTermOff = szLeaf;
  190946. }
  190947. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  190948. iOff = iTermOff;
  190949. while( iOff<szLeaf ){
  190950. int nAppend;
  190951. /* Read the term data for the next term*/
  190952. iOff += fts5GetVarint32(&a[iOff], nAppend);
  190953. term.n = nKeep;
  190954. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  190955. sqlite3Fts5BufferAppendPrintf(
  190956. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  190957. );
  190958. iOff += nAppend;
  190959. /* Figure out where the doclist for this term ends */
  190960. if( iPgidxOff<n ){
  190961. int nIncr;
  190962. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  190963. iTermOff += nIncr;
  190964. }else{
  190965. iTermOff = szLeaf;
  190966. }
  190967. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  190968. iOff = iTermOff;
  190969. if( iOff<szLeaf ){
  190970. iOff += fts5GetVarint32(&a[iOff], nKeep);
  190971. }
  190972. }
  190973. fts5BufferFree(&term);
  190974. }else{
  190975. Fts5Buffer term; /* Current term read from page */
  190976. int szLeaf; /* Offset of pgidx in a[] */
  190977. int iPgidxOff;
  190978. int iPgidxPrev = 0; /* Previous value read from pgidx */
  190979. int iTermOff = 0;
  190980. int iRowidOff = 0;
  190981. int iOff;
  190982. int nDoclist;
  190983. memset(&term, 0, sizeof(Fts5Buffer));
  190984. if( n<4 ){
  190985. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  190986. goto decode_out;
  190987. }else{
  190988. iRowidOff = fts5GetU16(&a[0]);
  190989. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  190990. if( iPgidxOff<n ){
  190991. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  190992. }
  190993. }
  190994. /* Decode the position list tail at the start of the page */
  190995. if( iRowidOff!=0 ){
  190996. iOff = iRowidOff;
  190997. }else if( iTermOff!=0 ){
  190998. iOff = iTermOff;
  190999. }else{
  191000. iOff = szLeaf;
  191001. }
  191002. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  191003. /* Decode any more doclist data that appears on the page before the
  191004. ** first term. */
  191005. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  191006. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  191007. while( iPgidxOff<n ){
  191008. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  191009. int nByte; /* Bytes of data */
  191010. int iEnd;
  191011. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  191012. iPgidxPrev += nByte;
  191013. iOff = iPgidxPrev;
  191014. if( iPgidxOff<n ){
  191015. fts5GetVarint32(&a[iPgidxOff], nByte);
  191016. iEnd = iPgidxPrev + nByte;
  191017. }else{
  191018. iEnd = szLeaf;
  191019. }
  191020. if( bFirst==0 ){
  191021. iOff += fts5GetVarint32(&a[iOff], nByte);
  191022. term.n = nByte;
  191023. }
  191024. iOff += fts5GetVarint32(&a[iOff], nByte);
  191025. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  191026. iOff += nByte;
  191027. sqlite3Fts5BufferAppendPrintf(
  191028. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  191029. );
  191030. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  191031. }
  191032. fts5BufferFree(&term);
  191033. }
  191034. decode_out:
  191035. sqlite3_free(a);
  191036. if( rc==SQLITE_OK ){
  191037. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  191038. }else{
  191039. sqlite3_result_error_code(pCtx, rc);
  191040. }
  191041. fts5BufferFree(&s);
  191042. }
  191043. /*
  191044. ** The implementation of user-defined scalar function fts5_rowid().
  191045. */
  191046. static void fts5RowidFunction(
  191047. sqlite3_context *pCtx, /* Function call context */
  191048. int nArg, /* Number of args (always 2) */
  191049. sqlite3_value **apVal /* Function arguments */
  191050. ){
  191051. const char *zArg;
  191052. if( nArg==0 ){
  191053. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  191054. }else{
  191055. zArg = (const char*)sqlite3_value_text(apVal[0]);
  191056. if( 0==sqlite3_stricmp(zArg, "segment") ){
  191057. i64 iRowid;
  191058. int segid, pgno;
  191059. if( nArg!=3 ){
  191060. sqlite3_result_error(pCtx,
  191061. "should be: fts5_rowid('segment', segid, pgno))", -1
  191062. );
  191063. }else{
  191064. segid = sqlite3_value_int(apVal[1]);
  191065. pgno = sqlite3_value_int(apVal[2]);
  191066. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  191067. sqlite3_result_int64(pCtx, iRowid);
  191068. }
  191069. }else{
  191070. sqlite3_result_error(pCtx,
  191071. "first arg to fts5_rowid() must be 'segment'" , -1
  191072. );
  191073. }
  191074. }
  191075. }
  191076. /*
  191077. ** This is called as part of registering the FTS5 module with database
  191078. ** connection db. It registers several user-defined scalar functions useful
  191079. ** with FTS5.
  191080. **
  191081. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  191082. ** SQLite error code is returned instead.
  191083. */
  191084. static int sqlite3Fts5IndexInit(sqlite3 *db){
  191085. int rc = sqlite3_create_function(
  191086. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  191087. );
  191088. if( rc==SQLITE_OK ){
  191089. rc = sqlite3_create_function(
  191090. db, "fts5_decode_none", 2,
  191091. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  191092. );
  191093. }
  191094. if( rc==SQLITE_OK ){
  191095. rc = sqlite3_create_function(
  191096. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  191097. );
  191098. }
  191099. return rc;
  191100. }
  191101. static int sqlite3Fts5IndexReset(Fts5Index *p){
  191102. assert( p->pStruct==0 || p->iStructVersion!=0 );
  191103. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  191104. fts5StructureInvalidate(p);
  191105. }
  191106. return fts5IndexReturn(p);
  191107. }
  191108. /*
  191109. ** 2014 Jun 09
  191110. **
  191111. ** The author disclaims copyright to this source code. In place of
  191112. ** a legal notice, here is a blessing:
  191113. **
  191114. ** May you do good and not evil.
  191115. ** May you find forgiveness for yourself and forgive others.
  191116. ** May you share freely, never taking more than you give.
  191117. **
  191118. ******************************************************************************
  191119. **
  191120. ** This is an SQLite module implementing full-text search.
  191121. */
  191122. /* #include "fts5Int.h" */
  191123. /*
  191124. ** This variable is set to false when running tests for which the on disk
  191125. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  191126. ** assert() conditions in the fts5 code are activated - conditions that are
  191127. ** only true if it is guaranteed that the fts5 database is not corrupt.
  191128. */
  191129. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  191130. typedef struct Fts5Auxdata Fts5Auxdata;
  191131. typedef struct Fts5Auxiliary Fts5Auxiliary;
  191132. typedef struct Fts5Cursor Fts5Cursor;
  191133. typedef struct Fts5Sorter Fts5Sorter;
  191134. typedef struct Fts5Table Fts5Table;
  191135. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  191136. /*
  191137. ** NOTES ON TRANSACTIONS:
  191138. **
  191139. ** SQLite invokes the following virtual table methods as transactions are
  191140. ** opened and closed by the user:
  191141. **
  191142. ** xBegin(): Start of a new transaction.
  191143. ** xSync(): Initial part of two-phase commit.
  191144. ** xCommit(): Final part of two-phase commit.
  191145. ** xRollback(): Rollback the transaction.
  191146. **
  191147. ** Anything that is required as part of a commit that may fail is performed
  191148. ** in the xSync() callback. Current versions of SQLite ignore any errors
  191149. ** returned by xCommit().
  191150. **
  191151. ** And as sub-transactions are opened/closed:
  191152. **
  191153. ** xSavepoint(int S): Open savepoint S.
  191154. ** xRelease(int S): Commit and close savepoint S.
  191155. ** xRollbackTo(int S): Rollback to start of savepoint S.
  191156. **
  191157. ** During a write-transaction the fts5_index.c module may cache some data
  191158. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  191159. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  191160. ** is called.
  191161. **
  191162. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  191163. ** structure is used to record the current transaction state. This information
  191164. ** is not required, but it is used in the assert() statements executed by
  191165. ** function fts5CheckTransactionState() (see below).
  191166. */
  191167. struct Fts5TransactionState {
  191168. int eState; /* 0==closed, 1==open, 2==synced */
  191169. int iSavepoint; /* Number of open savepoints (0 -> none) */
  191170. };
  191171. /*
  191172. ** A single object of this type is allocated when the FTS5 module is
  191173. ** registered with a database handle. It is used to store pointers to
  191174. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  191175. */
  191176. struct Fts5Global {
  191177. fts5_api api; /* User visible part of object (see fts5.h) */
  191178. sqlite3 *db; /* Associated database connection */
  191179. i64 iNextId; /* Used to allocate unique cursor ids */
  191180. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  191181. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  191182. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  191183. Fts5Cursor *pCsr; /* First in list of all open cursors */
  191184. };
  191185. /*
  191186. ** Each auxiliary function registered with the FTS5 module is represented
  191187. ** by an object of the following type. All such objects are stored as part
  191188. ** of the Fts5Global.pAux list.
  191189. */
  191190. struct Fts5Auxiliary {
  191191. Fts5Global *pGlobal; /* Global context for this function */
  191192. char *zFunc; /* Function name (nul-terminated) */
  191193. void *pUserData; /* User-data pointer */
  191194. fts5_extension_function xFunc; /* Callback function */
  191195. void (*xDestroy)(void*); /* Destructor function */
  191196. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  191197. };
  191198. /*
  191199. ** Each tokenizer module registered with the FTS5 module is represented
  191200. ** by an object of the following type. All such objects are stored as part
  191201. ** of the Fts5Global.pTok list.
  191202. */
  191203. struct Fts5TokenizerModule {
  191204. char *zName; /* Name of tokenizer */
  191205. void *pUserData; /* User pointer passed to xCreate() */
  191206. fts5_tokenizer x; /* Tokenizer functions */
  191207. void (*xDestroy)(void*); /* Destructor function */
  191208. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  191209. };
  191210. /*
  191211. ** Virtual-table object.
  191212. */
  191213. struct Fts5Table {
  191214. sqlite3_vtab base; /* Base class used by SQLite core */
  191215. Fts5Config *pConfig; /* Virtual table configuration */
  191216. Fts5Index *pIndex; /* Full-text index */
  191217. Fts5Storage *pStorage; /* Document store */
  191218. Fts5Global *pGlobal; /* Global (connection wide) data */
  191219. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  191220. #ifdef SQLITE_DEBUG
  191221. struct Fts5TransactionState ts;
  191222. #endif
  191223. };
  191224. struct Fts5MatchPhrase {
  191225. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  191226. int nTerm; /* Size of phrase in terms */
  191227. };
  191228. /*
  191229. ** pStmt:
  191230. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  191231. **
  191232. ** aIdx[]:
  191233. ** There is one entry in the aIdx[] array for each phrase in the query,
  191234. ** the value of which is the offset within aPoslist[] following the last
  191235. ** byte of the position list for the corresponding phrase.
  191236. */
  191237. struct Fts5Sorter {
  191238. sqlite3_stmt *pStmt;
  191239. i64 iRowid; /* Current rowid */
  191240. const u8 *aPoslist; /* Position lists for current row */
  191241. int nIdx; /* Number of entries in aIdx[] */
  191242. int aIdx[1]; /* Offsets into aPoslist for current row */
  191243. };
  191244. /*
  191245. ** Virtual-table cursor object.
  191246. **
  191247. ** iSpecial:
  191248. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  191249. ** then this variable contains the result of the query.
  191250. **
  191251. ** iFirstRowid, iLastRowid:
  191252. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  191253. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  191254. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  191255. ** WHERE clause in the user's query might have been:
  191256. **
  191257. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  191258. **
  191259. ** If the cursor iterates in descending order of rowid, iFirstRowid
  191260. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  191261. ** the lower.
  191262. */
  191263. struct Fts5Cursor {
  191264. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  191265. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  191266. int *aColumnSize; /* Values for xColumnSize() */
  191267. i64 iCsrId; /* Cursor id */
  191268. /* Zero from this point onwards on cursor reset */
  191269. int ePlan; /* FTS5_PLAN_XXX value */
  191270. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  191271. i64 iFirstRowid; /* Return no rowids earlier than this */
  191272. i64 iLastRowid; /* Return no rowids later than this */
  191273. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  191274. Fts5Expr *pExpr; /* Expression for MATCH queries */
  191275. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  191276. int csrflags; /* Mask of cursor flags (see below) */
  191277. i64 iSpecial; /* Result of special query */
  191278. /* "rank" function. Populated on demand from vtab.xColumn(). */
  191279. char *zRank; /* Custom rank function */
  191280. char *zRankArgs; /* Custom rank function args */
  191281. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  191282. int nRankArg; /* Number of trailing arguments for rank() */
  191283. sqlite3_value **apRankArg; /* Array of trailing arguments */
  191284. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  191285. /* Auxiliary data storage */
  191286. Fts5Auxiliary *pAux; /* Currently executing extension function */
  191287. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  191288. /* Cache used by auxiliary functions xInst() and xInstCount() */
  191289. Fts5PoslistReader *aInstIter; /* One for each phrase */
  191290. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  191291. int nInstCount; /* Number of phrase instances */
  191292. int *aInst; /* 3 integers per phrase instance */
  191293. };
  191294. /*
  191295. ** Bits that make up the "idxNum" parameter passed indirectly by
  191296. ** xBestIndex() to xFilter().
  191297. */
  191298. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  191299. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  191300. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  191301. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  191302. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  191303. #define FTS5_BI_ORDER_RANK 0x0020
  191304. #define FTS5_BI_ORDER_ROWID 0x0040
  191305. #define FTS5_BI_ORDER_DESC 0x0080
  191306. /*
  191307. ** Values for Fts5Cursor.csrflags
  191308. */
  191309. #define FTS5CSR_EOF 0x01
  191310. #define FTS5CSR_REQUIRE_CONTENT 0x02
  191311. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  191312. #define FTS5CSR_REQUIRE_INST 0x08
  191313. #define FTS5CSR_FREE_ZRANK 0x10
  191314. #define FTS5CSR_REQUIRE_RESEEK 0x20
  191315. #define FTS5CSR_REQUIRE_POSLIST 0x40
  191316. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  191317. #define BitFlagTest(x,y) (((x) & (y))!=0)
  191318. /*
  191319. ** Macros to Set(), Clear() and Test() cursor flags.
  191320. */
  191321. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  191322. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  191323. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  191324. struct Fts5Auxdata {
  191325. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  191326. void *pPtr; /* Pointer value */
  191327. void(*xDelete)(void*); /* Destructor */
  191328. Fts5Auxdata *pNext; /* Next object in linked list */
  191329. };
  191330. #ifdef SQLITE_DEBUG
  191331. #define FTS5_BEGIN 1
  191332. #define FTS5_SYNC 2
  191333. #define FTS5_COMMIT 3
  191334. #define FTS5_ROLLBACK 4
  191335. #define FTS5_SAVEPOINT 5
  191336. #define FTS5_RELEASE 6
  191337. #define FTS5_ROLLBACKTO 7
  191338. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  191339. switch( op ){
  191340. case FTS5_BEGIN:
  191341. assert( p->ts.eState==0 );
  191342. p->ts.eState = 1;
  191343. p->ts.iSavepoint = -1;
  191344. break;
  191345. case FTS5_SYNC:
  191346. assert( p->ts.eState==1 );
  191347. p->ts.eState = 2;
  191348. break;
  191349. case FTS5_COMMIT:
  191350. assert( p->ts.eState==2 );
  191351. p->ts.eState = 0;
  191352. break;
  191353. case FTS5_ROLLBACK:
  191354. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  191355. p->ts.eState = 0;
  191356. break;
  191357. case FTS5_SAVEPOINT:
  191358. assert( p->ts.eState==1 );
  191359. assert( iSavepoint>=0 );
  191360. assert( iSavepoint>p->ts.iSavepoint );
  191361. p->ts.iSavepoint = iSavepoint;
  191362. break;
  191363. case FTS5_RELEASE:
  191364. assert( p->ts.eState==1 );
  191365. assert( iSavepoint>=0 );
  191366. assert( iSavepoint<=p->ts.iSavepoint );
  191367. p->ts.iSavepoint = iSavepoint-1;
  191368. break;
  191369. case FTS5_ROLLBACKTO:
  191370. assert( p->ts.eState==1 );
  191371. assert( iSavepoint>=0 );
  191372. assert( iSavepoint<=p->ts.iSavepoint );
  191373. p->ts.iSavepoint = iSavepoint;
  191374. break;
  191375. }
  191376. }
  191377. #else
  191378. # define fts5CheckTransactionState(x,y,z)
  191379. #endif
  191380. /*
  191381. ** Return true if pTab is a contentless table.
  191382. */
  191383. static int fts5IsContentless(Fts5Table *pTab){
  191384. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  191385. }
  191386. /*
  191387. ** Delete a virtual table handle allocated by fts5InitVtab().
  191388. */
  191389. static void fts5FreeVtab(Fts5Table *pTab){
  191390. if( pTab ){
  191391. sqlite3Fts5IndexClose(pTab->pIndex);
  191392. sqlite3Fts5StorageClose(pTab->pStorage);
  191393. sqlite3Fts5ConfigFree(pTab->pConfig);
  191394. sqlite3_free(pTab);
  191395. }
  191396. }
  191397. /*
  191398. ** The xDisconnect() virtual table method.
  191399. */
  191400. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  191401. fts5FreeVtab((Fts5Table*)pVtab);
  191402. return SQLITE_OK;
  191403. }
  191404. /*
  191405. ** The xDestroy() virtual table method.
  191406. */
  191407. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  191408. Fts5Table *pTab = (Fts5Table*)pVtab;
  191409. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  191410. if( rc==SQLITE_OK ){
  191411. fts5FreeVtab((Fts5Table*)pVtab);
  191412. }
  191413. return rc;
  191414. }
  191415. /*
  191416. ** This function is the implementation of both the xConnect and xCreate
  191417. ** methods of the FTS3 virtual table.
  191418. **
  191419. ** The argv[] array contains the following:
  191420. **
  191421. ** argv[0] -> module name ("fts5")
  191422. ** argv[1] -> database name
  191423. ** argv[2] -> table name
  191424. ** argv[...] -> "column name" and other module argument fields.
  191425. */
  191426. static int fts5InitVtab(
  191427. int bCreate, /* True for xCreate, false for xConnect */
  191428. sqlite3 *db, /* The SQLite database connection */
  191429. void *pAux, /* Hash table containing tokenizers */
  191430. int argc, /* Number of elements in argv array */
  191431. const char * const *argv, /* xCreate/xConnect argument array */
  191432. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  191433. char **pzErr /* Write any error message here */
  191434. ){
  191435. Fts5Global *pGlobal = (Fts5Global*)pAux;
  191436. const char **azConfig = (const char**)argv;
  191437. int rc = SQLITE_OK; /* Return code */
  191438. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  191439. Fts5Table *pTab = 0; /* New virtual table object */
  191440. /* Allocate the new vtab object and parse the configuration */
  191441. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  191442. if( rc==SQLITE_OK ){
  191443. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  191444. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  191445. }
  191446. if( rc==SQLITE_OK ){
  191447. pTab->pConfig = pConfig;
  191448. pTab->pGlobal = pGlobal;
  191449. }
  191450. /* Open the index sub-system */
  191451. if( rc==SQLITE_OK ){
  191452. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  191453. }
  191454. /* Open the storage sub-system */
  191455. if( rc==SQLITE_OK ){
  191456. rc = sqlite3Fts5StorageOpen(
  191457. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  191458. );
  191459. }
  191460. /* Call sqlite3_declare_vtab() */
  191461. if( rc==SQLITE_OK ){
  191462. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  191463. }
  191464. /* Load the initial configuration */
  191465. if( rc==SQLITE_OK ){
  191466. assert( pConfig->pzErrmsg==0 );
  191467. pConfig->pzErrmsg = pzErr;
  191468. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  191469. sqlite3Fts5IndexRollback(pTab->pIndex);
  191470. pConfig->pzErrmsg = 0;
  191471. }
  191472. if( rc!=SQLITE_OK ){
  191473. fts5FreeVtab(pTab);
  191474. pTab = 0;
  191475. }else if( bCreate ){
  191476. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  191477. }
  191478. *ppVTab = (sqlite3_vtab*)pTab;
  191479. return rc;
  191480. }
  191481. /*
  191482. ** The xConnect() and xCreate() methods for the virtual table. All the
  191483. ** work is done in function fts5InitVtab().
  191484. */
  191485. static int fts5ConnectMethod(
  191486. sqlite3 *db, /* Database connection */
  191487. void *pAux, /* Pointer to tokenizer hash table */
  191488. int argc, /* Number of elements in argv array */
  191489. const char * const *argv, /* xCreate/xConnect argument array */
  191490. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  191491. char **pzErr /* OUT: sqlite3_malloc'd error message */
  191492. ){
  191493. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  191494. }
  191495. static int fts5CreateMethod(
  191496. sqlite3 *db, /* Database connection */
  191497. void *pAux, /* Pointer to tokenizer hash table */
  191498. int argc, /* Number of elements in argv array */
  191499. const char * const *argv, /* xCreate/xConnect argument array */
  191500. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  191501. char **pzErr /* OUT: sqlite3_malloc'd error message */
  191502. ){
  191503. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  191504. }
  191505. /*
  191506. ** The different query plans.
  191507. */
  191508. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  191509. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  191510. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  191511. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  191512. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  191513. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  191514. /*
  191515. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  191516. ** extension is currently being used by a version of SQLite too old to
  191517. ** support index-info flags. In that case this function is a no-op.
  191518. */
  191519. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  191520. #if SQLITE_VERSION_NUMBER>=3008012
  191521. #ifndef SQLITE_CORE
  191522. if( sqlite3_libversion_number()>=3008012 )
  191523. #endif
  191524. {
  191525. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  191526. }
  191527. #endif
  191528. }
  191529. /*
  191530. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  191531. ** WHERE constraint, it searches for the following:
  191532. **
  191533. ** 1. A MATCH constraint against the special column.
  191534. ** 2. A MATCH constraint against the "rank" column.
  191535. ** 3. An == constraint against the rowid column.
  191536. ** 4. A < or <= constraint against the rowid column.
  191537. ** 5. A > or >= constraint against the rowid column.
  191538. **
  191539. ** Within the ORDER BY, either:
  191540. **
  191541. ** 5. ORDER BY rank [ASC|DESC]
  191542. ** 6. ORDER BY rowid [ASC|DESC]
  191543. **
  191544. ** Costs are assigned as follows:
  191545. **
  191546. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  191547. ** cost is unconditionally set to 1e50 (a really big number).
  191548. **
  191549. ** a) If a MATCH operator is present, the cost depends on the other
  191550. ** constraints also present. As follows:
  191551. **
  191552. ** * No other constraints: cost=1000.0
  191553. ** * One rowid range constraint: cost=750.0
  191554. ** * Both rowid range constraints: cost=500.0
  191555. ** * An == rowid constraint: cost=100.0
  191556. **
  191557. ** b) Otherwise, if there is no MATCH:
  191558. **
  191559. ** * No other constraints: cost=1000000.0
  191560. ** * One rowid range constraint: cost=750000.0
  191561. ** * Both rowid range constraints: cost=250000.0
  191562. ** * An == rowid constraint: cost=10.0
  191563. **
  191564. ** Costs are not modified by the ORDER BY clause.
  191565. */
  191566. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  191567. Fts5Table *pTab = (Fts5Table*)pVTab;
  191568. Fts5Config *pConfig = pTab->pConfig;
  191569. const int nCol = pConfig->nCol;
  191570. int idxFlags = 0; /* Parameter passed through to xFilter() */
  191571. int bHasMatch;
  191572. int iNext;
  191573. int i;
  191574. struct Constraint {
  191575. int op; /* Mask against sqlite3_index_constraint.op */
  191576. int fts5op; /* FTS5 mask for idxFlags */
  191577. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  191578. int omit; /* True to omit this if found */
  191579. int iConsIndex; /* Index in pInfo->aConstraint[] */
  191580. } aConstraint[] = {
  191581. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  191582. FTS5_BI_MATCH, 1, 1, -1},
  191583. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  191584. FTS5_BI_RANK, 2, 1, -1},
  191585. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  191586. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  191587. FTS5_BI_ROWID_LE, 0, 0, -1},
  191588. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  191589. FTS5_BI_ROWID_GE, 0, 0, -1},
  191590. };
  191591. int aColMap[3];
  191592. aColMap[0] = -1;
  191593. aColMap[1] = nCol;
  191594. aColMap[2] = nCol+1;
  191595. assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
  191596. assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
  191597. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  191598. assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
  191599. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  191600. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  191601. for(i=0; i<pInfo->nConstraint; i++){
  191602. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  191603. int iCol = p->iColumn;
  191604. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  191605. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  191606. ){
  191607. /* A MATCH operator or equivalent */
  191608. if( p->usable ){
  191609. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  191610. aConstraint[0].iConsIndex = i;
  191611. }else{
  191612. /* As there exists an unusable MATCH constraint this is an
  191613. ** unusable plan. Set a prohibitively high cost. */
  191614. pInfo->estimatedCost = 1e50;
  191615. return SQLITE_OK;
  191616. }
  191617. }else if( p->op<=SQLITE_INDEX_CONSTRAINT_MATCH ){
  191618. int j;
  191619. for(j=1; j<ArraySize(aConstraint); j++){
  191620. struct Constraint *pC = &aConstraint[j];
  191621. if( iCol==aColMap[pC->iCol] && (p->op & pC->op) && p->usable ){
  191622. pC->iConsIndex = i;
  191623. idxFlags |= pC->fts5op;
  191624. }
  191625. }
  191626. }
  191627. }
  191628. /* Set idxFlags flags for the ORDER BY clause */
  191629. if( pInfo->nOrderBy==1 ){
  191630. int iSort = pInfo->aOrderBy[0].iColumn;
  191631. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  191632. idxFlags |= FTS5_BI_ORDER_RANK;
  191633. }else if( iSort==-1 ){
  191634. idxFlags |= FTS5_BI_ORDER_ROWID;
  191635. }
  191636. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  191637. pInfo->orderByConsumed = 1;
  191638. if( pInfo->aOrderBy[0].desc ){
  191639. idxFlags |= FTS5_BI_ORDER_DESC;
  191640. }
  191641. }
  191642. }
  191643. /* Calculate the estimated cost based on the flags set in idxFlags. */
  191644. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  191645. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  191646. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  191647. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  191648. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  191649. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  191650. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  191651. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  191652. }else{
  191653. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  191654. }
  191655. /* Assign argvIndex values to each constraint in use. */
  191656. iNext = 1;
  191657. for(i=0; i<ArraySize(aConstraint); i++){
  191658. struct Constraint *pC = &aConstraint[i];
  191659. if( pC->iConsIndex>=0 ){
  191660. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  191661. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  191662. }
  191663. }
  191664. pInfo->idxNum = idxFlags;
  191665. return SQLITE_OK;
  191666. }
  191667. static int fts5NewTransaction(Fts5Table *pTab){
  191668. Fts5Cursor *pCsr;
  191669. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  191670. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  191671. }
  191672. return sqlite3Fts5StorageReset(pTab->pStorage);
  191673. }
  191674. /*
  191675. ** Implementation of xOpen method.
  191676. */
  191677. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  191678. Fts5Table *pTab = (Fts5Table*)pVTab;
  191679. Fts5Config *pConfig = pTab->pConfig;
  191680. Fts5Cursor *pCsr = 0; /* New cursor object */
  191681. int nByte; /* Bytes of space to allocate */
  191682. int rc; /* Return code */
  191683. rc = fts5NewTransaction(pTab);
  191684. if( rc==SQLITE_OK ){
  191685. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  191686. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  191687. if( pCsr ){
  191688. Fts5Global *pGlobal = pTab->pGlobal;
  191689. memset(pCsr, 0, nByte);
  191690. pCsr->aColumnSize = (int*)&pCsr[1];
  191691. pCsr->pNext = pGlobal->pCsr;
  191692. pGlobal->pCsr = pCsr;
  191693. pCsr->iCsrId = ++pGlobal->iNextId;
  191694. }else{
  191695. rc = SQLITE_NOMEM;
  191696. }
  191697. }
  191698. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  191699. return rc;
  191700. }
  191701. static int fts5StmtType(Fts5Cursor *pCsr){
  191702. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  191703. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  191704. }
  191705. return FTS5_STMT_LOOKUP;
  191706. }
  191707. /*
  191708. ** This function is called after the cursor passed as the only argument
  191709. ** is moved to point at a different row. It clears all cached data
  191710. ** specific to the previous row stored by the cursor object.
  191711. */
  191712. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  191713. CsrFlagSet(pCsr,
  191714. FTS5CSR_REQUIRE_CONTENT
  191715. | FTS5CSR_REQUIRE_DOCSIZE
  191716. | FTS5CSR_REQUIRE_INST
  191717. | FTS5CSR_REQUIRE_POSLIST
  191718. );
  191719. }
  191720. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  191721. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  191722. Fts5Auxdata *pData;
  191723. Fts5Auxdata *pNext;
  191724. sqlite3_free(pCsr->aInstIter);
  191725. sqlite3_free(pCsr->aInst);
  191726. if( pCsr->pStmt ){
  191727. int eStmt = fts5StmtType(pCsr);
  191728. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  191729. }
  191730. if( pCsr->pSorter ){
  191731. Fts5Sorter *pSorter = pCsr->pSorter;
  191732. sqlite3_finalize(pSorter->pStmt);
  191733. sqlite3_free(pSorter);
  191734. }
  191735. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  191736. sqlite3Fts5ExprFree(pCsr->pExpr);
  191737. }
  191738. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  191739. pNext = pData->pNext;
  191740. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  191741. sqlite3_free(pData);
  191742. }
  191743. sqlite3_finalize(pCsr->pRankArgStmt);
  191744. sqlite3_free(pCsr->apRankArg);
  191745. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  191746. sqlite3_free(pCsr->zRank);
  191747. sqlite3_free(pCsr->zRankArgs);
  191748. }
  191749. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  191750. }
  191751. /*
  191752. ** Close the cursor. For additional information see the documentation
  191753. ** on the xClose method of the virtual table interface.
  191754. */
  191755. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  191756. if( pCursor ){
  191757. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  191758. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  191759. Fts5Cursor **pp;
  191760. fts5FreeCursorComponents(pCsr);
  191761. /* Remove the cursor from the Fts5Global.pCsr list */
  191762. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  191763. *pp = pCsr->pNext;
  191764. sqlite3_free(pCsr);
  191765. }
  191766. return SQLITE_OK;
  191767. }
  191768. static int fts5SorterNext(Fts5Cursor *pCsr){
  191769. Fts5Sorter *pSorter = pCsr->pSorter;
  191770. int rc;
  191771. rc = sqlite3_step(pSorter->pStmt);
  191772. if( rc==SQLITE_DONE ){
  191773. rc = SQLITE_OK;
  191774. CsrFlagSet(pCsr, FTS5CSR_EOF);
  191775. }else if( rc==SQLITE_ROW ){
  191776. const u8 *a;
  191777. const u8 *aBlob;
  191778. int nBlob;
  191779. int i;
  191780. int iOff = 0;
  191781. rc = SQLITE_OK;
  191782. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  191783. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  191784. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  191785. /* nBlob==0 in detail=none mode. */
  191786. if( nBlob>0 ){
  191787. for(i=0; i<(pSorter->nIdx-1); i++){
  191788. int iVal;
  191789. a += fts5GetVarint32(a, iVal);
  191790. iOff += iVal;
  191791. pSorter->aIdx[i] = iOff;
  191792. }
  191793. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  191794. pSorter->aPoslist = a;
  191795. }
  191796. fts5CsrNewrow(pCsr);
  191797. }
  191798. return rc;
  191799. }
  191800. /*
  191801. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  191802. ** open on table pTab.
  191803. */
  191804. static void fts5TripCursors(Fts5Table *pTab){
  191805. Fts5Cursor *pCsr;
  191806. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  191807. if( pCsr->ePlan==FTS5_PLAN_MATCH
  191808. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  191809. ){
  191810. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  191811. }
  191812. }
  191813. }
  191814. /*
  191815. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  191816. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  191817. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  191818. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  191819. **
  191820. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  191821. ** to 1 before returning. Otherwise, leave it unchanged.
  191822. **
  191823. ** Return SQLITE_OK if successful or if no reseek was required, or an
  191824. ** error code if an error occurred.
  191825. */
  191826. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  191827. int rc = SQLITE_OK;
  191828. assert( *pbSkip==0 );
  191829. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  191830. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  191831. int bDesc = pCsr->bDesc;
  191832. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  191833. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  191834. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  191835. *pbSkip = 1;
  191836. }
  191837. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  191838. fts5CsrNewrow(pCsr);
  191839. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  191840. CsrFlagSet(pCsr, FTS5CSR_EOF);
  191841. *pbSkip = 1;
  191842. }
  191843. }
  191844. return rc;
  191845. }
  191846. /*
  191847. ** Advance the cursor to the next row in the table that matches the
  191848. ** search criteria.
  191849. **
  191850. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  191851. ** even if we reach end-of-file. The fts5EofMethod() will be called
  191852. ** subsequently to determine whether or not an EOF was hit.
  191853. */
  191854. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  191855. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  191856. int rc;
  191857. assert( (pCsr->ePlan<3)==
  191858. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  191859. );
  191860. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  191861. if( pCsr->ePlan<3 ){
  191862. int bSkip = 0;
  191863. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  191864. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  191865. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  191866. fts5CsrNewrow(pCsr);
  191867. }else{
  191868. switch( pCsr->ePlan ){
  191869. case FTS5_PLAN_SPECIAL: {
  191870. CsrFlagSet(pCsr, FTS5CSR_EOF);
  191871. rc = SQLITE_OK;
  191872. break;
  191873. }
  191874. case FTS5_PLAN_SORTED_MATCH: {
  191875. rc = fts5SorterNext(pCsr);
  191876. break;
  191877. }
  191878. default:
  191879. rc = sqlite3_step(pCsr->pStmt);
  191880. if( rc!=SQLITE_ROW ){
  191881. CsrFlagSet(pCsr, FTS5CSR_EOF);
  191882. rc = sqlite3_reset(pCsr->pStmt);
  191883. }else{
  191884. rc = SQLITE_OK;
  191885. }
  191886. break;
  191887. }
  191888. }
  191889. return rc;
  191890. }
  191891. static int fts5PrepareStatement(
  191892. sqlite3_stmt **ppStmt,
  191893. Fts5Config *pConfig,
  191894. const char *zFmt,
  191895. ...
  191896. ){
  191897. sqlite3_stmt *pRet = 0;
  191898. int rc;
  191899. char *zSql;
  191900. va_list ap;
  191901. va_start(ap, zFmt);
  191902. zSql = sqlite3_vmprintf(zFmt, ap);
  191903. if( zSql==0 ){
  191904. rc = SQLITE_NOMEM;
  191905. }else{
  191906. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  191907. SQLITE_PREPARE_PERSISTENT, &pRet, 0);
  191908. if( rc!=SQLITE_OK ){
  191909. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  191910. }
  191911. sqlite3_free(zSql);
  191912. }
  191913. va_end(ap);
  191914. *ppStmt = pRet;
  191915. return rc;
  191916. }
  191917. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  191918. Fts5Config *pConfig = pTab->pConfig;
  191919. Fts5Sorter *pSorter;
  191920. int nPhrase;
  191921. int nByte;
  191922. int rc;
  191923. const char *zRank = pCsr->zRank;
  191924. const char *zRankArgs = pCsr->zRankArgs;
  191925. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  191926. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  191927. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  191928. if( pSorter==0 ) return SQLITE_NOMEM;
  191929. memset(pSorter, 0, nByte);
  191930. pSorter->nIdx = nPhrase;
  191931. /* TODO: It would be better to have some system for reusing statement
  191932. ** handles here, rather than preparing a new one for each query. But that
  191933. ** is not possible as SQLite reference counts the virtual table objects.
  191934. ** And since the statement required here reads from this very virtual
  191935. ** table, saving it creates a circular reference.
  191936. **
  191937. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  191938. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  191939. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  191940. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  191941. (zRankArgs ? ", " : ""),
  191942. (zRankArgs ? zRankArgs : ""),
  191943. bDesc ? "DESC" : "ASC"
  191944. );
  191945. pCsr->pSorter = pSorter;
  191946. if( rc==SQLITE_OK ){
  191947. assert( pTab->pSortCsr==0 );
  191948. pTab->pSortCsr = pCsr;
  191949. rc = fts5SorterNext(pCsr);
  191950. pTab->pSortCsr = 0;
  191951. }
  191952. if( rc!=SQLITE_OK ){
  191953. sqlite3_finalize(pSorter->pStmt);
  191954. sqlite3_free(pSorter);
  191955. pCsr->pSorter = 0;
  191956. }
  191957. return rc;
  191958. }
  191959. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  191960. int rc;
  191961. Fts5Expr *pExpr = pCsr->pExpr;
  191962. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  191963. if( sqlite3Fts5ExprEof(pExpr) ){
  191964. CsrFlagSet(pCsr, FTS5CSR_EOF);
  191965. }
  191966. fts5CsrNewrow(pCsr);
  191967. return rc;
  191968. }
  191969. /*
  191970. ** Process a "special" query. A special query is identified as one with a
  191971. ** MATCH expression that begins with a '*' character. The remainder of
  191972. ** the text passed to the MATCH operator are used as the special query
  191973. ** parameters.
  191974. */
  191975. static int fts5SpecialMatch(
  191976. Fts5Table *pTab,
  191977. Fts5Cursor *pCsr,
  191978. const char *zQuery
  191979. ){
  191980. int rc = SQLITE_OK; /* Return code */
  191981. const char *z = zQuery; /* Special query text */
  191982. int n; /* Number of bytes in text at z */
  191983. while( z[0]==' ' ) z++;
  191984. for(n=0; z[n] && z[n]!=' '; n++);
  191985. assert( pTab->base.zErrMsg==0 );
  191986. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  191987. if( 0==sqlite3_strnicmp("reads", z, n) ){
  191988. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  191989. }
  191990. else if( 0==sqlite3_strnicmp("id", z, n) ){
  191991. pCsr->iSpecial = pCsr->iCsrId;
  191992. }
  191993. else{
  191994. /* An unrecognized directive. Return an error message. */
  191995. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  191996. rc = SQLITE_ERROR;
  191997. }
  191998. return rc;
  191999. }
  192000. /*
  192001. ** Search for an auxiliary function named zName that can be used with table
  192002. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  192003. ** structure. Otherwise, if no such function exists, return NULL.
  192004. */
  192005. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  192006. Fts5Auxiliary *pAux;
  192007. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  192008. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  192009. }
  192010. /* No function of the specified name was found. Return 0. */
  192011. return 0;
  192012. }
  192013. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  192014. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  192015. Fts5Config *pConfig = pTab->pConfig;
  192016. int rc = SQLITE_OK;
  192017. Fts5Auxiliary *pAux = 0;
  192018. const char *zRank = pCsr->zRank;
  192019. const char *zRankArgs = pCsr->zRankArgs;
  192020. if( zRankArgs ){
  192021. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  192022. if( zSql ){
  192023. sqlite3_stmt *pStmt = 0;
  192024. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  192025. SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
  192026. sqlite3_free(zSql);
  192027. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  192028. if( rc==SQLITE_OK ){
  192029. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  192030. int nByte;
  192031. pCsr->nRankArg = sqlite3_column_count(pStmt);
  192032. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  192033. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  192034. if( rc==SQLITE_OK ){
  192035. int i;
  192036. for(i=0; i<pCsr->nRankArg; i++){
  192037. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  192038. }
  192039. }
  192040. pCsr->pRankArgStmt = pStmt;
  192041. }else{
  192042. rc = sqlite3_finalize(pStmt);
  192043. assert( rc!=SQLITE_OK );
  192044. }
  192045. }
  192046. }
  192047. }
  192048. if( rc==SQLITE_OK ){
  192049. pAux = fts5FindAuxiliary(pTab, zRank);
  192050. if( pAux==0 ){
  192051. assert( pTab->base.zErrMsg==0 );
  192052. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  192053. rc = SQLITE_ERROR;
  192054. }
  192055. }
  192056. pCsr->pRank = pAux;
  192057. return rc;
  192058. }
  192059. static int fts5CursorParseRank(
  192060. Fts5Config *pConfig,
  192061. Fts5Cursor *pCsr,
  192062. sqlite3_value *pRank
  192063. ){
  192064. int rc = SQLITE_OK;
  192065. if( pRank ){
  192066. const char *z = (const char*)sqlite3_value_text(pRank);
  192067. char *zRank = 0;
  192068. char *zRankArgs = 0;
  192069. if( z==0 ){
  192070. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  192071. }else{
  192072. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  192073. }
  192074. if( rc==SQLITE_OK ){
  192075. pCsr->zRank = zRank;
  192076. pCsr->zRankArgs = zRankArgs;
  192077. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  192078. }else if( rc==SQLITE_ERROR ){
  192079. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  192080. "parse error in rank function: %s", z
  192081. );
  192082. }
  192083. }else{
  192084. if( pConfig->zRank ){
  192085. pCsr->zRank = (char*)pConfig->zRank;
  192086. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  192087. }else{
  192088. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  192089. pCsr->zRankArgs = 0;
  192090. }
  192091. }
  192092. return rc;
  192093. }
  192094. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  192095. if( pVal ){
  192096. int eType = sqlite3_value_numeric_type(pVal);
  192097. if( eType==SQLITE_INTEGER ){
  192098. return sqlite3_value_int64(pVal);
  192099. }
  192100. }
  192101. return iDefault;
  192102. }
  192103. /*
  192104. ** This is the xFilter interface for the virtual table. See
  192105. ** the virtual table xFilter method documentation for additional
  192106. ** information.
  192107. **
  192108. ** There are three possible query strategies:
  192109. **
  192110. ** 1. Full-text search using a MATCH operator.
  192111. ** 2. A by-rowid lookup.
  192112. ** 3. A full-table scan.
  192113. */
  192114. static int fts5FilterMethod(
  192115. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  192116. int idxNum, /* Strategy index */
  192117. const char *zUnused, /* Unused */
  192118. int nVal, /* Number of elements in apVal */
  192119. sqlite3_value **apVal /* Arguments for the indexing scheme */
  192120. ){
  192121. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  192122. Fts5Config *pConfig = pTab->pConfig;
  192123. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  192124. int rc = SQLITE_OK; /* Error code */
  192125. int iVal = 0; /* Counter for apVal[] */
  192126. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  192127. int bOrderByRank; /* True if ORDER BY rank */
  192128. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  192129. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  192130. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  192131. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  192132. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  192133. int iCol; /* Column on LHS of MATCH operator */
  192134. char **pzErrmsg = pConfig->pzErrmsg;
  192135. UNUSED_PARAM(zUnused);
  192136. UNUSED_PARAM(nVal);
  192137. if( pCsr->ePlan ){
  192138. fts5FreeCursorComponents(pCsr);
  192139. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  192140. }
  192141. assert( pCsr->pStmt==0 );
  192142. assert( pCsr->pExpr==0 );
  192143. assert( pCsr->csrflags==0 );
  192144. assert( pCsr->pRank==0 );
  192145. assert( pCsr->zRank==0 );
  192146. assert( pCsr->zRankArgs==0 );
  192147. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  192148. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  192149. /* Decode the arguments passed through to this function.
  192150. **
  192151. ** Note: The following set of if(...) statements must be in the same
  192152. ** order as the corresponding entries in the struct at the top of
  192153. ** fts5BestIndexMethod(). */
  192154. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  192155. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  192156. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  192157. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  192158. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  192159. iCol = (idxNum>>16);
  192160. assert( iCol>=0 && iCol<=pConfig->nCol );
  192161. assert( iVal==nVal );
  192162. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  192163. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  192164. /* Set the cursor upper and lower rowid limits. Only some strategies
  192165. ** actually use them. This is ok, as the xBestIndex() method leaves the
  192166. ** sqlite3_index_constraint.omit flag clear for range constraints
  192167. ** on the rowid field. */
  192168. if( pRowidEq ){
  192169. pRowidLe = pRowidGe = pRowidEq;
  192170. }
  192171. if( bDesc ){
  192172. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  192173. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  192174. }else{
  192175. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  192176. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  192177. }
  192178. if( pTab->pSortCsr ){
  192179. /* If pSortCsr is non-NULL, then this call is being made as part of
  192180. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  192181. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  192182. ** return results to the user for this query. The current cursor
  192183. ** (pCursor) is used to execute the query issued by function
  192184. ** fts5CursorFirstSorted() above. */
  192185. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  192186. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  192187. assert( pCsr->iLastRowid==LARGEST_INT64 );
  192188. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  192189. pCsr->ePlan = FTS5_PLAN_SOURCE;
  192190. pCsr->pExpr = pTab->pSortCsr->pExpr;
  192191. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  192192. }else if( pMatch ){
  192193. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  192194. if( zExpr==0 ) zExpr = "";
  192195. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  192196. if( rc==SQLITE_OK ){
  192197. if( zExpr[0]=='*' ){
  192198. /* The user has issued a query of the form "MATCH '*...'". This
  192199. ** indicates that the MATCH expression is not a full text query,
  192200. ** but a request for an internal parameter. */
  192201. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  192202. }else{
  192203. char **pzErr = &pTab->base.zErrMsg;
  192204. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  192205. if( rc==SQLITE_OK ){
  192206. if( bOrderByRank ){
  192207. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  192208. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  192209. }else{
  192210. pCsr->ePlan = FTS5_PLAN_MATCH;
  192211. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  192212. }
  192213. }
  192214. }
  192215. }
  192216. }else if( pConfig->zContent==0 ){
  192217. *pConfig->pzErrmsg = sqlite3_mprintf(
  192218. "%s: table does not support scanning", pConfig->zName
  192219. );
  192220. rc = SQLITE_ERROR;
  192221. }else{
  192222. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  192223. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  192224. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  192225. rc = sqlite3Fts5StorageStmt(
  192226. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  192227. );
  192228. if( rc==SQLITE_OK ){
  192229. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  192230. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  192231. }else{
  192232. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  192233. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  192234. }
  192235. rc = fts5NextMethod(pCursor);
  192236. }
  192237. }
  192238. pConfig->pzErrmsg = pzErrmsg;
  192239. return rc;
  192240. }
  192241. /*
  192242. ** This is the xEof method of the virtual table. SQLite calls this
  192243. ** routine to find out if it has reached the end of a result set.
  192244. */
  192245. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  192246. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  192247. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  192248. }
  192249. /*
  192250. ** Return the rowid that the cursor currently points to.
  192251. */
  192252. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  192253. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  192254. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  192255. || pCsr->ePlan==FTS5_PLAN_SOURCE
  192256. );
  192257. if( pCsr->pSorter ){
  192258. return pCsr->pSorter->iRowid;
  192259. }else{
  192260. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  192261. }
  192262. }
  192263. /*
  192264. ** This is the xRowid method. The SQLite core calls this routine to
  192265. ** retrieve the rowid for the current row of the result set. fts5
  192266. ** exposes %_content.rowid as the rowid for the virtual table. The
  192267. ** rowid should be written to *pRowid.
  192268. */
  192269. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  192270. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  192271. int ePlan = pCsr->ePlan;
  192272. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  192273. switch( ePlan ){
  192274. case FTS5_PLAN_SPECIAL:
  192275. *pRowid = 0;
  192276. break;
  192277. case FTS5_PLAN_SOURCE:
  192278. case FTS5_PLAN_MATCH:
  192279. case FTS5_PLAN_SORTED_MATCH:
  192280. *pRowid = fts5CursorRowid(pCsr);
  192281. break;
  192282. default:
  192283. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  192284. break;
  192285. }
  192286. return SQLITE_OK;
  192287. }
  192288. /*
  192289. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  192290. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  192291. **
  192292. ** If argument bErrormsg is true and an error occurs, an error message may
  192293. ** be left in sqlite3_vtab.zErrMsg.
  192294. */
  192295. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  192296. int rc = SQLITE_OK;
  192297. /* If the cursor does not yet have a statement handle, obtain one now. */
  192298. if( pCsr->pStmt==0 ){
  192299. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  192300. int eStmt = fts5StmtType(pCsr);
  192301. rc = sqlite3Fts5StorageStmt(
  192302. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  192303. );
  192304. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  192305. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  192306. }
  192307. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  192308. assert( pCsr->pExpr );
  192309. sqlite3_reset(pCsr->pStmt);
  192310. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  192311. rc = sqlite3_step(pCsr->pStmt);
  192312. if( rc==SQLITE_ROW ){
  192313. rc = SQLITE_OK;
  192314. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  192315. }else{
  192316. rc = sqlite3_reset(pCsr->pStmt);
  192317. if( rc==SQLITE_OK ){
  192318. rc = FTS5_CORRUPT;
  192319. }
  192320. }
  192321. }
  192322. return rc;
  192323. }
  192324. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  192325. va_list ap; /* ... printf arguments */
  192326. va_start(ap, zFormat);
  192327. assert( p->base.zErrMsg==0 );
  192328. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  192329. va_end(ap);
  192330. }
  192331. /*
  192332. ** This function is called to handle an FTS INSERT command. In other words,
  192333. ** an INSERT statement of the form:
  192334. **
  192335. ** INSERT INTO fts(fts) VALUES($pCmd)
  192336. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  192337. **
  192338. ** Argument pVal is the value assigned to column "fts" by the INSERT
  192339. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  192340. ** error code if an error occurs.
  192341. **
  192342. ** The commands implemented by this function are documented in the "Special
  192343. ** INSERT Directives" section of the documentation. It should be updated if
  192344. ** more commands are added to this function.
  192345. */
  192346. static int fts5SpecialInsert(
  192347. Fts5Table *pTab, /* Fts5 table object */
  192348. const char *zCmd, /* Text inserted into table-name column */
  192349. sqlite3_value *pVal /* Value inserted into rank column */
  192350. ){
  192351. Fts5Config *pConfig = pTab->pConfig;
  192352. int rc = SQLITE_OK;
  192353. int bError = 0;
  192354. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  192355. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  192356. fts5SetVtabError(pTab,
  192357. "'delete-all' may only be used with a "
  192358. "contentless or external content fts5 table"
  192359. );
  192360. rc = SQLITE_ERROR;
  192361. }else{
  192362. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  192363. }
  192364. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  192365. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  192366. fts5SetVtabError(pTab,
  192367. "'rebuild' may not be used with a contentless fts5 table"
  192368. );
  192369. rc = SQLITE_ERROR;
  192370. }else{
  192371. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  192372. }
  192373. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  192374. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  192375. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  192376. int nMerge = sqlite3_value_int(pVal);
  192377. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  192378. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  192379. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  192380. #ifdef SQLITE_DEBUG
  192381. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  192382. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  192383. #endif
  192384. }else{
  192385. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  192386. if( rc==SQLITE_OK ){
  192387. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  192388. }
  192389. if( rc==SQLITE_OK ){
  192390. if( bError ){
  192391. rc = SQLITE_ERROR;
  192392. }else{
  192393. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  192394. }
  192395. }
  192396. }
  192397. return rc;
  192398. }
  192399. static int fts5SpecialDelete(
  192400. Fts5Table *pTab,
  192401. sqlite3_value **apVal
  192402. ){
  192403. int rc = SQLITE_OK;
  192404. int eType1 = sqlite3_value_type(apVal[1]);
  192405. if( eType1==SQLITE_INTEGER ){
  192406. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  192407. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  192408. }
  192409. return rc;
  192410. }
  192411. static void fts5StorageInsert(
  192412. int *pRc,
  192413. Fts5Table *pTab,
  192414. sqlite3_value **apVal,
  192415. i64 *piRowid
  192416. ){
  192417. int rc = *pRc;
  192418. if( rc==SQLITE_OK ){
  192419. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  192420. }
  192421. if( rc==SQLITE_OK ){
  192422. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  192423. }
  192424. *pRc = rc;
  192425. }
  192426. /*
  192427. ** This function is the implementation of the xUpdate callback used by
  192428. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  192429. ** inserted, updated or deleted.
  192430. **
  192431. ** A delete specifies a single argument - the rowid of the row to remove.
  192432. **
  192433. ** Update and insert operations pass:
  192434. **
  192435. ** 1. The "old" rowid, or NULL.
  192436. ** 2. The "new" rowid.
  192437. ** 3. Values for each of the nCol matchable columns.
  192438. ** 4. Values for the two hidden columns (<tablename> and "rank").
  192439. */
  192440. static int fts5UpdateMethod(
  192441. sqlite3_vtab *pVtab, /* Virtual table handle */
  192442. int nArg, /* Size of argument array */
  192443. sqlite3_value **apVal, /* Array of arguments */
  192444. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  192445. ){
  192446. Fts5Table *pTab = (Fts5Table*)pVtab;
  192447. Fts5Config *pConfig = pTab->pConfig;
  192448. int eType0; /* value_type() of apVal[0] */
  192449. int rc = SQLITE_OK; /* Return code */
  192450. /* A transaction must be open when this is called. */
  192451. assert( pTab->ts.eState==1 );
  192452. assert( pVtab->zErrMsg==0 );
  192453. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  192454. assert( nArg==1
  192455. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  192456. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  192457. );
  192458. assert( pTab->pConfig->pzErrmsg==0 );
  192459. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  192460. /* Put any active cursors into REQUIRE_SEEK state. */
  192461. fts5TripCursors(pTab);
  192462. eType0 = sqlite3_value_type(apVal[0]);
  192463. if( eType0==SQLITE_NULL
  192464. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  192465. ){
  192466. /* A "special" INSERT op. These are handled separately. */
  192467. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  192468. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  192469. && 0==sqlite3_stricmp("delete", z)
  192470. ){
  192471. rc = fts5SpecialDelete(pTab, apVal);
  192472. }else{
  192473. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  192474. }
  192475. }else{
  192476. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  192477. ** any conflict on the rowid value must be detected before any
  192478. ** modifications are made to the database file. There are 4 cases:
  192479. **
  192480. ** 1) DELETE
  192481. ** 2) UPDATE (rowid not modified)
  192482. ** 3) UPDATE (rowid modified)
  192483. ** 4) INSERT
  192484. **
  192485. ** Cases 3 and 4 may violate the rowid constraint.
  192486. */
  192487. int eConflict = SQLITE_ABORT;
  192488. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  192489. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  192490. }
  192491. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  192492. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  192493. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  192494. ** This is not suported. */
  192495. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  192496. pTab->base.zErrMsg = sqlite3_mprintf(
  192497. "cannot %s contentless fts5 table: %s",
  192498. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  192499. );
  192500. rc = SQLITE_ERROR;
  192501. }
  192502. /* DELETE */
  192503. else if( nArg==1 ){
  192504. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  192505. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  192506. }
  192507. /* INSERT */
  192508. else if( eType0!=SQLITE_INTEGER ){
  192509. /* If this is a REPLACE, first remove the current entry (if any) */
  192510. if( eConflict==SQLITE_REPLACE
  192511. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  192512. ){
  192513. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  192514. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  192515. }
  192516. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  192517. }
  192518. /* UPDATE */
  192519. else{
  192520. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  192521. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  192522. if( iOld!=iNew ){
  192523. if( eConflict==SQLITE_REPLACE ){
  192524. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  192525. if( rc==SQLITE_OK ){
  192526. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  192527. }
  192528. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  192529. }else{
  192530. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  192531. if( rc==SQLITE_OK ){
  192532. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  192533. }
  192534. if( rc==SQLITE_OK ){
  192535. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  192536. }
  192537. }
  192538. }else{
  192539. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  192540. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  192541. }
  192542. }
  192543. }
  192544. pTab->pConfig->pzErrmsg = 0;
  192545. return rc;
  192546. }
  192547. /*
  192548. ** Implementation of xSync() method.
  192549. */
  192550. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  192551. int rc;
  192552. Fts5Table *pTab = (Fts5Table*)pVtab;
  192553. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  192554. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  192555. fts5TripCursors(pTab);
  192556. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  192557. pTab->pConfig->pzErrmsg = 0;
  192558. return rc;
  192559. }
  192560. /*
  192561. ** Implementation of xBegin() method.
  192562. */
  192563. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  192564. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  192565. fts5NewTransaction((Fts5Table*)pVtab);
  192566. return SQLITE_OK;
  192567. }
  192568. /*
  192569. ** Implementation of xCommit() method. This is a no-op. The contents of
  192570. ** the pending-terms hash-table have already been flushed into the database
  192571. ** by fts5SyncMethod().
  192572. */
  192573. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  192574. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  192575. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  192576. return SQLITE_OK;
  192577. }
  192578. /*
  192579. ** Implementation of xRollback(). Discard the contents of the pending-terms
  192580. ** hash-table. Any changes made to the database are reverted by SQLite.
  192581. */
  192582. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  192583. int rc;
  192584. Fts5Table *pTab = (Fts5Table*)pVtab;
  192585. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  192586. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  192587. return rc;
  192588. }
  192589. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  192590. static void *fts5ApiUserData(Fts5Context *pCtx){
  192591. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192592. return pCsr->pAux->pUserData;
  192593. }
  192594. static int fts5ApiColumnCount(Fts5Context *pCtx){
  192595. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192596. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  192597. }
  192598. static int fts5ApiColumnTotalSize(
  192599. Fts5Context *pCtx,
  192600. int iCol,
  192601. sqlite3_int64 *pnToken
  192602. ){
  192603. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192604. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  192605. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  192606. }
  192607. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  192608. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192609. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  192610. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  192611. }
  192612. static int fts5ApiTokenize(
  192613. Fts5Context *pCtx,
  192614. const char *pText, int nText,
  192615. void *pUserData,
  192616. int (*xToken)(void*, int, const char*, int, int, int)
  192617. ){
  192618. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192619. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  192620. return sqlite3Fts5Tokenize(
  192621. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  192622. );
  192623. }
  192624. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  192625. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192626. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  192627. }
  192628. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  192629. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192630. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  192631. }
  192632. static int fts5ApiColumnText(
  192633. Fts5Context *pCtx,
  192634. int iCol,
  192635. const char **pz,
  192636. int *pn
  192637. ){
  192638. int rc = SQLITE_OK;
  192639. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192640. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  192641. *pz = 0;
  192642. *pn = 0;
  192643. }else{
  192644. rc = fts5SeekCursor(pCsr, 0);
  192645. if( rc==SQLITE_OK ){
  192646. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  192647. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  192648. }
  192649. }
  192650. return rc;
  192651. }
  192652. static int fts5CsrPoslist(
  192653. Fts5Cursor *pCsr,
  192654. int iPhrase,
  192655. const u8 **pa,
  192656. int *pn
  192657. ){
  192658. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  192659. int rc = SQLITE_OK;
  192660. int bLive = (pCsr->pSorter==0);
  192661. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  192662. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  192663. Fts5PoslistPopulator *aPopulator;
  192664. int i;
  192665. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  192666. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  192667. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  192668. int n; const char *z;
  192669. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  192670. if( rc==SQLITE_OK ){
  192671. rc = sqlite3Fts5ExprPopulatePoslists(
  192672. pConfig, pCsr->pExpr, aPopulator, i, z, n
  192673. );
  192674. }
  192675. }
  192676. sqlite3_free(aPopulator);
  192677. if( pCsr->pSorter ){
  192678. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  192679. }
  192680. }
  192681. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  192682. }
  192683. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  192684. Fts5Sorter *pSorter = pCsr->pSorter;
  192685. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  192686. *pn = pSorter->aIdx[iPhrase] - i1;
  192687. *pa = &pSorter->aPoslist[i1];
  192688. }else{
  192689. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  192690. }
  192691. return rc;
  192692. }
  192693. /*
  192694. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  192695. ** correctly for the current view. Return SQLITE_OK if successful, or an
  192696. ** SQLite error code otherwise.
  192697. */
  192698. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  192699. int rc = SQLITE_OK;
  192700. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  192701. int nIter; /* Number of iterators/phrases */
  192702. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  192703. if( pCsr->aInstIter==0 ){
  192704. int nByte = sizeof(Fts5PoslistReader) * nIter;
  192705. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  192706. }
  192707. aIter = pCsr->aInstIter;
  192708. if( aIter ){
  192709. int nInst = 0; /* Number instances seen so far */
  192710. int i;
  192711. /* Initialize all iterators */
  192712. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  192713. const u8 *a;
  192714. int n;
  192715. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  192716. if( rc==SQLITE_OK ){
  192717. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  192718. }
  192719. }
  192720. if( rc==SQLITE_OK ){
  192721. while( 1 ){
  192722. int *aInst;
  192723. int iBest = -1;
  192724. for(i=0; i<nIter; i++){
  192725. if( (aIter[i].bEof==0)
  192726. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  192727. ){
  192728. iBest = i;
  192729. }
  192730. }
  192731. if( iBest<0 ) break;
  192732. nInst++;
  192733. if( nInst>=pCsr->nInstAlloc ){
  192734. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  192735. aInst = (int*)sqlite3_realloc(
  192736. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  192737. );
  192738. if( aInst ){
  192739. pCsr->aInst = aInst;
  192740. }else{
  192741. rc = SQLITE_NOMEM;
  192742. break;
  192743. }
  192744. }
  192745. aInst = &pCsr->aInst[3 * (nInst-1)];
  192746. aInst[0] = iBest;
  192747. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  192748. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  192749. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  192750. }
  192751. }
  192752. pCsr->nInstCount = nInst;
  192753. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  192754. }
  192755. return rc;
  192756. }
  192757. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  192758. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192759. int rc = SQLITE_OK;
  192760. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  192761. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  192762. *pnInst = pCsr->nInstCount;
  192763. }
  192764. return rc;
  192765. }
  192766. static int fts5ApiInst(
  192767. Fts5Context *pCtx,
  192768. int iIdx,
  192769. int *piPhrase,
  192770. int *piCol,
  192771. int *piOff
  192772. ){
  192773. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192774. int rc = SQLITE_OK;
  192775. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  192776. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  192777. ){
  192778. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  192779. rc = SQLITE_RANGE;
  192780. #if 0
  192781. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  192782. *piPhrase = pCsr->aInst[iIdx*3];
  192783. *piCol = pCsr->aInst[iIdx*3 + 2];
  192784. *piOff = -1;
  192785. #endif
  192786. }else{
  192787. *piPhrase = pCsr->aInst[iIdx*3];
  192788. *piCol = pCsr->aInst[iIdx*3 + 1];
  192789. *piOff = pCsr->aInst[iIdx*3 + 2];
  192790. }
  192791. }
  192792. return rc;
  192793. }
  192794. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  192795. return fts5CursorRowid((Fts5Cursor*)pCtx);
  192796. }
  192797. static int fts5ColumnSizeCb(
  192798. void *pContext, /* Pointer to int */
  192799. int tflags,
  192800. const char *pUnused, /* Buffer containing token */
  192801. int nUnused, /* Size of token in bytes */
  192802. int iUnused1, /* Start offset of token */
  192803. int iUnused2 /* End offset of token */
  192804. ){
  192805. int *pCnt = (int*)pContext;
  192806. UNUSED_PARAM2(pUnused, nUnused);
  192807. UNUSED_PARAM2(iUnused1, iUnused2);
  192808. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  192809. (*pCnt)++;
  192810. }
  192811. return SQLITE_OK;
  192812. }
  192813. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  192814. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192815. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  192816. Fts5Config *pConfig = pTab->pConfig;
  192817. int rc = SQLITE_OK;
  192818. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  192819. if( pConfig->bColumnsize ){
  192820. i64 iRowid = fts5CursorRowid(pCsr);
  192821. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  192822. }else if( pConfig->zContent==0 ){
  192823. int i;
  192824. for(i=0; i<pConfig->nCol; i++){
  192825. if( pConfig->abUnindexed[i]==0 ){
  192826. pCsr->aColumnSize[i] = -1;
  192827. }
  192828. }
  192829. }else{
  192830. int i;
  192831. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  192832. if( pConfig->abUnindexed[i]==0 ){
  192833. const char *z; int n;
  192834. void *p = (void*)(&pCsr->aColumnSize[i]);
  192835. pCsr->aColumnSize[i] = 0;
  192836. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  192837. if( rc==SQLITE_OK ){
  192838. rc = sqlite3Fts5Tokenize(
  192839. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  192840. );
  192841. }
  192842. }
  192843. }
  192844. }
  192845. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  192846. }
  192847. if( iCol<0 ){
  192848. int i;
  192849. *pnToken = 0;
  192850. for(i=0; i<pConfig->nCol; i++){
  192851. *pnToken += pCsr->aColumnSize[i];
  192852. }
  192853. }else if( iCol<pConfig->nCol ){
  192854. *pnToken = pCsr->aColumnSize[iCol];
  192855. }else{
  192856. *pnToken = 0;
  192857. rc = SQLITE_RANGE;
  192858. }
  192859. return rc;
  192860. }
  192861. /*
  192862. ** Implementation of the xSetAuxdata() method.
  192863. */
  192864. static int fts5ApiSetAuxdata(
  192865. Fts5Context *pCtx, /* Fts5 context */
  192866. void *pPtr, /* Pointer to save as auxdata */
  192867. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  192868. ){
  192869. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192870. Fts5Auxdata *pData;
  192871. /* Search through the cursors list of Fts5Auxdata objects for one that
  192872. ** corresponds to the currently executing auxiliary function. */
  192873. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  192874. if( pData->pAux==pCsr->pAux ) break;
  192875. }
  192876. if( pData ){
  192877. if( pData->xDelete ){
  192878. pData->xDelete(pData->pPtr);
  192879. }
  192880. }else{
  192881. int rc = SQLITE_OK;
  192882. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  192883. if( pData==0 ){
  192884. if( xDelete ) xDelete(pPtr);
  192885. return rc;
  192886. }
  192887. pData->pAux = pCsr->pAux;
  192888. pData->pNext = pCsr->pAuxdata;
  192889. pCsr->pAuxdata = pData;
  192890. }
  192891. pData->xDelete = xDelete;
  192892. pData->pPtr = pPtr;
  192893. return SQLITE_OK;
  192894. }
  192895. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  192896. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192897. Fts5Auxdata *pData;
  192898. void *pRet = 0;
  192899. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  192900. if( pData->pAux==pCsr->pAux ) break;
  192901. }
  192902. if( pData ){
  192903. pRet = pData->pPtr;
  192904. if( bClear ){
  192905. pData->pPtr = 0;
  192906. pData->xDelete = 0;
  192907. }
  192908. }
  192909. return pRet;
  192910. }
  192911. static void fts5ApiPhraseNext(
  192912. Fts5Context *pUnused,
  192913. Fts5PhraseIter *pIter,
  192914. int *piCol, int *piOff
  192915. ){
  192916. UNUSED_PARAM(pUnused);
  192917. if( pIter->a>=pIter->b ){
  192918. *piCol = -1;
  192919. *piOff = -1;
  192920. }else{
  192921. int iVal;
  192922. pIter->a += fts5GetVarint32(pIter->a, iVal);
  192923. if( iVal==1 ){
  192924. pIter->a += fts5GetVarint32(pIter->a, iVal);
  192925. *piCol = iVal;
  192926. *piOff = 0;
  192927. pIter->a += fts5GetVarint32(pIter->a, iVal);
  192928. }
  192929. *piOff += (iVal-2);
  192930. }
  192931. }
  192932. static int fts5ApiPhraseFirst(
  192933. Fts5Context *pCtx,
  192934. int iPhrase,
  192935. Fts5PhraseIter *pIter,
  192936. int *piCol, int *piOff
  192937. ){
  192938. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192939. int n;
  192940. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  192941. if( rc==SQLITE_OK ){
  192942. pIter->b = &pIter->a[n];
  192943. *piCol = 0;
  192944. *piOff = 0;
  192945. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  192946. }
  192947. return rc;
  192948. }
  192949. static void fts5ApiPhraseNextColumn(
  192950. Fts5Context *pCtx,
  192951. Fts5PhraseIter *pIter,
  192952. int *piCol
  192953. ){
  192954. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192955. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  192956. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  192957. if( pIter->a>=pIter->b ){
  192958. *piCol = -1;
  192959. }else{
  192960. int iIncr;
  192961. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  192962. *piCol += (iIncr-2);
  192963. }
  192964. }else{
  192965. while( 1 ){
  192966. int dummy;
  192967. if( pIter->a>=pIter->b ){
  192968. *piCol = -1;
  192969. return;
  192970. }
  192971. if( pIter->a[0]==0x01 ) break;
  192972. pIter->a += fts5GetVarint32(pIter->a, dummy);
  192973. }
  192974. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  192975. }
  192976. }
  192977. static int fts5ApiPhraseFirstColumn(
  192978. Fts5Context *pCtx,
  192979. int iPhrase,
  192980. Fts5PhraseIter *pIter,
  192981. int *piCol
  192982. ){
  192983. int rc = SQLITE_OK;
  192984. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  192985. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  192986. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  192987. Fts5Sorter *pSorter = pCsr->pSorter;
  192988. int n;
  192989. if( pSorter ){
  192990. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  192991. n = pSorter->aIdx[iPhrase] - i1;
  192992. pIter->a = &pSorter->aPoslist[i1];
  192993. }else{
  192994. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  192995. }
  192996. if( rc==SQLITE_OK ){
  192997. pIter->b = &pIter->a[n];
  192998. *piCol = 0;
  192999. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  193000. }
  193001. }else{
  193002. int n;
  193003. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  193004. if( rc==SQLITE_OK ){
  193005. pIter->b = &pIter->a[n];
  193006. if( n<=0 ){
  193007. *piCol = -1;
  193008. }else if( pIter->a[0]==0x01 ){
  193009. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  193010. }else{
  193011. *piCol = 0;
  193012. }
  193013. }
  193014. }
  193015. return rc;
  193016. }
  193017. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  193018. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  193019. );
  193020. static const Fts5ExtensionApi sFts5Api = {
  193021. 2, /* iVersion */
  193022. fts5ApiUserData,
  193023. fts5ApiColumnCount,
  193024. fts5ApiRowCount,
  193025. fts5ApiColumnTotalSize,
  193026. fts5ApiTokenize,
  193027. fts5ApiPhraseCount,
  193028. fts5ApiPhraseSize,
  193029. fts5ApiInstCount,
  193030. fts5ApiInst,
  193031. fts5ApiRowid,
  193032. fts5ApiColumnText,
  193033. fts5ApiColumnSize,
  193034. fts5ApiQueryPhrase,
  193035. fts5ApiSetAuxdata,
  193036. fts5ApiGetAuxdata,
  193037. fts5ApiPhraseFirst,
  193038. fts5ApiPhraseNext,
  193039. fts5ApiPhraseFirstColumn,
  193040. fts5ApiPhraseNextColumn,
  193041. };
  193042. /*
  193043. ** Implementation of API function xQueryPhrase().
  193044. */
  193045. static int fts5ApiQueryPhrase(
  193046. Fts5Context *pCtx,
  193047. int iPhrase,
  193048. void *pUserData,
  193049. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  193050. ){
  193051. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  193052. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  193053. int rc;
  193054. Fts5Cursor *pNew = 0;
  193055. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  193056. if( rc==SQLITE_OK ){
  193057. pNew->ePlan = FTS5_PLAN_MATCH;
  193058. pNew->iFirstRowid = SMALLEST_INT64;
  193059. pNew->iLastRowid = LARGEST_INT64;
  193060. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  193061. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  193062. }
  193063. if( rc==SQLITE_OK ){
  193064. for(rc = fts5CursorFirst(pTab, pNew, 0);
  193065. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  193066. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  193067. ){
  193068. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  193069. if( rc!=SQLITE_OK ){
  193070. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  193071. break;
  193072. }
  193073. }
  193074. }
  193075. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  193076. return rc;
  193077. }
  193078. static void fts5ApiInvoke(
  193079. Fts5Auxiliary *pAux,
  193080. Fts5Cursor *pCsr,
  193081. sqlite3_context *context,
  193082. int argc,
  193083. sqlite3_value **argv
  193084. ){
  193085. assert( pCsr->pAux==0 );
  193086. pCsr->pAux = pAux;
  193087. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  193088. pCsr->pAux = 0;
  193089. }
  193090. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  193091. Fts5Cursor *pCsr;
  193092. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  193093. if( pCsr->iCsrId==iCsrId ) break;
  193094. }
  193095. return pCsr;
  193096. }
  193097. static void fts5ApiCallback(
  193098. sqlite3_context *context,
  193099. int argc,
  193100. sqlite3_value **argv
  193101. ){
  193102. Fts5Auxiliary *pAux;
  193103. Fts5Cursor *pCsr;
  193104. i64 iCsrId;
  193105. assert( argc>=1 );
  193106. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  193107. iCsrId = sqlite3_value_int64(argv[0]);
  193108. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  193109. if( pCsr==0 ){
  193110. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  193111. sqlite3_result_error(context, zErr, -1);
  193112. sqlite3_free(zErr);
  193113. }else{
  193114. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  193115. }
  193116. }
  193117. /*
  193118. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  193119. ** object. Or NULL If the cursor id does not exist.
  193120. **
  193121. ** If successful, set *ppConfig to point to the associated config object
  193122. ** before returning.
  193123. */
  193124. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  193125. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  193126. i64 iCsrId, /* Id of cursor to find */
  193127. Fts5Config **ppConfig /* OUT: Configuration object */
  193128. ){
  193129. Fts5Cursor *pCsr;
  193130. Fts5Table *pTab;
  193131. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  193132. pTab = (Fts5Table*)pCsr->base.pVtab;
  193133. *ppConfig = pTab->pConfig;
  193134. return pTab->pIndex;
  193135. }
  193136. /*
  193137. ** Return a "position-list blob" corresponding to the current position of
  193138. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  193139. ** the current position-list for each phrase in the query associated with
  193140. ** cursor pCsr.
  193141. **
  193142. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  193143. ** the number of phrases in the query. Following the varints are the
  193144. ** concatenated position lists for each phrase, in order.
  193145. **
  193146. ** The first varint (if it exists) contains the size of the position list
  193147. ** for phrase 0. The second (same disclaimer) contains the size of position
  193148. ** list 1. And so on. There is no size field for the final position list,
  193149. ** as it can be derived from the total size of the blob.
  193150. */
  193151. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  193152. int i;
  193153. int rc = SQLITE_OK;
  193154. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  193155. Fts5Buffer val;
  193156. memset(&val, 0, sizeof(Fts5Buffer));
  193157. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  193158. case FTS5_DETAIL_FULL:
  193159. /* Append the varints */
  193160. for(i=0; i<(nPhrase-1); i++){
  193161. const u8 *dummy;
  193162. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  193163. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  193164. }
  193165. /* Append the position lists */
  193166. for(i=0; i<nPhrase; i++){
  193167. const u8 *pPoslist;
  193168. int nPoslist;
  193169. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  193170. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  193171. }
  193172. break;
  193173. case FTS5_DETAIL_COLUMNS:
  193174. /* Append the varints */
  193175. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  193176. const u8 *dummy;
  193177. int nByte;
  193178. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  193179. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  193180. }
  193181. /* Append the position lists */
  193182. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  193183. const u8 *pPoslist;
  193184. int nPoslist;
  193185. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  193186. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  193187. }
  193188. break;
  193189. default:
  193190. break;
  193191. }
  193192. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  193193. return rc;
  193194. }
  193195. /*
  193196. ** This is the xColumn method, called by SQLite to request a value from
  193197. ** the row that the supplied cursor currently points to.
  193198. */
  193199. static int fts5ColumnMethod(
  193200. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  193201. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  193202. int iCol /* Index of column to read value from */
  193203. ){
  193204. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  193205. Fts5Config *pConfig = pTab->pConfig;
  193206. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  193207. int rc = SQLITE_OK;
  193208. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  193209. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  193210. if( iCol==pConfig->nCol ){
  193211. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  193212. }
  193213. }else
  193214. if( iCol==pConfig->nCol ){
  193215. /* User is requesting the value of the special column with the same name
  193216. ** as the table. Return the cursor integer id number. This value is only
  193217. ** useful in that it may be passed as the first argument to an FTS5
  193218. ** auxiliary function. */
  193219. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  193220. }else if( iCol==pConfig->nCol+1 ){
  193221. /* The value of the "rank" column. */
  193222. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  193223. fts5PoslistBlob(pCtx, pCsr);
  193224. }else if(
  193225. pCsr->ePlan==FTS5_PLAN_MATCH
  193226. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  193227. ){
  193228. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  193229. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  193230. }
  193231. }
  193232. }else if( !fts5IsContentless(pTab) ){
  193233. rc = fts5SeekCursor(pCsr, 1);
  193234. if( rc==SQLITE_OK ){
  193235. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  193236. }
  193237. }
  193238. return rc;
  193239. }
  193240. /*
  193241. ** This routine implements the xFindFunction method for the FTS3
  193242. ** virtual table.
  193243. */
  193244. static int fts5FindFunctionMethod(
  193245. sqlite3_vtab *pVtab, /* Virtual table handle */
  193246. int nUnused, /* Number of SQL function arguments */
  193247. const char *zName, /* Name of SQL function */
  193248. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  193249. void **ppArg /* OUT: User data for *pxFunc */
  193250. ){
  193251. Fts5Table *pTab = (Fts5Table*)pVtab;
  193252. Fts5Auxiliary *pAux;
  193253. UNUSED_PARAM(nUnused);
  193254. pAux = fts5FindAuxiliary(pTab, zName);
  193255. if( pAux ){
  193256. *pxFunc = fts5ApiCallback;
  193257. *ppArg = (void*)pAux;
  193258. return 1;
  193259. }
  193260. /* No function of the specified name was found. Return 0. */
  193261. return 0;
  193262. }
  193263. /*
  193264. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  193265. */
  193266. static int fts5RenameMethod(
  193267. sqlite3_vtab *pVtab, /* Virtual table handle */
  193268. const char *zName /* New name of table */
  193269. ){
  193270. Fts5Table *pTab = (Fts5Table*)pVtab;
  193271. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  193272. }
  193273. /*
  193274. ** The xSavepoint() method.
  193275. **
  193276. ** Flush the contents of the pending-terms table to disk.
  193277. */
  193278. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  193279. Fts5Table *pTab = (Fts5Table*)pVtab;
  193280. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  193281. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  193282. fts5TripCursors(pTab);
  193283. return sqlite3Fts5StorageSync(pTab->pStorage);
  193284. }
  193285. /*
  193286. ** The xRelease() method.
  193287. **
  193288. ** This is a no-op.
  193289. */
  193290. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  193291. Fts5Table *pTab = (Fts5Table*)pVtab;
  193292. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  193293. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  193294. fts5TripCursors(pTab);
  193295. return sqlite3Fts5StorageSync(pTab->pStorage);
  193296. }
  193297. /*
  193298. ** The xRollbackTo() method.
  193299. **
  193300. ** Discard the contents of the pending terms table.
  193301. */
  193302. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  193303. Fts5Table *pTab = (Fts5Table*)pVtab;
  193304. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  193305. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  193306. fts5TripCursors(pTab);
  193307. return sqlite3Fts5StorageRollback(pTab->pStorage);
  193308. }
  193309. /*
  193310. ** Register a new auxiliary function with global context pGlobal.
  193311. */
  193312. static int fts5CreateAux(
  193313. fts5_api *pApi, /* Global context (one per db handle) */
  193314. const char *zName, /* Name of new function */
  193315. void *pUserData, /* User data for aux. function */
  193316. fts5_extension_function xFunc, /* Aux. function implementation */
  193317. void(*xDestroy)(void*) /* Destructor for pUserData */
  193318. ){
  193319. Fts5Global *pGlobal = (Fts5Global*)pApi;
  193320. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  193321. if( rc==SQLITE_OK ){
  193322. Fts5Auxiliary *pAux;
  193323. int nName; /* Size of zName in bytes, including \0 */
  193324. int nByte; /* Bytes of space to allocate */
  193325. nName = (int)strlen(zName) + 1;
  193326. nByte = sizeof(Fts5Auxiliary) + nName;
  193327. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  193328. if( pAux ){
  193329. memset(pAux, 0, nByte);
  193330. pAux->zFunc = (char*)&pAux[1];
  193331. memcpy(pAux->zFunc, zName, nName);
  193332. pAux->pGlobal = pGlobal;
  193333. pAux->pUserData = pUserData;
  193334. pAux->xFunc = xFunc;
  193335. pAux->xDestroy = xDestroy;
  193336. pAux->pNext = pGlobal->pAux;
  193337. pGlobal->pAux = pAux;
  193338. }else{
  193339. rc = SQLITE_NOMEM;
  193340. }
  193341. }
  193342. return rc;
  193343. }
  193344. /*
  193345. ** Register a new tokenizer. This is the implementation of the
  193346. ** fts5_api.xCreateTokenizer() method.
  193347. */
  193348. static int fts5CreateTokenizer(
  193349. fts5_api *pApi, /* Global context (one per db handle) */
  193350. const char *zName, /* Name of new function */
  193351. void *pUserData, /* User data for aux. function */
  193352. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  193353. void(*xDestroy)(void*) /* Destructor for pUserData */
  193354. ){
  193355. Fts5Global *pGlobal = (Fts5Global*)pApi;
  193356. Fts5TokenizerModule *pNew;
  193357. int nName; /* Size of zName and its \0 terminator */
  193358. int nByte; /* Bytes of space to allocate */
  193359. int rc = SQLITE_OK;
  193360. nName = (int)strlen(zName) + 1;
  193361. nByte = sizeof(Fts5TokenizerModule) + nName;
  193362. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  193363. if( pNew ){
  193364. memset(pNew, 0, nByte);
  193365. pNew->zName = (char*)&pNew[1];
  193366. memcpy(pNew->zName, zName, nName);
  193367. pNew->pUserData = pUserData;
  193368. pNew->x = *pTokenizer;
  193369. pNew->xDestroy = xDestroy;
  193370. pNew->pNext = pGlobal->pTok;
  193371. pGlobal->pTok = pNew;
  193372. if( pNew->pNext==0 ){
  193373. pGlobal->pDfltTok = pNew;
  193374. }
  193375. }else{
  193376. rc = SQLITE_NOMEM;
  193377. }
  193378. return rc;
  193379. }
  193380. static Fts5TokenizerModule *fts5LocateTokenizer(
  193381. Fts5Global *pGlobal,
  193382. const char *zName
  193383. ){
  193384. Fts5TokenizerModule *pMod = 0;
  193385. if( zName==0 ){
  193386. pMod = pGlobal->pDfltTok;
  193387. }else{
  193388. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  193389. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  193390. }
  193391. }
  193392. return pMod;
  193393. }
  193394. /*
  193395. ** Find a tokenizer. This is the implementation of the
  193396. ** fts5_api.xFindTokenizer() method.
  193397. */
  193398. static int fts5FindTokenizer(
  193399. fts5_api *pApi, /* Global context (one per db handle) */
  193400. const char *zName, /* Name of new function */
  193401. void **ppUserData,
  193402. fts5_tokenizer *pTokenizer /* Populate this object */
  193403. ){
  193404. int rc = SQLITE_OK;
  193405. Fts5TokenizerModule *pMod;
  193406. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  193407. if( pMod ){
  193408. *pTokenizer = pMod->x;
  193409. *ppUserData = pMod->pUserData;
  193410. }else{
  193411. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  193412. rc = SQLITE_ERROR;
  193413. }
  193414. return rc;
  193415. }
  193416. static int sqlite3Fts5GetTokenizer(
  193417. Fts5Global *pGlobal,
  193418. const char **azArg,
  193419. int nArg,
  193420. Fts5Tokenizer **ppTok,
  193421. fts5_tokenizer **ppTokApi,
  193422. char **pzErr
  193423. ){
  193424. Fts5TokenizerModule *pMod;
  193425. int rc = SQLITE_OK;
  193426. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  193427. if( pMod==0 ){
  193428. assert( nArg>0 );
  193429. rc = SQLITE_ERROR;
  193430. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  193431. }else{
  193432. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  193433. *ppTokApi = &pMod->x;
  193434. if( rc!=SQLITE_OK && pzErr ){
  193435. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  193436. }
  193437. }
  193438. if( rc!=SQLITE_OK ){
  193439. *ppTokApi = 0;
  193440. *ppTok = 0;
  193441. }
  193442. return rc;
  193443. }
  193444. static void fts5ModuleDestroy(void *pCtx){
  193445. Fts5TokenizerModule *pTok, *pNextTok;
  193446. Fts5Auxiliary *pAux, *pNextAux;
  193447. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  193448. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  193449. pNextAux = pAux->pNext;
  193450. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  193451. sqlite3_free(pAux);
  193452. }
  193453. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  193454. pNextTok = pTok->pNext;
  193455. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  193456. sqlite3_free(pTok);
  193457. }
  193458. sqlite3_free(pGlobal);
  193459. }
  193460. static void fts5Fts5Func(
  193461. sqlite3_context *pCtx, /* Function call context */
  193462. int nArg, /* Number of args */
  193463. sqlite3_value **apArg /* Function arguments */
  193464. ){
  193465. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  193466. fts5_api **ppApi;
  193467. UNUSED_PARAM(nArg);
  193468. assert( nArg==1 );
  193469. ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
  193470. if( ppApi ) *ppApi = &pGlobal->api;
  193471. }
  193472. /*
  193473. ** Implementation of fts5_source_id() function.
  193474. */
  193475. static void fts5SourceIdFunc(
  193476. sqlite3_context *pCtx, /* Function call context */
  193477. int nArg, /* Number of args */
  193478. sqlite3_value **apUnused /* Function arguments */
  193479. ){
  193480. assert( nArg==0 );
  193481. UNUSED_PARAM2(nArg, apUnused);
  193482. sqlite3_result_text(pCtx, "fts5: 2018-06-04 19:24:41 c7ee0833225bfd8c5ec2f9bf62b97c4e04d03bd9566366d5221ac8fb199a87ca", -1, SQLITE_TRANSIENT);
  193483. }
  193484. static int fts5Init(sqlite3 *db){
  193485. static const sqlite3_module fts5Mod = {
  193486. /* iVersion */ 2,
  193487. /* xCreate */ fts5CreateMethod,
  193488. /* xConnect */ fts5ConnectMethod,
  193489. /* xBestIndex */ fts5BestIndexMethod,
  193490. /* xDisconnect */ fts5DisconnectMethod,
  193491. /* xDestroy */ fts5DestroyMethod,
  193492. /* xOpen */ fts5OpenMethod,
  193493. /* xClose */ fts5CloseMethod,
  193494. /* xFilter */ fts5FilterMethod,
  193495. /* xNext */ fts5NextMethod,
  193496. /* xEof */ fts5EofMethod,
  193497. /* xColumn */ fts5ColumnMethod,
  193498. /* xRowid */ fts5RowidMethod,
  193499. /* xUpdate */ fts5UpdateMethod,
  193500. /* xBegin */ fts5BeginMethod,
  193501. /* xSync */ fts5SyncMethod,
  193502. /* xCommit */ fts5CommitMethod,
  193503. /* xRollback */ fts5RollbackMethod,
  193504. /* xFindFunction */ fts5FindFunctionMethod,
  193505. /* xRename */ fts5RenameMethod,
  193506. /* xSavepoint */ fts5SavepointMethod,
  193507. /* xRelease */ fts5ReleaseMethod,
  193508. /* xRollbackTo */ fts5RollbackToMethod,
  193509. };
  193510. int rc;
  193511. Fts5Global *pGlobal = 0;
  193512. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  193513. if( pGlobal==0 ){
  193514. rc = SQLITE_NOMEM;
  193515. }else{
  193516. void *p = (void*)pGlobal;
  193517. memset(pGlobal, 0, sizeof(Fts5Global));
  193518. pGlobal->db = db;
  193519. pGlobal->api.iVersion = 2;
  193520. pGlobal->api.xCreateFunction = fts5CreateAux;
  193521. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  193522. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  193523. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  193524. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  193525. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  193526. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  193527. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  193528. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  193529. if( rc==SQLITE_OK ){
  193530. rc = sqlite3_create_function(
  193531. db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  193532. );
  193533. }
  193534. if( rc==SQLITE_OK ){
  193535. rc = sqlite3_create_function(
  193536. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  193537. );
  193538. }
  193539. }
  193540. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  193541. ** fts5_test_mi.c is compiled and linked into the executable. And call
  193542. ** its entry point to enable the matchinfo() demo. */
  193543. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  193544. if( rc==SQLITE_OK ){
  193545. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  193546. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  193547. }
  193548. #endif
  193549. return rc;
  193550. }
  193551. /*
  193552. ** The following functions are used to register the module with SQLite. If
  193553. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  193554. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  193555. **
  193556. ** Or, if this module is being built as a loadable extension,
  193557. ** sqlite3Fts5Init() is omitted and the two standard entry points
  193558. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  193559. */
  193560. #ifndef SQLITE_CORE
  193561. #ifdef _WIN32
  193562. __declspec(dllexport)
  193563. #endif
  193564. SQLITE_API int sqlite3_fts_init(
  193565. sqlite3 *db,
  193566. char **pzErrMsg,
  193567. const sqlite3_api_routines *pApi
  193568. ){
  193569. SQLITE_EXTENSION_INIT2(pApi);
  193570. (void)pzErrMsg; /* Unused parameter */
  193571. return fts5Init(db);
  193572. }
  193573. #ifdef _WIN32
  193574. __declspec(dllexport)
  193575. #endif
  193576. SQLITE_API int sqlite3_fts5_init(
  193577. sqlite3 *db,
  193578. char **pzErrMsg,
  193579. const sqlite3_api_routines *pApi
  193580. ){
  193581. SQLITE_EXTENSION_INIT2(pApi);
  193582. (void)pzErrMsg; /* Unused parameter */
  193583. return fts5Init(db);
  193584. }
  193585. #else
  193586. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  193587. return fts5Init(db);
  193588. }
  193589. #endif
  193590. /*
  193591. ** 2014 May 31
  193592. **
  193593. ** The author disclaims copyright to this source code. In place of
  193594. ** a legal notice, here is a blessing:
  193595. **
  193596. ** May you do good and not evil.
  193597. ** May you find forgiveness for yourself and forgive others.
  193598. ** May you share freely, never taking more than you give.
  193599. **
  193600. ******************************************************************************
  193601. **
  193602. */
  193603. /* #include "fts5Int.h" */
  193604. struct Fts5Storage {
  193605. Fts5Config *pConfig;
  193606. Fts5Index *pIndex;
  193607. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  193608. i64 nTotalRow; /* Total number of rows in FTS table */
  193609. i64 *aTotalSize; /* Total sizes of each column */
  193610. sqlite3_stmt *aStmt[11];
  193611. };
  193612. #if FTS5_STMT_SCAN_ASC!=0
  193613. # error "FTS5_STMT_SCAN_ASC mismatch"
  193614. #endif
  193615. #if FTS5_STMT_SCAN_DESC!=1
  193616. # error "FTS5_STMT_SCAN_DESC mismatch"
  193617. #endif
  193618. #if FTS5_STMT_LOOKUP!=2
  193619. # error "FTS5_STMT_LOOKUP mismatch"
  193620. #endif
  193621. #define FTS5_STMT_INSERT_CONTENT 3
  193622. #define FTS5_STMT_REPLACE_CONTENT 4
  193623. #define FTS5_STMT_DELETE_CONTENT 5
  193624. #define FTS5_STMT_REPLACE_DOCSIZE 6
  193625. #define FTS5_STMT_DELETE_DOCSIZE 7
  193626. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  193627. #define FTS5_STMT_REPLACE_CONFIG 9
  193628. #define FTS5_STMT_SCAN 10
  193629. /*
  193630. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  193631. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  193632. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  193633. ** occurs.
  193634. */
  193635. static int fts5StorageGetStmt(
  193636. Fts5Storage *p, /* Storage handle */
  193637. int eStmt, /* FTS5_STMT_XXX constant */
  193638. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  193639. char **pzErrMsg /* OUT: Error message (if any) */
  193640. ){
  193641. int rc = SQLITE_OK;
  193642. /* If there is no %_docsize table, there should be no requests for
  193643. ** statements to operate on it. */
  193644. assert( p->pConfig->bColumnsize || (
  193645. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  193646. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  193647. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  193648. ));
  193649. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  193650. if( p->aStmt[eStmt]==0 ){
  193651. const char *azStmt[] = {
  193652. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  193653. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  193654. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  193655. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  193656. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  193657. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  193658. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  193659. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  193660. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  193661. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  193662. "SELECT %s FROM %s AS T", /* SCAN */
  193663. };
  193664. Fts5Config *pC = p->pConfig;
  193665. char *zSql = 0;
  193666. switch( eStmt ){
  193667. case FTS5_STMT_SCAN:
  193668. zSql = sqlite3_mprintf(azStmt[eStmt],
  193669. pC->zContentExprlist, pC->zContent
  193670. );
  193671. break;
  193672. case FTS5_STMT_SCAN_ASC:
  193673. case FTS5_STMT_SCAN_DESC:
  193674. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  193675. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  193676. pC->zContentRowid
  193677. );
  193678. break;
  193679. case FTS5_STMT_LOOKUP:
  193680. zSql = sqlite3_mprintf(azStmt[eStmt],
  193681. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  193682. );
  193683. break;
  193684. case FTS5_STMT_INSERT_CONTENT:
  193685. case FTS5_STMT_REPLACE_CONTENT: {
  193686. int nCol = pC->nCol + 1;
  193687. char *zBind;
  193688. int i;
  193689. zBind = sqlite3_malloc(1 + nCol*2);
  193690. if( zBind ){
  193691. for(i=0; i<nCol; i++){
  193692. zBind[i*2] = '?';
  193693. zBind[i*2 + 1] = ',';
  193694. }
  193695. zBind[i*2-1] = '\0';
  193696. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  193697. sqlite3_free(zBind);
  193698. }
  193699. break;
  193700. }
  193701. default:
  193702. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  193703. break;
  193704. }
  193705. if( zSql==0 ){
  193706. rc = SQLITE_NOMEM;
  193707. }else{
  193708. rc = sqlite3_prepare_v3(pC->db, zSql, -1,
  193709. SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
  193710. sqlite3_free(zSql);
  193711. if( rc!=SQLITE_OK && pzErrMsg ){
  193712. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  193713. }
  193714. }
  193715. }
  193716. *ppStmt = p->aStmt[eStmt];
  193717. sqlite3_reset(*ppStmt);
  193718. return rc;
  193719. }
  193720. static int fts5ExecPrintf(
  193721. sqlite3 *db,
  193722. char **pzErr,
  193723. const char *zFormat,
  193724. ...
  193725. ){
  193726. int rc;
  193727. va_list ap; /* ... printf arguments */
  193728. char *zSql;
  193729. va_start(ap, zFormat);
  193730. zSql = sqlite3_vmprintf(zFormat, ap);
  193731. if( zSql==0 ){
  193732. rc = SQLITE_NOMEM;
  193733. }else{
  193734. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  193735. sqlite3_free(zSql);
  193736. }
  193737. va_end(ap);
  193738. return rc;
  193739. }
  193740. /*
  193741. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  193742. ** code otherwise.
  193743. */
  193744. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  193745. int rc = fts5ExecPrintf(pConfig->db, 0,
  193746. "DROP TABLE IF EXISTS %Q.'%q_data';"
  193747. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  193748. "DROP TABLE IF EXISTS %Q.'%q_config';",
  193749. pConfig->zDb, pConfig->zName,
  193750. pConfig->zDb, pConfig->zName,
  193751. pConfig->zDb, pConfig->zName
  193752. );
  193753. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  193754. rc = fts5ExecPrintf(pConfig->db, 0,
  193755. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  193756. pConfig->zDb, pConfig->zName
  193757. );
  193758. }
  193759. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  193760. rc = fts5ExecPrintf(pConfig->db, 0,
  193761. "DROP TABLE IF EXISTS %Q.'%q_content';",
  193762. pConfig->zDb, pConfig->zName
  193763. );
  193764. }
  193765. return rc;
  193766. }
  193767. static void fts5StorageRenameOne(
  193768. Fts5Config *pConfig, /* Current FTS5 configuration */
  193769. int *pRc, /* IN/OUT: Error code */
  193770. const char *zTail, /* Tail of table name e.g. "data", "config" */
  193771. const char *zName /* New name of FTS5 table */
  193772. ){
  193773. if( *pRc==SQLITE_OK ){
  193774. *pRc = fts5ExecPrintf(pConfig->db, 0,
  193775. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  193776. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  193777. );
  193778. }
  193779. }
  193780. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  193781. Fts5Config *pConfig = pStorage->pConfig;
  193782. int rc = sqlite3Fts5StorageSync(pStorage);
  193783. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  193784. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  193785. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  193786. if( pConfig->bColumnsize ){
  193787. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  193788. }
  193789. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  193790. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  193791. }
  193792. return rc;
  193793. }
  193794. /*
  193795. ** Create the shadow table named zPost, with definition zDefn. Return
  193796. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  193797. */
  193798. static int sqlite3Fts5CreateTable(
  193799. Fts5Config *pConfig, /* FTS5 configuration */
  193800. const char *zPost, /* Shadow table to create (e.g. "content") */
  193801. const char *zDefn, /* Columns etc. for shadow table */
  193802. int bWithout, /* True for without rowid */
  193803. char **pzErr /* OUT: Error message */
  193804. ){
  193805. int rc;
  193806. char *zErr = 0;
  193807. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  193808. pConfig->zDb, pConfig->zName, zPost, zDefn,
  193809. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  193810. bWithout?" WITHOUT ROWID":
  193811. #endif
  193812. ""
  193813. );
  193814. if( zErr ){
  193815. *pzErr = sqlite3_mprintf(
  193816. "fts5: error creating shadow table %q_%s: %s",
  193817. pConfig->zName, zPost, zErr
  193818. );
  193819. sqlite3_free(zErr);
  193820. }
  193821. return rc;
  193822. }
  193823. /*
  193824. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  193825. ** and initialize the underlying tables
  193826. **
  193827. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  193828. ** Otherwise, set *pp to NULL and return an SQLite error code.
  193829. */
  193830. static int sqlite3Fts5StorageOpen(
  193831. Fts5Config *pConfig,
  193832. Fts5Index *pIndex,
  193833. int bCreate,
  193834. Fts5Storage **pp,
  193835. char **pzErr /* OUT: Error message */
  193836. ){
  193837. int rc = SQLITE_OK;
  193838. Fts5Storage *p; /* New object */
  193839. int nByte; /* Bytes of space to allocate */
  193840. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  193841. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  193842. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  193843. if( !p ) return SQLITE_NOMEM;
  193844. memset(p, 0, nByte);
  193845. p->aTotalSize = (i64*)&p[1];
  193846. p->pConfig = pConfig;
  193847. p->pIndex = pIndex;
  193848. if( bCreate ){
  193849. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  193850. int nDefn = 32 + pConfig->nCol*10;
  193851. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  193852. if( zDefn==0 ){
  193853. rc = SQLITE_NOMEM;
  193854. }else{
  193855. int i;
  193856. int iOff;
  193857. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  193858. iOff = (int)strlen(zDefn);
  193859. for(i=0; i<pConfig->nCol; i++){
  193860. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  193861. iOff += (int)strlen(&zDefn[iOff]);
  193862. }
  193863. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  193864. }
  193865. sqlite3_free(zDefn);
  193866. }
  193867. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  193868. rc = sqlite3Fts5CreateTable(
  193869. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  193870. );
  193871. }
  193872. if( rc==SQLITE_OK ){
  193873. rc = sqlite3Fts5CreateTable(
  193874. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  193875. );
  193876. }
  193877. if( rc==SQLITE_OK ){
  193878. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  193879. }
  193880. }
  193881. if( rc ){
  193882. sqlite3Fts5StorageClose(p);
  193883. *pp = 0;
  193884. }
  193885. return rc;
  193886. }
  193887. /*
  193888. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  193889. */
  193890. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  193891. int rc = SQLITE_OK;
  193892. if( p ){
  193893. int i;
  193894. /* Finalize all SQL statements */
  193895. for(i=0; i<ArraySize(p->aStmt); i++){
  193896. sqlite3_finalize(p->aStmt[i]);
  193897. }
  193898. sqlite3_free(p);
  193899. }
  193900. return rc;
  193901. }
  193902. typedef struct Fts5InsertCtx Fts5InsertCtx;
  193903. struct Fts5InsertCtx {
  193904. Fts5Storage *pStorage;
  193905. int iCol;
  193906. int szCol; /* Size of column value in tokens */
  193907. };
  193908. /*
  193909. ** Tokenization callback used when inserting tokens into the FTS index.
  193910. */
  193911. static int fts5StorageInsertCallback(
  193912. void *pContext, /* Pointer to Fts5InsertCtx object */
  193913. int tflags,
  193914. const char *pToken, /* Buffer containing token */
  193915. int nToken, /* Size of token in bytes */
  193916. int iUnused1, /* Start offset of token */
  193917. int iUnused2 /* End offset of token */
  193918. ){
  193919. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  193920. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  193921. UNUSED_PARAM2(iUnused1, iUnused2);
  193922. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  193923. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  193924. pCtx->szCol++;
  193925. }
  193926. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  193927. }
  193928. /*
  193929. ** If a row with rowid iDel is present in the %_content table, add the
  193930. ** delete-markers to the FTS index necessary to delete it. Do not actually
  193931. ** remove the %_content row at this time though.
  193932. */
  193933. static int fts5StorageDeleteFromIndex(
  193934. Fts5Storage *p,
  193935. i64 iDel,
  193936. sqlite3_value **apVal
  193937. ){
  193938. Fts5Config *pConfig = p->pConfig;
  193939. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  193940. int rc; /* Return code */
  193941. int rc2; /* sqlite3_reset() return code */
  193942. int iCol;
  193943. Fts5InsertCtx ctx;
  193944. if( apVal==0 ){
  193945. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  193946. if( rc!=SQLITE_OK ) return rc;
  193947. sqlite3_bind_int64(pSeek, 1, iDel);
  193948. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  193949. return sqlite3_reset(pSeek);
  193950. }
  193951. }
  193952. ctx.pStorage = p;
  193953. ctx.iCol = -1;
  193954. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  193955. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  193956. if( pConfig->abUnindexed[iCol-1]==0 ){
  193957. const char *zText;
  193958. int nText;
  193959. if( pSeek ){
  193960. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  193961. nText = sqlite3_column_bytes(pSeek, iCol);
  193962. }else{
  193963. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  193964. nText = sqlite3_value_bytes(apVal[iCol-1]);
  193965. }
  193966. ctx.szCol = 0;
  193967. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  193968. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  193969. );
  193970. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  193971. }
  193972. }
  193973. p->nTotalRow--;
  193974. rc2 = sqlite3_reset(pSeek);
  193975. if( rc==SQLITE_OK ) rc = rc2;
  193976. return rc;
  193977. }
  193978. /*
  193979. ** Insert a record into the %_docsize table. Specifically, do:
  193980. **
  193981. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  193982. **
  193983. ** If there is no %_docsize table (as happens if the columnsize=0 option
  193984. ** is specified when the FTS5 table is created), this function is a no-op.
  193985. */
  193986. static int fts5StorageInsertDocsize(
  193987. Fts5Storage *p, /* Storage module to write to */
  193988. i64 iRowid, /* id value */
  193989. Fts5Buffer *pBuf /* sz value */
  193990. ){
  193991. int rc = SQLITE_OK;
  193992. if( p->pConfig->bColumnsize ){
  193993. sqlite3_stmt *pReplace = 0;
  193994. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  193995. if( rc==SQLITE_OK ){
  193996. sqlite3_bind_int64(pReplace, 1, iRowid);
  193997. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  193998. sqlite3_step(pReplace);
  193999. rc = sqlite3_reset(pReplace);
  194000. sqlite3_bind_null(pReplace, 2);
  194001. }
  194002. }
  194003. return rc;
  194004. }
  194005. /*
  194006. ** Load the contents of the "averages" record from disk into the
  194007. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  194008. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  194009. ** that the contents of aTotalSize[] and nTotalRow are valid until
  194010. ** further notice.
  194011. **
  194012. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  194013. ** occurs.
  194014. */
  194015. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  194016. int rc = SQLITE_OK;
  194017. if( p->bTotalsValid==0 ){
  194018. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  194019. p->bTotalsValid = bCache;
  194020. }
  194021. return rc;
  194022. }
  194023. /*
  194024. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  194025. ** variables in the "averages" record on disk.
  194026. **
  194027. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  194028. ** occurs.
  194029. */
  194030. static int fts5StorageSaveTotals(Fts5Storage *p){
  194031. int nCol = p->pConfig->nCol;
  194032. int i;
  194033. Fts5Buffer buf;
  194034. int rc = SQLITE_OK;
  194035. memset(&buf, 0, sizeof(buf));
  194036. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  194037. for(i=0; i<nCol; i++){
  194038. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  194039. }
  194040. if( rc==SQLITE_OK ){
  194041. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  194042. }
  194043. sqlite3_free(buf.p);
  194044. return rc;
  194045. }
  194046. /*
  194047. ** Remove a row from the FTS table.
  194048. */
  194049. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  194050. Fts5Config *pConfig = p->pConfig;
  194051. int rc;
  194052. sqlite3_stmt *pDel = 0;
  194053. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  194054. rc = fts5StorageLoadTotals(p, 1);
  194055. /* Delete the index records */
  194056. if( rc==SQLITE_OK ){
  194057. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  194058. }
  194059. /* Delete the %_docsize record */
  194060. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  194061. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  194062. if( rc==SQLITE_OK ){
  194063. sqlite3_bind_int64(pDel, 1, iDel);
  194064. sqlite3_step(pDel);
  194065. rc = sqlite3_reset(pDel);
  194066. }
  194067. }
  194068. /* Delete the %_content record */
  194069. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  194070. if( rc==SQLITE_OK ){
  194071. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  194072. }
  194073. if( rc==SQLITE_OK ){
  194074. sqlite3_bind_int64(pDel, 1, iDel);
  194075. sqlite3_step(pDel);
  194076. rc = sqlite3_reset(pDel);
  194077. }
  194078. }
  194079. return rc;
  194080. }
  194081. /*
  194082. ** Delete all entries in the FTS5 index.
  194083. */
  194084. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  194085. Fts5Config *pConfig = p->pConfig;
  194086. int rc;
  194087. /* Delete the contents of the %_data and %_docsize tables. */
  194088. rc = fts5ExecPrintf(pConfig->db, 0,
  194089. "DELETE FROM %Q.'%q_data';"
  194090. "DELETE FROM %Q.'%q_idx';",
  194091. pConfig->zDb, pConfig->zName,
  194092. pConfig->zDb, pConfig->zName
  194093. );
  194094. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  194095. rc = fts5ExecPrintf(pConfig->db, 0,
  194096. "DELETE FROM %Q.'%q_docsize';",
  194097. pConfig->zDb, pConfig->zName
  194098. );
  194099. }
  194100. /* Reinitialize the %_data table. This call creates the initial structure
  194101. ** and averages records. */
  194102. if( rc==SQLITE_OK ){
  194103. rc = sqlite3Fts5IndexReinit(p->pIndex);
  194104. }
  194105. if( rc==SQLITE_OK ){
  194106. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  194107. }
  194108. return rc;
  194109. }
  194110. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  194111. Fts5Buffer buf = {0,0,0};
  194112. Fts5Config *pConfig = p->pConfig;
  194113. sqlite3_stmt *pScan = 0;
  194114. Fts5InsertCtx ctx;
  194115. int rc;
  194116. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  194117. ctx.pStorage = p;
  194118. rc = sqlite3Fts5StorageDeleteAll(p);
  194119. if( rc==SQLITE_OK ){
  194120. rc = fts5StorageLoadTotals(p, 1);
  194121. }
  194122. if( rc==SQLITE_OK ){
  194123. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  194124. }
  194125. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  194126. i64 iRowid = sqlite3_column_int64(pScan, 0);
  194127. sqlite3Fts5BufferZero(&buf);
  194128. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  194129. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  194130. ctx.szCol = 0;
  194131. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  194132. rc = sqlite3Fts5Tokenize(pConfig,
  194133. FTS5_TOKENIZE_DOCUMENT,
  194134. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  194135. sqlite3_column_bytes(pScan, ctx.iCol+1),
  194136. (void*)&ctx,
  194137. fts5StorageInsertCallback
  194138. );
  194139. }
  194140. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  194141. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  194142. }
  194143. p->nTotalRow++;
  194144. if( rc==SQLITE_OK ){
  194145. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  194146. }
  194147. }
  194148. sqlite3_free(buf.p);
  194149. /* Write the averages record */
  194150. if( rc==SQLITE_OK ){
  194151. rc = fts5StorageSaveTotals(p);
  194152. }
  194153. return rc;
  194154. }
  194155. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  194156. return sqlite3Fts5IndexOptimize(p->pIndex);
  194157. }
  194158. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  194159. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  194160. }
  194161. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  194162. return sqlite3Fts5IndexReset(p->pIndex);
  194163. }
  194164. /*
  194165. ** Allocate a new rowid. This is used for "external content" tables when
  194166. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  194167. ** by inserting a dummy row into the %_docsize table. The dummy will be
  194168. ** overwritten later.
  194169. **
  194170. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  194171. ** this case the user is required to provide a rowid explicitly.
  194172. */
  194173. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  194174. int rc = SQLITE_MISMATCH;
  194175. if( p->pConfig->bColumnsize ){
  194176. sqlite3_stmt *pReplace = 0;
  194177. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  194178. if( rc==SQLITE_OK ){
  194179. sqlite3_bind_null(pReplace, 1);
  194180. sqlite3_bind_null(pReplace, 2);
  194181. sqlite3_step(pReplace);
  194182. rc = sqlite3_reset(pReplace);
  194183. }
  194184. if( rc==SQLITE_OK ){
  194185. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  194186. }
  194187. }
  194188. return rc;
  194189. }
  194190. /*
  194191. ** Insert a new row into the FTS content table.
  194192. */
  194193. static int sqlite3Fts5StorageContentInsert(
  194194. Fts5Storage *p,
  194195. sqlite3_value **apVal,
  194196. i64 *piRowid
  194197. ){
  194198. Fts5Config *pConfig = p->pConfig;
  194199. int rc = SQLITE_OK;
  194200. /* Insert the new row into the %_content table. */
  194201. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  194202. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  194203. *piRowid = sqlite3_value_int64(apVal[1]);
  194204. }else{
  194205. rc = fts5StorageNewRowid(p, piRowid);
  194206. }
  194207. }else{
  194208. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  194209. int i; /* Counter variable */
  194210. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  194211. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  194212. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  194213. }
  194214. if( rc==SQLITE_OK ){
  194215. sqlite3_step(pInsert);
  194216. rc = sqlite3_reset(pInsert);
  194217. }
  194218. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  194219. }
  194220. return rc;
  194221. }
  194222. /*
  194223. ** Insert new entries into the FTS index and %_docsize table.
  194224. */
  194225. static int sqlite3Fts5StorageIndexInsert(
  194226. Fts5Storage *p,
  194227. sqlite3_value **apVal,
  194228. i64 iRowid
  194229. ){
  194230. Fts5Config *pConfig = p->pConfig;
  194231. int rc = SQLITE_OK; /* Return code */
  194232. Fts5InsertCtx ctx; /* Tokenization callback context object */
  194233. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  194234. memset(&buf, 0, sizeof(Fts5Buffer));
  194235. ctx.pStorage = p;
  194236. rc = fts5StorageLoadTotals(p, 1);
  194237. if( rc==SQLITE_OK ){
  194238. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  194239. }
  194240. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  194241. ctx.szCol = 0;
  194242. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  194243. rc = sqlite3Fts5Tokenize(pConfig,
  194244. FTS5_TOKENIZE_DOCUMENT,
  194245. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  194246. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  194247. (void*)&ctx,
  194248. fts5StorageInsertCallback
  194249. );
  194250. }
  194251. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  194252. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  194253. }
  194254. p->nTotalRow++;
  194255. /* Write the %_docsize record */
  194256. if( rc==SQLITE_OK ){
  194257. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  194258. }
  194259. sqlite3_free(buf.p);
  194260. return rc;
  194261. }
  194262. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  194263. Fts5Config *pConfig = p->pConfig;
  194264. char *zSql;
  194265. int rc;
  194266. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  194267. pConfig->zDb, pConfig->zName, zSuffix
  194268. );
  194269. if( zSql==0 ){
  194270. rc = SQLITE_NOMEM;
  194271. }else{
  194272. sqlite3_stmt *pCnt = 0;
  194273. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  194274. if( rc==SQLITE_OK ){
  194275. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  194276. *pnRow = sqlite3_column_int64(pCnt, 0);
  194277. }
  194278. rc = sqlite3_finalize(pCnt);
  194279. }
  194280. }
  194281. sqlite3_free(zSql);
  194282. return rc;
  194283. }
  194284. /*
  194285. ** Context object used by sqlite3Fts5StorageIntegrity().
  194286. */
  194287. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  194288. struct Fts5IntegrityCtx {
  194289. i64 iRowid;
  194290. int iCol;
  194291. int szCol;
  194292. u64 cksum;
  194293. Fts5Termset *pTermset;
  194294. Fts5Config *pConfig;
  194295. };
  194296. /*
  194297. ** Tokenization callback used by integrity check.
  194298. */
  194299. static int fts5StorageIntegrityCallback(
  194300. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  194301. int tflags,
  194302. const char *pToken, /* Buffer containing token */
  194303. int nToken, /* Size of token in bytes */
  194304. int iUnused1, /* Start offset of token */
  194305. int iUnused2 /* End offset of token */
  194306. ){
  194307. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  194308. Fts5Termset *pTermset = pCtx->pTermset;
  194309. int bPresent;
  194310. int ii;
  194311. int rc = SQLITE_OK;
  194312. int iPos;
  194313. int iCol;
  194314. UNUSED_PARAM2(iUnused1, iUnused2);
  194315. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  194316. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  194317. pCtx->szCol++;
  194318. }
  194319. switch( pCtx->pConfig->eDetail ){
  194320. case FTS5_DETAIL_FULL:
  194321. iPos = pCtx->szCol-1;
  194322. iCol = pCtx->iCol;
  194323. break;
  194324. case FTS5_DETAIL_COLUMNS:
  194325. iPos = pCtx->iCol;
  194326. iCol = 0;
  194327. break;
  194328. default:
  194329. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  194330. iPos = 0;
  194331. iCol = 0;
  194332. break;
  194333. }
  194334. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  194335. if( rc==SQLITE_OK && bPresent==0 ){
  194336. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  194337. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  194338. );
  194339. }
  194340. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  194341. const int nChar = pCtx->pConfig->aPrefix[ii];
  194342. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  194343. if( nByte ){
  194344. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  194345. if( bPresent==0 ){
  194346. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  194347. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  194348. );
  194349. }
  194350. }
  194351. }
  194352. return rc;
  194353. }
  194354. /*
  194355. ** Check that the contents of the FTS index match that of the %_content
  194356. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  194357. ** some other SQLite error code if an error occurs while attempting to
  194358. ** determine this.
  194359. */
  194360. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  194361. Fts5Config *pConfig = p->pConfig;
  194362. int rc; /* Return code */
  194363. int *aColSize; /* Array of size pConfig->nCol */
  194364. i64 *aTotalSize; /* Array of size pConfig->nCol */
  194365. Fts5IntegrityCtx ctx;
  194366. sqlite3_stmt *pScan;
  194367. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  194368. ctx.pConfig = p->pConfig;
  194369. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  194370. if( !aTotalSize ) return SQLITE_NOMEM;
  194371. aColSize = (int*)&aTotalSize[pConfig->nCol];
  194372. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  194373. /* Generate the expected index checksum based on the contents of the
  194374. ** %_content table. This block stores the checksum in ctx.cksum. */
  194375. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  194376. if( rc==SQLITE_OK ){
  194377. int rc2;
  194378. while( SQLITE_ROW==sqlite3_step(pScan) ){
  194379. int i;
  194380. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  194381. ctx.szCol = 0;
  194382. if( pConfig->bColumnsize ){
  194383. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  194384. }
  194385. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  194386. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  194387. }
  194388. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  194389. if( pConfig->abUnindexed[i] ) continue;
  194390. ctx.iCol = i;
  194391. ctx.szCol = 0;
  194392. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  194393. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  194394. }
  194395. if( rc==SQLITE_OK ){
  194396. rc = sqlite3Fts5Tokenize(pConfig,
  194397. FTS5_TOKENIZE_DOCUMENT,
  194398. (const char*)sqlite3_column_text(pScan, i+1),
  194399. sqlite3_column_bytes(pScan, i+1),
  194400. (void*)&ctx,
  194401. fts5StorageIntegrityCallback
  194402. );
  194403. }
  194404. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  194405. rc = FTS5_CORRUPT;
  194406. }
  194407. aTotalSize[i] += ctx.szCol;
  194408. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  194409. sqlite3Fts5TermsetFree(ctx.pTermset);
  194410. ctx.pTermset = 0;
  194411. }
  194412. }
  194413. sqlite3Fts5TermsetFree(ctx.pTermset);
  194414. ctx.pTermset = 0;
  194415. if( rc!=SQLITE_OK ) break;
  194416. }
  194417. rc2 = sqlite3_reset(pScan);
  194418. if( rc==SQLITE_OK ) rc = rc2;
  194419. }
  194420. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  194421. if( rc==SQLITE_OK ){
  194422. int i;
  194423. rc = fts5StorageLoadTotals(p, 0);
  194424. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  194425. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  194426. }
  194427. }
  194428. /* Check that the %_docsize and %_content tables contain the expected
  194429. ** number of rows. */
  194430. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  194431. i64 nRow = 0;
  194432. rc = fts5StorageCount(p, "content", &nRow);
  194433. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  194434. }
  194435. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  194436. i64 nRow = 0;
  194437. rc = fts5StorageCount(p, "docsize", &nRow);
  194438. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  194439. }
  194440. /* Pass the expected checksum down to the FTS index module. It will
  194441. ** verify, amongst other things, that it matches the checksum generated by
  194442. ** inspecting the index itself. */
  194443. if( rc==SQLITE_OK ){
  194444. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  194445. }
  194446. sqlite3_free(aTotalSize);
  194447. return rc;
  194448. }
  194449. /*
  194450. ** Obtain an SQLite statement handle that may be used to read data from the
  194451. ** %_content table.
  194452. */
  194453. static int sqlite3Fts5StorageStmt(
  194454. Fts5Storage *p,
  194455. int eStmt,
  194456. sqlite3_stmt **pp,
  194457. char **pzErrMsg
  194458. ){
  194459. int rc;
  194460. assert( eStmt==FTS5_STMT_SCAN_ASC
  194461. || eStmt==FTS5_STMT_SCAN_DESC
  194462. || eStmt==FTS5_STMT_LOOKUP
  194463. );
  194464. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  194465. if( rc==SQLITE_OK ){
  194466. assert( p->aStmt[eStmt]==*pp );
  194467. p->aStmt[eStmt] = 0;
  194468. }
  194469. return rc;
  194470. }
  194471. /*
  194472. ** Release an SQLite statement handle obtained via an earlier call to
  194473. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  194474. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  194475. */
  194476. static void sqlite3Fts5StorageStmtRelease(
  194477. Fts5Storage *p,
  194478. int eStmt,
  194479. sqlite3_stmt *pStmt
  194480. ){
  194481. assert( eStmt==FTS5_STMT_SCAN_ASC
  194482. || eStmt==FTS5_STMT_SCAN_DESC
  194483. || eStmt==FTS5_STMT_LOOKUP
  194484. );
  194485. if( p->aStmt[eStmt]==0 ){
  194486. sqlite3_reset(pStmt);
  194487. p->aStmt[eStmt] = pStmt;
  194488. }else{
  194489. sqlite3_finalize(pStmt);
  194490. }
  194491. }
  194492. static int fts5StorageDecodeSizeArray(
  194493. int *aCol, int nCol, /* Array to populate */
  194494. const u8 *aBlob, int nBlob /* Record to read varints from */
  194495. ){
  194496. int i;
  194497. int iOff = 0;
  194498. for(i=0; i<nCol; i++){
  194499. if( iOff>=nBlob ) return 1;
  194500. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  194501. }
  194502. return (iOff!=nBlob);
  194503. }
  194504. /*
  194505. ** Argument aCol points to an array of integers containing one entry for
  194506. ** each table column. This function reads the %_docsize record for the
  194507. ** specified rowid and populates aCol[] with the results.
  194508. **
  194509. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  194510. ** otherwise.
  194511. */
  194512. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  194513. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  194514. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  194515. int rc; /* Return Code */
  194516. assert( p->pConfig->bColumnsize );
  194517. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  194518. if( rc==SQLITE_OK ){
  194519. int bCorrupt = 1;
  194520. sqlite3_bind_int64(pLookup, 1, iRowid);
  194521. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  194522. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  194523. int nBlob = sqlite3_column_bytes(pLookup, 0);
  194524. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  194525. bCorrupt = 0;
  194526. }
  194527. }
  194528. rc = sqlite3_reset(pLookup);
  194529. if( bCorrupt && rc==SQLITE_OK ){
  194530. rc = FTS5_CORRUPT;
  194531. }
  194532. }
  194533. return rc;
  194534. }
  194535. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  194536. int rc = fts5StorageLoadTotals(p, 0);
  194537. if( rc==SQLITE_OK ){
  194538. *pnToken = 0;
  194539. if( iCol<0 ){
  194540. int i;
  194541. for(i=0; i<p->pConfig->nCol; i++){
  194542. *pnToken += p->aTotalSize[i];
  194543. }
  194544. }else if( iCol<p->pConfig->nCol ){
  194545. *pnToken = p->aTotalSize[iCol];
  194546. }else{
  194547. rc = SQLITE_RANGE;
  194548. }
  194549. }
  194550. return rc;
  194551. }
  194552. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  194553. int rc = fts5StorageLoadTotals(p, 0);
  194554. if( rc==SQLITE_OK ){
  194555. *pnRow = p->nTotalRow;
  194556. }
  194557. return rc;
  194558. }
  194559. /*
  194560. ** Flush any data currently held in-memory to disk.
  194561. */
  194562. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  194563. int rc = SQLITE_OK;
  194564. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  194565. if( p->bTotalsValid ){
  194566. rc = fts5StorageSaveTotals(p);
  194567. p->bTotalsValid = 0;
  194568. }
  194569. if( rc==SQLITE_OK ){
  194570. rc = sqlite3Fts5IndexSync(p->pIndex);
  194571. }
  194572. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  194573. return rc;
  194574. }
  194575. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  194576. p->bTotalsValid = 0;
  194577. return sqlite3Fts5IndexRollback(p->pIndex);
  194578. }
  194579. static int sqlite3Fts5StorageConfigValue(
  194580. Fts5Storage *p,
  194581. const char *z,
  194582. sqlite3_value *pVal,
  194583. int iVal
  194584. ){
  194585. sqlite3_stmt *pReplace = 0;
  194586. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  194587. if( rc==SQLITE_OK ){
  194588. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  194589. if( pVal ){
  194590. sqlite3_bind_value(pReplace, 2, pVal);
  194591. }else{
  194592. sqlite3_bind_int(pReplace, 2, iVal);
  194593. }
  194594. sqlite3_step(pReplace);
  194595. rc = sqlite3_reset(pReplace);
  194596. sqlite3_bind_null(pReplace, 1);
  194597. }
  194598. if( rc==SQLITE_OK && pVal ){
  194599. int iNew = p->pConfig->iCookie + 1;
  194600. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  194601. if( rc==SQLITE_OK ){
  194602. p->pConfig->iCookie = iNew;
  194603. }
  194604. }
  194605. return rc;
  194606. }
  194607. /*
  194608. ** 2014 May 31
  194609. **
  194610. ** The author disclaims copyright to this source code. In place of
  194611. ** a legal notice, here is a blessing:
  194612. **
  194613. ** May you do good and not evil.
  194614. ** May you find forgiveness for yourself and forgive others.
  194615. ** May you share freely, never taking more than you give.
  194616. **
  194617. ******************************************************************************
  194618. */
  194619. /* #include "fts5Int.h" */
  194620. /**************************************************************************
  194621. ** Start of ascii tokenizer implementation.
  194622. */
  194623. /*
  194624. ** For tokenizers with no "unicode" modifier, the set of token characters
  194625. ** is the same as the set of ASCII range alphanumeric characters.
  194626. */
  194627. static unsigned char aAsciiTokenChar[128] = {
  194628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  194629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  194630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  194631. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  194632. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  194633. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  194634. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  194635. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  194636. };
  194637. typedef struct AsciiTokenizer AsciiTokenizer;
  194638. struct AsciiTokenizer {
  194639. unsigned char aTokenChar[128];
  194640. };
  194641. static void fts5AsciiAddExceptions(
  194642. AsciiTokenizer *p,
  194643. const char *zArg,
  194644. int bTokenChars
  194645. ){
  194646. int i;
  194647. for(i=0; zArg[i]; i++){
  194648. if( (zArg[i] & 0x80)==0 ){
  194649. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  194650. }
  194651. }
  194652. }
  194653. /*
  194654. ** Delete a "ascii" tokenizer.
  194655. */
  194656. static void fts5AsciiDelete(Fts5Tokenizer *p){
  194657. sqlite3_free(p);
  194658. }
  194659. /*
  194660. ** Create an "ascii" tokenizer.
  194661. */
  194662. static int fts5AsciiCreate(
  194663. void *pUnused,
  194664. const char **azArg, int nArg,
  194665. Fts5Tokenizer **ppOut
  194666. ){
  194667. int rc = SQLITE_OK;
  194668. AsciiTokenizer *p = 0;
  194669. UNUSED_PARAM(pUnused);
  194670. if( nArg%2 ){
  194671. rc = SQLITE_ERROR;
  194672. }else{
  194673. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  194674. if( p==0 ){
  194675. rc = SQLITE_NOMEM;
  194676. }else{
  194677. int i;
  194678. memset(p, 0, sizeof(AsciiTokenizer));
  194679. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  194680. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  194681. const char *zArg = azArg[i+1];
  194682. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  194683. fts5AsciiAddExceptions(p, zArg, 1);
  194684. }else
  194685. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  194686. fts5AsciiAddExceptions(p, zArg, 0);
  194687. }else{
  194688. rc = SQLITE_ERROR;
  194689. }
  194690. }
  194691. if( rc!=SQLITE_OK ){
  194692. fts5AsciiDelete((Fts5Tokenizer*)p);
  194693. p = 0;
  194694. }
  194695. }
  194696. }
  194697. *ppOut = (Fts5Tokenizer*)p;
  194698. return rc;
  194699. }
  194700. static void asciiFold(char *aOut, const char *aIn, int nByte){
  194701. int i;
  194702. for(i=0; i<nByte; i++){
  194703. char c = aIn[i];
  194704. if( c>='A' && c<='Z' ) c += 32;
  194705. aOut[i] = c;
  194706. }
  194707. }
  194708. /*
  194709. ** Tokenize some text using the ascii tokenizer.
  194710. */
  194711. static int fts5AsciiTokenize(
  194712. Fts5Tokenizer *pTokenizer,
  194713. void *pCtx,
  194714. int iUnused,
  194715. const char *pText, int nText,
  194716. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  194717. ){
  194718. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  194719. int rc = SQLITE_OK;
  194720. int ie;
  194721. int is = 0;
  194722. char aFold[64];
  194723. int nFold = sizeof(aFold);
  194724. char *pFold = aFold;
  194725. unsigned char *a = p->aTokenChar;
  194726. UNUSED_PARAM(iUnused);
  194727. while( is<nText && rc==SQLITE_OK ){
  194728. int nByte;
  194729. /* Skip any leading divider characters. */
  194730. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  194731. is++;
  194732. }
  194733. if( is==nText ) break;
  194734. /* Count the token characters */
  194735. ie = is+1;
  194736. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  194737. ie++;
  194738. }
  194739. /* Fold to lower case */
  194740. nByte = ie-is;
  194741. if( nByte>nFold ){
  194742. if( pFold!=aFold ) sqlite3_free(pFold);
  194743. pFold = sqlite3_malloc(nByte*2);
  194744. if( pFold==0 ){
  194745. rc = SQLITE_NOMEM;
  194746. break;
  194747. }
  194748. nFold = nByte*2;
  194749. }
  194750. asciiFold(pFold, &pText[is], nByte);
  194751. /* Invoke the token callback */
  194752. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  194753. is = ie+1;
  194754. }
  194755. if( pFold!=aFold ) sqlite3_free(pFold);
  194756. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  194757. return rc;
  194758. }
  194759. /**************************************************************************
  194760. ** Start of unicode61 tokenizer implementation.
  194761. */
  194762. /*
  194763. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  194764. ** from the sqlite3 source file utf.c. If this file is compiled as part
  194765. ** of the amalgamation, they are not required.
  194766. */
  194767. #ifndef SQLITE_AMALGAMATION
  194768. static const unsigned char sqlite3Utf8Trans1[] = {
  194769. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  194770. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  194771. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  194772. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  194773. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  194774. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  194775. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  194776. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  194777. };
  194778. #define READ_UTF8(zIn, zTerm, c) \
  194779. c = *(zIn++); \
  194780. if( c>=0xc0 ){ \
  194781. c = sqlite3Utf8Trans1[c-0xc0]; \
  194782. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  194783. c = (c<<6) + (0x3f & *(zIn++)); \
  194784. } \
  194785. if( c<0x80 \
  194786. || (c&0xFFFFF800)==0xD800 \
  194787. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  194788. }
  194789. #define WRITE_UTF8(zOut, c) { \
  194790. if( c<0x00080 ){ \
  194791. *zOut++ = (unsigned char)(c&0xFF); \
  194792. } \
  194793. else if( c<0x00800 ){ \
  194794. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  194795. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  194796. } \
  194797. else if( c<0x10000 ){ \
  194798. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  194799. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  194800. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  194801. }else{ \
  194802. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  194803. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  194804. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  194805. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  194806. } \
  194807. }
  194808. #endif /* ifndef SQLITE_AMALGAMATION */
  194809. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  194810. struct Unicode61Tokenizer {
  194811. unsigned char aTokenChar[128]; /* ASCII range token characters */
  194812. char *aFold; /* Buffer to fold text into */
  194813. int nFold; /* Size of aFold[] in bytes */
  194814. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  194815. int nException;
  194816. int *aiException;
  194817. };
  194818. static int fts5UnicodeAddExceptions(
  194819. Unicode61Tokenizer *p, /* Tokenizer object */
  194820. const char *z, /* Characters to treat as exceptions */
  194821. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  194822. ){
  194823. int rc = SQLITE_OK;
  194824. int n = (int)strlen(z);
  194825. int *aNew;
  194826. if( n>0 ){
  194827. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  194828. if( aNew ){
  194829. int nNew = p->nException;
  194830. const unsigned char *zCsr = (const unsigned char*)z;
  194831. const unsigned char *zTerm = (const unsigned char*)&z[n];
  194832. while( zCsr<zTerm ){
  194833. int iCode;
  194834. int bToken;
  194835. READ_UTF8(zCsr, zTerm, iCode);
  194836. if( iCode<128 ){
  194837. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  194838. }else{
  194839. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  194840. assert( (bToken==0 || bToken==1) );
  194841. assert( (bTokenChars==0 || bTokenChars==1) );
  194842. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  194843. int i;
  194844. for(i=0; i<nNew; i++){
  194845. if( aNew[i]>iCode ) break;
  194846. }
  194847. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  194848. aNew[i] = iCode;
  194849. nNew++;
  194850. }
  194851. }
  194852. }
  194853. p->aiException = aNew;
  194854. p->nException = nNew;
  194855. }else{
  194856. rc = SQLITE_NOMEM;
  194857. }
  194858. }
  194859. return rc;
  194860. }
  194861. /*
  194862. ** Return true if the p->aiException[] array contains the value iCode.
  194863. */
  194864. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  194865. if( p->nException>0 ){
  194866. int *a = p->aiException;
  194867. int iLo = 0;
  194868. int iHi = p->nException-1;
  194869. while( iHi>=iLo ){
  194870. int iTest = (iHi + iLo) / 2;
  194871. if( iCode==a[iTest] ){
  194872. return 1;
  194873. }else if( iCode>a[iTest] ){
  194874. iLo = iTest+1;
  194875. }else{
  194876. iHi = iTest-1;
  194877. }
  194878. }
  194879. }
  194880. return 0;
  194881. }
  194882. /*
  194883. ** Delete a "unicode61" tokenizer.
  194884. */
  194885. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  194886. if( pTok ){
  194887. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  194888. sqlite3_free(p->aiException);
  194889. sqlite3_free(p->aFold);
  194890. sqlite3_free(p);
  194891. }
  194892. return;
  194893. }
  194894. /*
  194895. ** Create a "unicode61" tokenizer.
  194896. */
  194897. static int fts5UnicodeCreate(
  194898. void *pUnused,
  194899. const char **azArg, int nArg,
  194900. Fts5Tokenizer **ppOut
  194901. ){
  194902. int rc = SQLITE_OK; /* Return code */
  194903. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  194904. UNUSED_PARAM(pUnused);
  194905. if( nArg%2 ){
  194906. rc = SQLITE_ERROR;
  194907. }else{
  194908. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  194909. if( p ){
  194910. int i;
  194911. memset(p, 0, sizeof(Unicode61Tokenizer));
  194912. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  194913. p->bRemoveDiacritic = 1;
  194914. p->nFold = 64;
  194915. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  194916. if( p->aFold==0 ){
  194917. rc = SQLITE_NOMEM;
  194918. }
  194919. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  194920. const char *zArg = azArg[i+1];
  194921. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  194922. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  194923. rc = SQLITE_ERROR;
  194924. }
  194925. p->bRemoveDiacritic = (zArg[0]=='1');
  194926. }else
  194927. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  194928. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  194929. }else
  194930. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  194931. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  194932. }else{
  194933. rc = SQLITE_ERROR;
  194934. }
  194935. }
  194936. }else{
  194937. rc = SQLITE_NOMEM;
  194938. }
  194939. if( rc!=SQLITE_OK ){
  194940. fts5UnicodeDelete((Fts5Tokenizer*)p);
  194941. p = 0;
  194942. }
  194943. *ppOut = (Fts5Tokenizer*)p;
  194944. }
  194945. return rc;
  194946. }
  194947. /*
  194948. ** Return true if, for the purposes of tokenizing with the tokenizer
  194949. ** passed as the first argument, codepoint iCode is considered a token
  194950. ** character (not a separator).
  194951. */
  194952. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  194953. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  194954. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  194955. }
  194956. static int fts5UnicodeTokenize(
  194957. Fts5Tokenizer *pTokenizer,
  194958. void *pCtx,
  194959. int iUnused,
  194960. const char *pText, int nText,
  194961. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  194962. ){
  194963. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  194964. int rc = SQLITE_OK;
  194965. unsigned char *a = p->aTokenChar;
  194966. unsigned char *zTerm = (unsigned char*)&pText[nText];
  194967. unsigned char *zCsr = (unsigned char *)pText;
  194968. /* Output buffer */
  194969. char *aFold = p->aFold;
  194970. int nFold = p->nFold;
  194971. const char *pEnd = &aFold[nFold-6];
  194972. UNUSED_PARAM(iUnused);
  194973. /* Each iteration of this loop gobbles up a contiguous run of separators,
  194974. ** then the next token. */
  194975. while( rc==SQLITE_OK ){
  194976. int iCode; /* non-ASCII codepoint read from input */
  194977. char *zOut = aFold;
  194978. int is;
  194979. int ie;
  194980. /* Skip any separator characters. */
  194981. while( 1 ){
  194982. if( zCsr>=zTerm ) goto tokenize_done;
  194983. if( *zCsr & 0x80 ) {
  194984. /* A character outside of the ascii range. Skip past it if it is
  194985. ** a separator character. Or break out of the loop if it is not. */
  194986. is = zCsr - (unsigned char*)pText;
  194987. READ_UTF8(zCsr, zTerm, iCode);
  194988. if( fts5UnicodeIsAlnum(p, iCode) ){
  194989. goto non_ascii_tokenchar;
  194990. }
  194991. }else{
  194992. if( a[*zCsr] ){
  194993. is = zCsr - (unsigned char*)pText;
  194994. goto ascii_tokenchar;
  194995. }
  194996. zCsr++;
  194997. }
  194998. }
  194999. /* Run through the tokenchars. Fold them into the output buffer along
  195000. ** the way. */
  195001. while( zCsr<zTerm ){
  195002. /* Grow the output buffer so that there is sufficient space to fit the
  195003. ** largest possible utf-8 character. */
  195004. if( zOut>pEnd ){
  195005. aFold = sqlite3_malloc(nFold*2);
  195006. if( aFold==0 ){
  195007. rc = SQLITE_NOMEM;
  195008. goto tokenize_done;
  195009. }
  195010. zOut = &aFold[zOut - p->aFold];
  195011. memcpy(aFold, p->aFold, nFold);
  195012. sqlite3_free(p->aFold);
  195013. p->aFold = aFold;
  195014. p->nFold = nFold = nFold*2;
  195015. pEnd = &aFold[nFold-6];
  195016. }
  195017. if( *zCsr & 0x80 ){
  195018. /* An non-ascii-range character. Fold it into the output buffer if
  195019. ** it is a token character, or break out of the loop if it is not. */
  195020. READ_UTF8(zCsr, zTerm, iCode);
  195021. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  195022. non_ascii_tokenchar:
  195023. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  195024. if( iCode ) WRITE_UTF8(zOut, iCode);
  195025. }else{
  195026. break;
  195027. }
  195028. }else if( a[*zCsr]==0 ){
  195029. /* An ascii-range separator character. End of token. */
  195030. break;
  195031. }else{
  195032. ascii_tokenchar:
  195033. if( *zCsr>='A' && *zCsr<='Z' ){
  195034. *zOut++ = *zCsr + 32;
  195035. }else{
  195036. *zOut++ = *zCsr;
  195037. }
  195038. zCsr++;
  195039. }
  195040. ie = zCsr - (unsigned char*)pText;
  195041. }
  195042. /* Invoke the token callback */
  195043. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  195044. }
  195045. tokenize_done:
  195046. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  195047. return rc;
  195048. }
  195049. /**************************************************************************
  195050. ** Start of porter stemmer implementation.
  195051. */
  195052. /* Any tokens larger than this (in bytes) are passed through without
  195053. ** stemming. */
  195054. #define FTS5_PORTER_MAX_TOKEN 64
  195055. typedef struct PorterTokenizer PorterTokenizer;
  195056. struct PorterTokenizer {
  195057. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  195058. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  195059. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  195060. };
  195061. /*
  195062. ** Delete a "porter" tokenizer.
  195063. */
  195064. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  195065. if( pTok ){
  195066. PorterTokenizer *p = (PorterTokenizer*)pTok;
  195067. if( p->pTokenizer ){
  195068. p->tokenizer.xDelete(p->pTokenizer);
  195069. }
  195070. sqlite3_free(p);
  195071. }
  195072. }
  195073. /*
  195074. ** Create a "porter" tokenizer.
  195075. */
  195076. static int fts5PorterCreate(
  195077. void *pCtx,
  195078. const char **azArg, int nArg,
  195079. Fts5Tokenizer **ppOut
  195080. ){
  195081. fts5_api *pApi = (fts5_api*)pCtx;
  195082. int rc = SQLITE_OK;
  195083. PorterTokenizer *pRet;
  195084. void *pUserdata = 0;
  195085. const char *zBase = "unicode61";
  195086. if( nArg>0 ){
  195087. zBase = azArg[0];
  195088. }
  195089. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  195090. if( pRet ){
  195091. memset(pRet, 0, sizeof(PorterTokenizer));
  195092. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  195093. }else{
  195094. rc = SQLITE_NOMEM;
  195095. }
  195096. if( rc==SQLITE_OK ){
  195097. int nArg2 = (nArg>0 ? nArg-1 : 0);
  195098. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  195099. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  195100. }
  195101. if( rc!=SQLITE_OK ){
  195102. fts5PorterDelete((Fts5Tokenizer*)pRet);
  195103. pRet = 0;
  195104. }
  195105. *ppOut = (Fts5Tokenizer*)pRet;
  195106. return rc;
  195107. }
  195108. typedef struct PorterContext PorterContext;
  195109. struct PorterContext {
  195110. void *pCtx;
  195111. int (*xToken)(void*, int, const char*, int, int, int);
  195112. char *aBuf;
  195113. };
  195114. typedef struct PorterRule PorterRule;
  195115. struct PorterRule {
  195116. const char *zSuffix;
  195117. int nSuffix;
  195118. int (*xCond)(char *zStem, int nStem);
  195119. const char *zOutput;
  195120. int nOutput;
  195121. };
  195122. #if 0
  195123. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  195124. int ret = -1;
  195125. int nBuf = *pnBuf;
  195126. PorterRule *p;
  195127. for(p=aRule; p->zSuffix; p++){
  195128. assert( strlen(p->zSuffix)==p->nSuffix );
  195129. assert( strlen(p->zOutput)==p->nOutput );
  195130. if( nBuf<p->nSuffix ) continue;
  195131. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  195132. }
  195133. if( p->zSuffix ){
  195134. int nStem = nBuf - p->nSuffix;
  195135. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  195136. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  195137. *pnBuf = nStem + p->nOutput;
  195138. ret = p - aRule;
  195139. }
  195140. }
  195141. return ret;
  195142. }
  195143. #endif
  195144. static int fts5PorterIsVowel(char c, int bYIsVowel){
  195145. return (
  195146. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  195147. );
  195148. }
  195149. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  195150. int i;
  195151. int bCons = bPrevCons;
  195152. /* Scan for a vowel */
  195153. for(i=0; i<nStem; i++){
  195154. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  195155. }
  195156. /* Scan for a consonent */
  195157. for(i++; i<nStem; i++){
  195158. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  195159. }
  195160. return 0;
  195161. }
  195162. /* porter rule condition: (m > 0) */
  195163. static int fts5Porter_MGt0(char *zStem, int nStem){
  195164. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  195165. }
  195166. /* porter rule condition: (m > 1) */
  195167. static int fts5Porter_MGt1(char *zStem, int nStem){
  195168. int n;
  195169. n = fts5PorterGobbleVC(zStem, nStem, 0);
  195170. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  195171. return 1;
  195172. }
  195173. return 0;
  195174. }
  195175. /* porter rule condition: (m = 1) */
  195176. static int fts5Porter_MEq1(char *zStem, int nStem){
  195177. int n;
  195178. n = fts5PorterGobbleVC(zStem, nStem, 0);
  195179. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  195180. return 1;
  195181. }
  195182. return 0;
  195183. }
  195184. /* porter rule condition: (*o) */
  195185. static int fts5Porter_Ostar(char *zStem, int nStem){
  195186. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  195187. return 0;
  195188. }else{
  195189. int i;
  195190. int mask = 0;
  195191. int bCons = 0;
  195192. for(i=0; i<nStem; i++){
  195193. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  195194. assert( bCons==0 || bCons==1 );
  195195. mask = (mask << 1) + bCons;
  195196. }
  195197. return ((mask & 0x0007)==0x0005);
  195198. }
  195199. }
  195200. /* porter rule condition: (m > 1 and (*S or *T)) */
  195201. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  195202. assert( nStem>0 );
  195203. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  195204. && fts5Porter_MGt1(zStem, nStem);
  195205. }
  195206. /* porter rule condition: (*v*) */
  195207. static int fts5Porter_Vowel(char *zStem, int nStem){
  195208. int i;
  195209. for(i=0; i<nStem; i++){
  195210. if( fts5PorterIsVowel(zStem[i], i>0) ){
  195211. return 1;
  195212. }
  195213. }
  195214. return 0;
  195215. }
  195216. /**************************************************************************
  195217. ***************************************************************************
  195218. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  195219. */
  195220. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  195221. int ret = 0;
  195222. int nBuf = *pnBuf;
  195223. switch( aBuf[nBuf-2] ){
  195224. case 'a':
  195225. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  195226. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  195227. *pnBuf = nBuf - 2;
  195228. }
  195229. }
  195230. break;
  195231. case 'c':
  195232. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  195233. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  195234. *pnBuf = nBuf - 4;
  195235. }
  195236. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  195237. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  195238. *pnBuf = nBuf - 4;
  195239. }
  195240. }
  195241. break;
  195242. case 'e':
  195243. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  195244. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  195245. *pnBuf = nBuf - 2;
  195246. }
  195247. }
  195248. break;
  195249. case 'i':
  195250. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  195251. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  195252. *pnBuf = nBuf - 2;
  195253. }
  195254. }
  195255. break;
  195256. case 'l':
  195257. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  195258. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  195259. *pnBuf = nBuf - 4;
  195260. }
  195261. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  195262. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  195263. *pnBuf = nBuf - 4;
  195264. }
  195265. }
  195266. break;
  195267. case 'n':
  195268. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  195269. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195270. *pnBuf = nBuf - 3;
  195271. }
  195272. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  195273. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  195274. *pnBuf = nBuf - 5;
  195275. }
  195276. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  195277. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  195278. *pnBuf = nBuf - 4;
  195279. }
  195280. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  195281. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195282. *pnBuf = nBuf - 3;
  195283. }
  195284. }
  195285. break;
  195286. case 'o':
  195287. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  195288. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  195289. *pnBuf = nBuf - 3;
  195290. }
  195291. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  195292. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  195293. *pnBuf = nBuf - 2;
  195294. }
  195295. }
  195296. break;
  195297. case 's':
  195298. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  195299. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195300. *pnBuf = nBuf - 3;
  195301. }
  195302. }
  195303. break;
  195304. case 't':
  195305. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  195306. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195307. *pnBuf = nBuf - 3;
  195308. }
  195309. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  195310. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195311. *pnBuf = nBuf - 3;
  195312. }
  195313. }
  195314. break;
  195315. case 'u':
  195316. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  195317. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195318. *pnBuf = nBuf - 3;
  195319. }
  195320. }
  195321. break;
  195322. case 'v':
  195323. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  195324. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195325. *pnBuf = nBuf - 3;
  195326. }
  195327. }
  195328. break;
  195329. case 'z':
  195330. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  195331. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  195332. *pnBuf = nBuf - 3;
  195333. }
  195334. }
  195335. break;
  195336. }
  195337. return ret;
  195338. }
  195339. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  195340. int ret = 0;
  195341. int nBuf = *pnBuf;
  195342. switch( aBuf[nBuf-2] ){
  195343. case 'a':
  195344. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  195345. memcpy(&aBuf[nBuf-2], "ate", 3);
  195346. *pnBuf = nBuf - 2 + 3;
  195347. ret = 1;
  195348. }
  195349. break;
  195350. case 'b':
  195351. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  195352. memcpy(&aBuf[nBuf-2], "ble", 3);
  195353. *pnBuf = nBuf - 2 + 3;
  195354. ret = 1;
  195355. }
  195356. break;
  195357. case 'i':
  195358. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  195359. memcpy(&aBuf[nBuf-2], "ize", 3);
  195360. *pnBuf = nBuf - 2 + 3;
  195361. ret = 1;
  195362. }
  195363. break;
  195364. }
  195365. return ret;
  195366. }
  195367. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  195368. int ret = 0;
  195369. int nBuf = *pnBuf;
  195370. switch( aBuf[nBuf-2] ){
  195371. case 'a':
  195372. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  195373. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  195374. memcpy(&aBuf[nBuf-7], "ate", 3);
  195375. *pnBuf = nBuf - 7 + 3;
  195376. }
  195377. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  195378. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  195379. memcpy(&aBuf[nBuf-6], "tion", 4);
  195380. *pnBuf = nBuf - 6 + 4;
  195381. }
  195382. }
  195383. break;
  195384. case 'c':
  195385. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  195386. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195387. memcpy(&aBuf[nBuf-4], "ence", 4);
  195388. *pnBuf = nBuf - 4 + 4;
  195389. }
  195390. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  195391. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195392. memcpy(&aBuf[nBuf-4], "ance", 4);
  195393. *pnBuf = nBuf - 4 + 4;
  195394. }
  195395. }
  195396. break;
  195397. case 'e':
  195398. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  195399. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195400. memcpy(&aBuf[nBuf-4], "ize", 3);
  195401. *pnBuf = nBuf - 4 + 3;
  195402. }
  195403. }
  195404. break;
  195405. case 'g':
  195406. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  195407. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195408. memcpy(&aBuf[nBuf-4], "log", 3);
  195409. *pnBuf = nBuf - 4 + 3;
  195410. }
  195411. }
  195412. break;
  195413. case 'l':
  195414. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  195415. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  195416. memcpy(&aBuf[nBuf-3], "ble", 3);
  195417. *pnBuf = nBuf - 3 + 3;
  195418. }
  195419. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  195420. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195421. memcpy(&aBuf[nBuf-4], "al", 2);
  195422. *pnBuf = nBuf - 4 + 2;
  195423. }
  195424. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  195425. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195426. memcpy(&aBuf[nBuf-5], "ent", 3);
  195427. *pnBuf = nBuf - 5 + 3;
  195428. }
  195429. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  195430. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  195431. memcpy(&aBuf[nBuf-3], "e", 1);
  195432. *pnBuf = nBuf - 3 + 1;
  195433. }
  195434. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  195435. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195436. memcpy(&aBuf[nBuf-5], "ous", 3);
  195437. *pnBuf = nBuf - 5 + 3;
  195438. }
  195439. }
  195440. break;
  195441. case 'o':
  195442. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  195443. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  195444. memcpy(&aBuf[nBuf-7], "ize", 3);
  195445. *pnBuf = nBuf - 7 + 3;
  195446. }
  195447. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  195448. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195449. memcpy(&aBuf[nBuf-5], "ate", 3);
  195450. *pnBuf = nBuf - 5 + 3;
  195451. }
  195452. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  195453. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195454. memcpy(&aBuf[nBuf-4], "ate", 3);
  195455. *pnBuf = nBuf - 4 + 3;
  195456. }
  195457. }
  195458. break;
  195459. case 's':
  195460. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  195461. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195462. memcpy(&aBuf[nBuf-5], "al", 2);
  195463. *pnBuf = nBuf - 5 + 2;
  195464. }
  195465. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  195466. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  195467. memcpy(&aBuf[nBuf-7], "ive", 3);
  195468. *pnBuf = nBuf - 7 + 3;
  195469. }
  195470. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  195471. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  195472. memcpy(&aBuf[nBuf-7], "ful", 3);
  195473. *pnBuf = nBuf - 7 + 3;
  195474. }
  195475. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  195476. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  195477. memcpy(&aBuf[nBuf-7], "ous", 3);
  195478. *pnBuf = nBuf - 7 + 3;
  195479. }
  195480. }
  195481. break;
  195482. case 't':
  195483. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  195484. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195485. memcpy(&aBuf[nBuf-5], "al", 2);
  195486. *pnBuf = nBuf - 5 + 2;
  195487. }
  195488. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  195489. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195490. memcpy(&aBuf[nBuf-5], "ive", 3);
  195491. *pnBuf = nBuf - 5 + 3;
  195492. }
  195493. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  195494. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  195495. memcpy(&aBuf[nBuf-6], "ble", 3);
  195496. *pnBuf = nBuf - 6 + 3;
  195497. }
  195498. }
  195499. break;
  195500. }
  195501. return ret;
  195502. }
  195503. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  195504. int ret = 0;
  195505. int nBuf = *pnBuf;
  195506. switch( aBuf[nBuf-2] ){
  195507. case 'a':
  195508. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  195509. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195510. memcpy(&aBuf[nBuf-4], "ic", 2);
  195511. *pnBuf = nBuf - 4 + 2;
  195512. }
  195513. }
  195514. break;
  195515. case 's':
  195516. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  195517. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  195518. *pnBuf = nBuf - 4;
  195519. }
  195520. }
  195521. break;
  195522. case 't':
  195523. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  195524. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195525. memcpy(&aBuf[nBuf-5], "ic", 2);
  195526. *pnBuf = nBuf - 5 + 2;
  195527. }
  195528. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  195529. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195530. memcpy(&aBuf[nBuf-5], "ic", 2);
  195531. *pnBuf = nBuf - 5 + 2;
  195532. }
  195533. }
  195534. break;
  195535. case 'u':
  195536. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  195537. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  195538. *pnBuf = nBuf - 3;
  195539. }
  195540. }
  195541. break;
  195542. case 'v':
  195543. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  195544. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195545. *pnBuf = nBuf - 5;
  195546. }
  195547. }
  195548. break;
  195549. case 'z':
  195550. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  195551. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  195552. memcpy(&aBuf[nBuf-5], "al", 2);
  195553. *pnBuf = nBuf - 5 + 2;
  195554. }
  195555. }
  195556. break;
  195557. }
  195558. return ret;
  195559. }
  195560. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  195561. int ret = 0;
  195562. int nBuf = *pnBuf;
  195563. switch( aBuf[nBuf-2] ){
  195564. case 'e':
  195565. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  195566. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  195567. memcpy(&aBuf[nBuf-3], "ee", 2);
  195568. *pnBuf = nBuf - 3 + 2;
  195569. }
  195570. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  195571. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  195572. *pnBuf = nBuf - 2;
  195573. ret = 1;
  195574. }
  195575. }
  195576. break;
  195577. case 'n':
  195578. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  195579. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  195580. *pnBuf = nBuf - 3;
  195581. ret = 1;
  195582. }
  195583. }
  195584. break;
  195585. }
  195586. return ret;
  195587. }
  195588. /*
  195589. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  195590. ***************************************************************************
  195591. **************************************************************************/
  195592. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  195593. int nBuf = *pnBuf;
  195594. if( aBuf[nBuf-1]=='s' ){
  195595. if( aBuf[nBuf-2]=='e' ){
  195596. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  195597. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  195598. ){
  195599. *pnBuf = nBuf-2;
  195600. }else{
  195601. *pnBuf = nBuf-1;
  195602. }
  195603. }
  195604. else if( aBuf[nBuf-2]!='s' ){
  195605. *pnBuf = nBuf-1;
  195606. }
  195607. }
  195608. }
  195609. static int fts5PorterCb(
  195610. void *pCtx,
  195611. int tflags,
  195612. const char *pToken,
  195613. int nToken,
  195614. int iStart,
  195615. int iEnd
  195616. ){
  195617. PorterContext *p = (PorterContext*)pCtx;
  195618. char *aBuf;
  195619. int nBuf;
  195620. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  195621. aBuf = p->aBuf;
  195622. nBuf = nToken;
  195623. memcpy(aBuf, pToken, nBuf);
  195624. /* Step 1. */
  195625. fts5PorterStep1A(aBuf, &nBuf);
  195626. if( fts5PorterStep1B(aBuf, &nBuf) ){
  195627. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  195628. char c = aBuf[nBuf-1];
  195629. if( fts5PorterIsVowel(c, 0)==0
  195630. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  195631. ){
  195632. nBuf--;
  195633. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  195634. aBuf[nBuf++] = 'e';
  195635. }
  195636. }
  195637. }
  195638. /* Step 1C. */
  195639. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  195640. aBuf[nBuf-1] = 'i';
  195641. }
  195642. /* Steps 2 through 4. */
  195643. fts5PorterStep2(aBuf, &nBuf);
  195644. fts5PorterStep3(aBuf, &nBuf);
  195645. fts5PorterStep4(aBuf, &nBuf);
  195646. /* Step 5a. */
  195647. assert( nBuf>0 );
  195648. if( aBuf[nBuf-1]=='e' ){
  195649. if( fts5Porter_MGt1(aBuf, nBuf-1)
  195650. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  195651. ){
  195652. nBuf--;
  195653. }
  195654. }
  195655. /* Step 5b. */
  195656. if( nBuf>1 && aBuf[nBuf-1]=='l'
  195657. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  195658. ){
  195659. nBuf--;
  195660. }
  195661. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  195662. pass_through:
  195663. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  195664. }
  195665. /*
  195666. ** Tokenize using the porter tokenizer.
  195667. */
  195668. static int fts5PorterTokenize(
  195669. Fts5Tokenizer *pTokenizer,
  195670. void *pCtx,
  195671. int flags,
  195672. const char *pText, int nText,
  195673. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  195674. ){
  195675. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  195676. PorterContext sCtx;
  195677. sCtx.xToken = xToken;
  195678. sCtx.pCtx = pCtx;
  195679. sCtx.aBuf = p->aBuf;
  195680. return p->tokenizer.xTokenize(
  195681. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  195682. );
  195683. }
  195684. /*
  195685. ** Register all built-in tokenizers with FTS5.
  195686. */
  195687. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  195688. struct BuiltinTokenizer {
  195689. const char *zName;
  195690. fts5_tokenizer x;
  195691. } aBuiltin[] = {
  195692. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  195693. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  195694. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  195695. };
  195696. int rc = SQLITE_OK; /* Return code */
  195697. int i; /* To iterate through builtin functions */
  195698. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  195699. rc = pApi->xCreateTokenizer(pApi,
  195700. aBuiltin[i].zName,
  195701. (void*)pApi,
  195702. &aBuiltin[i].x,
  195703. 0
  195704. );
  195705. }
  195706. return rc;
  195707. }
  195708. /*
  195709. ** 2012 May 25
  195710. **
  195711. ** The author disclaims copyright to this source code. In place of
  195712. ** a legal notice, here is a blessing:
  195713. **
  195714. ** May you do good and not evil.
  195715. ** May you find forgiveness for yourself and forgive others.
  195716. ** May you share freely, never taking more than you give.
  195717. **
  195718. ******************************************************************************
  195719. */
  195720. /*
  195721. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  195722. */
  195723. /* #include <assert.h> */
  195724. /*
  195725. ** Return true if the argument corresponds to a unicode codepoint
  195726. ** classified as either a letter or a number. Otherwise false.
  195727. **
  195728. ** The results are undefined if the value passed to this function
  195729. ** is less than zero.
  195730. */
  195731. static int sqlite3Fts5UnicodeIsalnum(int c){
  195732. /* Each unsigned integer in the following array corresponds to a contiguous
  195733. ** range of unicode codepoints that are not either letters or numbers (i.e.
  195734. ** codepoints for which this function should return 0).
  195735. **
  195736. ** The most significant 22 bits in each 32-bit value contain the first
  195737. ** codepoint in the range. The least significant 10 bits are used to store
  195738. ** the size of the range (always at least 1). In other words, the value
  195739. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  195740. ** C. It is not possible to represent a range larger than 1023 codepoints
  195741. ** using this format.
  195742. */
  195743. static const unsigned int aEntry[] = {
  195744. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  195745. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  195746. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  195747. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  195748. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  195749. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  195750. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  195751. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  195752. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  195753. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  195754. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  195755. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  195756. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  195757. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  195758. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  195759. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  195760. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  195761. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  195762. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  195763. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  195764. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  195765. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  195766. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  195767. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  195768. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  195769. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  195770. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  195771. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  195772. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  195773. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  195774. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  195775. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  195776. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  195777. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  195778. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  195779. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  195780. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  195781. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  195782. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  195783. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  195784. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  195785. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  195786. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  195787. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  195788. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  195789. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  195790. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  195791. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  195792. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  195793. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  195794. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  195795. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  195796. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  195797. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  195798. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  195799. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  195800. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  195801. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  195802. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  195803. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  195804. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  195805. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  195806. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  195807. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  195808. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  195809. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  195810. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  195811. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  195812. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  195813. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  195814. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  195815. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  195816. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  195817. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  195818. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  195819. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  195820. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  195821. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  195822. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  195823. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  195824. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  195825. 0x380400F0,
  195826. };
  195827. static const unsigned int aAscii[4] = {
  195828. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  195829. };
  195830. if( (unsigned int)c<128 ){
  195831. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  195832. }else if( (unsigned int)c<(1<<22) ){
  195833. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  195834. int iRes = 0;
  195835. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  195836. int iLo = 0;
  195837. while( iHi>=iLo ){
  195838. int iTest = (iHi + iLo) / 2;
  195839. if( key >= aEntry[iTest] ){
  195840. iRes = iTest;
  195841. iLo = iTest+1;
  195842. }else{
  195843. iHi = iTest-1;
  195844. }
  195845. }
  195846. assert( aEntry[0]<key );
  195847. assert( key>=aEntry[iRes] );
  195848. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  195849. }
  195850. return 1;
  195851. }
  195852. /*
  195853. ** If the argument is a codepoint corresponding to a lowercase letter
  195854. ** in the ASCII range with a diacritic added, return the codepoint
  195855. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  195856. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  195857. ** E"). The resuls of passing a codepoint that corresponds to an
  195858. ** uppercase letter are undefined.
  195859. */
  195860. static int fts5_remove_diacritic(int c){
  195861. unsigned short aDia[] = {
  195862. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  195863. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  195864. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  195865. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  195866. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  195867. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  195868. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  195869. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  195870. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  195871. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  195872. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  195873. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  195874. 62924, 63050, 63082, 63274, 63390,
  195875. };
  195876. char aChar[] = {
  195877. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  195878. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  195879. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  195880. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  195881. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  195882. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  195883. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  195884. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  195885. 'e', 'i', 'o', 'u', 'y',
  195886. };
  195887. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  195888. int iRes = 0;
  195889. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  195890. int iLo = 0;
  195891. while( iHi>=iLo ){
  195892. int iTest = (iHi + iLo) / 2;
  195893. if( key >= aDia[iTest] ){
  195894. iRes = iTest;
  195895. iLo = iTest+1;
  195896. }else{
  195897. iHi = iTest-1;
  195898. }
  195899. }
  195900. assert( key>=aDia[iRes] );
  195901. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  195902. }
  195903. /*
  195904. ** Return true if the argument interpreted as a unicode codepoint
  195905. ** is a diacritical modifier character.
  195906. */
  195907. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  195908. unsigned int mask0 = 0x08029FDF;
  195909. unsigned int mask1 = 0x000361F8;
  195910. if( c<768 || c>817 ) return 0;
  195911. return (c < 768+32) ?
  195912. (mask0 & (1 << (c-768))) :
  195913. (mask1 & (1 << (c-768-32)));
  195914. }
  195915. /*
  195916. ** Interpret the argument as a unicode codepoint. If the codepoint
  195917. ** is an upper case character that has a lower case equivalent,
  195918. ** return the codepoint corresponding to the lower case version.
  195919. ** Otherwise, return a copy of the argument.
  195920. **
  195921. ** The results are undefined if the value passed to this function
  195922. ** is less than zero.
  195923. */
  195924. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  195925. /* Each entry in the following array defines a rule for folding a range
  195926. ** of codepoints to lower case. The rule applies to a range of nRange
  195927. ** codepoints starting at codepoint iCode.
  195928. **
  195929. ** If the least significant bit in flags is clear, then the rule applies
  195930. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  195931. ** need to be folded). Or, if it is set, then the rule only applies to
  195932. ** every second codepoint in the range, starting with codepoint C.
  195933. **
  195934. ** The 7 most significant bits in flags are an index into the aiOff[]
  195935. ** array. If a specific codepoint C does require folding, then its lower
  195936. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  195937. **
  195938. ** The contents of this array are generated by parsing the CaseFolding.txt
  195939. ** file distributed as part of the "Unicode Character Database". See
  195940. ** http://www.unicode.org for details.
  195941. */
  195942. static const struct TableEntry {
  195943. unsigned short iCode;
  195944. unsigned char flags;
  195945. unsigned char nRange;
  195946. } aEntry[] = {
  195947. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  195948. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  195949. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  195950. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  195951. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  195952. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  195953. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  195954. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  195955. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  195956. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  195957. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  195958. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  195959. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  195960. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  195961. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  195962. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  195963. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  195964. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  195965. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  195966. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  195967. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  195968. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  195969. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  195970. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  195971. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  195972. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  195973. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  195974. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  195975. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  195976. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  195977. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  195978. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  195979. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  195980. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  195981. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  195982. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  195983. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  195984. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  195985. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  195986. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  195987. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  195988. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  195989. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  195990. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  195991. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  195992. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  195993. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  195994. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  195995. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  195996. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  195997. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  195998. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  195999. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  196000. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  196001. {65313, 14, 26},
  196002. };
  196003. static const unsigned short aiOff[] = {
  196004. 1, 2, 8, 15, 16, 26, 28, 32,
  196005. 37, 38, 40, 48, 63, 64, 69, 71,
  196006. 79, 80, 116, 202, 203, 205, 206, 207,
  196007. 209, 210, 211, 213, 214, 217, 218, 219,
  196008. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  196009. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  196010. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  196011. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  196012. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  196013. 65514, 65521, 65527, 65528, 65529,
  196014. };
  196015. int ret = c;
  196016. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  196017. if( c<128 ){
  196018. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  196019. }else if( c<65536 ){
  196020. const struct TableEntry *p;
  196021. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  196022. int iLo = 0;
  196023. int iRes = -1;
  196024. assert( c>aEntry[0].iCode );
  196025. while( iHi>=iLo ){
  196026. int iTest = (iHi + iLo) / 2;
  196027. int cmp = (c - aEntry[iTest].iCode);
  196028. if( cmp>=0 ){
  196029. iRes = iTest;
  196030. iLo = iTest+1;
  196031. }else{
  196032. iHi = iTest-1;
  196033. }
  196034. }
  196035. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  196036. p = &aEntry[iRes];
  196037. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  196038. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  196039. assert( ret>0 );
  196040. }
  196041. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  196042. }
  196043. else if( c>=66560 && c<66600 ){
  196044. ret = c + 40;
  196045. }
  196046. return ret;
  196047. }
  196048. /*
  196049. ** 2015 May 30
  196050. **
  196051. ** The author disclaims copyright to this source code. In place of
  196052. ** a legal notice, here is a blessing:
  196053. **
  196054. ** May you do good and not evil.
  196055. ** May you find forgiveness for yourself and forgive others.
  196056. ** May you share freely, never taking more than you give.
  196057. **
  196058. ******************************************************************************
  196059. **
  196060. ** Routines for varint serialization and deserialization.
  196061. */
  196062. /* #include "fts5Int.h" */
  196063. /*
  196064. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  196065. ** Except, this version does handle the single byte case that the core
  196066. ** version depends on being handled before its function is called.
  196067. */
  196068. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  196069. u32 a,b;
  196070. /* The 1-byte case. Overwhelmingly the most common. */
  196071. a = *p;
  196072. /* a: p0 (unmasked) */
  196073. if (!(a&0x80))
  196074. {
  196075. /* Values between 0 and 127 */
  196076. *v = a;
  196077. return 1;
  196078. }
  196079. /* The 2-byte case */
  196080. p++;
  196081. b = *p;
  196082. /* b: p1 (unmasked) */
  196083. if (!(b&0x80))
  196084. {
  196085. /* Values between 128 and 16383 */
  196086. a &= 0x7f;
  196087. a = a<<7;
  196088. *v = a | b;
  196089. return 2;
  196090. }
  196091. /* The 3-byte case */
  196092. p++;
  196093. a = a<<14;
  196094. a |= *p;
  196095. /* a: p0<<14 | p2 (unmasked) */
  196096. if (!(a&0x80))
  196097. {
  196098. /* Values between 16384 and 2097151 */
  196099. a &= (0x7f<<14)|(0x7f);
  196100. b &= 0x7f;
  196101. b = b<<7;
  196102. *v = a | b;
  196103. return 3;
  196104. }
  196105. /* A 32-bit varint is used to store size information in btrees.
  196106. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  196107. ** A 3-byte varint is sufficient, for example, to record the size
  196108. ** of a 1048569-byte BLOB or string.
  196109. **
  196110. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  196111. ** rare larger cases can be handled by the slower 64-bit varint
  196112. ** routine.
  196113. */
  196114. {
  196115. u64 v64;
  196116. u8 n;
  196117. p -= 2;
  196118. n = sqlite3Fts5GetVarint(p, &v64);
  196119. *v = (u32)v64;
  196120. assert( n>3 && n<=9 );
  196121. return n;
  196122. }
  196123. }
  196124. /*
  196125. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  196126. ** are defined here rather than simply putting the constant expressions
  196127. ** inline in order to work around bugs in the RVT compiler.
  196128. **
  196129. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  196130. **
  196131. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  196132. */
  196133. #define SLOT_2_0 0x001fc07f
  196134. #define SLOT_4_2_0 0xf01fc07f
  196135. /*
  196136. ** Read a 64-bit variable-length integer from memory starting at p[0].
  196137. ** Return the number of bytes read. The value is stored in *v.
  196138. */
  196139. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  196140. u32 a,b,s;
  196141. a = *p;
  196142. /* a: p0 (unmasked) */
  196143. if (!(a&0x80))
  196144. {
  196145. *v = a;
  196146. return 1;
  196147. }
  196148. p++;
  196149. b = *p;
  196150. /* b: p1 (unmasked) */
  196151. if (!(b&0x80))
  196152. {
  196153. a &= 0x7f;
  196154. a = a<<7;
  196155. a |= b;
  196156. *v = a;
  196157. return 2;
  196158. }
  196159. /* Verify that constants are precomputed correctly */
  196160. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  196161. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  196162. p++;
  196163. a = a<<14;
  196164. a |= *p;
  196165. /* a: p0<<14 | p2 (unmasked) */
  196166. if (!(a&0x80))
  196167. {
  196168. a &= SLOT_2_0;
  196169. b &= 0x7f;
  196170. b = b<<7;
  196171. a |= b;
  196172. *v = a;
  196173. return 3;
  196174. }
  196175. /* CSE1 from below */
  196176. a &= SLOT_2_0;
  196177. p++;
  196178. b = b<<14;
  196179. b |= *p;
  196180. /* b: p1<<14 | p3 (unmasked) */
  196181. if (!(b&0x80))
  196182. {
  196183. b &= SLOT_2_0;
  196184. /* moved CSE1 up */
  196185. /* a &= (0x7f<<14)|(0x7f); */
  196186. a = a<<7;
  196187. a |= b;
  196188. *v = a;
  196189. return 4;
  196190. }
  196191. /* a: p0<<14 | p2 (masked) */
  196192. /* b: p1<<14 | p3 (unmasked) */
  196193. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  196194. /* moved CSE1 up */
  196195. /* a &= (0x7f<<14)|(0x7f); */
  196196. b &= SLOT_2_0;
  196197. s = a;
  196198. /* s: p0<<14 | p2 (masked) */
  196199. p++;
  196200. a = a<<14;
  196201. a |= *p;
  196202. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  196203. if (!(a&0x80))
  196204. {
  196205. /* we can skip these cause they were (effectively) done above in calc'ing s */
  196206. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  196207. /* b &= (0x7f<<14)|(0x7f); */
  196208. b = b<<7;
  196209. a |= b;
  196210. s = s>>18;
  196211. *v = ((u64)s)<<32 | a;
  196212. return 5;
  196213. }
  196214. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  196215. s = s<<7;
  196216. s |= b;
  196217. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  196218. p++;
  196219. b = b<<14;
  196220. b |= *p;
  196221. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  196222. if (!(b&0x80))
  196223. {
  196224. /* we can skip this cause it was (effectively) done above in calc'ing s */
  196225. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  196226. a &= SLOT_2_0;
  196227. a = a<<7;
  196228. a |= b;
  196229. s = s>>18;
  196230. *v = ((u64)s)<<32 | a;
  196231. return 6;
  196232. }
  196233. p++;
  196234. a = a<<14;
  196235. a |= *p;
  196236. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  196237. if (!(a&0x80))
  196238. {
  196239. a &= SLOT_4_2_0;
  196240. b &= SLOT_2_0;
  196241. b = b<<7;
  196242. a |= b;
  196243. s = s>>11;
  196244. *v = ((u64)s)<<32 | a;
  196245. return 7;
  196246. }
  196247. /* CSE2 from below */
  196248. a &= SLOT_2_0;
  196249. p++;
  196250. b = b<<14;
  196251. b |= *p;
  196252. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  196253. if (!(b&0x80))
  196254. {
  196255. b &= SLOT_4_2_0;
  196256. /* moved CSE2 up */
  196257. /* a &= (0x7f<<14)|(0x7f); */
  196258. a = a<<7;
  196259. a |= b;
  196260. s = s>>4;
  196261. *v = ((u64)s)<<32 | a;
  196262. return 8;
  196263. }
  196264. p++;
  196265. a = a<<15;
  196266. a |= *p;
  196267. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  196268. /* moved CSE2 up */
  196269. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  196270. b &= SLOT_2_0;
  196271. b = b<<8;
  196272. a |= b;
  196273. s = s<<4;
  196274. b = p[-4];
  196275. b &= 0x7f;
  196276. b = b>>3;
  196277. s |= b;
  196278. *v = ((u64)s)<<32 | a;
  196279. return 9;
  196280. }
  196281. /*
  196282. ** The variable-length integer encoding is as follows:
  196283. **
  196284. ** KEY:
  196285. ** A = 0xxxxxxx 7 bits of data and one flag bit
  196286. ** B = 1xxxxxxx 7 bits of data and one flag bit
  196287. ** C = xxxxxxxx 8 bits of data
  196288. **
  196289. ** 7 bits - A
  196290. ** 14 bits - BA
  196291. ** 21 bits - BBA
  196292. ** 28 bits - BBBA
  196293. ** 35 bits - BBBBA
  196294. ** 42 bits - BBBBBA
  196295. ** 49 bits - BBBBBBA
  196296. ** 56 bits - BBBBBBBA
  196297. ** 64 bits - BBBBBBBBC
  196298. */
  196299. #ifdef SQLITE_NOINLINE
  196300. # define FTS5_NOINLINE SQLITE_NOINLINE
  196301. #else
  196302. # define FTS5_NOINLINE
  196303. #endif
  196304. /*
  196305. ** Write a 64-bit variable-length integer to memory starting at p[0].
  196306. ** The length of data write will be between 1 and 9 bytes. The number
  196307. ** of bytes written is returned.
  196308. **
  196309. ** A variable-length integer consists of the lower 7 bits of each byte
  196310. ** for all bytes that have the 8th bit set and one byte with the 8th
  196311. ** bit clear. Except, if we get to the 9th byte, it stores the full
  196312. ** 8 bits and is the last byte.
  196313. */
  196314. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  196315. int i, j, n;
  196316. u8 buf[10];
  196317. if( v & (((u64)0xff000000)<<32) ){
  196318. p[8] = (u8)v;
  196319. v >>= 8;
  196320. for(i=7; i>=0; i--){
  196321. p[i] = (u8)((v & 0x7f) | 0x80);
  196322. v >>= 7;
  196323. }
  196324. return 9;
  196325. }
  196326. n = 0;
  196327. do{
  196328. buf[n++] = (u8)((v & 0x7f) | 0x80);
  196329. v >>= 7;
  196330. }while( v!=0 );
  196331. buf[0] &= 0x7f;
  196332. assert( n<=9 );
  196333. for(i=0, j=n-1; j>=0; j--, i++){
  196334. p[i] = buf[j];
  196335. }
  196336. return n;
  196337. }
  196338. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  196339. if( v<=0x7f ){
  196340. p[0] = v&0x7f;
  196341. return 1;
  196342. }
  196343. if( v<=0x3fff ){
  196344. p[0] = ((v>>7)&0x7f)|0x80;
  196345. p[1] = v&0x7f;
  196346. return 2;
  196347. }
  196348. return fts5PutVarint64(p,v);
  196349. }
  196350. static int sqlite3Fts5GetVarintLen(u32 iVal){
  196351. #if 0
  196352. if( iVal<(1 << 7 ) ) return 1;
  196353. #endif
  196354. assert( iVal>=(1 << 7) );
  196355. if( iVal<(1 << 14) ) return 2;
  196356. if( iVal<(1 << 21) ) return 3;
  196357. if( iVal<(1 << 28) ) return 4;
  196358. return 5;
  196359. }
  196360. /*
  196361. ** 2015 May 08
  196362. **
  196363. ** The author disclaims copyright to this source code. In place of
  196364. ** a legal notice, here is a blessing:
  196365. **
  196366. ** May you do good and not evil.
  196367. ** May you find forgiveness for yourself and forgive others.
  196368. ** May you share freely, never taking more than you give.
  196369. **
  196370. ******************************************************************************
  196371. **
  196372. ** This is an SQLite virtual table module implementing direct access to an
  196373. ** existing FTS5 index. The module may create several different types of
  196374. ** tables:
  196375. **
  196376. ** col:
  196377. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  196378. **
  196379. ** One row for each term/column combination. The value of $doc is set to
  196380. ** the number of fts5 rows that contain at least one instance of term
  196381. ** $term within column $col. Field $cnt is set to the total number of
  196382. ** instances of term $term in column $col (in any row of the fts5 table).
  196383. **
  196384. ** row:
  196385. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  196386. **
  196387. ** One row for each term in the database. The value of $doc is set to
  196388. ** the number of fts5 rows that contain at least one instance of term
  196389. ** $term. Field $cnt is set to the total number of instances of term
  196390. ** $term in the database.
  196391. **
  196392. ** instance:
  196393. ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
  196394. **
  196395. ** One row for each term instance in the database.
  196396. */
  196397. /* #include "fts5Int.h" */
  196398. typedef struct Fts5VocabTable Fts5VocabTable;
  196399. typedef struct Fts5VocabCursor Fts5VocabCursor;
  196400. struct Fts5VocabTable {
  196401. sqlite3_vtab base;
  196402. char *zFts5Tbl; /* Name of fts5 table */
  196403. char *zFts5Db; /* Db containing fts5 table */
  196404. sqlite3 *db; /* Database handle */
  196405. Fts5Global *pGlobal; /* FTS5 global object for this database */
  196406. int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
  196407. };
  196408. struct Fts5VocabCursor {
  196409. sqlite3_vtab_cursor base;
  196410. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  196411. Fts5Index *pIndex; /* Associated FTS5 index */
  196412. int bEof; /* True if this cursor is at EOF */
  196413. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  196414. int nLeTerm; /* Size of zLeTerm in bytes */
  196415. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  196416. /* These are used by 'col' tables only */
  196417. Fts5Config *pConfig; /* Fts5 table configuration */
  196418. int iCol;
  196419. i64 *aCnt;
  196420. i64 *aDoc;
  196421. /* Output values used by all tables. */
  196422. i64 rowid; /* This table's current rowid value */
  196423. Fts5Buffer term; /* Current value of 'term' column */
  196424. /* Output values Used by 'instance' tables only */
  196425. i64 iInstPos;
  196426. int iInstOff;
  196427. };
  196428. #define FTS5_VOCAB_COL 0
  196429. #define FTS5_VOCAB_ROW 1
  196430. #define FTS5_VOCAB_INSTANCE 2
  196431. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  196432. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  196433. #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
  196434. /*
  196435. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  196436. */
  196437. #define FTS5_VOCAB_TERM_EQ 0x01
  196438. #define FTS5_VOCAB_TERM_GE 0x02
  196439. #define FTS5_VOCAB_TERM_LE 0x04
  196440. /*
  196441. ** Translate a string containing an fts5vocab table type to an
  196442. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  196443. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  196444. ** and return SQLITE_ERROR.
  196445. */
  196446. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  196447. int rc = SQLITE_OK;
  196448. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  196449. if( rc==SQLITE_OK ){
  196450. sqlite3Fts5Dequote(zCopy);
  196451. if( sqlite3_stricmp(zCopy, "col")==0 ){
  196452. *peType = FTS5_VOCAB_COL;
  196453. }else
  196454. if( sqlite3_stricmp(zCopy, "row")==0 ){
  196455. *peType = FTS5_VOCAB_ROW;
  196456. }else
  196457. if( sqlite3_stricmp(zCopy, "instance")==0 ){
  196458. *peType = FTS5_VOCAB_INSTANCE;
  196459. }else
  196460. {
  196461. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  196462. rc = SQLITE_ERROR;
  196463. }
  196464. sqlite3_free(zCopy);
  196465. }
  196466. return rc;
  196467. }
  196468. /*
  196469. ** The xDisconnect() virtual table method.
  196470. */
  196471. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  196472. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  196473. sqlite3_free(pTab);
  196474. return SQLITE_OK;
  196475. }
  196476. /*
  196477. ** The xDestroy() virtual table method.
  196478. */
  196479. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  196480. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  196481. sqlite3_free(pTab);
  196482. return SQLITE_OK;
  196483. }
  196484. /*
  196485. ** This function is the implementation of both the xConnect and xCreate
  196486. ** methods of the FTS3 virtual table.
  196487. **
  196488. ** The argv[] array contains the following:
  196489. **
  196490. ** argv[0] -> module name ("fts5vocab")
  196491. ** argv[1] -> database name
  196492. ** argv[2] -> table name
  196493. **
  196494. ** then:
  196495. **
  196496. ** argv[3] -> name of fts5 table
  196497. ** argv[4] -> type of fts5vocab table
  196498. **
  196499. ** or, for tables in the TEMP schema only.
  196500. **
  196501. ** argv[3] -> name of fts5 tables database
  196502. ** argv[4] -> name of fts5 table
  196503. ** argv[5] -> type of fts5vocab table
  196504. */
  196505. static int fts5VocabInitVtab(
  196506. sqlite3 *db, /* The SQLite database connection */
  196507. void *pAux, /* Pointer to Fts5Global object */
  196508. int argc, /* Number of elements in argv array */
  196509. const char * const *argv, /* xCreate/xConnect argument array */
  196510. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  196511. char **pzErr /* Write any error message here */
  196512. ){
  196513. const char *azSchema[] = {
  196514. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  196515. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
  196516. "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
  196517. };
  196518. Fts5VocabTable *pRet = 0;
  196519. int rc = SQLITE_OK; /* Return code */
  196520. int bDb;
  196521. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  196522. if( argc!=5 && bDb==0 ){
  196523. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  196524. rc = SQLITE_ERROR;
  196525. }else{
  196526. int nByte; /* Bytes of space to allocate */
  196527. const char *zDb = bDb ? argv[3] : argv[1];
  196528. const char *zTab = bDb ? argv[4] : argv[3];
  196529. const char *zType = bDb ? argv[5] : argv[4];
  196530. int nDb = (int)strlen(zDb)+1;
  196531. int nTab = (int)strlen(zTab)+1;
  196532. int eType = 0;
  196533. rc = fts5VocabTableType(zType, pzErr, &eType);
  196534. if( rc==SQLITE_OK ){
  196535. assert( eType>=0 && eType<ArraySize(azSchema) );
  196536. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  196537. }
  196538. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  196539. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  196540. if( pRet ){
  196541. pRet->pGlobal = (Fts5Global*)pAux;
  196542. pRet->eType = eType;
  196543. pRet->db = db;
  196544. pRet->zFts5Tbl = (char*)&pRet[1];
  196545. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  196546. memcpy(pRet->zFts5Tbl, zTab, nTab);
  196547. memcpy(pRet->zFts5Db, zDb, nDb);
  196548. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  196549. sqlite3Fts5Dequote(pRet->zFts5Db);
  196550. }
  196551. }
  196552. *ppVTab = (sqlite3_vtab*)pRet;
  196553. return rc;
  196554. }
  196555. /*
  196556. ** The xConnect() and xCreate() methods for the virtual table. All the
  196557. ** work is done in function fts5VocabInitVtab().
  196558. */
  196559. static int fts5VocabConnectMethod(
  196560. sqlite3 *db, /* Database connection */
  196561. void *pAux, /* Pointer to tokenizer hash table */
  196562. int argc, /* Number of elements in argv array */
  196563. const char * const *argv, /* xCreate/xConnect argument array */
  196564. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  196565. char **pzErr /* OUT: sqlite3_malloc'd error message */
  196566. ){
  196567. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  196568. }
  196569. static int fts5VocabCreateMethod(
  196570. sqlite3 *db, /* Database connection */
  196571. void *pAux, /* Pointer to tokenizer hash table */
  196572. int argc, /* Number of elements in argv array */
  196573. const char * const *argv, /* xCreate/xConnect argument array */
  196574. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  196575. char **pzErr /* OUT: sqlite3_malloc'd error message */
  196576. ){
  196577. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  196578. }
  196579. /*
  196580. ** Implementation of the xBestIndex method.
  196581. **
  196582. ** Only constraints of the form:
  196583. **
  196584. ** term <= ?
  196585. ** term == ?
  196586. ** term >= ?
  196587. **
  196588. ** are interpreted. Less-than and less-than-or-equal are treated
  196589. ** identically, as are greater-than and greater-than-or-equal.
  196590. */
  196591. static int fts5VocabBestIndexMethod(
  196592. sqlite3_vtab *pUnused,
  196593. sqlite3_index_info *pInfo
  196594. ){
  196595. int i;
  196596. int iTermEq = -1;
  196597. int iTermGe = -1;
  196598. int iTermLe = -1;
  196599. int idxNum = 0;
  196600. int nArg = 0;
  196601. UNUSED_PARAM(pUnused);
  196602. for(i=0; i<pInfo->nConstraint; i++){
  196603. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  196604. if( p->usable==0 ) continue;
  196605. if( p->iColumn==0 ){ /* term column */
  196606. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  196607. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  196608. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  196609. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  196610. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  196611. }
  196612. }
  196613. if( iTermEq>=0 ){
  196614. idxNum |= FTS5_VOCAB_TERM_EQ;
  196615. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  196616. pInfo->estimatedCost = 100;
  196617. }else{
  196618. pInfo->estimatedCost = 1000000;
  196619. if( iTermGe>=0 ){
  196620. idxNum |= FTS5_VOCAB_TERM_GE;
  196621. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  196622. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  196623. }
  196624. if( iTermLe>=0 ){
  196625. idxNum |= FTS5_VOCAB_TERM_LE;
  196626. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  196627. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  196628. }
  196629. }
  196630. /* This virtual table always delivers results in ascending order of
  196631. ** the "term" column (column 0). So if the user has requested this
  196632. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  196633. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  196634. ** are already in sorted order. */
  196635. if( pInfo->nOrderBy==1
  196636. && pInfo->aOrderBy[0].iColumn==0
  196637. && pInfo->aOrderBy[0].desc==0
  196638. ){
  196639. pInfo->orderByConsumed = 1;
  196640. }
  196641. pInfo->idxNum = idxNum;
  196642. return SQLITE_OK;
  196643. }
  196644. /*
  196645. ** Implementation of xOpen method.
  196646. */
  196647. static int fts5VocabOpenMethod(
  196648. sqlite3_vtab *pVTab,
  196649. sqlite3_vtab_cursor **ppCsr
  196650. ){
  196651. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  196652. Fts5Index *pIndex = 0;
  196653. Fts5Config *pConfig = 0;
  196654. Fts5VocabCursor *pCsr = 0;
  196655. int rc = SQLITE_OK;
  196656. sqlite3_stmt *pStmt = 0;
  196657. char *zSql = 0;
  196658. zSql = sqlite3Fts5Mprintf(&rc,
  196659. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  196660. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  196661. );
  196662. if( zSql ){
  196663. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  196664. }
  196665. sqlite3_free(zSql);
  196666. assert( rc==SQLITE_OK || pStmt==0 );
  196667. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  196668. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  196669. i64 iId = sqlite3_column_int64(pStmt, 0);
  196670. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  196671. }
  196672. if( rc==SQLITE_OK && pIndex==0 ){
  196673. rc = sqlite3_finalize(pStmt);
  196674. pStmt = 0;
  196675. if( rc==SQLITE_OK ){
  196676. pVTab->zErrMsg = sqlite3_mprintf(
  196677. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  196678. );
  196679. rc = SQLITE_ERROR;
  196680. }
  196681. }
  196682. if( rc==SQLITE_OK ){
  196683. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  196684. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  196685. }
  196686. if( pCsr ){
  196687. pCsr->pIndex = pIndex;
  196688. pCsr->pStmt = pStmt;
  196689. pCsr->pConfig = pConfig;
  196690. pCsr->aCnt = (i64*)&pCsr[1];
  196691. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  196692. }else{
  196693. sqlite3_finalize(pStmt);
  196694. }
  196695. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  196696. return rc;
  196697. }
  196698. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  196699. pCsr->rowid = 0;
  196700. sqlite3Fts5IterClose(pCsr->pIter);
  196701. pCsr->pIter = 0;
  196702. sqlite3_free(pCsr->zLeTerm);
  196703. pCsr->nLeTerm = -1;
  196704. pCsr->zLeTerm = 0;
  196705. }
  196706. /*
  196707. ** Close the cursor. For additional information see the documentation
  196708. ** on the xClose method of the virtual table interface.
  196709. */
  196710. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  196711. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  196712. fts5VocabResetCursor(pCsr);
  196713. sqlite3Fts5BufferFree(&pCsr->term);
  196714. sqlite3_finalize(pCsr->pStmt);
  196715. sqlite3_free(pCsr);
  196716. return SQLITE_OK;
  196717. }
  196718. static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
  196719. int rc = SQLITE_OK;
  196720. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  196721. pCsr->bEof = 1;
  196722. }else{
  196723. const char *zTerm;
  196724. int nTerm;
  196725. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  196726. if( pCsr->nLeTerm>=0 ){
  196727. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  196728. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  196729. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  196730. pCsr->bEof = 1;
  196731. }
  196732. }
  196733. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  196734. }
  196735. return rc;
  196736. }
  196737. static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
  196738. int eDetail = pCsr->pConfig->eDetail;
  196739. int rc = SQLITE_OK;
  196740. Fts5IndexIter *pIter = pCsr->pIter;
  196741. i64 *pp = &pCsr->iInstPos;
  196742. int *po = &pCsr->iInstOff;
  196743. while( eDetail==FTS5_DETAIL_NONE
  196744. || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
  196745. ){
  196746. pCsr->iInstPos = 0;
  196747. pCsr->iInstOff = 0;
  196748. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  196749. if( rc==SQLITE_OK ){
  196750. rc = fts5VocabInstanceNewTerm(pCsr);
  196751. if( eDetail==FTS5_DETAIL_NONE ) break;
  196752. }
  196753. if( rc ){
  196754. pCsr->bEof = 1;
  196755. break;
  196756. }
  196757. }
  196758. return rc;
  196759. }
  196760. /*
  196761. ** Advance the cursor to the next row in the table.
  196762. */
  196763. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  196764. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  196765. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  196766. int rc = SQLITE_OK;
  196767. int nCol = pCsr->pConfig->nCol;
  196768. pCsr->rowid++;
  196769. if( pTab->eType==FTS5_VOCAB_INSTANCE ){
  196770. return fts5VocabInstanceNext(pCsr);
  196771. }
  196772. if( pTab->eType==FTS5_VOCAB_COL ){
  196773. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  196774. if( pCsr->aDoc[pCsr->iCol] ) break;
  196775. }
  196776. }
  196777. if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
  196778. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  196779. pCsr->bEof = 1;
  196780. }else{
  196781. const char *zTerm;
  196782. int nTerm;
  196783. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  196784. if( pCsr->nLeTerm>=0 ){
  196785. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  196786. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  196787. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  196788. pCsr->bEof = 1;
  196789. return SQLITE_OK;
  196790. }
  196791. }
  196792. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  196793. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  196794. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  196795. pCsr->iCol = 0;
  196796. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  196797. while( rc==SQLITE_OK ){
  196798. int eDetail = pCsr->pConfig->eDetail;
  196799. const u8 *pPos; int nPos; /* Position list */
  196800. i64 iPos = 0; /* 64-bit position read from poslist */
  196801. int iOff = 0; /* Current offset within position list */
  196802. pPos = pCsr->pIter->pData;
  196803. nPos = pCsr->pIter->nData;
  196804. switch( pTab->eType ){
  196805. case FTS5_VOCAB_ROW:
  196806. if( eDetail==FTS5_DETAIL_FULL ){
  196807. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  196808. pCsr->aCnt[0]++;
  196809. }
  196810. }
  196811. pCsr->aDoc[0]++;
  196812. break;
  196813. case FTS5_VOCAB_COL:
  196814. if( eDetail==FTS5_DETAIL_FULL ){
  196815. int iCol = -1;
  196816. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  196817. int ii = FTS5_POS2COLUMN(iPos);
  196818. pCsr->aCnt[ii]++;
  196819. if( iCol!=ii ){
  196820. if( ii>=nCol ){
  196821. rc = FTS5_CORRUPT;
  196822. break;
  196823. }
  196824. pCsr->aDoc[ii]++;
  196825. iCol = ii;
  196826. }
  196827. }
  196828. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  196829. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  196830. assert_nc( iPos>=0 && iPos<nCol );
  196831. if( iPos>=nCol ){
  196832. rc = FTS5_CORRUPT;
  196833. break;
  196834. }
  196835. pCsr->aDoc[iPos]++;
  196836. }
  196837. }else{
  196838. assert( eDetail==FTS5_DETAIL_NONE );
  196839. pCsr->aDoc[0]++;
  196840. }
  196841. break;
  196842. default:
  196843. assert( pTab->eType==FTS5_VOCAB_INSTANCE );
  196844. break;
  196845. }
  196846. if( rc==SQLITE_OK ){
  196847. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  196848. }
  196849. if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
  196850. if( rc==SQLITE_OK ){
  196851. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  196852. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  196853. break;
  196854. }
  196855. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  196856. }
  196857. }
  196858. }
  196859. }
  196860. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  196861. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  196862. assert( pCsr->iCol<pCsr->pConfig->nCol );
  196863. }
  196864. return rc;
  196865. }
  196866. /*
  196867. ** This is the xFilter implementation for the virtual table.
  196868. */
  196869. static int fts5VocabFilterMethod(
  196870. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  196871. int idxNum, /* Strategy index */
  196872. const char *zUnused, /* Unused */
  196873. int nUnused, /* Number of elements in apVal */
  196874. sqlite3_value **apVal /* Arguments for the indexing scheme */
  196875. ){
  196876. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  196877. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  196878. int eType = pTab->eType;
  196879. int rc = SQLITE_OK;
  196880. int iVal = 0;
  196881. int f = FTS5INDEX_QUERY_SCAN;
  196882. const char *zTerm = 0;
  196883. int nTerm = 0;
  196884. sqlite3_value *pEq = 0;
  196885. sqlite3_value *pGe = 0;
  196886. sqlite3_value *pLe = 0;
  196887. UNUSED_PARAM2(zUnused, nUnused);
  196888. fts5VocabResetCursor(pCsr);
  196889. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  196890. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  196891. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  196892. if( pEq ){
  196893. zTerm = (const char *)sqlite3_value_text(pEq);
  196894. nTerm = sqlite3_value_bytes(pEq);
  196895. f = 0;
  196896. }else{
  196897. if( pGe ){
  196898. zTerm = (const char *)sqlite3_value_text(pGe);
  196899. nTerm = sqlite3_value_bytes(pGe);
  196900. }
  196901. if( pLe ){
  196902. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  196903. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  196904. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  196905. if( pCsr->zLeTerm==0 ){
  196906. rc = SQLITE_NOMEM;
  196907. }else{
  196908. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  196909. }
  196910. }
  196911. }
  196912. if( rc==SQLITE_OK ){
  196913. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  196914. }
  196915. if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
  196916. rc = fts5VocabInstanceNewTerm(pCsr);
  196917. }
  196918. if( rc==SQLITE_OK
  196919. && !pCsr->bEof
  196920. && (eType!=FTS5_VOCAB_INSTANCE || pCsr->pConfig->eDetail!=FTS5_DETAIL_NONE)
  196921. ){
  196922. rc = fts5VocabNextMethod(pCursor);
  196923. }
  196924. return rc;
  196925. }
  196926. /*
  196927. ** This is the xEof method of the virtual table. SQLite calls this
  196928. ** routine to find out if it has reached the end of a result set.
  196929. */
  196930. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  196931. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  196932. return pCsr->bEof;
  196933. }
  196934. static int fts5VocabColumnMethod(
  196935. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  196936. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  196937. int iCol /* Index of column to read value from */
  196938. ){
  196939. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  196940. int eDetail = pCsr->pConfig->eDetail;
  196941. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  196942. i64 iVal = 0;
  196943. if( iCol==0 ){
  196944. sqlite3_result_text(
  196945. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  196946. );
  196947. }else if( eType==FTS5_VOCAB_COL ){
  196948. assert( iCol==1 || iCol==2 || iCol==3 );
  196949. if( iCol==1 ){
  196950. if( eDetail!=FTS5_DETAIL_NONE ){
  196951. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  196952. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  196953. }
  196954. }else if( iCol==2 ){
  196955. iVal = pCsr->aDoc[pCsr->iCol];
  196956. }else{
  196957. iVal = pCsr->aCnt[pCsr->iCol];
  196958. }
  196959. }else if( eType==FTS5_VOCAB_ROW ){
  196960. assert( iCol==1 || iCol==2 );
  196961. if( iCol==1 ){
  196962. iVal = pCsr->aDoc[0];
  196963. }else{
  196964. iVal = pCsr->aCnt[0];
  196965. }
  196966. }else{
  196967. assert( eType==FTS5_VOCAB_INSTANCE );
  196968. switch( iCol ){
  196969. case 1:
  196970. sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
  196971. break;
  196972. case 2: {
  196973. int ii = -1;
  196974. if( eDetail==FTS5_DETAIL_FULL ){
  196975. ii = FTS5_POS2COLUMN(pCsr->iInstPos);
  196976. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  196977. ii = (int)pCsr->iInstPos;
  196978. }
  196979. if( ii>=0 && ii<pCsr->pConfig->nCol ){
  196980. const char *z = pCsr->pConfig->azCol[ii];
  196981. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  196982. }
  196983. break;
  196984. }
  196985. default: {
  196986. assert( iCol==3 );
  196987. if( eDetail==FTS5_DETAIL_FULL ){
  196988. int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
  196989. sqlite3_result_int(pCtx, ii);
  196990. }
  196991. break;
  196992. }
  196993. }
  196994. }
  196995. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  196996. return SQLITE_OK;
  196997. }
  196998. /*
  196999. ** This is the xRowid method. The SQLite core calls this routine to
  197000. ** retrieve the rowid for the current row of the result set. The
  197001. ** rowid should be written to *pRowid.
  197002. */
  197003. static int fts5VocabRowidMethod(
  197004. sqlite3_vtab_cursor *pCursor,
  197005. sqlite_int64 *pRowid
  197006. ){
  197007. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  197008. *pRowid = pCsr->rowid;
  197009. return SQLITE_OK;
  197010. }
  197011. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  197012. static const sqlite3_module fts5Vocab = {
  197013. /* iVersion */ 2,
  197014. /* xCreate */ fts5VocabCreateMethod,
  197015. /* xConnect */ fts5VocabConnectMethod,
  197016. /* xBestIndex */ fts5VocabBestIndexMethod,
  197017. /* xDisconnect */ fts5VocabDisconnectMethod,
  197018. /* xDestroy */ fts5VocabDestroyMethod,
  197019. /* xOpen */ fts5VocabOpenMethod,
  197020. /* xClose */ fts5VocabCloseMethod,
  197021. /* xFilter */ fts5VocabFilterMethod,
  197022. /* xNext */ fts5VocabNextMethod,
  197023. /* xEof */ fts5VocabEofMethod,
  197024. /* xColumn */ fts5VocabColumnMethod,
  197025. /* xRowid */ fts5VocabRowidMethod,
  197026. /* xUpdate */ 0,
  197027. /* xBegin */ 0,
  197028. /* xSync */ 0,
  197029. /* xCommit */ 0,
  197030. /* xRollback */ 0,
  197031. /* xFindFunction */ 0,
  197032. /* xRename */ 0,
  197033. /* xSavepoint */ 0,
  197034. /* xRelease */ 0,
  197035. /* xRollbackTo */ 0,
  197036. };
  197037. void *p = (void*)pGlobal;
  197038. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  197039. }
  197040. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  197041. /************** End of fts5.c ************************************************/
  197042. /************** Begin file stmt.c ********************************************/
  197043. /*
  197044. ** 2017-05-31
  197045. **
  197046. ** The author disclaims copyright to this source code. In place of
  197047. ** a legal notice, here is a blessing:
  197048. **
  197049. ** May you do good and not evil.
  197050. ** May you find forgiveness for yourself and forgive others.
  197051. ** May you share freely, never taking more than you give.
  197052. **
  197053. *************************************************************************
  197054. **
  197055. ** This file demonstrates an eponymous virtual table that returns information
  197056. ** about all prepared statements for the database connection.
  197057. **
  197058. ** Usage example:
  197059. **
  197060. ** .load ./stmt
  197061. ** .mode line
  197062. ** .header on
  197063. ** SELECT * FROM stmt;
  197064. */
  197065. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
  197066. #if !defined(SQLITEINT_H)
  197067. /* #include "sqlite3ext.h" */
  197068. #endif
  197069. SQLITE_EXTENSION_INIT1
  197070. /* #include <assert.h> */
  197071. /* #include <string.h> */
  197072. #ifndef SQLITE_OMIT_VIRTUALTABLE
  197073. /* stmt_vtab is a subclass of sqlite3_vtab which will
  197074. ** serve as the underlying representation of a stmt virtual table
  197075. */
  197076. typedef struct stmt_vtab stmt_vtab;
  197077. struct stmt_vtab {
  197078. sqlite3_vtab base; /* Base class - must be first */
  197079. sqlite3 *db; /* Database connection for this stmt vtab */
  197080. };
  197081. /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
  197082. ** serve as the underlying representation of a cursor that scans
  197083. ** over rows of the result
  197084. */
  197085. typedef struct stmt_cursor stmt_cursor;
  197086. struct stmt_cursor {
  197087. sqlite3_vtab_cursor base; /* Base class - must be first */
  197088. sqlite3 *db; /* Database connection for this cursor */
  197089. sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
  197090. sqlite3_int64 iRowid; /* The rowid */
  197091. };
  197092. /*
  197093. ** The stmtConnect() method is invoked to create a new
  197094. ** stmt_vtab that describes the stmt virtual table.
  197095. **
  197096. ** Think of this routine as the constructor for stmt_vtab objects.
  197097. **
  197098. ** All this routine needs to do is:
  197099. **
  197100. ** (1) Allocate the stmt_vtab object and initialize all fields.
  197101. **
  197102. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  197103. ** result set of queries against stmt will look like.
  197104. */
  197105. static int stmtConnect(
  197106. sqlite3 *db,
  197107. void *pAux,
  197108. int argc, const char *const*argv,
  197109. sqlite3_vtab **ppVtab,
  197110. char **pzErr
  197111. ){
  197112. stmt_vtab *pNew;
  197113. int rc;
  197114. /* Column numbers */
  197115. #define STMT_COLUMN_SQL 0 /* SQL for the statement */
  197116. #define STMT_COLUMN_NCOL 1 /* Number of result columns */
  197117. #define STMT_COLUMN_RO 2 /* True if read-only */
  197118. #define STMT_COLUMN_BUSY 3 /* True if currently busy */
  197119. #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
  197120. #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
  197121. #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
  197122. #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
  197123. #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
  197124. #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
  197125. #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
  197126. rc = sqlite3_declare_vtab(db,
  197127. "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
  197128. "reprep,run,mem)");
  197129. if( rc==SQLITE_OK ){
  197130. pNew = sqlite3_malloc( sizeof(*pNew) );
  197131. *ppVtab = (sqlite3_vtab*)pNew;
  197132. if( pNew==0 ) return SQLITE_NOMEM;
  197133. memset(pNew, 0, sizeof(*pNew));
  197134. pNew->db = db;
  197135. }
  197136. return rc;
  197137. }
  197138. /*
  197139. ** This method is the destructor for stmt_cursor objects.
  197140. */
  197141. static int stmtDisconnect(sqlite3_vtab *pVtab){
  197142. sqlite3_free(pVtab);
  197143. return SQLITE_OK;
  197144. }
  197145. /*
  197146. ** Constructor for a new stmt_cursor object.
  197147. */
  197148. static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  197149. stmt_cursor *pCur;
  197150. pCur = sqlite3_malloc( sizeof(*pCur) );
  197151. if( pCur==0 ) return SQLITE_NOMEM;
  197152. memset(pCur, 0, sizeof(*pCur));
  197153. pCur->db = ((stmt_vtab*)p)->db;
  197154. *ppCursor = &pCur->base;
  197155. return SQLITE_OK;
  197156. }
  197157. /*
  197158. ** Destructor for a stmt_cursor.
  197159. */
  197160. static int stmtClose(sqlite3_vtab_cursor *cur){
  197161. sqlite3_free(cur);
  197162. return SQLITE_OK;
  197163. }
  197164. /*
  197165. ** Advance a stmt_cursor to its next row of output.
  197166. */
  197167. static int stmtNext(sqlite3_vtab_cursor *cur){
  197168. stmt_cursor *pCur = (stmt_cursor*)cur;
  197169. pCur->iRowid++;
  197170. pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
  197171. return SQLITE_OK;
  197172. }
  197173. /*
  197174. ** Return values of columns for the row at which the stmt_cursor
  197175. ** is currently pointing.
  197176. */
  197177. static int stmtColumn(
  197178. sqlite3_vtab_cursor *cur, /* The cursor */
  197179. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  197180. int i /* Which column to return */
  197181. ){
  197182. stmt_cursor *pCur = (stmt_cursor*)cur;
  197183. switch( i ){
  197184. case STMT_COLUMN_SQL: {
  197185. sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
  197186. break;
  197187. }
  197188. case STMT_COLUMN_NCOL: {
  197189. sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
  197190. break;
  197191. }
  197192. case STMT_COLUMN_RO: {
  197193. sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
  197194. break;
  197195. }
  197196. case STMT_COLUMN_BUSY: {
  197197. sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
  197198. break;
  197199. }
  197200. case STMT_COLUMN_MEM: {
  197201. i = SQLITE_STMTSTATUS_MEMUSED +
  197202. STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
  197203. /* Fall thru */
  197204. }
  197205. case STMT_COLUMN_NSCAN:
  197206. case STMT_COLUMN_NSORT:
  197207. case STMT_COLUMN_NAIDX:
  197208. case STMT_COLUMN_NSTEP:
  197209. case STMT_COLUMN_REPREP:
  197210. case STMT_COLUMN_RUN: {
  197211. sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
  197212. i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
  197213. break;
  197214. }
  197215. }
  197216. return SQLITE_OK;
  197217. }
  197218. /*
  197219. ** Return the rowid for the current row. In this implementation, the
  197220. ** rowid is the same as the output value.
  197221. */
  197222. static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  197223. stmt_cursor *pCur = (stmt_cursor*)cur;
  197224. *pRowid = pCur->iRowid;
  197225. return SQLITE_OK;
  197226. }
  197227. /*
  197228. ** Return TRUE if the cursor has been moved off of the last
  197229. ** row of output.
  197230. */
  197231. static int stmtEof(sqlite3_vtab_cursor *cur){
  197232. stmt_cursor *pCur = (stmt_cursor*)cur;
  197233. return pCur->pStmt==0;
  197234. }
  197235. /*
  197236. ** This method is called to "rewind" the stmt_cursor object back
  197237. ** to the first row of output. This method is always called at least
  197238. ** once prior to any call to stmtColumn() or stmtRowid() or
  197239. ** stmtEof().
  197240. */
  197241. static int stmtFilter(
  197242. sqlite3_vtab_cursor *pVtabCursor,
  197243. int idxNum, const char *idxStr,
  197244. int argc, sqlite3_value **argv
  197245. ){
  197246. stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
  197247. pCur->pStmt = 0;
  197248. pCur->iRowid = 0;
  197249. return stmtNext(pVtabCursor);
  197250. }
  197251. /*
  197252. ** SQLite will invoke this method one or more times while planning a query
  197253. ** that uses the stmt virtual table. This routine needs to create
  197254. ** a query plan for each invocation and compute an estimated cost for that
  197255. ** plan.
  197256. */
  197257. static int stmtBestIndex(
  197258. sqlite3_vtab *tab,
  197259. sqlite3_index_info *pIdxInfo
  197260. ){
  197261. pIdxInfo->estimatedCost = (double)500;
  197262. pIdxInfo->estimatedRows = 500;
  197263. return SQLITE_OK;
  197264. }
  197265. /*
  197266. ** This following structure defines all the methods for the
  197267. ** stmt virtual table.
  197268. */
  197269. static sqlite3_module stmtModule = {
  197270. 0, /* iVersion */
  197271. 0, /* xCreate */
  197272. stmtConnect, /* xConnect */
  197273. stmtBestIndex, /* xBestIndex */
  197274. stmtDisconnect, /* xDisconnect */
  197275. 0, /* xDestroy */
  197276. stmtOpen, /* xOpen - open a cursor */
  197277. stmtClose, /* xClose - close a cursor */
  197278. stmtFilter, /* xFilter - configure scan constraints */
  197279. stmtNext, /* xNext - advance a cursor */
  197280. stmtEof, /* xEof - check for end of scan */
  197281. stmtColumn, /* xColumn - read data */
  197282. stmtRowid, /* xRowid - read data */
  197283. 0, /* xUpdate */
  197284. 0, /* xBegin */
  197285. 0, /* xSync */
  197286. 0, /* xCommit */
  197287. 0, /* xRollback */
  197288. 0, /* xFindMethod */
  197289. 0, /* xRename */
  197290. 0, /* xSavepoint */
  197291. 0, /* xRelease */
  197292. 0, /* xRollbackTo */
  197293. };
  197294. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  197295. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
  197296. int rc = SQLITE_OK;
  197297. #ifndef SQLITE_OMIT_VIRTUALTABLE
  197298. rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
  197299. #endif
  197300. return rc;
  197301. }
  197302. #ifndef SQLITE_CORE
  197303. #ifdef _WIN32
  197304. __declspec(dllexport)
  197305. #endif
  197306. SQLITE_API int sqlite3_stmt_init(
  197307. sqlite3 *db,
  197308. char **pzErrMsg,
  197309. const sqlite3_api_routines *pApi
  197310. ){
  197311. int rc = SQLITE_OK;
  197312. SQLITE_EXTENSION_INIT2(pApi);
  197313. #ifndef SQLITE_OMIT_VIRTUALTABLE
  197314. rc = sqlite3StmtVtabInit(db);
  197315. #endif
  197316. return rc;
  197317. }
  197318. #endif /* SQLITE_CORE */
  197319. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
  197320. /************** End of stmt.c ************************************************/
  197321. #if __LINE__!=211858
  197322. #undef SQLITE_SOURCE_ID
  197323. #define SQLITE_SOURCE_ID "2018-06-04 19:24:41 c7ee0833225bfd8c5ec2f9bf62b97c4e04d03bd9566366d5221ac8fb199aalt2"
  197324. #endif
  197325. /* Return the source-id for this library */
  197326. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  197327. /************************** End of sqlite3.c ******************************/
  197328. #else // USE_LIBSQLITE3
  197329. // If users really want to link against the system sqlite3 we
  197330. // need to make this file a noop.
  197331. #endif
  197332. /*
  197333. ** 2014-09-08
  197334. **
  197335. ** The author disclaims copyright to this source code. In place of
  197336. ** a legal notice, here is a blessing:
  197337. **
  197338. ** May you do good and not evil.
  197339. ** May you find forgiveness for yourself and forgive others.
  197340. ** May you share freely, never taking more than you give.
  197341. **
  197342. *************************************************************************
  197343. **
  197344. ** This file contains the bulk of the implementation of the
  197345. ** user-authentication extension feature. Some parts of the user-
  197346. ** authentication code are contained within the SQLite core (in the
  197347. ** src/ subdirectory of the main source code tree) but those parts
  197348. ** that could reasonable be separated out are moved into this file.
  197349. **
  197350. ** To compile with the user-authentication feature, append this file to
  197351. ** end of an SQLite amalgamation, then add the SQLITE_USER_AUTHENTICATION
  197352. ** compile-time option. See the user-auth.txt file in the same source
  197353. ** directory as this file for additional information.
  197354. */
  197355. #ifdef SQLITE_USER_AUTHENTICATION
  197356. #ifndef SQLITEINT_H
  197357. # include "sqliteInt.h"
  197358. #endif
  197359. /*
  197360. ** Prepare an SQL statement for use by the user authentication logic.
  197361. ** Return a pointer to the prepared statement on success. Return a
  197362. ** NULL pointer if there is an error of any kind.
  197363. */
  197364. static sqlite3_stmt *sqlite3UserAuthPrepare(
  197365. sqlite3 *db,
  197366. const char *zFormat,
  197367. ...
  197368. ){
  197369. sqlite3_stmt *pStmt;
  197370. char *zSql;
  197371. int rc;
  197372. va_list ap;
  197373. int savedFlags = db->flags;
  197374. va_start(ap, zFormat);
  197375. zSql = sqlite3_vmprintf(zFormat, ap);
  197376. va_end(ap);
  197377. if( zSql==0 ) return 0;
  197378. db->flags |= SQLITE_WriteSchema;
  197379. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  197380. db->flags = savedFlags;
  197381. sqlite3_free(zSql);
  197382. if( rc ){
  197383. sqlite3_finalize(pStmt);
  197384. pStmt = 0;
  197385. }
  197386. return pStmt;
  197387. }
  197388. /*
  197389. ** Check to see if the sqlite_user table exists in database zDb.
  197390. */
  197391. static int userTableExists(sqlite3 *db, const char *zDb){
  197392. int rc;
  197393. sqlite3_mutex_enter(db->mutex);
  197394. sqlite3BtreeEnterAll(db);
  197395. if( db->init.busy==0 ){
  197396. char *zErr = 0;
  197397. sqlite3Init(db, &zErr);
  197398. sqlite3DbFree(db, zErr);
  197399. }
  197400. rc = sqlite3FindTable(db, "sqlite_user", zDb)!=0;
  197401. sqlite3BtreeLeaveAll(db);
  197402. sqlite3_mutex_leave(db->mutex);
  197403. return rc;
  197404. }
  197405. /*
  197406. ** Check to see if database zDb has a "sqlite_user" table and if it does
  197407. ** whether that table can authenticate zUser with nPw,zPw. Write one of
  197408. ** the UAUTH_* user authorization level codes into *peAuth and return a
  197409. ** result code.
  197410. */
  197411. static int userAuthCheckLogin(
  197412. sqlite3 *db, /* The database connection to check */
  197413. const char *zDb, /* Name of specific database to check */
  197414. u8 *peAuth /* OUT: One of UAUTH_* constants */
  197415. ){
  197416. sqlite3_stmt *pStmt;
  197417. int rc;
  197418. *peAuth = UAUTH_Unknown;
  197419. if( !userTableExists(db, "main") ){
  197420. *peAuth = UAUTH_Admin; /* No sqlite_user table. Everybody is admin. */
  197421. return SQLITE_OK;
  197422. }
  197423. if( db->auth.zAuthUser==0 ){
  197424. *peAuth = UAUTH_Fail;
  197425. return SQLITE_OK;
  197426. }
  197427. pStmt = sqlite3UserAuthPrepare(db,
  197428. "SELECT pw=sqlite_crypt(?1,pw), isAdmin FROM \"%w\".sqlite_user"
  197429. " WHERE uname=?2", zDb);
  197430. if( pStmt==0 ) return SQLITE_NOMEM;
  197431. sqlite3_bind_blob(pStmt, 1, db->auth.zAuthPW, db->auth.nAuthPW,SQLITE_STATIC);
  197432. sqlite3_bind_text(pStmt, 2, db->auth.zAuthUser, -1, SQLITE_STATIC);
  197433. rc = sqlite3_step(pStmt);
  197434. if( rc==SQLITE_ROW && sqlite3_column_int(pStmt,0) ){
  197435. *peAuth = sqlite3_column_int(pStmt, 1) + UAUTH_User;
  197436. }else{
  197437. *peAuth = UAUTH_Fail;
  197438. }
  197439. return sqlite3_finalize(pStmt);
  197440. }
  197441. int sqlite3UserAuthCheckLogin(
  197442. sqlite3 *db, /* The database connection to check */
  197443. const char *zDb, /* Name of specific database to check */
  197444. u8 *peAuth /* OUT: One of UAUTH_* constants */
  197445. ){
  197446. int rc;
  197447. u8 savedAuthLevel;
  197448. assert( zDb!=0 );
  197449. assert( peAuth!=0 );
  197450. savedAuthLevel = db->auth.authLevel;
  197451. db->auth.authLevel = UAUTH_Admin;
  197452. rc = userAuthCheckLogin(db, zDb, peAuth);
  197453. db->auth.authLevel = savedAuthLevel;
  197454. return rc;
  197455. }
  197456. /*
  197457. ** If the current authLevel is UAUTH_Unknown, the take actions to figure
  197458. ** out what authLevel should be
  197459. */
  197460. void sqlite3UserAuthInit(sqlite3 *db){
  197461. if( db->auth.authLevel==UAUTH_Unknown ){
  197462. u8 authLevel = UAUTH_Fail;
  197463. sqlite3UserAuthCheckLogin(db, "main", &authLevel);
  197464. db->auth.authLevel = authLevel;
  197465. if( authLevel<UAUTH_Admin ) db->flags &= ~SQLITE_WriteSchema;
  197466. }
  197467. }
  197468. /*
  197469. ** Implementation of the sqlite_crypt(X,Y) function.
  197470. **
  197471. ** If Y is NULL then generate a new hash for password X and return that
  197472. ** hash. If Y is not null, then generate a hash for password X using the
  197473. ** same salt as the previous hash Y and return the new hash.
  197474. */
  197475. void sqlite3CryptFunc(
  197476. sqlite3_context *context,
  197477. int NotUsed,
  197478. sqlite3_value **argv
  197479. ){
  197480. const char *zIn;
  197481. int nIn, ii;
  197482. u8 *zOut;
  197483. char zSalt[8];
  197484. zIn = sqlite3_value_blob(argv[0]);
  197485. nIn = sqlite3_value_bytes(argv[0]);
  197486. if( sqlite3_value_type(argv[1])==SQLITE_BLOB
  197487. && sqlite3_value_bytes(argv[1])==nIn+sizeof(zSalt)
  197488. ){
  197489. memcpy(zSalt, sqlite3_value_blob(argv[1]), sizeof(zSalt));
  197490. }else{
  197491. sqlite3_randomness(sizeof(zSalt), zSalt);
  197492. }
  197493. zOut = sqlite3_malloc( nIn+sizeof(zSalt) );
  197494. if( zOut==0 ){
  197495. sqlite3_result_error_nomem(context);
  197496. }else{
  197497. memcpy(zOut, zSalt, sizeof(zSalt));
  197498. for(ii=0; ii<nIn; ii++){
  197499. zOut[ii+sizeof(zSalt)] = zIn[ii]^zSalt[ii&0x7];
  197500. }
  197501. sqlite3_result_blob(context, zOut, nIn+sizeof(zSalt), sqlite3_free);
  197502. }
  197503. }
  197504. /*
  197505. ** If a database contains the SQLITE_USER table, then the
  197506. ** sqlite3_user_authenticate() interface must be invoked with an
  197507. ** appropriate username and password prior to enable read and write
  197508. ** access to the database.
  197509. **
  197510. ** Return SQLITE_OK on success or SQLITE_ERROR if the username/password
  197511. ** combination is incorrect or unknown.
  197512. **
  197513. ** If the SQLITE_USER table is not present in the database file, then
  197514. ** this interface is a harmless no-op returnning SQLITE_OK.
  197515. */
  197516. int sqlite3_user_authenticate(
  197517. sqlite3 *db, /* The database connection */
  197518. const char *zUsername, /* Username */
  197519. const char *zPW, /* Password or credentials */
  197520. int nPW /* Number of bytes in aPW[] */
  197521. ){
  197522. int rc;
  197523. u8 authLevel = UAUTH_Fail;
  197524. db->auth.authLevel = UAUTH_Unknown;
  197525. sqlite3_free(db->auth.zAuthUser);
  197526. sqlite3_free(db->auth.zAuthPW);
  197527. memset(&db->auth, 0, sizeof(db->auth));
  197528. db->auth.zAuthUser = sqlite3_mprintf("%s", zUsername);
  197529. if( db->auth.zAuthUser==0 ) return SQLITE_NOMEM;
  197530. db->auth.zAuthPW = sqlite3_malloc( nPW+1 );
  197531. if( db->auth.zAuthPW==0 ) return SQLITE_NOMEM;
  197532. memcpy(db->auth.zAuthPW,zPW,nPW);
  197533. db->auth.nAuthPW = nPW;
  197534. rc = sqlite3UserAuthCheckLogin(db, "main", &authLevel);
  197535. db->auth.authLevel = authLevel;
  197536. sqlite3ExpirePreparedStatements(db);
  197537. if( rc ){
  197538. return rc; /* OOM error, I/O error, etc. */
  197539. }
  197540. if( authLevel<UAUTH_User ){
  197541. return SQLITE_AUTH; /* Incorrect username and/or password */
  197542. }
  197543. return SQLITE_OK; /* Successful login */
  197544. }
  197545. /*
  197546. ** The sqlite3_user_add() interface can be used (by an admin user only)
  197547. ** to create a new user. When called on a no-authentication-required
  197548. ** database, this routine converts the database into an authentication-
  197549. ** required database, automatically makes the added user an
  197550. ** administrator, and logs in the current connection as that user.
  197551. ** The sqlite3_user_add() interface only works for the "main" database, not
  197552. ** for any ATTACH-ed databases. Any call to sqlite3_user_add() by a
  197553. ** non-admin user results in an error.
  197554. */
  197555. int sqlite3_user_add(
  197556. sqlite3 *db, /* Database connection */
  197557. const char *zUsername, /* Username to be added */
  197558. const char *aPW, /* Password or credentials */
  197559. int nPW, /* Number of bytes in aPW[] */
  197560. int isAdmin /* True to give new user admin privilege */
  197561. ){
  197562. sqlite3_stmt *pStmt;
  197563. int rc;
  197564. sqlite3UserAuthInit(db);
  197565. if( db->auth.authLevel<UAUTH_Admin ) return SQLITE_AUTH;
  197566. if( !userTableExists(db, "main") ){
  197567. if( !isAdmin ) return SQLITE_AUTH;
  197568. pStmt = sqlite3UserAuthPrepare(db,
  197569. "CREATE TABLE sqlite_user(\n"
  197570. " uname TEXT PRIMARY KEY,\n"
  197571. " isAdmin BOOLEAN,\n"
  197572. " pw BLOB\n"
  197573. ") WITHOUT ROWID;");
  197574. if( pStmt==0 ) return SQLITE_NOMEM;
  197575. sqlite3_step(pStmt);
  197576. rc = sqlite3_finalize(pStmt);
  197577. if( rc ) return rc;
  197578. }
  197579. pStmt = sqlite3UserAuthPrepare(db,
  197580. "INSERT INTO sqlite_user(uname,isAdmin,pw)"
  197581. " VALUES(%Q,%d,sqlite_crypt(?1,NULL))",
  197582. zUsername, isAdmin!=0);
  197583. if( pStmt==0 ) return SQLITE_NOMEM;
  197584. sqlite3_bind_blob(pStmt, 1, aPW, nPW, SQLITE_STATIC);
  197585. sqlite3_step(pStmt);
  197586. rc = sqlite3_finalize(pStmt);
  197587. if( rc ) return rc;
  197588. if( db->auth.zAuthUser==0 ){
  197589. assert( isAdmin!=0 );
  197590. sqlite3_user_authenticate(db, zUsername, aPW, nPW);
  197591. }
  197592. return SQLITE_OK;
  197593. }
  197594. /*
  197595. ** The sqlite3_user_change() interface can be used to change a users
  197596. ** login credentials or admin privilege. Any user can change their own
  197597. ** login credentials. Only an admin user can change another users login
  197598. ** credentials or admin privilege setting. No user may change their own
  197599. ** admin privilege setting.
  197600. */
  197601. int sqlite3_user_change(
  197602. sqlite3 *db, /* Database connection */
  197603. const char *zUsername, /* Username to change */
  197604. const char *aPW, /* Modified password or credentials */
  197605. int nPW, /* Number of bytes in aPW[] */
  197606. int isAdmin /* Modified admin privilege for the user */
  197607. ){
  197608. sqlite3_stmt *pStmt;
  197609. int rc;
  197610. u8 authLevel;
  197611. authLevel = db->auth.authLevel;
  197612. if( authLevel<UAUTH_User ){
  197613. /* Must be logged in to make a change */
  197614. return SQLITE_AUTH;
  197615. }
  197616. if( strcmp(db->auth.zAuthUser, zUsername)!=0 ){
  197617. if( db->auth.authLevel<UAUTH_Admin ){
  197618. /* Must be an administrator to change a different user */
  197619. return SQLITE_AUTH;
  197620. }
  197621. }else if( isAdmin!=(authLevel==UAUTH_Admin) ){
  197622. /* Cannot change the isAdmin setting for self */
  197623. return SQLITE_AUTH;
  197624. }
  197625. db->auth.authLevel = UAUTH_Admin;
  197626. if( !userTableExists(db, "main") ){
  197627. /* This routine is a no-op if the user to be modified does not exist */
  197628. }else{
  197629. pStmt = sqlite3UserAuthPrepare(db,
  197630. "UPDATE sqlite_user SET isAdmin=%d, pw=sqlite_crypt(?1,NULL)"
  197631. " WHERE uname=%Q", isAdmin, zUsername);
  197632. if( pStmt==0 ){
  197633. rc = SQLITE_NOMEM;
  197634. }else{
  197635. sqlite3_bind_blob(pStmt, 1, aPW, nPW, SQLITE_STATIC);
  197636. sqlite3_step(pStmt);
  197637. rc = sqlite3_finalize(pStmt);
  197638. }
  197639. }
  197640. db->auth.authLevel = authLevel;
  197641. return rc;
  197642. }
  197643. /*
  197644. ** The sqlite3_user_delete() interface can be used (by an admin user only)
  197645. ** to delete a user. The currently logged-in user cannot be deleted,
  197646. ** which guarantees that there is always an admin user and hence that
  197647. ** the database cannot be converted into a no-authentication-required
  197648. ** database.
  197649. */
  197650. int sqlite3_user_delete(
  197651. sqlite3 *db, /* Database connection */
  197652. const char *zUsername /* Username to remove */
  197653. ){
  197654. sqlite3_stmt *pStmt;
  197655. if( db->auth.authLevel<UAUTH_Admin ){
  197656. /* Must be an administrator to delete a user */
  197657. return SQLITE_AUTH;
  197658. }
  197659. if( strcmp(db->auth.zAuthUser, zUsername)==0 ){
  197660. /* Cannot delete self */
  197661. return SQLITE_AUTH;
  197662. }
  197663. if( !userTableExists(db, "main") ){
  197664. /* This routine is a no-op if the user to be deleted does not exist */
  197665. return SQLITE_OK;
  197666. }
  197667. pStmt = sqlite3UserAuthPrepare(db,
  197668. "DELETE FROM sqlite_user WHERE uname=%Q", zUsername);
  197669. if( pStmt==0 ) return SQLITE_NOMEM;
  197670. sqlite3_step(pStmt);
  197671. return sqlite3_finalize(pStmt);
  197672. }
  197673. #endif /* SQLITE_USER_AUTHENTICATION */